1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
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:
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
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
25 * @brief API implementation
27 ******************************************************************************/
35 #include "core/backend.h"
36 #include "core/context.h"
37 #include "core/depthstencil.h"
38 #include "core/frontend.h"
39 #include "core/rasterizer.h"
40 #include "core/rdtsc_core.h"
41 #include "core/threads.h"
42 #include "core/tilemgr.h"
43 #include "core/clip.h"
44 #include "core/utils.h"
46 #include "common/simdintrin.h"
47 #include "common/os.h"
49 void SetupDefaultState(SWR_CONTEXT
*pContext
);
51 static INLINE SWR_CONTEXT
* GetContext(HANDLE hContext
)
53 return (SWR_CONTEXT
*)hContext
;
56 //////////////////////////////////////////////////////////////////////////
57 /// @brief Create SWR Context.
58 /// @param pCreateInfo - pointer to creation info.
59 HANDLE
SwrCreateContext(
60 SWR_CREATECONTEXT_INFO
* pCreateInfo
)
65 void* pContextMem
= AlignedMalloc(sizeof(SWR_CONTEXT
), KNOB_SIMD_WIDTH
* 4);
66 memset(pContextMem
, 0, sizeof(SWR_CONTEXT
));
67 SWR_CONTEXT
*pContext
= new (pContextMem
) SWR_CONTEXT();
69 pContext
->driverType
= pCreateInfo
->driver
;
70 pContext
->privateStateSize
= pCreateInfo
->privateStateSize
;
72 pContext
->dcRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
73 pContext
->dsRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
75 pContext
->pMacroTileManagerArray
= (MacroTileMgr
*)AlignedMalloc(sizeof(MacroTileMgr
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
76 pContext
->pDispatchQueueArray
= (DispatchQueue
*)AlignedMalloc(sizeof(DispatchQueue
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
78 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
80 pContext
->dcRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
81 new (&pContext
->pMacroTileManagerArray
[dc
]) MacroTileMgr(*pContext
->dcRing
[dc
].pArena
);
82 new (&pContext
->pDispatchQueueArray
[dc
]) DispatchQueue();
84 pContext
->dsRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
87 if (!KNOB_SINGLE_THREADED
)
89 memset(&pContext
->WaitLock
, 0, sizeof(pContext
->WaitLock
));
90 memset(&pContext
->FifosNotEmpty
, 0, sizeof(pContext
->FifosNotEmpty
));
91 new (&pContext
->WaitLock
) std::mutex();
92 new (&pContext
->FifosNotEmpty
) std::condition_variable();
94 CreateThreadPool(pContext
, &pContext
->threadPool
);
97 // Calling createThreadPool() above can set SINGLE_THREADED
98 if (KNOB_SINGLE_THREADED
)
100 SET_KNOB(HYPERTHREADED_FE
, false);
101 pContext
->NumWorkerThreads
= 1;
102 pContext
->NumFEThreads
= 1;
103 pContext
->NumBEThreads
= 1;
106 // Allocate scratch space for workers.
107 ///@note We could lazily allocate this but its rather small amount of memory.
108 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
111 uint32_t numaNode
= pContext
->threadPool
.pThreadData
?
112 pContext
->threadPool
.pThreadData
[i
].numaId
: 0;
113 pContext
->pScratch
[i
] = (uint8_t*)VirtualAllocExNuma(
114 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE
),
115 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
,
118 pContext
->pScratch
[i
] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE
), KNOB_SIMD_WIDTH
* 4);
122 // State setup AFTER context is fully initialized
123 SetupDefaultState(pContext
);
125 // initialize hot tile manager
126 pContext
->pHotTileMgr
= new HotTileMgr();
128 // initialize function pointer tables
129 InitClearTilesTable();
131 // initialize callback functions
132 pContext
->pfnLoadTile
= pCreateInfo
->pfnLoadTile
;
133 pContext
->pfnStoreTile
= pCreateInfo
->pfnStoreTile
;
134 pContext
->pfnClearTile
= pCreateInfo
->pfnClearTile
;
135 pContext
->pfnUpdateSoWriteOffset
= pCreateInfo
->pfnUpdateSoWriteOffset
;
137 // pass pointer to bucket manager back to caller
138 #ifdef KNOB_ENABLE_RDTSC
139 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
142 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
144 return (HANDLE
)pContext
;
147 void SwrDestroyContext(HANDLE hContext
)
149 SWR_CONTEXT
*pContext
= GetContext(hContext
);
150 DestroyThreadPool(pContext
, &pContext
->threadPool
);
153 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
155 delete pContext
->dcRing
[i
].pArena
;
156 delete pContext
->dsRing
[i
].pArena
;
157 pContext
->pMacroTileManagerArray
[i
].~MacroTileMgr();
158 pContext
->pDispatchQueueArray
[i
].~DispatchQueue();
161 AlignedFree(pContext
->pDispatchQueueArray
);
162 AlignedFree(pContext
->pMacroTileManagerArray
);
164 // Free scratch space.
165 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
168 VirtualFree(pContext
->pScratch
[i
], 0, MEM_RELEASE
);
170 AlignedFree(pContext
->pScratch
[i
]);
174 delete(pContext
->pHotTileMgr
);
176 pContext
->~SWR_CONTEXT();
177 AlignedFree(GetContext(hContext
));
180 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
182 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
185 void WakeAllThreads(SWR_CONTEXT
*pContext
)
187 pContext
->FifosNotEmpty
.notify_all();
190 static TileSet gSingleThreadLockedTiles
;
192 template<bool IsDraw
>
193 void QueueWork(SWR_CONTEXT
*pContext
)
195 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
196 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
200 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
201 pDC
->pTileMgr
->initialize();
204 // Each worker thread looks at a DC for both FE and BE work at different times and so we
205 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
206 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
207 // then moved on if all work is done.)
208 pContext
->pCurDrawContext
->threadsDone
= pContext
->NumFEThreads
+ pContext
->NumBEThreads
;
212 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
217 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
218 pContext
->dcRing
.Enqueue();
221 if (KNOB_SINGLE_THREADED
)
223 // flush denormals to 0
224 uint32_t mxcsr
= _mm_getcsr();
225 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
229 uint32_t curDraw
[2] = { pContext
->pCurDrawContext
->drawId
, pContext
->pCurDrawContext
->drawId
};
230 WorkOnFifoFE(pContext
, 0, curDraw
[0]);
231 WorkOnFifoBE(pContext
, 0, curDraw
[1], gSingleThreadLockedTiles
, 0, 0);
235 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
236 WorkOnCompute(pContext
, 0, curDispatch
);
239 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
240 while (CompleteDrawContext(pContext
, pContext
->pCurDrawContext
) > 0) {}
247 RDTSC_START(APIDrawWakeAllThreads
);
248 WakeAllThreads(pContext
);
249 RDTSC_STOP(APIDrawWakeAllThreads
, 1, 0);
252 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
253 pContext
->pPrevDrawContext
= pContext
->pCurDrawContext
;
254 pContext
->pCurDrawContext
= nullptr;
257 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
259 QueueWork
<true>(pContext
);
262 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
264 QueueWork
<false>(pContext
);
267 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
269 RDTSC_START(APIGetDrawContext
);
270 // If current draw context is null then need to obtain a new draw context to use from ring.
271 if (pContext
->pCurDrawContext
== nullptr)
273 // Need to wait for a free entry.
274 while (pContext
->dcRing
.IsFull())
279 uint64_t curDraw
= pContext
->dcRing
.GetHead();
280 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
282 static uint64_t lastDrawChecked
;
283 static uint32_t lastFrameChecked
;
284 if ((pContext
->frameCount
- lastFrameChecked
) > 2 ||
285 (curDraw
- lastDrawChecked
) > 0x10000)
287 // Take this opportunity to clean-up old arena allocations
288 pContext
->cachingArenaAllocator
.FreeOldBlocks();
290 lastFrameChecked
= pContext
->frameCount
;
291 lastDrawChecked
= curDraw
;
294 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
295 pContext
->pCurDrawContext
= pCurDrawContext
;
297 // Assign next available entry in DS ring to this DC.
298 uint32_t dsIndex
= pContext
->curStateId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
299 pCurDrawContext
->pState
= &pContext
->dsRing
[dsIndex
];
301 // Copy previous state to current state.
302 if (pContext
->pPrevDrawContext
)
304 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
306 // If we're splitting our draw then we can just use the same state from the previous
307 // draw. In this case, we won't increment the DS ring index so the next non-split
308 // draw can receive the state.
309 if (isSplitDraw
== false)
311 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
313 // Should have been cleaned up previously
314 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
316 pCurDrawContext
->pState
->pPrivateState
= nullptr;
318 pContext
->curStateId
++; // Progress state ring index forward.
322 // If its a split draw then just copy the state pointer over
323 // since its the same draw.
324 pCurDrawContext
->pState
= pPrevDrawContext
->pState
;
325 SWR_ASSERT(pPrevDrawContext
->cleanupState
== false);
330 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
331 pContext
->curStateId
++; // Progress state ring index forward.
334 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
336 pCurDrawContext
->dependent
= false;
337 pCurDrawContext
->pContext
= pContext
;
338 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
340 pCurDrawContext
->doneFE
= false;
341 pCurDrawContext
->FeLock
= 0;
342 pCurDrawContext
->threadsDone
= 0;
343 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
345 memset(&pCurDrawContext
->dynState
, 0, sizeof(pCurDrawContext
->dynState
));
347 // Assign unique drawId for this DC
348 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
350 pCurDrawContext
->cleanupState
= true;
354 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
357 RDTSC_STOP(APIGetDrawContext
, 0, 0);
358 return pContext
->pCurDrawContext
;
361 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
363 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
364 SWR_ASSERT(pDC
->pState
!= nullptr);
366 return &pDC
->pState
->state
;
369 void SWR_API
SwrSaveState(
371 void* pOutputStateBlock
,
374 SWR_CONTEXT
*pContext
= GetContext(hContext
);
375 auto pSrc
= GetDrawState(pContext
);
376 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
378 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
381 void SWR_API
SwrRestoreState(
383 const void* pStateBlock
,
386 SWR_CONTEXT
*pContext
= GetContext(hContext
);
387 auto pDst
= GetDrawState(pContext
);
388 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
390 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
393 void SetupDefaultState(SWR_CONTEXT
*pContext
)
395 API_STATE
* pState
= GetDrawState(pContext
);
397 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
398 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
401 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
403 RDTSC_START(APISync
);
405 SWR_ASSERT(pfnFunc
!= nullptr);
407 SWR_CONTEXT
*pContext
= GetContext(hContext
);
408 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
410 pDC
->FeWork
.type
= SYNC
;
411 pDC
->FeWork
.pfnWork
= ProcessSync
;
413 // Setup callback function
414 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
415 pDC
->retireCallback
.userData
= userData
;
416 pDC
->retireCallback
.userData2
= userData2
;
417 pDC
->retireCallback
.userData3
= userData3
;
422 RDTSC_STOP(APISync
, 1, 0);
425 void SwrWaitForIdle(HANDLE hContext
)
427 SWR_CONTEXT
*pContext
= GetContext(hContext
);
429 RDTSC_START(APIWaitForIdle
);
431 while (!pContext
->dcRing
.IsEmpty())
436 RDTSC_STOP(APIWaitForIdle
, 1, 0);
439 void SwrWaitForIdleFE(HANDLE hContext
)
441 SWR_CONTEXT
*pContext
= GetContext(hContext
);
443 RDTSC_START(APIWaitForIdle
);
445 while (pContext
->drawsOutstandingFE
> 0)
450 RDTSC_STOP(APIWaitForIdle
, 1, 0);
453 void SwrSetVertexBuffers(
456 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
458 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
460 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
462 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
463 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
467 void SwrSetIndexBuffer(
469 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
471 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
473 pState
->indexBuffer
= *pIndexBuffer
;
476 void SwrSetFetchFunc(
478 PFN_FETCH_FUNC pfnFetchFunc
)
480 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
482 pState
->pfnFetchFunc
= pfnFetchFunc
;
487 PFN_SO_FUNC pfnSoFunc
,
488 uint32_t streamIndex
)
490 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
492 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
494 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
499 SWR_STREAMOUT_STATE
* pSoState
)
501 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
503 pState
->soState
= *pSoState
;
506 void SwrSetSoBuffers(
508 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
511 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
513 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
515 pState
->soBuffer
[slot
] = *pSoBuffer
;
518 void SwrSetVertexFunc(
520 PFN_VERTEX_FUNC pfnVertexFunc
)
522 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
524 pState
->pfnVertexFunc
= pfnVertexFunc
;
527 void SwrSetFrontendState(
529 SWR_FRONTEND_STATE
*pFEState
)
531 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
532 pState
->frontendState
= *pFEState
;
537 SWR_GS_STATE
*pGSState
)
539 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
540 pState
->gsState
= *pGSState
;
545 PFN_GS_FUNC pfnGsFunc
)
547 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
548 pState
->pfnGsFunc
= pfnGsFunc
;
553 PFN_CS_FUNC pfnCsFunc
,
554 uint32_t totalThreadsInGroup
,
555 uint32_t totalSpillFillSize
)
557 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
558 pState
->pfnCsFunc
= pfnCsFunc
;
559 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
560 pState
->totalSpillFillSize
= totalSpillFillSize
;
565 SWR_TS_STATE
*pState
)
567 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
568 pApiState
->tsState
= *pState
;
575 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
576 pApiState
->pfnHsFunc
= pfnFunc
;
583 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
584 pApiState
->pfnDsFunc
= pfnFunc
;
587 void SwrSetDepthStencilState(
589 SWR_DEPTH_STENCIL_STATE
*pDSState
)
591 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
593 pState
->depthStencilState
= *pDSState
;
596 void SwrSetBackendState(
598 SWR_BACKEND_STATE
*pBEState
)
600 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
602 pState
->backendState
= *pBEState
;
605 void SwrSetPixelShaderState(
607 SWR_PS_STATE
*pPSState
)
609 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
610 pState
->psState
= *pPSState
;
613 void SwrSetBlendState(
615 SWR_BLEND_STATE
*pBlendState
)
617 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
618 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
621 void SwrSetBlendFunc(
623 uint32_t renderTarget
,
624 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
626 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
627 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
628 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
631 // update guardband multipliers for the viewport
632 void updateGuardband(API_STATE
*pState
)
634 // guardband center is viewport center
635 pState
->gbState
.left
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
636 pState
->gbState
.right
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
637 pState
->gbState
.top
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
638 pState
->gbState
.bottom
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
641 void SwrSetRastState(
643 const SWR_RASTSTATE
*pRastState
)
645 SWR_CONTEXT
*pContext
= GetContext(hContext
);
646 API_STATE
* pState
= GetDrawState(pContext
);
648 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
651 void SwrSetViewports(
653 uint32_t numViewports
,
654 const SWR_VIEWPORT
* pViewports
,
655 const SWR_VIEWPORT_MATRIX
* pMatrices
)
657 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
658 "Invalid number of viewports.");
660 SWR_CONTEXT
*pContext
= GetContext(hContext
);
661 API_STATE
* pState
= GetDrawState(pContext
);
663 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
665 if (pMatrices
!= nullptr)
667 memcpy(&pState
->vpMatrix
[0], pMatrices
, sizeof(SWR_VIEWPORT_MATRIX
) * numViewports
);
671 // Compute default viewport transform.
672 for (uint32_t i
= 0; i
< numViewports
; ++i
)
674 if (pContext
->driverType
== DX
)
676 pState
->vpMatrix
[i
].m00
= pState
->vp
[i
].width
/ 2.0f
;
677 pState
->vpMatrix
[i
].m11
= -pState
->vp
[i
].height
/ 2.0f
;
678 pState
->vpMatrix
[i
].m22
= pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
679 pState
->vpMatrix
[i
].m30
= pState
->vp
[i
].x
+ pState
->vpMatrix
[i
].m00
;
680 pState
->vpMatrix
[i
].m31
= pState
->vp
[i
].y
- pState
->vpMatrix
[i
].m11
;
681 pState
->vpMatrix
[i
].m32
= pState
->vp
[i
].minZ
;
685 // Standard, with the exception that Y is inverted.
686 pState
->vpMatrix
[i
].m00
= (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
687 pState
->vpMatrix
[i
].m11
= (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
688 pState
->vpMatrix
[i
].m22
= (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
689 pState
->vpMatrix
[i
].m30
= pState
->vp
[i
].x
+ pState
->vpMatrix
[i
].m00
;
690 pState
->vpMatrix
[i
].m31
= pState
->vp
[i
].height
+ pState
->vpMatrix
[i
].m11
;
691 pState
->vpMatrix
[i
].m32
= pState
->vp
[i
].minZ
+ pState
->vpMatrix
[i
].m22
;
693 // Now that the matrix is calculated, clip the view coords to screen size.
694 // OpenGL allows for -ve x,y in the viewport.
695 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
696 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
701 updateGuardband(pState
);
704 void SwrSetScissorRects(
706 uint32_t numScissors
,
707 const BBOX
* pScissors
)
709 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
710 "Invalid number of scissor rects.");
712 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
713 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(BBOX
));
716 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
718 API_STATE
*pState
= &pDC
->pState
->state
;
719 uint32_t left
, right
, top
, bottom
;
721 // Set up scissor dimensions based on scissor or viewport
722 if (pState
->rastState
.scissorEnable
)
724 // scissor rect right/bottom edge are exclusive, core expects scissor dimensions to be inclusive, so subtract one pixel from right/bottom edges
725 left
= pState
->scissorRects
[0].left
;
726 right
= pState
->scissorRects
[0].right
;
727 top
= pState
->scissorRects
[0].top
;
728 bottom
= pState
->scissorRects
[0].bottom
;
732 // the vp width and height must be added to origin un-rounded then the result round to -inf.
733 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
734 left
= (int32_t)pState
->vp
[0].x
;
735 right
= (int32_t)(pState
->vp
[0].x
+ pState
->vp
[0].width
);
736 top
= (int32_t)pState
->vp
[0].y
;
737 bottom
= (int32_t)(pState
->vp
[0].y
+ pState
->vp
[0].height
);
740 right
= std::min
<uint32_t>(right
, KNOB_MAX_SCISSOR_X
);
741 bottom
= std::min
<uint32_t>(bottom
, KNOB_MAX_SCISSOR_Y
);
743 if (left
> KNOB_MAX_SCISSOR_X
|| top
> KNOB_MAX_SCISSOR_Y
)
745 pState
->scissorInFixedPoint
.left
= 0;
746 pState
->scissorInFixedPoint
.right
= 0;
747 pState
->scissorInFixedPoint
.top
= 0;
748 pState
->scissorInFixedPoint
.bottom
= 0;
752 pState
->scissorInFixedPoint
.left
= left
* FIXED_POINT_SCALE
;
753 pState
->scissorInFixedPoint
.right
= right
* FIXED_POINT_SCALE
- 1;
754 pState
->scissorInFixedPoint
.top
= top
* FIXED_POINT_SCALE
;
755 pState
->scissorInFixedPoint
.bottom
= bottom
* FIXED_POINT_SCALE
- 1;
759 // templated backend function tables
760 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
761 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
762 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
763 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
764 void SetupPipeline(DRAW_CONTEXT
*pDC
)
766 DRAW_STATE
* pState
= pDC
->pState
;
767 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
768 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
769 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
770 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
773 if (psState
.pfnPixelShader
== nullptr)
775 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
779 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
780 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
781 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
783 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
785 // select backend function
786 switch(psState
.shadingRate
)
788 case SWR_SHADING_RATE_PIXEL
:
789 if(bMultisampleEnable
)
791 // always need to generate I & J per sample for Z interpolation
792 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
793 backendFuncs
.pfnBackend
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
797 // always need to generate I & J per pixel for Z interpolation
798 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
799 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
802 case SWR_SHADING_RATE_SAMPLE
:
803 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
804 // always need to generate I & J per sample for Z interpolation
805 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
806 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
809 SWR_ASSERT(0 && "Invalid shading rate");
814 PFN_PROCESS_PRIMS pfnBinner
;
815 switch (pState
->state
.topology
)
818 pState
->pfnProcessPrims
= ClipPoints
;
819 pfnBinner
= BinPoints
;
824 case TOP_LINE_LIST_ADJ
:
825 case TOP_LISTSTRIP_ADJ
:
826 pState
->pfnProcessPrims
= ClipLines
;
827 pfnBinner
= BinLines
;
830 pState
->pfnProcessPrims
= ClipTriangles
;
831 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
835 // disable clipper if viewport transform is disabled
836 if (pState
->state
.frontendState
.vpTransformDisable
)
838 pState
->pfnProcessPrims
= pfnBinner
;
841 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
842 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
843 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
844 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
845 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
846 (pState
->state
.backendState
.numAttributes
== 0))
848 pState
->pfnProcessPrims
= nullptr;
851 if (pState
->state
.soState
.rasterizerDisable
== true)
853 pState
->pfnProcessPrims
= nullptr;
856 // set up the frontend attribute count
857 pState
->state
.feNumAttributes
= 0;
858 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
859 if (backendState
.swizzleEnable
)
861 // attribute swizzling is enabled, iterate over the map and record the max attribute used
862 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
864 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
869 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
872 if (pState
->state
.soState
.soEnable
)
874 uint32_t streamMasks
= 0;
875 for (uint32_t i
= 0; i
< 4; ++i
)
877 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
881 if (_BitScanReverse(&maxAttrib
, streamMasks
))
883 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
887 // complicated logic to test for cases where we don't need backing hottile memory for a draw
888 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
889 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
890 !pState
->state
.depthStencilState
.depthWriteEnable
&&
891 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
892 (pState
->state
.depthStencilState
.depthTestEnable
||
893 pState
->state
.depthStencilState
.depthWriteEnable
)) ? true : false;
895 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
896 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
897 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
898 // for stencil we have to check the double sided state as well
899 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
900 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
901 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
902 (pState
->state
.depthStencilState
.stencilTestEnable
||
903 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
905 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
906 pState
->state
.colorHottileEnable
= 0;
907 if (psState
.pfnPixelShader
!= nullptr)
909 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
911 pState
->state
.colorHottileEnable
|=
912 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
913 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
914 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
915 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
919 // Setup depth quantization function
920 if (pState
->state
.depthHottileEnable
)
922 switch (pState
->state
.rastState
.depthFormat
)
924 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
925 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
926 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
927 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
928 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
929 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
934 // set up pass-through quantize if depth isn't enabled
935 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
939 //////////////////////////////////////////////////////////////////////////
941 /// @param pDC - Draw context to initialize for this draw.
946 // We don't need to re-setup the scissors/pipeline state again for split draw.
947 if (isSplitDraw
== false)
949 SetupMacroTileScissors(pDC
);
954 //////////////////////////////////////////////////////////////////////////
955 /// @brief We can split the draw for certain topologies for better performance.
956 /// @param totalVerts - Total vertices for draw
957 /// @param topology - Topology used for draw
958 uint32_t MaxVertsPerDraw(
961 PRIMITIVE_TOPOLOGY topology
)
963 API_STATE
& state
= pDC
->pState
->state
;
965 uint32_t vertsPerDraw
= totalVerts
;
967 if (state
.soState
.soEnable
)
975 case TOP_TRIANGLE_LIST
:
976 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
979 case TOP_PATCHLIST_1
:
980 case TOP_PATCHLIST_2
:
981 case TOP_PATCHLIST_3
:
982 case TOP_PATCHLIST_4
:
983 case TOP_PATCHLIST_5
:
984 case TOP_PATCHLIST_6
:
985 case TOP_PATCHLIST_7
:
986 case TOP_PATCHLIST_8
:
987 case TOP_PATCHLIST_9
:
988 case TOP_PATCHLIST_10
:
989 case TOP_PATCHLIST_11
:
990 case TOP_PATCHLIST_12
:
991 case TOP_PATCHLIST_13
:
992 case TOP_PATCHLIST_14
:
993 case TOP_PATCHLIST_15
:
994 case TOP_PATCHLIST_16
:
995 case TOP_PATCHLIST_17
:
996 case TOP_PATCHLIST_18
:
997 case TOP_PATCHLIST_19
:
998 case TOP_PATCHLIST_20
:
999 case TOP_PATCHLIST_21
:
1000 case TOP_PATCHLIST_22
:
1001 case TOP_PATCHLIST_23
:
1002 case TOP_PATCHLIST_24
:
1003 case TOP_PATCHLIST_25
:
1004 case TOP_PATCHLIST_26
:
1005 case TOP_PATCHLIST_27
:
1006 case TOP_PATCHLIST_28
:
1007 case TOP_PATCHLIST_29
:
1008 case TOP_PATCHLIST_30
:
1009 case TOP_PATCHLIST_31
:
1010 case TOP_PATCHLIST_32
:
1011 if (pDC
->pState
->state
.tsState
.tsEnable
)
1013 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1014 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1018 // The Primitive Assembly code can only handle 1 RECT at a time.
1024 // We are not splitting up draws for other topologies.
1028 return vertsPerDraw
;
1032 //////////////////////////////////////////////////////////////////////////
1033 /// @brief DrawInstanced
1034 /// @param hContext - Handle passed back from SwrCreateContext
1035 /// @param topology - Specifies topology for draw.
1036 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1037 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1038 /// @param numInstances - How many instances to render.
1039 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1042 PRIMITIVE_TOPOLOGY topology
,
1043 uint32_t numVertices
,
1044 uint32_t startVertex
,
1045 uint32_t numInstances
= 1,
1046 uint32_t startInstance
= 0)
1053 RDTSC_START(APIDraw
);
1055 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1056 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1058 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1059 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1060 uint32_t remainingVerts
= numVertices
;
1062 API_STATE
*pState
= &pDC
->pState
->state
;
1063 pState
->topology
= topology
;
1064 pState
->forceFront
= false;
1066 // disable culling for points/lines
1067 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1068 if (topology
== TOP_POINT_LIST
)
1070 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1071 pState
->forceFront
= true;
1075 while (remainingVerts
)
1077 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1078 remainingVerts
: maxVertsPerDraw
;
1080 bool isSplitDraw
= (draw
> 0) ? true : false;
1081 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1082 InitDraw(pDC
, isSplitDraw
);
1084 pDC
->FeWork
.type
= DRAW
;
1085 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1087 false, // bEnableCutIndex
1088 pState
->tsState
.tsEnable
,
1089 pState
->gsState
.gsEnable
,
1090 pState
->soState
.soEnable
,
1091 pDC
->pState
->pfnProcessPrims
!= nullptr);
1092 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1093 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1094 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1095 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1096 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1097 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1099 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1102 QueueDraw(pContext
);
1104 remainingVerts
-= numVertsForDraw
;
1108 // restore culling state
1109 pDC
= GetDrawContext(pContext
);
1110 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1112 RDTSC_STOP(APIDraw
, numVertices
* numInstances
, 0);
1115 //////////////////////////////////////////////////////////////////////////
1117 /// @param hContext - Handle passed back from SwrCreateContext
1118 /// @param topology - Specifies topology for draw.
1119 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1120 /// @param primCount - Number of vertices.
1123 PRIMITIVE_TOPOLOGY topology
,
1124 uint32_t startVertex
,
1125 uint32_t numVertices
)
1127 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1130 //////////////////////////////////////////////////////////////////////////
1131 /// @brief SwrDrawInstanced
1132 /// @param hContext - Handle passed back from SwrCreateContext
1133 /// @param topology - Specifies topology for draw.
1134 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1135 /// @param numInstances - How many instances to render.
1136 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1137 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1138 void SwrDrawInstanced(
1140 PRIMITIVE_TOPOLOGY topology
,
1141 uint32_t numVertsPerInstance
,
1142 uint32_t numInstances
,
1143 uint32_t startVertex
,
1144 uint32_t startInstance
1147 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1150 //////////////////////////////////////////////////////////////////////////
1151 /// @brief DrawIndexedInstanced
1152 /// @param hContext - Handle passed back from SwrCreateContext
1153 /// @param topology - Specifies topology for draw.
1154 /// @param numIndices - Number of indices to read sequentially from index buffer.
1155 /// @param indexOffset - Starting index into index buffer.
1156 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1157 /// @param numInstances - Number of instances to render.
1158 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1159 void DrawIndexedInstance(
1161 PRIMITIVE_TOPOLOGY topology
,
1162 uint32_t numIndices
,
1163 uint32_t indexOffset
,
1165 uint32_t numInstances
= 1,
1166 uint32_t startInstance
= 0)
1173 RDTSC_START(APIDrawIndexed
);
1175 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1176 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1177 API_STATE
* pState
= &pDC
->pState
->state
;
1179 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1180 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1181 uint32_t remainingIndices
= numIndices
;
1183 uint32_t indexSize
= 0;
1184 switch (pState
->indexBuffer
.format
)
1186 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1187 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1188 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1194 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1195 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1197 pState
->topology
= topology
;
1198 pState
->forceFront
= false;
1200 // disable culling for points/lines
1201 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1202 if (topology
== TOP_POINT_LIST
)
1204 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1205 pState
->forceFront
= true;
1208 while (remainingIndices
)
1210 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1211 remainingIndices
: maxIndicesPerDraw
;
1213 // When breaking up draw, we need to obtain new draw context for each iteration.
1214 bool isSplitDraw
= (draw
> 0) ? true : false;
1215 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1216 InitDraw(pDC
, isSplitDraw
);
1218 pDC
->FeWork
.type
= DRAW
;
1219 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1221 pState
->frontendState
.bEnableCutIndex
,
1222 pState
->tsState
.tsEnable
,
1223 pState
->gsState
.gsEnable
,
1224 pState
->soState
.soEnable
,
1225 pDC
->pState
->pfnProcessPrims
!= nullptr);
1226 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1227 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1228 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1229 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1231 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1232 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1233 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1234 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1236 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1239 QueueDraw(pContext
);
1241 pIB
+= maxIndicesPerDraw
* indexSize
;
1242 remainingIndices
-= numIndicesForDraw
;
1246 // restore culling state
1247 pDC
= GetDrawContext(pContext
);
1248 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1250 RDTSC_STOP(APIDrawIndexed
, numIndices
* numInstances
, 0);
1254 //////////////////////////////////////////////////////////////////////////
1255 /// @brief DrawIndexed
1256 /// @param hContext - Handle passed back from SwrCreateContext
1257 /// @param topology - Specifies topology for draw.
1258 /// @param numIndices - Number of indices to read sequentially from index buffer.
1259 /// @param indexOffset - Starting index into index buffer.
1260 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1261 void SwrDrawIndexed(
1263 PRIMITIVE_TOPOLOGY topology
,
1264 uint32_t numIndices
,
1265 uint32_t indexOffset
,
1269 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1272 //////////////////////////////////////////////////////////////////////////
1273 /// @brief SwrDrawIndexedInstanced
1274 /// @param hContext - Handle passed back from SwrCreateContext
1275 /// @param topology - Specifies topology for draw.
1276 /// @param numIndices - Number of indices to read sequentially from index buffer.
1277 /// @param numInstances - Number of instances to render.
1278 /// @param indexOffset - Starting index into index buffer.
1279 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1280 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1281 void SwrDrawIndexedInstanced(
1283 PRIMITIVE_TOPOLOGY topology
,
1284 uint32_t numIndices
,
1285 uint32_t numInstances
,
1286 uint32_t indexOffset
,
1288 uint32_t startInstance
)
1290 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1293 //////////////////////////////////////////////////////////////////////////
1294 /// @brief SwrInvalidateTiles
1295 /// @param hContext - Handle passed back from SwrCreateContext
1296 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1297 void SwrInvalidateTiles(
1299 uint32_t attachmentMask
)
1306 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1307 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1309 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1310 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1311 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1312 memset(&pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
, 0, sizeof(SWR_RECT
));
1313 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1314 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1315 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1318 QueueDraw(pContext
);
1321 //////////////////////////////////////////////////////////////////////////
1322 /// @brief SwrDiscardRect
1323 /// @param hContext - Handle passed back from SwrCreateContext
1324 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1325 /// @param rect - if rect is all zeros, the entire attachment surface will be discarded
1326 void SwrDiscardRect(
1328 uint32_t attachmentMask
,
1336 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1337 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1339 // Queue a load to the hottile
1340 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1341 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1342 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1343 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1344 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1345 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1346 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1349 QueueDraw(pContext
);
1352 //////////////////////////////////////////////////////////////////////////
1353 /// @brief SwrDispatch
1354 /// @param hContext - Handle passed back from SwrCreateContext
1355 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1356 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1357 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1360 uint32_t threadGroupCountX
,
1361 uint32_t threadGroupCountY
,
1362 uint32_t threadGroupCountZ
)
1369 RDTSC_START(APIDispatch
);
1370 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1371 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1373 pDC
->isCompute
= true; // This is a compute context.
1375 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1377 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1378 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1379 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1381 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1382 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1383 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1384 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
);
1386 QueueDispatch(pContext
);
1387 RDTSC_STOP(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
, 0);
1390 // Deswizzles, converts and stores current contents of the hot tiles to surface
1391 // described by pState
1394 SWR_RENDERTARGET_ATTACHMENT attachment
,
1395 SWR_TILE_STATE postStoreTileState
)
1402 RDTSC_START(APIStoreTiles
);
1404 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1405 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1407 SetupMacroTileScissors(pDC
);
1409 pDC
->FeWork
.type
= STORETILES
;
1410 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1411 pDC
->FeWork
.desc
.storeTiles
.attachment
= attachment
;
1412 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1415 QueueDraw(pContext
);
1417 RDTSC_STOP(APIStoreTiles
, 0, 0);
1420 void SwrClearRenderTarget(
1423 const float clearColor
[4],
1432 RDTSC_START(APIClearRenderTarget
);
1434 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1436 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1438 SetupMacroTileScissors(pDC
);
1441 flags
.mask
= clearMask
;
1443 pDC
->FeWork
.type
= CLEAR
;
1444 pDC
->FeWork
.pfnWork
= ProcessClear
;
1445 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1446 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1447 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1448 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1449 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1450 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1451 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1454 QueueDraw(pContext
);
1456 RDTSC_STOP(APIClearRenderTarget
, 0, pDC
->drawId
);
1459 //////////////////////////////////////////////////////////////////////////
1460 /// @brief Returns a pointer to the private context state for the current
1461 /// draw operation. This is used for external componets such as the
1463 /// SWR is responsible for the allocation of the private context state.
1464 /// @param hContext - Handle passed back from SwrCreateContext
1465 VOID
* SwrGetPrivateContextState(
1468 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1469 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1470 DRAW_STATE
* pState
= pDC
->pState
;
1472 if (pState
->pPrivateState
== nullptr)
1474 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1477 return pState
->pPrivateState
;
1480 //////////////////////////////////////////////////////////////////////////
1481 /// @brief Clients can use this to allocate memory for draw/dispatch
1482 /// operations. The memory will automatically be freed once operation
1483 /// has completed. Client can use this to allocate binding tables,
1484 /// etc. needed for shader execution.
1485 /// @param hContext - Handle passed back from SwrCreateContext
1486 /// @param size - Size of allocation
1487 /// @param align - Alignment needed for allocation.
1488 VOID
* SwrAllocDrawContextMemory(
1493 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1494 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1496 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1499 //////////////////////////////////////////////////////////////////////////
1500 /// @brief Returns pointer to SWR stats.
1501 /// @note The counters are atomically incremented by multiple threads.
1502 /// When calling this, you need to ensure all previous operations
1504 /// @todo If necessary, add a callback to avoid stalling the pipe to
1505 /// sample the counters.
1506 /// @param hContext - Handle passed back from SwrCreateContext
1507 /// @param pStats - SWR will fill this out for caller.
1512 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1513 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1515 pDC
->FeWork
.type
= QUERYSTATS
;
1516 pDC
->FeWork
.pfnWork
= ProcessQueryStats
;
1517 pDC
->FeWork
.desc
.queryStats
.pStats
= pStats
;
1519 // cannot execute until all previous draws have completed
1520 pDC
->dependent
= true;
1523 QueueDraw(pContext
);
1526 //////////////////////////////////////////////////////////////////////////
1527 /// @brief Enables stats counting
1528 /// @param hContext - Handle passed back from SwrCreateContext
1529 /// @param enable - If true then counts are incremented.
1530 void SwrEnableStats(
1534 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1535 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1537 pDC
->pState
->state
.enableStats
= enable
;
1540 //////////////////////////////////////////////////////////////////////////
1541 /// @brief Mark end of frame - used for performance profiling
1542 /// @param hContext - Handle passed back from SwrCreateContext
1543 void SWR_API
SwrEndFrame(
1547 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1548 pContext
->frameCount
++;