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 static const SWR_RECT g_MaxScissorRect
= { 0, 0, KNOB_MAX_SCISSOR_X
, KNOB_MAX_SCISSOR_Y
};
51 void SetupDefaultState(SWR_CONTEXT
*pContext
);
53 static INLINE SWR_CONTEXT
* GetContext(HANDLE hContext
)
55 return (SWR_CONTEXT
*)hContext
;
58 void WakeAllThreads(SWR_CONTEXT
*pContext
)
60 pContext
->FifosNotEmpty
.notify_all();
63 //////////////////////////////////////////////////////////////////////////
64 /// @brief Create SWR Context.
65 /// @param pCreateInfo - pointer to creation info.
66 HANDLE
SwrCreateContext(
67 SWR_CREATECONTEXT_INFO
* pCreateInfo
)
72 void* pContextMem
= AlignedMalloc(sizeof(SWR_CONTEXT
), KNOB_SIMD_WIDTH
* 4);
73 memset(pContextMem
, 0, sizeof(SWR_CONTEXT
));
74 SWR_CONTEXT
*pContext
= new (pContextMem
) SWR_CONTEXT();
76 pContext
->driverType
= pCreateInfo
->driver
;
77 pContext
->privateStateSize
= pCreateInfo
->privateStateSize
;
79 pContext
->dcRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
80 pContext
->dsRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
82 pContext
->pMacroTileManagerArray
= (MacroTileMgr
*)AlignedMalloc(sizeof(MacroTileMgr
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
83 pContext
->pDispatchQueueArray
= (DispatchQueue
*)AlignedMalloc(sizeof(DispatchQueue
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
85 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
87 pContext
->dcRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
88 new (&pContext
->pMacroTileManagerArray
[dc
]) MacroTileMgr(*pContext
->dcRing
[dc
].pArena
);
89 new (&pContext
->pDispatchQueueArray
[dc
]) DispatchQueue();
91 pContext
->dsRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
94 pContext
->threadInfo
.MAX_WORKER_THREADS
= KNOB_MAX_WORKER_THREADS
;
95 pContext
->threadInfo
.MAX_NUMA_NODES
= KNOB_MAX_NUMA_NODES
;
96 pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
= KNOB_MAX_CORES_PER_NUMA_NODE
;
97 pContext
->threadInfo
.MAX_THREADS_PER_CORE
= KNOB_MAX_THREADS_PER_CORE
;
98 pContext
->threadInfo
.SINGLE_THREADED
= KNOB_SINGLE_THREADED
;
100 if (pCreateInfo
->pThreadInfo
)
102 pContext
->threadInfo
= *pCreateInfo
->pThreadInfo
;
105 memset(&pContext
->WaitLock
, 0, sizeof(pContext
->WaitLock
));
106 memset(&pContext
->FifosNotEmpty
, 0, sizeof(pContext
->FifosNotEmpty
));
107 new (&pContext
->WaitLock
) std::mutex();
108 new (&pContext
->FifosNotEmpty
) std::condition_variable();
110 CreateThreadPool(pContext
, &pContext
->threadPool
);
112 pContext
->ppScratch
= new uint8_t*[pContext
->NumWorkerThreads
];
113 pContext
->pStats
= new SWR_STATS
[pContext
->NumWorkerThreads
];
115 #if defined(KNOB_ENABLE_AR)
116 // Setup ArchRast thread contexts which includes +1 for API thread.
117 pContext
->pArContext
= new HANDLE
[pContext
->NumWorkerThreads
+1];
118 pContext
->pArContext
[pContext
->NumWorkerThreads
] = ArchRast::CreateThreadContext();
119 _AR_EVENT(pContext
->pArContext
[pContext
->NumWorkerThreads
], ThreadStartApiEvent());
122 // Allocate scratch space for workers.
123 ///@note We could lazily allocate this but its rather small amount of memory.
124 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
127 uint32_t numaNode
= pContext
->threadPool
.pThreadData
?
128 pContext
->threadPool
.pThreadData
[i
].numaId
: 0;
129 pContext
->ppScratch
[i
] = (uint8_t*)VirtualAllocExNuma(
130 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE
),
131 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
,
134 pContext
->ppScratch
[i
] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE
), KNOB_SIMD_WIDTH
* 4);
137 #if defined(KNOB_ENABLE_AR)
138 // Initialize worker thread context for ArchRast.
139 pContext
->pArContext
[i
] = ArchRast::CreateThreadContext();
140 _AR_EVENT(pContext
->pArContext
[i
], ThreadStartWorkerEvent());
144 // State setup AFTER context is fully initialized
145 SetupDefaultState(pContext
);
147 // initialize hot tile manager
148 pContext
->pHotTileMgr
= new HotTileMgr();
150 // initialize function pointer tables
151 InitClearTilesTable();
153 // initialize callback functions
154 pContext
->pfnLoadTile
= pCreateInfo
->pfnLoadTile
;
155 pContext
->pfnStoreTile
= pCreateInfo
->pfnStoreTile
;
156 pContext
->pfnClearTile
= pCreateInfo
->pfnClearTile
;
157 pContext
->pfnUpdateSoWriteOffset
= pCreateInfo
->pfnUpdateSoWriteOffset
;
158 pContext
->pfnUpdateStats
= pCreateInfo
->pfnUpdateStats
;
159 pContext
->pfnUpdateStatsFE
= pCreateInfo
->pfnUpdateStatsFE
;
161 // pass pointer to bucket manager back to caller
162 #ifdef KNOB_ENABLE_RDTSC
163 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
166 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
168 StartThreadPool(pContext
, &pContext
->threadPool
);
170 return (HANDLE
)pContext
;
173 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
175 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
178 template<bool IsDraw
>
179 void QueueWork(SWR_CONTEXT
*pContext
)
181 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
182 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
186 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
187 pDC
->pTileMgr
->initialize();
190 // Each worker thread looks at a DC for both FE and BE work at different times and so we
191 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
192 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
193 // then moved on if all work is done.)
194 pContext
->pCurDrawContext
->threadsDone
= pContext
->NumFEThreads
+ pContext
->NumBEThreads
;
198 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
203 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
204 pContext
->dcRing
.Enqueue();
207 if (pContext
->threadInfo
.SINGLE_THREADED
)
209 // flush denormals to 0
210 uint32_t mxcsr
= _mm_getcsr();
211 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
215 uint32_t curDraw
[2] = { pContext
->pCurDrawContext
->drawId
, pContext
->pCurDrawContext
->drawId
};
216 WorkOnFifoFE(pContext
, 0, curDraw
[0]);
217 WorkOnFifoBE(pContext
, 0, curDraw
[1], pContext
->singleThreadLockedTiles
, 0, 0);
221 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
222 WorkOnCompute(pContext
, 0, curDispatch
);
225 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
226 while (CompleteDrawContext(pContext
, pContext
->pCurDrawContext
) > 0) {}
233 AR_API_BEGIN(APIDrawWakeAllThreads
, pDC
->drawId
);
234 WakeAllThreads(pContext
);
235 AR_API_END(APIDrawWakeAllThreads
, 1);
238 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
239 pContext
->pPrevDrawContext
= pContext
->pCurDrawContext
;
240 pContext
->pCurDrawContext
= nullptr;
243 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
245 QueueWork
<true>(pContext
);
248 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
250 QueueWork
<false>(pContext
);
253 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
255 AR_API_BEGIN(APIGetDrawContext
, 0);
256 // If current draw context is null then need to obtain a new draw context to use from ring.
257 if (pContext
->pCurDrawContext
== nullptr)
259 // Need to wait for a free entry.
260 while (pContext
->dcRing
.IsFull())
265 uint64_t curDraw
= pContext
->dcRing
.GetHead();
266 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
268 if ((pContext
->frameCount
- pContext
->lastFrameChecked
) > 2 ||
269 (curDraw
- pContext
->lastDrawChecked
) > 0x10000)
271 // Take this opportunity to clean-up old arena allocations
272 pContext
->cachingArenaAllocator
.FreeOldBlocks();
274 pContext
->lastFrameChecked
= pContext
->frameCount
;
275 pContext
->lastDrawChecked
= curDraw
;
278 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
279 pContext
->pCurDrawContext
= pCurDrawContext
;
281 // Assign next available entry in DS ring to this DC.
282 uint32_t dsIndex
= pContext
->curStateId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
283 pCurDrawContext
->pState
= &pContext
->dsRing
[dsIndex
];
285 // Copy previous state to current state.
286 if (pContext
->pPrevDrawContext
)
288 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
290 // If we're splitting our draw then we can just use the same state from the previous
291 // draw. In this case, we won't increment the DS ring index so the next non-split
292 // draw can receive the state.
293 if (isSplitDraw
== false)
295 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
297 // Should have been cleaned up previously
298 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
300 pCurDrawContext
->pState
->pPrivateState
= nullptr;
302 pContext
->curStateId
++; // Progress state ring index forward.
306 // If its a split draw then just copy the state pointer over
307 // since its the same draw.
308 pCurDrawContext
->pState
= pPrevDrawContext
->pState
;
309 SWR_ASSERT(pPrevDrawContext
->cleanupState
== false);
314 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
315 pContext
->curStateId
++; // Progress state ring index forward.
318 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
321 pCurDrawContext
->dependent
= false;
322 pCurDrawContext
->dependentFE
= false;
324 pCurDrawContext
->pContext
= pContext
;
325 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
327 pCurDrawContext
->doneFE
= false;
328 pCurDrawContext
->FeLock
= 0;
329 pCurDrawContext
->threadsDone
= 0;
330 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
332 pCurDrawContext
->dynState
.Reset(pContext
->NumWorkerThreads
);
334 // Assign unique drawId for this DC
335 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
337 pCurDrawContext
->cleanupState
= true;
341 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
344 AR_API_END(APIGetDrawContext
, 0);
345 return pContext
->pCurDrawContext
;
348 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
350 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
351 SWR_ASSERT(pDC
->pState
!= nullptr);
353 return &pDC
->pState
->state
;
356 void SwrDestroyContext(HANDLE hContext
)
358 SWR_CONTEXT
*pContext
= GetContext(hContext
);
359 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
361 pDC
->FeWork
.type
= SHUTDOWN
;
362 pDC
->FeWork
.pfnWork
= ProcessShutdown
;
367 DestroyThreadPool(pContext
, &pContext
->threadPool
);
370 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
372 delete[] pContext
->dcRing
[i
].dynState
.pStats
;
373 delete pContext
->dcRing
[i
].pArena
;
374 delete pContext
->dsRing
[i
].pArena
;
375 pContext
->pMacroTileManagerArray
[i
].~MacroTileMgr();
376 pContext
->pDispatchQueueArray
[i
].~DispatchQueue();
379 AlignedFree(pContext
->pDispatchQueueArray
);
380 AlignedFree(pContext
->pMacroTileManagerArray
);
382 // Free scratch space.
383 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
386 VirtualFree(pContext
->ppScratch
[i
], 0, MEM_RELEASE
);
388 AlignedFree(pContext
->ppScratch
[i
]);
391 #if defined(KNOB_ENABLE_AR)
392 ArchRast::DestroyThreadContext(pContext
->pArContext
[i
]);
396 delete[] pContext
->ppScratch
;
397 delete[] pContext
->pStats
;
399 delete(pContext
->pHotTileMgr
);
401 pContext
->~SWR_CONTEXT();
402 AlignedFree(GetContext(hContext
));
405 void SWR_API
SwrSaveState(
407 void* pOutputStateBlock
,
410 SWR_CONTEXT
*pContext
= GetContext(hContext
);
411 auto pSrc
= GetDrawState(pContext
);
412 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
414 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
417 void SWR_API
SwrRestoreState(
419 const void* pStateBlock
,
422 SWR_CONTEXT
*pContext
= GetContext(hContext
);
423 auto pDst
= GetDrawState(pContext
);
424 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
426 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
429 void SetupDefaultState(SWR_CONTEXT
*pContext
)
431 API_STATE
* pState
= GetDrawState(pContext
);
433 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
434 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
436 pState
->depthBoundsState
.depthBoundsTestEnable
= false;
437 pState
->depthBoundsState
.depthBoundsTestMinValue
= 0.0f
;
438 pState
->depthBoundsState
.depthBoundsTestMaxValue
= 1.0f
;
441 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
443 SWR_ASSERT(pfnFunc
!= nullptr);
445 SWR_CONTEXT
*pContext
= GetContext(hContext
);
446 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
448 AR_API_BEGIN(APISync
, 0);
450 pDC
->FeWork
.type
= SYNC
;
451 pDC
->FeWork
.pfnWork
= ProcessSync
;
453 // Setup callback function
454 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
455 pDC
->retireCallback
.userData
= userData
;
456 pDC
->retireCallback
.userData2
= userData2
;
457 pDC
->retireCallback
.userData3
= userData3
;
462 AR_API_END(APISync
, 1);
465 void SwrWaitForIdle(HANDLE hContext
)
467 SWR_CONTEXT
*pContext
= GetContext(hContext
);
469 AR_API_BEGIN(APIWaitForIdle
, 0);
471 while (!pContext
->dcRing
.IsEmpty())
476 AR_API_END(APIWaitForIdle
, 1);
479 void SwrWaitForIdleFE(HANDLE hContext
)
481 SWR_CONTEXT
*pContext
= GetContext(hContext
);
483 AR_API_BEGIN(APIWaitForIdle
, 0);
485 while (pContext
->drawsOutstandingFE
> 0)
490 AR_API_END(APIWaitForIdle
, 1);
493 void SwrSetVertexBuffers(
496 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
498 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
500 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
502 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
503 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
507 void SwrSetIndexBuffer(
509 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
511 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
513 pState
->indexBuffer
= *pIndexBuffer
;
516 void SwrSetFetchFunc(
518 PFN_FETCH_FUNC pfnFetchFunc
)
520 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
522 pState
->pfnFetchFunc
= pfnFetchFunc
;
527 PFN_SO_FUNC pfnSoFunc
,
528 uint32_t streamIndex
)
530 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
532 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
534 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
539 SWR_STREAMOUT_STATE
* pSoState
)
541 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
543 pState
->soState
= *pSoState
;
546 void SwrSetSoBuffers(
548 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
551 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
553 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
555 pState
->soBuffer
[slot
] = *pSoBuffer
;
558 void SwrSetVertexFunc(
560 PFN_VERTEX_FUNC pfnVertexFunc
)
562 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
564 pState
->pfnVertexFunc
= pfnVertexFunc
;
567 void SwrSetFrontendState(
569 SWR_FRONTEND_STATE
*pFEState
)
571 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
572 pState
->frontendState
= *pFEState
;
577 SWR_GS_STATE
*pGSState
)
579 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
580 pState
->gsState
= *pGSState
;
585 PFN_GS_FUNC pfnGsFunc
)
587 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
588 pState
->pfnGsFunc
= pfnGsFunc
;
593 PFN_CS_FUNC pfnCsFunc
,
594 uint32_t totalThreadsInGroup
,
595 uint32_t totalSpillFillSize
)
597 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
598 pState
->pfnCsFunc
= pfnCsFunc
;
599 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
600 pState
->totalSpillFillSize
= totalSpillFillSize
;
605 SWR_TS_STATE
*pState
)
607 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
608 pApiState
->tsState
= *pState
;
615 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
616 pApiState
->pfnHsFunc
= pfnFunc
;
623 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
624 pApiState
->pfnDsFunc
= pfnFunc
;
627 void SwrSetDepthStencilState(
629 SWR_DEPTH_STENCIL_STATE
*pDSState
)
631 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
633 pState
->depthStencilState
= *pDSState
;
636 void SwrSetBackendState(
638 SWR_BACKEND_STATE
*pBEState
)
640 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
642 pState
->backendState
= *pBEState
;
645 void SwrSetDepthBoundsState(
647 SWR_DEPTH_BOUNDS_STATE
*pDBState
)
649 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
651 pState
->depthBoundsState
= *pDBState
;
654 void SwrSetPixelShaderState(
656 SWR_PS_STATE
*pPSState
)
658 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
659 pState
->psState
= *pPSState
;
662 void SwrSetBlendState(
664 SWR_BLEND_STATE
*pBlendState
)
666 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
667 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
670 void SwrSetBlendFunc(
672 uint32_t renderTarget
,
673 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
675 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
676 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
677 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
680 // update guardband multipliers for the viewport
681 void updateGuardbands(API_STATE
*pState
)
683 uint32_t numGbs
= pState
->gsState
.emitsRenderTargetArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
685 for(uint32_t i
= 0; i
< numGbs
; ++i
)
687 // guardband center is viewport center
688 pState
->gbState
.left
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
689 pState
->gbState
.right
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
690 pState
->gbState
.top
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
691 pState
->gbState
.bottom
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
695 void SwrSetRastState(
697 const SWR_RASTSTATE
*pRastState
)
699 SWR_CONTEXT
*pContext
= GetContext(hContext
);
700 API_STATE
* pState
= GetDrawState(pContext
);
702 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
705 void SwrSetViewports(
707 uint32_t numViewports
,
708 const SWR_VIEWPORT
* pViewports
,
709 const SWR_VIEWPORT_MATRICES
* pMatrices
)
711 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
712 "Invalid number of viewports.");
714 SWR_CONTEXT
*pContext
= GetContext(hContext
);
715 API_STATE
* pState
= GetDrawState(pContext
);
717 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
719 if (pMatrices
!= nullptr)
721 // @todo Faster to copy portions of the SOA or just copy all of it?
722 memcpy(&pState
->vpMatrices
, pMatrices
, sizeof(SWR_VIEWPORT_MATRICES
));
726 // Compute default viewport transform.
727 for (uint32_t i
= 0; i
< numViewports
; ++i
)
729 if (pContext
->driverType
== DX
)
731 pState
->vpMatrices
.m00
[i
] = pState
->vp
[i
].width
/ 2.0f
;
732 pState
->vpMatrices
.m11
[i
] = -pState
->vp
[i
].height
/ 2.0f
;
733 pState
->vpMatrices
.m22
[i
] = pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
734 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
735 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].y
- pState
->vpMatrices
.m11
[i
];
736 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
;
740 // Standard, with the exception that Y is inverted.
741 pState
->vpMatrices
.m00
[i
] = (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
742 pState
->vpMatrices
.m11
[i
] = (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
743 pState
->vpMatrices
.m22
[i
] = (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
744 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
745 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].height
+ pState
->vpMatrices
.m11
[i
];
746 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
+ pState
->vpMatrices
.m22
[i
];
748 // Now that the matrix is calculated, clip the view coords to screen size.
749 // OpenGL allows for -ve x,y in the viewport.
750 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
751 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
756 updateGuardbands(pState
);
759 void SwrSetScissorRects(
761 uint32_t numScissors
,
762 const SWR_RECT
* pScissors
)
764 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
765 "Invalid number of scissor rects.");
767 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
768 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(pScissors
[0]));
771 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
773 API_STATE
*pState
= &pDC
->pState
->state
;
774 uint32_t numScissors
= pState
->gsState
.emitsViewportArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
775 pState
->scissorsTileAligned
= true;
777 for (uint32_t index
= 0; index
< numScissors
; ++index
)
779 SWR_RECT
&scissorInFixedPoint
= pState
->scissorsInFixedPoint
[index
];
781 // Set up scissor dimensions based on scissor or viewport
782 if (pState
->rastState
.scissorEnable
)
784 scissorInFixedPoint
= pState
->scissorRects
[index
];
788 // the vp width and height must be added to origin un-rounded then the result round to -inf.
789 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
790 scissorInFixedPoint
.xmin
= (int32_t)pState
->vp
[index
].x
;
791 scissorInFixedPoint
.xmax
= (int32_t)(pState
->vp
[index
].x
+ pState
->vp
[index
].width
);
792 scissorInFixedPoint
.ymin
= (int32_t)pState
->vp
[index
].y
;
793 scissorInFixedPoint
.ymax
= (int32_t)(pState
->vp
[index
].y
+ pState
->vp
[index
].height
);
797 scissorInFixedPoint
&= g_MaxScissorRect
;
799 // Test for tile alignment
801 tileAligned
= (scissorInFixedPoint
.xmin
% KNOB_TILE_X_DIM
) == 0;
802 tileAligned
&= (scissorInFixedPoint
.ymin
% KNOB_TILE_Y_DIM
) == 0;
803 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_X_DIM
) == 0;
804 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_Y_DIM
) == 0;
806 pState
->scissorsTileAligned
&= tileAligned
;
808 // Scale to fixed point
809 scissorInFixedPoint
.xmin
*= FIXED_POINT_SCALE
;
810 scissorInFixedPoint
.xmax
*= FIXED_POINT_SCALE
;
811 scissorInFixedPoint
.ymin
*= FIXED_POINT_SCALE
;
812 scissorInFixedPoint
.ymax
*= FIXED_POINT_SCALE
;
814 // Make scissor inclusive
815 scissorInFixedPoint
.xmax
-= 1;
816 scissorInFixedPoint
.ymax
-= 1;
820 // templated backend function tables
821 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
822 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
823 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
824 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
825 void SetupPipeline(DRAW_CONTEXT
*pDC
)
827 DRAW_STATE
* pState
= pDC
->pState
;
828 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
829 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
830 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
831 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
834 if (psState
.pfnPixelShader
== nullptr)
836 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
840 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
841 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
842 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
844 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
846 // select backend function
847 switch(psState
.shadingRate
)
849 case SWR_SHADING_RATE_PIXEL
:
850 if(bMultisampleEnable
)
852 // always need to generate I & J per sample for Z interpolation
853 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
854 backendFuncs
.pfnBackend
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
858 // always need to generate I & J per pixel for Z interpolation
859 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
860 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
863 case SWR_SHADING_RATE_SAMPLE
:
864 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
865 // always need to generate I & J per sample for Z interpolation
866 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
867 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
870 SWR_ASSERT(0 && "Invalid shading rate");
875 PFN_PROCESS_PRIMS pfnBinner
;
876 switch (pState
->state
.topology
)
879 pState
->pfnProcessPrims
= ClipPoints
;
880 pfnBinner
= BinPoints
;
885 case TOP_LINE_LIST_ADJ
:
886 case TOP_LISTSTRIP_ADJ
:
887 pState
->pfnProcessPrims
= ClipLines
;
888 pfnBinner
= BinLines
;
891 pState
->pfnProcessPrims
= ClipTriangles
;
892 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
896 // disable clipper if viewport transform is disabled
897 if (pState
->state
.frontendState
.vpTransformDisable
)
899 pState
->pfnProcessPrims
= pfnBinner
;
902 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
903 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
904 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
905 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
906 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
907 (pState
->state
.backendState
.numAttributes
== 0))
909 pState
->pfnProcessPrims
= nullptr;
912 if (pState
->state
.soState
.rasterizerDisable
== true)
914 pState
->pfnProcessPrims
= nullptr;
917 // set up the frontend attribute count
918 pState
->state
.feNumAttributes
= 0;
919 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
920 if (backendState
.swizzleEnable
)
922 // attribute swizzling is enabled, iterate over the map and record the max attribute used
923 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
925 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
930 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
933 if (pState
->state
.soState
.soEnable
)
935 uint32_t streamMasks
= 0;
936 for (uint32_t i
= 0; i
< 4; ++i
)
938 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
942 if (_BitScanReverse(&maxAttrib
, streamMasks
))
944 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
948 // complicated logic to test for cases where we don't need backing hottile memory for a draw
949 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
950 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
951 !pState
->state
.depthStencilState
.depthWriteEnable
&&
952 !pState
->state
.depthBoundsState
.depthBoundsTestEnable
&&
953 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
954 (pState
->state
.depthStencilState
.depthTestEnable
||
955 pState
->state
.depthStencilState
.depthWriteEnable
||
956 pState
->state
.depthBoundsState
.depthBoundsTestEnable
)) ? true : false;
958 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
959 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
960 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
961 // for stencil we have to check the double sided state as well
962 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
963 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
964 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
965 (pState
->state
.depthStencilState
.stencilTestEnable
||
966 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
968 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
969 pState
->state
.colorHottileEnable
= 0;
970 if (psState
.pfnPixelShader
!= nullptr)
972 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
974 pState
->state
.colorHottileEnable
|=
975 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
976 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
977 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
978 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
982 // Setup depth quantization function
983 if (pState
->state
.depthHottileEnable
)
985 switch (pState
->state
.rastState
.depthFormat
)
987 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
988 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
989 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
990 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
991 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
992 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
997 // set up pass-through quantize if depth isn't enabled
998 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
1002 //////////////////////////////////////////////////////////////////////////
1004 /// @param pDC - Draw context to initialize for this draw.
1009 // We don't need to re-setup the scissors/pipeline state again for split draw.
1010 if (isSplitDraw
== false)
1012 SetupMacroTileScissors(pDC
);
1017 //////////////////////////////////////////////////////////////////////////
1018 /// @brief We can split the draw for certain topologies for better performance.
1019 /// @param totalVerts - Total vertices for draw
1020 /// @param topology - Topology used for draw
1021 uint32_t MaxVertsPerDraw(
1023 uint32_t totalVerts
,
1024 PRIMITIVE_TOPOLOGY topology
)
1026 API_STATE
& state
= pDC
->pState
->state
;
1028 uint32_t vertsPerDraw
= totalVerts
;
1030 if (state
.soState
.soEnable
)
1037 case TOP_POINT_LIST
:
1038 case TOP_TRIANGLE_LIST
:
1039 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
1042 case TOP_PATCHLIST_1
:
1043 case TOP_PATCHLIST_2
:
1044 case TOP_PATCHLIST_3
:
1045 case TOP_PATCHLIST_4
:
1046 case TOP_PATCHLIST_5
:
1047 case TOP_PATCHLIST_6
:
1048 case TOP_PATCHLIST_7
:
1049 case TOP_PATCHLIST_8
:
1050 case TOP_PATCHLIST_9
:
1051 case TOP_PATCHLIST_10
:
1052 case TOP_PATCHLIST_11
:
1053 case TOP_PATCHLIST_12
:
1054 case TOP_PATCHLIST_13
:
1055 case TOP_PATCHLIST_14
:
1056 case TOP_PATCHLIST_15
:
1057 case TOP_PATCHLIST_16
:
1058 case TOP_PATCHLIST_17
:
1059 case TOP_PATCHLIST_18
:
1060 case TOP_PATCHLIST_19
:
1061 case TOP_PATCHLIST_20
:
1062 case TOP_PATCHLIST_21
:
1063 case TOP_PATCHLIST_22
:
1064 case TOP_PATCHLIST_23
:
1065 case TOP_PATCHLIST_24
:
1066 case TOP_PATCHLIST_25
:
1067 case TOP_PATCHLIST_26
:
1068 case TOP_PATCHLIST_27
:
1069 case TOP_PATCHLIST_28
:
1070 case TOP_PATCHLIST_29
:
1071 case TOP_PATCHLIST_30
:
1072 case TOP_PATCHLIST_31
:
1073 case TOP_PATCHLIST_32
:
1074 if (pDC
->pState
->state
.tsState
.tsEnable
)
1076 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1077 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1081 // The Primitive Assembly code can only handle 1 RECT at a time.
1087 // We are not splitting up draws for other topologies.
1091 return vertsPerDraw
;
1095 //////////////////////////////////////////////////////////////////////////
1096 /// @brief DrawInstanced
1097 /// @param hContext - Handle passed back from SwrCreateContext
1098 /// @param topology - Specifies topology for draw.
1099 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1100 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1101 /// @param numInstances - How many instances to render.
1102 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1105 PRIMITIVE_TOPOLOGY topology
,
1106 uint32_t numVertices
,
1107 uint32_t startVertex
,
1108 uint32_t numInstances
= 1,
1109 uint32_t startInstance
= 0)
1116 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1117 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1119 AR_API_BEGIN(APIDraw
, pDC
->drawId
);
1120 AR_API_EVENT(DrawInstancedEvent(pDC
->drawId
, topology
, numVertices
, startVertex
, numInstances
, startInstance
));
1122 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1123 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1124 uint32_t remainingVerts
= numVertices
;
1126 API_STATE
*pState
= &pDC
->pState
->state
;
1127 pState
->topology
= topology
;
1128 pState
->forceFront
= false;
1130 // disable culling for points/lines
1131 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1132 if (topology
== TOP_POINT_LIST
)
1134 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1135 pState
->forceFront
= true;
1137 else if (topology
== TOP_RECT_LIST
)
1139 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1143 while (remainingVerts
)
1145 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1146 remainingVerts
: maxVertsPerDraw
;
1148 bool isSplitDraw
= (draw
> 0) ? true : false;
1149 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1150 InitDraw(pDC
, isSplitDraw
);
1152 pDC
->FeWork
.type
= DRAW
;
1153 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1155 false, // bEnableCutIndex
1156 pState
->tsState
.tsEnable
,
1157 pState
->gsState
.gsEnable
,
1158 pState
->soState
.soEnable
,
1159 pDC
->pState
->pfnProcessPrims
!= nullptr);
1160 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1161 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1162 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1163 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1164 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1165 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1167 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1170 QueueDraw(pContext
);
1172 remainingVerts
-= numVertsForDraw
;
1176 // restore culling state
1177 pDC
= GetDrawContext(pContext
);
1178 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1180 AR_API_END(APIDraw
, numVertices
* numInstances
);
1183 //////////////////////////////////////////////////////////////////////////
1185 /// @param hContext - Handle passed back from SwrCreateContext
1186 /// @param topology - Specifies topology for draw.
1187 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1188 /// @param primCount - Number of vertices.
1191 PRIMITIVE_TOPOLOGY topology
,
1192 uint32_t startVertex
,
1193 uint32_t numVertices
)
1195 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1198 //////////////////////////////////////////////////////////////////////////
1199 /// @brief SwrDrawInstanced
1200 /// @param hContext - Handle passed back from SwrCreateContext
1201 /// @param topology - Specifies topology for draw.
1202 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1203 /// @param numInstances - How many instances to render.
1204 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1205 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1206 void SwrDrawInstanced(
1208 PRIMITIVE_TOPOLOGY topology
,
1209 uint32_t numVertsPerInstance
,
1210 uint32_t numInstances
,
1211 uint32_t startVertex
,
1212 uint32_t startInstance
1215 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1218 //////////////////////////////////////////////////////////////////////////
1219 /// @brief DrawIndexedInstanced
1220 /// @param hContext - Handle passed back from SwrCreateContext
1221 /// @param topology - Specifies topology for draw.
1222 /// @param numIndices - Number of indices to read sequentially from index buffer.
1223 /// @param indexOffset - Starting index into index buffer.
1224 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1225 /// @param numInstances - Number of instances to render.
1226 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1227 void DrawIndexedInstance(
1229 PRIMITIVE_TOPOLOGY topology
,
1230 uint32_t numIndices
,
1231 uint32_t indexOffset
,
1233 uint32_t numInstances
= 1,
1234 uint32_t startInstance
= 0)
1241 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1242 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1243 API_STATE
* pState
= &pDC
->pState
->state
;
1245 AR_API_BEGIN(APIDrawIndexed
, pDC
->drawId
);
1246 AR_API_EVENT(DrawIndexedInstancedEvent(pDC
->drawId
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
));
1248 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1249 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1250 uint32_t remainingIndices
= numIndices
;
1252 uint32_t indexSize
= 0;
1253 switch (pState
->indexBuffer
.format
)
1255 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1256 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1257 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1263 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1264 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1266 pState
->topology
= topology
;
1267 pState
->forceFront
= false;
1269 // disable culling for points/lines
1270 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1271 if (topology
== TOP_POINT_LIST
)
1273 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1274 pState
->forceFront
= true;
1276 else if (topology
== TOP_RECT_LIST
)
1278 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1281 while (remainingIndices
)
1283 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1284 remainingIndices
: maxIndicesPerDraw
;
1286 // When breaking up draw, we need to obtain new draw context for each iteration.
1287 bool isSplitDraw
= (draw
> 0) ? true : false;
1288 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1289 InitDraw(pDC
, isSplitDraw
);
1291 pDC
->FeWork
.type
= DRAW
;
1292 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1294 pState
->frontendState
.bEnableCutIndex
,
1295 pState
->tsState
.tsEnable
,
1296 pState
->gsState
.gsEnable
,
1297 pState
->soState
.soEnable
,
1298 pDC
->pState
->pfnProcessPrims
!= nullptr);
1299 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1300 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1301 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1302 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1304 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1305 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1306 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1307 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1309 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1312 QueueDraw(pContext
);
1314 pIB
+= maxIndicesPerDraw
* indexSize
;
1315 remainingIndices
-= numIndicesForDraw
;
1319 // restore culling state
1320 pDC
= GetDrawContext(pContext
);
1321 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1323 AR_API_END(APIDrawIndexed
, numIndices
* numInstances
);
1327 //////////////////////////////////////////////////////////////////////////
1328 /// @brief DrawIndexed
1329 /// @param hContext - Handle passed back from SwrCreateContext
1330 /// @param topology - Specifies topology for draw.
1331 /// @param numIndices - Number of indices to read sequentially from index buffer.
1332 /// @param indexOffset - Starting index into index buffer.
1333 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1334 void SwrDrawIndexed(
1336 PRIMITIVE_TOPOLOGY topology
,
1337 uint32_t numIndices
,
1338 uint32_t indexOffset
,
1342 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1345 //////////////////////////////////////////////////////////////////////////
1346 /// @brief SwrDrawIndexedInstanced
1347 /// @param hContext - Handle passed back from SwrCreateContext
1348 /// @param topology - Specifies topology for draw.
1349 /// @param numIndices - Number of indices to read sequentially from index buffer.
1350 /// @param numInstances - Number of instances to render.
1351 /// @param indexOffset - Starting index into index buffer.
1352 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1353 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1354 void SwrDrawIndexedInstanced(
1356 PRIMITIVE_TOPOLOGY topology
,
1357 uint32_t numIndices
,
1358 uint32_t numInstances
,
1359 uint32_t indexOffset
,
1361 uint32_t startInstance
)
1363 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1366 //////////////////////////////////////////////////////////////////////////
1367 /// @brief SwrInvalidateTiles
1368 /// @param hContext - Handle passed back from SwrCreateContext
1369 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1370 /// @param invalidateRect - The pixel-coordinate rectangle to invalidate. This will be expanded to
1371 /// be hottile size-aligned.
1372 void SWR_API
SwrInvalidateTiles(
1374 uint32_t attachmentMask
,
1375 const SWR_RECT
& invalidateRect
)
1382 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1383 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1385 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1386 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1387 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1388 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= invalidateRect
;
1389 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1390 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1391 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1392 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1395 QueueDraw(pContext
);
1398 //////////////////////////////////////////////////////////////////////////
1399 /// @brief SwrDiscardRect
1400 /// @param hContext - Handle passed back from SwrCreateContext
1401 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1402 /// @param rect - The pixel-coordinate rectangle to discard. Only fully-covered hottiles will be
1404 void SWR_API
SwrDiscardRect(
1406 uint32_t attachmentMask
,
1407 const SWR_RECT
& rect
)
1414 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1415 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1417 // Queue a load to the hottile
1418 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1419 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1420 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1421 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1422 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1423 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1424 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1425 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1428 QueueDraw(pContext
);
1431 //////////////////////////////////////////////////////////////////////////
1432 /// @brief SwrDispatch
1433 /// @param hContext - Handle passed back from SwrCreateContext
1434 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1435 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1436 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1439 uint32_t threadGroupCountX
,
1440 uint32_t threadGroupCountY
,
1441 uint32_t threadGroupCountZ
)
1448 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1449 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1451 AR_API_BEGIN(APIDispatch
, pDC
->drawId
);
1452 AR_API_EVENT(DispatchEvent(pDC
->drawId
, threadGroupCountX
, threadGroupCountY
, threadGroupCountZ
));
1453 pDC
->isCompute
= true; // This is a compute context.
1455 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1457 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1458 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1459 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1461 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1462 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1463 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1464 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
, &ProcessComputeBE
);
1466 QueueDispatch(pContext
);
1467 AR_API_END(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
);
1470 // Deswizzles, converts and stores current contents of the hot tiles to surface
1471 // described by pState
1472 void SWR_API
SwrStoreTiles(
1474 uint32_t attachmentMask
,
1475 SWR_TILE_STATE postStoreTileState
,
1476 const SWR_RECT
& storeRect
)
1483 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1484 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1486 AR_API_BEGIN(APIStoreTiles
, pDC
->drawId
);
1488 pDC
->FeWork
.type
= STORETILES
;
1489 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1490 pDC
->FeWork
.desc
.storeTiles
.attachmentMask
= attachmentMask
;
1491 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1492 pDC
->FeWork
.desc
.storeTiles
.rect
= storeRect
;
1493 pDC
->FeWork
.desc
.storeTiles
.rect
&= g_MaxScissorRect
;
1496 QueueDraw(pContext
);
1498 AR_API_END(APIStoreTiles
, 1);
1501 //////////////////////////////////////////////////////////////////////////
1502 /// @brief SwrClearRenderTarget - Clear attached render targets / depth / stencil
1503 /// @param hContext - Handle passed back from SwrCreateContext
1504 /// @param clearMask - combination of SWR_CLEAR_COLOR / SWR_CLEAR_DEPTH / SWR_CLEAR_STENCIL flags (or SWR_CLEAR_NONE)
1505 /// @param clearColor - color use for clearing render targets
1506 /// @param z - depth value use for clearing depth buffer
1507 /// @param stencil - stencil value used for clearing stencil buffer
1508 /// @param clearRect - The pixel-coordinate rectangle to clear in all cleared buffers
1509 void SWR_API
SwrClearRenderTarget(
1512 const float clearColor
[4],
1515 const SWR_RECT
& clearRect
)
1522 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1523 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1525 AR_API_BEGIN(APIClearRenderTarget
, pDC
->drawId
);
1529 flags
.mask
= clearMask
;
1531 pDC
->FeWork
.type
= CLEAR
;
1532 pDC
->FeWork
.pfnWork
= ProcessClear
;
1533 pDC
->FeWork
.desc
.clear
.rect
= clearRect
;
1534 pDC
->FeWork
.desc
.clear
.rect
&= g_MaxScissorRect
;
1535 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1536 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1537 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1538 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1539 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1540 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1541 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1544 QueueDraw(pContext
);
1546 AR_API_END(APIClearRenderTarget
, 1);
1549 //////////////////////////////////////////////////////////////////////////
1550 /// @brief Returns a pointer to the private context state for the current
1551 /// draw operation. This is used for external componets such as the
1553 /// SWR is responsible for the allocation of the private context state.
1554 /// @param hContext - Handle passed back from SwrCreateContext
1555 VOID
* SwrGetPrivateContextState(
1558 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1559 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1560 DRAW_STATE
* pState
= pDC
->pState
;
1562 if (pState
->pPrivateState
== nullptr)
1564 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1567 return pState
->pPrivateState
;
1570 //////////////////////////////////////////////////////////////////////////
1571 /// @brief Clients can use this to allocate memory for draw/dispatch
1572 /// operations. The memory will automatically be freed once operation
1573 /// has completed. Client can use this to allocate binding tables,
1574 /// etc. needed for shader execution.
1575 /// @param hContext - Handle passed back from SwrCreateContext
1576 /// @param size - Size of allocation
1577 /// @param align - Alignment needed for allocation.
1578 VOID
* SwrAllocDrawContextMemory(
1583 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1584 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1586 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1589 //////////////////////////////////////////////////////////////////////////
1590 /// @brief Enables stats counting
1591 /// @param hContext - Handle passed back from SwrCreateContext
1592 /// @param enable - If true then counts are incremented.
1593 void SwrEnableStatsFE(
1597 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1598 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1600 pDC
->pState
->state
.enableStatsFE
= enable
;
1603 //////////////////////////////////////////////////////////////////////////
1604 /// @brief Enables stats counting
1605 /// @param hContext - Handle passed back from SwrCreateContext
1606 /// @param enable - If true then counts are incremented.
1607 void SwrEnableStatsBE(
1611 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1612 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1614 pDC
->pState
->state
.enableStatsBE
= enable
;
1617 //////////////////////////////////////////////////////////////////////////
1618 /// @brief Mark end of frame - used for performance profiling
1619 /// @param hContext - Handle passed back from SwrCreateContext
1620 void SWR_API
SwrEndFrame(
1623 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1624 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1627 AR_API_EVENT(FrameEndEvent(pContext
->frameCount
, pDC
->drawId
));
1629 pContext
->frameCount
++;