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 #include "archrast/archrast.h"
51 static const SWR_RECT g_MaxScissorRect
= { 0, 0, KNOB_MAX_SCISSOR_X
, KNOB_MAX_SCISSOR_Y
};
53 void SetupDefaultState(SWR_CONTEXT
*pContext
);
55 static INLINE SWR_CONTEXT
* GetContext(HANDLE hContext
)
57 return (SWR_CONTEXT
*)hContext
;
60 //////////////////////////////////////////////////////////////////////////
61 /// @brief Create SWR Context.
62 /// @param pCreateInfo - pointer to creation info.
63 HANDLE
SwrCreateContext(
64 SWR_CREATECONTEXT_INFO
* pCreateInfo
)
69 void* pContextMem
= AlignedMalloc(sizeof(SWR_CONTEXT
), KNOB_SIMD_WIDTH
* 4);
70 memset(pContextMem
, 0, sizeof(SWR_CONTEXT
));
71 SWR_CONTEXT
*pContext
= new (pContextMem
) SWR_CONTEXT();
73 pContext
->driverType
= pCreateInfo
->driver
;
74 pContext
->privateStateSize
= pCreateInfo
->privateStateSize
;
76 pContext
->dcRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
77 pContext
->dsRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
79 pContext
->pMacroTileManagerArray
= (MacroTileMgr
*)AlignedMalloc(sizeof(MacroTileMgr
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
80 pContext
->pDispatchQueueArray
= (DispatchQueue
*)AlignedMalloc(sizeof(DispatchQueue
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
82 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
84 pContext
->dcRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
85 new (&pContext
->pMacroTileManagerArray
[dc
]) MacroTileMgr(*pContext
->dcRing
[dc
].pArena
);
86 new (&pContext
->pDispatchQueueArray
[dc
]) DispatchQueue();
88 pContext
->dsRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
91 pContext
->threadInfo
.MAX_WORKER_THREADS
= KNOB_MAX_WORKER_THREADS
;
92 pContext
->threadInfo
.MAX_NUMA_NODES
= KNOB_MAX_NUMA_NODES
;
93 pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
= KNOB_MAX_CORES_PER_NUMA_NODE
;
94 pContext
->threadInfo
.MAX_THREADS_PER_CORE
= KNOB_MAX_THREADS_PER_CORE
;
95 pContext
->threadInfo
.SINGLE_THREADED
= KNOB_SINGLE_THREADED
;
97 if (pCreateInfo
->pThreadInfo
)
99 pContext
->threadInfo
= *pCreateInfo
->pThreadInfo
;
102 memset(&pContext
->WaitLock
, 0, sizeof(pContext
->WaitLock
));
103 memset(&pContext
->FifosNotEmpty
, 0, sizeof(pContext
->FifosNotEmpty
));
104 new (&pContext
->WaitLock
) std::mutex();
105 new (&pContext
->FifosNotEmpty
) std::condition_variable();
107 CreateThreadPool(pContext
, &pContext
->threadPool
);
109 pContext
->ppScratch
= new uint8_t*[pContext
->NumWorkerThreads
];
110 pContext
->pStats
= new SWR_STATS
[pContext
->NumWorkerThreads
];
112 // Setup ArchRast thread contexts which includes +1 for API thread.
113 pContext
->pArContext
= new HANDLE
[pContext
->NumWorkerThreads
+1];
114 pContext
->pArContext
[pContext
->NumWorkerThreads
] = ArchRast::CreateThreadContext();
116 // Allocate scratch space for workers.
117 ///@note We could lazily allocate this but its rather small amount of memory.
118 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
121 uint32_t numaNode
= pContext
->threadPool
.pThreadData
?
122 pContext
->threadPool
.pThreadData
[i
].numaId
: 0;
123 pContext
->ppScratch
[i
] = (uint8_t*)VirtualAllocExNuma(
124 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE
),
125 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
,
128 pContext
->ppScratch
[i
] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE
), KNOB_SIMD_WIDTH
* 4);
131 // Initialize worker thread context for ArchRast.
132 pContext
->pArContext
[i
] = ArchRast::CreateThreadContext();
135 // State setup AFTER context is fully initialized
136 SetupDefaultState(pContext
);
138 // initialize hot tile manager
139 pContext
->pHotTileMgr
= new HotTileMgr();
141 // initialize function pointer tables
142 InitClearTilesTable();
144 // initialize callback functions
145 pContext
->pfnLoadTile
= pCreateInfo
->pfnLoadTile
;
146 pContext
->pfnStoreTile
= pCreateInfo
->pfnStoreTile
;
147 pContext
->pfnClearTile
= pCreateInfo
->pfnClearTile
;
148 pContext
->pfnUpdateSoWriteOffset
= pCreateInfo
->pfnUpdateSoWriteOffset
;
149 pContext
->pfnUpdateStats
= pCreateInfo
->pfnUpdateStats
;
150 pContext
->pfnUpdateStatsFE
= pCreateInfo
->pfnUpdateStatsFE
;
152 // pass pointer to bucket manager back to caller
153 #ifdef KNOB_ENABLE_RDTSC
154 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
157 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
159 return (HANDLE
)pContext
;
162 void SwrDestroyContext(HANDLE hContext
)
164 SWR_CONTEXT
*pContext
= GetContext(hContext
);
165 DestroyThreadPool(pContext
, &pContext
->threadPool
);
168 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
170 delete [] pContext
->dcRing
[i
].dynState
.pStats
;
171 delete pContext
->dcRing
[i
].pArena
;
172 delete pContext
->dsRing
[i
].pArena
;
173 pContext
->pMacroTileManagerArray
[i
].~MacroTileMgr();
174 pContext
->pDispatchQueueArray
[i
].~DispatchQueue();
177 AlignedFree(pContext
->pDispatchQueueArray
);
178 AlignedFree(pContext
->pMacroTileManagerArray
);
180 // Free scratch space.
181 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
184 VirtualFree(pContext
->ppScratch
[i
], 0, MEM_RELEASE
);
186 AlignedFree(pContext
->ppScratch
[i
]);
189 ArchRast::DestroyThreadContext(pContext
->pArContext
[i
]);
192 delete [] pContext
->ppScratch
;
193 delete [] pContext
->pArContext
;
194 delete [] pContext
->pStats
;
196 delete(pContext
->pHotTileMgr
);
198 pContext
->~SWR_CONTEXT();
199 AlignedFree(GetContext(hContext
));
202 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
204 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
207 void WakeAllThreads(SWR_CONTEXT
*pContext
)
209 pContext
->FifosNotEmpty
.notify_all();
212 template<bool IsDraw
>
213 void QueueWork(SWR_CONTEXT
*pContext
)
215 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
216 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
220 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
221 pDC
->pTileMgr
->initialize();
224 // Each worker thread looks at a DC for both FE and BE work at different times and so we
225 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
226 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
227 // then moved on if all work is done.)
228 pContext
->pCurDrawContext
->threadsDone
= pContext
->NumFEThreads
+ pContext
->NumBEThreads
;
232 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
237 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
238 pContext
->dcRing
.Enqueue();
241 if (pContext
->threadInfo
.SINGLE_THREADED
)
243 // flush denormals to 0
244 uint32_t mxcsr
= _mm_getcsr();
245 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
249 uint32_t curDraw
[2] = { pContext
->pCurDrawContext
->drawId
, pContext
->pCurDrawContext
->drawId
};
250 WorkOnFifoFE(pContext
, 0, curDraw
[0]);
251 WorkOnFifoBE(pContext
, 0, curDraw
[1], pContext
->singleThreadLockedTiles
, 0, 0);
255 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
256 WorkOnCompute(pContext
, 0, curDispatch
);
259 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
260 while (CompleteDrawContext(pContext
, pContext
->pCurDrawContext
) > 0) {}
267 RDTSC_START(APIDrawWakeAllThreads
);
268 WakeAllThreads(pContext
);
269 RDTSC_STOP(APIDrawWakeAllThreads
, 1, 0);
272 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
273 pContext
->pPrevDrawContext
= pContext
->pCurDrawContext
;
274 pContext
->pCurDrawContext
= nullptr;
277 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
279 QueueWork
<true>(pContext
);
282 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
284 QueueWork
<false>(pContext
);
287 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
289 RDTSC_START(APIGetDrawContext
);
290 // If current draw context is null then need to obtain a new draw context to use from ring.
291 if (pContext
->pCurDrawContext
== nullptr)
293 // Need to wait for a free entry.
294 while (pContext
->dcRing
.IsFull())
299 uint64_t curDraw
= pContext
->dcRing
.GetHead();
300 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
302 if ((pContext
->frameCount
- pContext
->lastFrameChecked
) > 2 ||
303 (curDraw
- pContext
->lastDrawChecked
) > 0x10000)
305 // Take this opportunity to clean-up old arena allocations
306 pContext
->cachingArenaAllocator
.FreeOldBlocks();
308 pContext
->lastFrameChecked
= pContext
->frameCount
;
309 pContext
->lastDrawChecked
= curDraw
;
312 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
313 pContext
->pCurDrawContext
= pCurDrawContext
;
315 // Assign next available entry in DS ring to this DC.
316 uint32_t dsIndex
= pContext
->curStateId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
317 pCurDrawContext
->pState
= &pContext
->dsRing
[dsIndex
];
319 // Copy previous state to current state.
320 if (pContext
->pPrevDrawContext
)
322 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
324 // If we're splitting our draw then we can just use the same state from the previous
325 // draw. In this case, we won't increment the DS ring index so the next non-split
326 // draw can receive the state.
327 if (isSplitDraw
== false)
329 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
331 // Should have been cleaned up previously
332 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
334 pCurDrawContext
->pState
->pPrivateState
= nullptr;
336 pContext
->curStateId
++; // Progress state ring index forward.
340 // If its a split draw then just copy the state pointer over
341 // since its the same draw.
342 pCurDrawContext
->pState
= pPrevDrawContext
->pState
;
343 SWR_ASSERT(pPrevDrawContext
->cleanupState
== false);
348 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
349 pContext
->curStateId
++; // Progress state ring index forward.
352 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
354 pCurDrawContext
->dependent
= false;
355 pCurDrawContext
->pContext
= pContext
;
356 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
358 pCurDrawContext
->doneFE
= false;
359 pCurDrawContext
->FeLock
= 0;
360 pCurDrawContext
->threadsDone
= 0;
361 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
363 pCurDrawContext
->dynState
.Reset(pContext
->NumWorkerThreads
);
365 // Assign unique drawId for this DC
366 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
368 pCurDrawContext
->cleanupState
= true;
372 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
375 RDTSC_STOP(APIGetDrawContext
, 0, 0);
376 return pContext
->pCurDrawContext
;
379 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
381 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
382 SWR_ASSERT(pDC
->pState
!= nullptr);
384 return &pDC
->pState
->state
;
387 void SWR_API
SwrSaveState(
389 void* pOutputStateBlock
,
392 SWR_CONTEXT
*pContext
= GetContext(hContext
);
393 auto pSrc
= GetDrawState(pContext
);
394 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
396 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
399 void SWR_API
SwrRestoreState(
401 const void* pStateBlock
,
404 SWR_CONTEXT
*pContext
= GetContext(hContext
);
405 auto pDst
= GetDrawState(pContext
);
406 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
408 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
411 void SetupDefaultState(SWR_CONTEXT
*pContext
)
413 API_STATE
* pState
= GetDrawState(pContext
);
415 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
416 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
419 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
421 RDTSC_START(APISync
);
423 SWR_ASSERT(pfnFunc
!= nullptr);
425 SWR_CONTEXT
*pContext
= GetContext(hContext
);
426 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
428 pDC
->FeWork
.type
= SYNC
;
429 pDC
->FeWork
.pfnWork
= ProcessSync
;
431 // Setup callback function
432 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
433 pDC
->retireCallback
.userData
= userData
;
434 pDC
->retireCallback
.userData2
= userData2
;
435 pDC
->retireCallback
.userData3
= userData3
;
440 RDTSC_STOP(APISync
, 1, 0);
443 void SwrWaitForIdle(HANDLE hContext
)
445 SWR_CONTEXT
*pContext
= GetContext(hContext
);
447 RDTSC_START(APIWaitForIdle
);
449 while (!pContext
->dcRing
.IsEmpty())
454 RDTSC_STOP(APIWaitForIdle
, 1, 0);
457 void SwrWaitForIdleFE(HANDLE hContext
)
459 SWR_CONTEXT
*pContext
= GetContext(hContext
);
461 RDTSC_START(APIWaitForIdle
);
463 while (pContext
->drawsOutstandingFE
> 0)
468 RDTSC_STOP(APIWaitForIdle
, 1, 0);
471 void SwrSetVertexBuffers(
474 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
476 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
478 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
480 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
481 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
485 void SwrSetIndexBuffer(
487 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
489 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
491 pState
->indexBuffer
= *pIndexBuffer
;
494 void SwrSetFetchFunc(
496 PFN_FETCH_FUNC pfnFetchFunc
)
498 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
500 pState
->pfnFetchFunc
= pfnFetchFunc
;
505 PFN_SO_FUNC pfnSoFunc
,
506 uint32_t streamIndex
)
508 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
510 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
512 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
517 SWR_STREAMOUT_STATE
* pSoState
)
519 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
521 pState
->soState
= *pSoState
;
524 void SwrSetSoBuffers(
526 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
529 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
531 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
533 pState
->soBuffer
[slot
] = *pSoBuffer
;
536 void SwrSetVertexFunc(
538 PFN_VERTEX_FUNC pfnVertexFunc
)
540 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
542 pState
->pfnVertexFunc
= pfnVertexFunc
;
545 void SwrSetFrontendState(
547 SWR_FRONTEND_STATE
*pFEState
)
549 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
550 pState
->frontendState
= *pFEState
;
555 SWR_GS_STATE
*pGSState
)
557 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
558 pState
->gsState
= *pGSState
;
563 PFN_GS_FUNC pfnGsFunc
)
565 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
566 pState
->pfnGsFunc
= pfnGsFunc
;
571 PFN_CS_FUNC pfnCsFunc
,
572 uint32_t totalThreadsInGroup
,
573 uint32_t totalSpillFillSize
)
575 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
576 pState
->pfnCsFunc
= pfnCsFunc
;
577 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
578 pState
->totalSpillFillSize
= totalSpillFillSize
;
583 SWR_TS_STATE
*pState
)
585 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
586 pApiState
->tsState
= *pState
;
593 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
594 pApiState
->pfnHsFunc
= pfnFunc
;
601 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
602 pApiState
->pfnDsFunc
= pfnFunc
;
605 void SwrSetDepthStencilState(
607 SWR_DEPTH_STENCIL_STATE
*pDSState
)
609 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
611 pState
->depthStencilState
= *pDSState
;
614 void SwrSetBackendState(
616 SWR_BACKEND_STATE
*pBEState
)
618 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
620 pState
->backendState
= *pBEState
;
623 void SwrSetPixelShaderState(
625 SWR_PS_STATE
*pPSState
)
627 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
628 pState
->psState
= *pPSState
;
631 void SwrSetBlendState(
633 SWR_BLEND_STATE
*pBlendState
)
635 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
636 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
639 void SwrSetBlendFunc(
641 uint32_t renderTarget
,
642 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
644 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
645 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
646 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
649 // update guardband multipliers for the viewport
650 void updateGuardbands(API_STATE
*pState
)
652 uint32_t numGbs
= pState
->gsState
.emitsRenderTargetArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
654 for(uint32_t i
= 0; i
< numGbs
; ++i
)
656 // guardband center is viewport center
657 pState
->gbState
.left
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
658 pState
->gbState
.right
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
659 pState
->gbState
.top
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
660 pState
->gbState
.bottom
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
664 void SwrSetRastState(
666 const SWR_RASTSTATE
*pRastState
)
668 SWR_CONTEXT
*pContext
= GetContext(hContext
);
669 API_STATE
* pState
= GetDrawState(pContext
);
671 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
674 void SwrSetViewports(
676 uint32_t numViewports
,
677 const SWR_VIEWPORT
* pViewports
,
678 const SWR_VIEWPORT_MATRICES
* pMatrices
)
680 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
681 "Invalid number of viewports.");
683 SWR_CONTEXT
*pContext
= GetContext(hContext
);
684 API_STATE
* pState
= GetDrawState(pContext
);
686 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
688 if (pMatrices
!= nullptr)
690 // @todo Faster to copy portions of the SOA or just copy all of it?
691 memcpy(&pState
->vpMatrices
, pMatrices
, sizeof(SWR_VIEWPORT_MATRICES
));
695 // Compute default viewport transform.
696 for (uint32_t i
= 0; i
< numViewports
; ++i
)
698 if (pContext
->driverType
== DX
)
700 pState
->vpMatrices
.m00
[i
] = pState
->vp
[i
].width
/ 2.0f
;
701 pState
->vpMatrices
.m11
[i
] = -pState
->vp
[i
].height
/ 2.0f
;
702 pState
->vpMatrices
.m22
[i
] = pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
703 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
704 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].y
- pState
->vpMatrices
.m11
[i
];
705 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
;
709 // Standard, with the exception that Y is inverted.
710 pState
->vpMatrices
.m00
[i
] = (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
711 pState
->vpMatrices
.m11
[i
] = (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
712 pState
->vpMatrices
.m22
[i
] = (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
713 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
714 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].height
+ pState
->vpMatrices
.m11
[i
];
715 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
+ pState
->vpMatrices
.m22
[i
];
717 // Now that the matrix is calculated, clip the view coords to screen size.
718 // OpenGL allows for -ve x,y in the viewport.
719 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
720 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
725 updateGuardbands(pState
);
728 void SwrSetScissorRects(
730 uint32_t numScissors
,
731 const SWR_RECT
* pScissors
)
733 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
734 "Invalid number of scissor rects.");
736 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
737 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(pScissors
[0]));
740 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
742 API_STATE
*pState
= &pDC
->pState
->state
;
743 uint32_t numScissors
= pState
->gsState
.emitsViewportArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
744 pState
->scissorsTileAligned
= true;
746 for (uint32_t index
= 0; index
< numScissors
; ++index
)
748 SWR_RECT
&scissorInFixedPoint
= pState
->scissorsInFixedPoint
[index
];
750 // Set up scissor dimensions based on scissor or viewport
751 if (pState
->rastState
.scissorEnable
)
753 scissorInFixedPoint
= pState
->scissorRects
[index
];
757 // the vp width and height must be added to origin un-rounded then the result round to -inf.
758 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
759 scissorInFixedPoint
.xmin
= (int32_t)pState
->vp
[index
].x
;
760 scissorInFixedPoint
.xmax
= (int32_t)(pState
->vp
[index
].x
+ pState
->vp
[index
].width
);
761 scissorInFixedPoint
.ymin
= (int32_t)pState
->vp
[index
].y
;
762 scissorInFixedPoint
.ymax
= (int32_t)(pState
->vp
[index
].y
+ pState
->vp
[index
].height
);
766 scissorInFixedPoint
&= g_MaxScissorRect
;
768 // Test for tile alignment
770 tileAligned
= (scissorInFixedPoint
.xmin
% KNOB_TILE_X_DIM
) == 0;
771 tileAligned
&= (scissorInFixedPoint
.ymin
% KNOB_TILE_Y_DIM
) == 0;
772 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_X_DIM
) == 0;
773 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_Y_DIM
) == 0;
775 pState
->scissorsTileAligned
&= tileAligned
;
777 // Scale to fixed point
778 scissorInFixedPoint
.xmin
*= FIXED_POINT_SCALE
;
779 scissorInFixedPoint
.xmax
*= FIXED_POINT_SCALE
;
780 scissorInFixedPoint
.ymin
*= FIXED_POINT_SCALE
;
781 scissorInFixedPoint
.ymax
*= FIXED_POINT_SCALE
;
783 // Make scissor inclusive
784 scissorInFixedPoint
.xmax
-= 1;
785 scissorInFixedPoint
.ymax
-= 1;
789 // templated backend function tables
790 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
791 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
792 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
793 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
794 void SetupPipeline(DRAW_CONTEXT
*pDC
)
796 DRAW_STATE
* pState
= pDC
->pState
;
797 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
798 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
799 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
800 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
803 if (psState
.pfnPixelShader
== nullptr)
805 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
809 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
810 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
811 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
813 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
815 // select backend function
816 switch(psState
.shadingRate
)
818 case SWR_SHADING_RATE_PIXEL
:
819 if(bMultisampleEnable
)
821 // always need to generate I & J per sample for Z interpolation
822 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
823 backendFuncs
.pfnBackend
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
827 // always need to generate I & J per pixel for Z interpolation
828 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
829 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
832 case SWR_SHADING_RATE_SAMPLE
:
833 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
834 // always need to generate I & J per sample for Z interpolation
835 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
836 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
839 SWR_ASSERT(0 && "Invalid shading rate");
844 PFN_PROCESS_PRIMS pfnBinner
;
845 switch (pState
->state
.topology
)
848 pState
->pfnProcessPrims
= ClipPoints
;
849 pfnBinner
= BinPoints
;
854 case TOP_LINE_LIST_ADJ
:
855 case TOP_LISTSTRIP_ADJ
:
856 pState
->pfnProcessPrims
= ClipLines
;
857 pfnBinner
= BinLines
;
860 pState
->pfnProcessPrims
= ClipTriangles
;
861 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
865 // disable clipper if viewport transform is disabled
866 if (pState
->state
.frontendState
.vpTransformDisable
)
868 pState
->pfnProcessPrims
= pfnBinner
;
871 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
872 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
873 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
874 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
875 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
876 (pState
->state
.backendState
.numAttributes
== 0))
878 pState
->pfnProcessPrims
= nullptr;
881 if (pState
->state
.soState
.rasterizerDisable
== true)
883 pState
->pfnProcessPrims
= nullptr;
886 // set up the frontend attribute count
887 pState
->state
.feNumAttributes
= 0;
888 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
889 if (backendState
.swizzleEnable
)
891 // attribute swizzling is enabled, iterate over the map and record the max attribute used
892 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
894 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
899 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
902 if (pState
->state
.soState
.soEnable
)
904 uint32_t streamMasks
= 0;
905 for (uint32_t i
= 0; i
< 4; ++i
)
907 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
911 if (_BitScanReverse(&maxAttrib
, streamMasks
))
913 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
917 // complicated logic to test for cases where we don't need backing hottile memory for a draw
918 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
919 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
920 !pState
->state
.depthStencilState
.depthWriteEnable
&&
921 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
922 (pState
->state
.depthStencilState
.depthTestEnable
||
923 pState
->state
.depthStencilState
.depthWriteEnable
)) ? true : false;
925 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
926 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
927 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
928 // for stencil we have to check the double sided state as well
929 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
930 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
931 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
932 (pState
->state
.depthStencilState
.stencilTestEnable
||
933 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
935 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
936 pState
->state
.colorHottileEnable
= 0;
937 if (psState
.pfnPixelShader
!= nullptr)
939 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
941 pState
->state
.colorHottileEnable
|=
942 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
943 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
944 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
945 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
949 // Setup depth quantization function
950 if (pState
->state
.depthHottileEnable
)
952 switch (pState
->state
.rastState
.depthFormat
)
954 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
955 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
956 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
957 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
958 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
959 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
964 // set up pass-through quantize if depth isn't enabled
965 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
969 //////////////////////////////////////////////////////////////////////////
971 /// @param pDC - Draw context to initialize for this draw.
976 // We don't need to re-setup the scissors/pipeline state again for split draw.
977 if (isSplitDraw
== false)
979 SetupMacroTileScissors(pDC
);
984 //////////////////////////////////////////////////////////////////////////
985 /// @brief We can split the draw for certain topologies for better performance.
986 /// @param totalVerts - Total vertices for draw
987 /// @param topology - Topology used for draw
988 uint32_t MaxVertsPerDraw(
991 PRIMITIVE_TOPOLOGY topology
)
993 API_STATE
& state
= pDC
->pState
->state
;
995 uint32_t vertsPerDraw
= totalVerts
;
997 if (state
.soState
.soEnable
)
1004 case TOP_POINT_LIST
:
1005 case TOP_TRIANGLE_LIST
:
1006 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
1009 case TOP_PATCHLIST_1
:
1010 case TOP_PATCHLIST_2
:
1011 case TOP_PATCHLIST_3
:
1012 case TOP_PATCHLIST_4
:
1013 case TOP_PATCHLIST_5
:
1014 case TOP_PATCHLIST_6
:
1015 case TOP_PATCHLIST_7
:
1016 case TOP_PATCHLIST_8
:
1017 case TOP_PATCHLIST_9
:
1018 case TOP_PATCHLIST_10
:
1019 case TOP_PATCHLIST_11
:
1020 case TOP_PATCHLIST_12
:
1021 case TOP_PATCHLIST_13
:
1022 case TOP_PATCHLIST_14
:
1023 case TOP_PATCHLIST_15
:
1024 case TOP_PATCHLIST_16
:
1025 case TOP_PATCHLIST_17
:
1026 case TOP_PATCHLIST_18
:
1027 case TOP_PATCHLIST_19
:
1028 case TOP_PATCHLIST_20
:
1029 case TOP_PATCHLIST_21
:
1030 case TOP_PATCHLIST_22
:
1031 case TOP_PATCHLIST_23
:
1032 case TOP_PATCHLIST_24
:
1033 case TOP_PATCHLIST_25
:
1034 case TOP_PATCHLIST_26
:
1035 case TOP_PATCHLIST_27
:
1036 case TOP_PATCHLIST_28
:
1037 case TOP_PATCHLIST_29
:
1038 case TOP_PATCHLIST_30
:
1039 case TOP_PATCHLIST_31
:
1040 case TOP_PATCHLIST_32
:
1041 if (pDC
->pState
->state
.tsState
.tsEnable
)
1043 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1044 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1048 // The Primitive Assembly code can only handle 1 RECT at a time.
1054 // We are not splitting up draws for other topologies.
1058 return vertsPerDraw
;
1062 //////////////////////////////////////////////////////////////////////////
1063 /// @brief DrawInstanced
1064 /// @param hContext - Handle passed back from SwrCreateContext
1065 /// @param topology - Specifies topology for draw.
1066 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1067 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1068 /// @param numInstances - How many instances to render.
1069 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1072 PRIMITIVE_TOPOLOGY topology
,
1073 uint32_t numVertices
,
1074 uint32_t startVertex
,
1075 uint32_t numInstances
= 1,
1076 uint32_t startInstance
= 0)
1083 RDTSC_START(APIDraw
);
1085 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1086 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1088 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1089 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1090 uint32_t remainingVerts
= numVertices
;
1092 API_STATE
*pState
= &pDC
->pState
->state
;
1093 pState
->topology
= topology
;
1094 pState
->forceFront
= false;
1096 // disable culling for points/lines
1097 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1098 if (topology
== TOP_POINT_LIST
)
1100 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1101 pState
->forceFront
= true;
1105 while (remainingVerts
)
1107 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1108 remainingVerts
: maxVertsPerDraw
;
1110 bool isSplitDraw
= (draw
> 0) ? true : false;
1111 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1112 InitDraw(pDC
, isSplitDraw
);
1114 pDC
->FeWork
.type
= DRAW
;
1115 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1117 false, // bEnableCutIndex
1118 pState
->tsState
.tsEnable
,
1119 pState
->gsState
.gsEnable
,
1120 pState
->soState
.soEnable
,
1121 pDC
->pState
->pfnProcessPrims
!= nullptr);
1122 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1123 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1124 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1125 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1126 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1127 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1129 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1132 QueueDraw(pContext
);
1134 remainingVerts
-= numVertsForDraw
;
1138 // restore culling state
1139 pDC
= GetDrawContext(pContext
);
1140 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1142 RDTSC_STOP(APIDraw
, numVertices
* numInstances
, 0);
1145 //////////////////////////////////////////////////////////////////////////
1147 /// @param hContext - Handle passed back from SwrCreateContext
1148 /// @param topology - Specifies topology for draw.
1149 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1150 /// @param primCount - Number of vertices.
1153 PRIMITIVE_TOPOLOGY topology
,
1154 uint32_t startVertex
,
1155 uint32_t numVertices
)
1157 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1160 //////////////////////////////////////////////////////////////////////////
1161 /// @brief SwrDrawInstanced
1162 /// @param hContext - Handle passed back from SwrCreateContext
1163 /// @param topology - Specifies topology for draw.
1164 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1165 /// @param numInstances - How many instances to render.
1166 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1167 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1168 void SwrDrawInstanced(
1170 PRIMITIVE_TOPOLOGY topology
,
1171 uint32_t numVertsPerInstance
,
1172 uint32_t numInstances
,
1173 uint32_t startVertex
,
1174 uint32_t startInstance
1177 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1180 //////////////////////////////////////////////////////////////////////////
1181 /// @brief DrawIndexedInstanced
1182 /// @param hContext - Handle passed back from SwrCreateContext
1183 /// @param topology - Specifies topology for draw.
1184 /// @param numIndices - Number of indices to read sequentially from index buffer.
1185 /// @param indexOffset - Starting index into index buffer.
1186 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1187 /// @param numInstances - Number of instances to render.
1188 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1189 void DrawIndexedInstance(
1191 PRIMITIVE_TOPOLOGY topology
,
1192 uint32_t numIndices
,
1193 uint32_t indexOffset
,
1195 uint32_t numInstances
= 1,
1196 uint32_t startInstance
= 0)
1203 RDTSC_START(APIDrawIndexed
);
1205 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1206 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1207 API_STATE
* pState
= &pDC
->pState
->state
;
1209 AR_BEGIN(AR_API_CTX
, APIDrawIndexed
, pDC
->drawId
);
1210 AR_EVENT(AR_API_CTX
, DrawIndexedInstance(topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
));
1212 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1213 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1214 uint32_t remainingIndices
= numIndices
;
1216 uint32_t indexSize
= 0;
1217 switch (pState
->indexBuffer
.format
)
1219 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1220 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1221 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1227 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1228 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1230 pState
->topology
= topology
;
1231 pState
->forceFront
= false;
1233 // disable culling for points/lines
1234 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1235 if (topology
== TOP_POINT_LIST
)
1237 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1238 pState
->forceFront
= true;
1241 while (remainingIndices
)
1243 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1244 remainingIndices
: maxIndicesPerDraw
;
1246 // When breaking up draw, we need to obtain new draw context for each iteration.
1247 bool isSplitDraw
= (draw
> 0) ? true : false;
1248 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1249 InitDraw(pDC
, isSplitDraw
);
1251 pDC
->FeWork
.type
= DRAW
;
1252 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1254 pState
->frontendState
.bEnableCutIndex
,
1255 pState
->tsState
.tsEnable
,
1256 pState
->gsState
.gsEnable
,
1257 pState
->soState
.soEnable
,
1258 pDC
->pState
->pfnProcessPrims
!= nullptr);
1259 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1260 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1261 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1262 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1264 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1265 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1266 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1267 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1269 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1272 QueueDraw(pContext
);
1274 pIB
+= maxIndicesPerDraw
* indexSize
;
1275 remainingIndices
-= numIndicesForDraw
;
1279 // restore culling state
1280 pDC
= GetDrawContext(pContext
);
1281 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1283 AR_END(AR_API_CTX
, APIDrawIndexed
, numIndices
* numInstances
);
1284 RDTSC_STOP(APIDrawIndexed
, numIndices
* numInstances
, 0);
1288 //////////////////////////////////////////////////////////////////////////
1289 /// @brief DrawIndexed
1290 /// @param hContext - Handle passed back from SwrCreateContext
1291 /// @param topology - Specifies topology for draw.
1292 /// @param numIndices - Number of indices to read sequentially from index buffer.
1293 /// @param indexOffset - Starting index into index buffer.
1294 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1295 void SwrDrawIndexed(
1297 PRIMITIVE_TOPOLOGY topology
,
1298 uint32_t numIndices
,
1299 uint32_t indexOffset
,
1303 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1306 //////////////////////////////////////////////////////////////////////////
1307 /// @brief SwrDrawIndexedInstanced
1308 /// @param hContext - Handle passed back from SwrCreateContext
1309 /// @param topology - Specifies topology for draw.
1310 /// @param numIndices - Number of indices to read sequentially from index buffer.
1311 /// @param numInstances - Number of instances to render.
1312 /// @param indexOffset - Starting index into index buffer.
1313 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1314 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1315 void SwrDrawIndexedInstanced(
1317 PRIMITIVE_TOPOLOGY topology
,
1318 uint32_t numIndices
,
1319 uint32_t numInstances
,
1320 uint32_t indexOffset
,
1322 uint32_t startInstance
)
1324 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1327 //////////////////////////////////////////////////////////////////////////
1328 /// @brief SwrInvalidateTiles
1329 /// @param hContext - Handle passed back from SwrCreateContext
1330 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1331 /// @param invalidateRect - The pixel-coordinate rectangle to invalidate. This will be expanded to
1332 /// be hottile size-aligned.
1333 void SWR_API
SwrInvalidateTiles(
1335 uint32_t attachmentMask
,
1336 const SWR_RECT
& invalidateRect
)
1343 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1344 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1346 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1347 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1348 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1349 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= invalidateRect
;
1350 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1351 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1352 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1353 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1356 QueueDraw(pContext
);
1359 //////////////////////////////////////////////////////////////////////////
1360 /// @brief SwrDiscardRect
1361 /// @param hContext - Handle passed back from SwrCreateContext
1362 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1363 /// @param rect - The pixel-coordinate rectangle to discard. Only fully-covered hottiles will be
1365 void SWR_API
SwrDiscardRect(
1367 uint32_t attachmentMask
,
1368 const SWR_RECT
& rect
)
1375 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1376 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1378 // Queue a load to the hottile
1379 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1380 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1381 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1382 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1383 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1384 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1385 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1386 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1389 QueueDraw(pContext
);
1392 //////////////////////////////////////////////////////////////////////////
1393 /// @brief SwrDispatch
1394 /// @param hContext - Handle passed back from SwrCreateContext
1395 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1396 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1397 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1400 uint32_t threadGroupCountX
,
1401 uint32_t threadGroupCountY
,
1402 uint32_t threadGroupCountZ
)
1409 RDTSC_START(APIDispatch
);
1410 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1411 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1413 pDC
->isCompute
= true; // This is a compute context.
1415 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1417 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1418 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1419 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1421 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1422 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1423 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1424 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
);
1426 QueueDispatch(pContext
);
1427 RDTSC_STOP(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
, 0);
1430 // Deswizzles, converts and stores current contents of the hot tiles to surface
1431 // described by pState
1432 void SWR_API
SwrStoreTiles(
1434 SWR_RENDERTARGET_ATTACHMENT attachment
,
1435 SWR_TILE_STATE postStoreTileState
,
1436 const SWR_RECT
& storeRect
)
1443 RDTSC_START(APIStoreTiles
);
1445 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1446 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1448 pDC
->FeWork
.type
= STORETILES
;
1449 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1450 pDC
->FeWork
.desc
.storeTiles
.attachment
= attachment
;
1451 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1452 pDC
->FeWork
.desc
.storeTiles
.rect
= storeRect
;
1453 pDC
->FeWork
.desc
.storeTiles
.rect
&= g_MaxScissorRect
;
1456 QueueDraw(pContext
);
1458 RDTSC_STOP(APIStoreTiles
, 0, 0);
1461 //////////////////////////////////////////////////////////////////////////
1462 /// @brief SwrClearRenderTarget - Clear attached render targets / depth / stencil
1463 /// @param hContext - Handle passed back from SwrCreateContext
1464 /// @param clearMask - combination of SWR_CLEAR_COLOR / SWR_CLEAR_DEPTH / SWR_CLEAR_STENCIL flags (or SWR_CLEAR_NONE)
1465 /// @param clearColor - color use for clearing render targets
1466 /// @param z - depth value use for clearing depth buffer
1467 /// @param stencil - stencil value used for clearing stencil buffer
1468 /// @param clearRect - The pixel-coordinate rectangle to clear in all cleared buffers
1469 void SWR_API
SwrClearRenderTarget(
1472 const float clearColor
[4],
1475 const SWR_RECT
& clearRect
)
1482 RDTSC_START(APIClearRenderTarget
);
1484 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1485 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1489 flags
.mask
= clearMask
;
1491 pDC
->FeWork
.type
= CLEAR
;
1492 pDC
->FeWork
.pfnWork
= ProcessClear
;
1493 pDC
->FeWork
.desc
.clear
.rect
= clearRect
;
1494 pDC
->FeWork
.desc
.clear
.rect
&= g_MaxScissorRect
;
1495 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1496 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1497 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1498 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1499 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1500 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1501 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1504 QueueDraw(pContext
);
1506 RDTSC_STOP(APIClearRenderTarget
, 0, pDC
->drawId
);
1509 //////////////////////////////////////////////////////////////////////////
1510 /// @brief Returns a pointer to the private context state for the current
1511 /// draw operation. This is used for external componets such as the
1513 /// SWR is responsible for the allocation of the private context state.
1514 /// @param hContext - Handle passed back from SwrCreateContext
1515 VOID
* SwrGetPrivateContextState(
1518 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1519 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1520 DRAW_STATE
* pState
= pDC
->pState
;
1522 if (pState
->pPrivateState
== nullptr)
1524 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1527 return pState
->pPrivateState
;
1530 //////////////////////////////////////////////////////////////////////////
1531 /// @brief Clients can use this to allocate memory for draw/dispatch
1532 /// operations. The memory will automatically be freed once operation
1533 /// has completed. Client can use this to allocate binding tables,
1534 /// etc. needed for shader execution.
1535 /// @param hContext - Handle passed back from SwrCreateContext
1536 /// @param size - Size of allocation
1537 /// @param align - Alignment needed for allocation.
1538 VOID
* SwrAllocDrawContextMemory(
1543 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1544 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1546 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1549 //////////////////////////////////////////////////////////////////////////
1550 /// @brief Enables stats counting
1551 /// @param hContext - Handle passed back from SwrCreateContext
1552 /// @param enable - If true then counts are incremented.
1553 void SwrEnableStats(
1557 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1558 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1560 pDC
->pState
->state
.enableStats
= enable
;
1563 //////////////////////////////////////////////////////////////////////////
1564 /// @brief Mark end of frame - used for performance profiling
1565 /// @param hContext - Handle passed back from SwrCreateContext
1566 void SWR_API
SwrEndFrame(
1570 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1571 pContext
->frameCount
++;