radeonsi: Don't use global variables for tess lds
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / api.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file api.cpp
24 *
25 * @brief API implementation
26 *
27 ******************************************************************************/
28
29 #include <cfloat>
30 #include <cmath>
31 #include <cstdio>
32 #include <new>
33
34 #include "core/api.h"
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"
45
46 #include "common/simdintrin.h"
47 #include "common/os.h"
48
49 static const SWR_RECT g_MaxScissorRect = { 0, 0, KNOB_MAX_SCISSOR_X, KNOB_MAX_SCISSOR_Y };
50
51 void SetupDefaultState(SWR_CONTEXT *pContext);
52
53 static INLINE SWR_CONTEXT* GetContext(HANDLE hContext)
54 {
55 return (SWR_CONTEXT*)hContext;
56 }
57
58 //////////////////////////////////////////////////////////////////////////
59 /// @brief Create SWR Context.
60 /// @param pCreateInfo - pointer to creation info.
61 HANDLE SwrCreateContext(
62 SWR_CREATECONTEXT_INFO* pCreateInfo)
63 {
64 RDTSC_RESET();
65 RDTSC_INIT(0);
66
67 void* pContextMem = AlignedMalloc(sizeof(SWR_CONTEXT), KNOB_SIMD_WIDTH * 4);
68 memset(pContextMem, 0, sizeof(SWR_CONTEXT));
69 SWR_CONTEXT *pContext = new (pContextMem) SWR_CONTEXT();
70
71 pContext->driverType = pCreateInfo->driver;
72 pContext->privateStateSize = pCreateInfo->privateStateSize;
73
74 pContext->dcRing.Init(KNOB_MAX_DRAWS_IN_FLIGHT);
75 pContext->dsRing.Init(KNOB_MAX_DRAWS_IN_FLIGHT);
76
77 pContext->pMacroTileManagerArray = (MacroTileMgr*)AlignedMalloc(sizeof(MacroTileMgr) * KNOB_MAX_DRAWS_IN_FLIGHT, 64);
78 pContext->pDispatchQueueArray = (DispatchQueue*)AlignedMalloc(sizeof(DispatchQueue) * KNOB_MAX_DRAWS_IN_FLIGHT, 64);
79
80 pContext->threadInfo.MAX_WORKER_THREADS = KNOB_MAX_WORKER_THREADS;
81 pContext->threadInfo.MAX_NUMA_NODES = KNOB_MAX_NUMA_NODES;
82 pContext->threadInfo.MAX_CORES_PER_NUMA_NODE = KNOB_MAX_CORES_PER_NUMA_NODE;
83 pContext->threadInfo.MAX_THREADS_PER_CORE = KNOB_MAX_THREADS_PER_CORE;
84 pContext->threadInfo.SINGLE_THREADED = KNOB_SINGLE_THREADED;
85
86 if (pCreateInfo->pThreadInfo)
87 {
88 pContext->threadInfo = *pCreateInfo->pThreadInfo;
89 }
90
91 for (uint32_t dc = 0; dc < KNOB_MAX_DRAWS_IN_FLIGHT; ++dc)
92 {
93 pContext->dcRing[dc].pArena = new CachingArena(pContext->cachingArenaAllocator);
94 new (&pContext->pMacroTileManagerArray[dc]) MacroTileMgr(*pContext->dcRing[dc].pArena);
95 new (&pContext->pDispatchQueueArray[dc]) DispatchQueue();
96
97 pContext->dsRing[dc].pArena = new CachingArena(pContext->cachingArenaAllocator);
98 }
99
100 if (!pContext->threadInfo.SINGLE_THREADED)
101 {
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();
106
107 CreateThreadPool(pContext, &pContext->threadPool);
108 }
109
110 // Calling createThreadPool() above can set SINGLE_THREADED
111 if (pContext->threadInfo.SINGLE_THREADED)
112 {
113 pContext->NumWorkerThreads = 1;
114 pContext->NumFEThreads = 1;
115 pContext->NumBEThreads = 1;
116 }
117
118 // Allocate scratch space for workers.
119 ///@note We could lazily allocate this but its rather small amount of memory.
120 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
121 {
122 #if defined(_WIN32)
123 uint32_t numaNode = pContext->threadPool.pThreadData ?
124 pContext->threadPool.pThreadData[i].numaId : 0;
125 pContext->pScratch[i] = (uint8_t*)VirtualAllocExNuma(
126 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE),
127 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE,
128 numaNode);
129 #else
130 pContext->pScratch[i] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE), KNOB_SIMD_WIDTH * 4);
131 #endif
132 }
133
134 // State setup AFTER context is fully initialized
135 SetupDefaultState(pContext);
136
137 // initialize hot tile manager
138 pContext->pHotTileMgr = new HotTileMgr();
139
140 // initialize function pointer tables
141 InitClearTilesTable();
142
143 // initialize callback functions
144 pContext->pfnLoadTile = pCreateInfo->pfnLoadTile;
145 pContext->pfnStoreTile = pCreateInfo->pfnStoreTile;
146 pContext->pfnClearTile = pCreateInfo->pfnClearTile;
147 pContext->pfnUpdateSoWriteOffset = pCreateInfo->pfnUpdateSoWriteOffset;
148 pContext->pfnUpdateStats = pCreateInfo->pfnUpdateStats;
149 pContext->pfnUpdateStatsFE = pCreateInfo->pfnUpdateStatsFE;
150
151 // pass pointer to bucket manager back to caller
152 #ifdef KNOB_ENABLE_RDTSC
153 pCreateInfo->pBucketMgr = &gBucketMgr;
154 #endif
155
156 pCreateInfo->contextSaveSize = sizeof(API_STATE);
157
158 return (HANDLE)pContext;
159 }
160
161 void SwrDestroyContext(HANDLE hContext)
162 {
163 SWR_CONTEXT *pContext = GetContext(hContext);
164 DestroyThreadPool(pContext, &pContext->threadPool);
165
166 // free the fifos
167 for (uint32_t i = 0; i < KNOB_MAX_DRAWS_IN_FLIGHT; ++i)
168 {
169 delete pContext->dcRing[i].pArena;
170 delete pContext->dsRing[i].pArena;
171 pContext->pMacroTileManagerArray[i].~MacroTileMgr();
172 pContext->pDispatchQueueArray[i].~DispatchQueue();
173 }
174
175 AlignedFree(pContext->pDispatchQueueArray);
176 AlignedFree(pContext->pMacroTileManagerArray);
177
178 // Free scratch space.
179 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
180 {
181 #if defined(_WIN32)
182 VirtualFree(pContext->pScratch[i], 0, MEM_RELEASE);
183 #else
184 AlignedFree(pContext->pScratch[i]);
185 #endif
186 }
187
188 delete(pContext->pHotTileMgr);
189
190 pContext->~SWR_CONTEXT();
191 AlignedFree(GetContext(hContext));
192 }
193
194 void CopyState(DRAW_STATE& dst, const DRAW_STATE& src)
195 {
196 memcpy(&dst.state, &src.state, sizeof(API_STATE));
197 }
198
199 void WakeAllThreads(SWR_CONTEXT *pContext)
200 {
201 pContext->FifosNotEmpty.notify_all();
202 }
203
204 template<bool IsDraw>
205 void QueueWork(SWR_CONTEXT *pContext)
206 {
207 DRAW_CONTEXT* pDC = pContext->pCurDrawContext;
208 uint32_t dcIndex = pDC->drawId % KNOB_MAX_DRAWS_IN_FLIGHT;
209
210 if (IsDraw)
211 {
212 pDC->pTileMgr = &pContext->pMacroTileManagerArray[dcIndex];
213 pDC->pTileMgr->initialize();
214 }
215
216 // Each worker thread looks at a DC for both FE and BE work at different times and so we
217 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
218 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
219 // then moved on if all work is done.)
220 pContext->pCurDrawContext->threadsDone = pContext->NumFEThreads + pContext->NumBEThreads;
221
222 if (IsDraw)
223 {
224 InterlockedIncrement((volatile LONG*)&pContext->drawsOutstandingFE);
225 }
226
227 _ReadWriteBarrier();
228 {
229 std::unique_lock<std::mutex> lock(pContext->WaitLock);
230 pContext->dcRing.Enqueue();
231 }
232
233 if (pContext->threadInfo.SINGLE_THREADED)
234 {
235 // flush denormals to 0
236 uint32_t mxcsr = _mm_getcsr();
237 _mm_setcsr(mxcsr | _MM_FLUSH_ZERO_ON | _MM_DENORMALS_ZERO_ON);
238
239 if (IsDraw)
240 {
241 uint32_t curDraw[2] = { pContext->pCurDrawContext->drawId, pContext->pCurDrawContext->drawId };
242 WorkOnFifoFE(pContext, 0, curDraw[0]);
243 WorkOnFifoBE(pContext, 0, curDraw[1], pContext->singleThreadLockedTiles, 0, 0);
244 }
245 else
246 {
247 uint32_t curDispatch = pContext->pCurDrawContext->drawId;
248 WorkOnCompute(pContext, 0, curDispatch);
249 }
250
251 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
252 while (CompleteDrawContext(pContext, pContext->pCurDrawContext) > 0) {}
253
254 // restore csr
255 _mm_setcsr(mxcsr);
256 }
257 else
258 {
259 RDTSC_START(APIDrawWakeAllThreads);
260 WakeAllThreads(pContext);
261 RDTSC_STOP(APIDrawWakeAllThreads, 1, 0);
262 }
263
264 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
265 pContext->pPrevDrawContext = pContext->pCurDrawContext;
266 pContext->pCurDrawContext = nullptr;
267 }
268
269 INLINE void QueueDraw(SWR_CONTEXT* pContext)
270 {
271 QueueWork<true>(pContext);
272 }
273
274 INLINE void QueueDispatch(SWR_CONTEXT* pContext)
275 {
276 QueueWork<false>(pContext);
277 }
278
279 DRAW_CONTEXT* GetDrawContext(SWR_CONTEXT *pContext, bool isSplitDraw = false)
280 {
281 RDTSC_START(APIGetDrawContext);
282 // If current draw context is null then need to obtain a new draw context to use from ring.
283 if (pContext->pCurDrawContext == nullptr)
284 {
285 // Need to wait for a free entry.
286 while (pContext->dcRing.IsFull())
287 {
288 _mm_pause();
289 }
290
291 uint64_t curDraw = pContext->dcRing.GetHead();
292 uint32_t dcIndex = curDraw % KNOB_MAX_DRAWS_IN_FLIGHT;
293
294 if ((pContext->frameCount - pContext->lastFrameChecked) > 2 ||
295 (curDraw - pContext->lastDrawChecked) > 0x10000)
296 {
297 // Take this opportunity to clean-up old arena allocations
298 pContext->cachingArenaAllocator.FreeOldBlocks();
299
300 pContext->lastFrameChecked = pContext->frameCount;
301 pContext->lastDrawChecked = curDraw;
302 }
303
304 DRAW_CONTEXT* pCurDrawContext = &pContext->dcRing[dcIndex];
305 pContext->pCurDrawContext = pCurDrawContext;
306
307 // Assign next available entry in DS ring to this DC.
308 uint32_t dsIndex = pContext->curStateId % KNOB_MAX_DRAWS_IN_FLIGHT;
309 pCurDrawContext->pState = &pContext->dsRing[dsIndex];
310
311 // Copy previous state to current state.
312 if (pContext->pPrevDrawContext)
313 {
314 DRAW_CONTEXT* pPrevDrawContext = pContext->pPrevDrawContext;
315
316 // If we're splitting our draw then we can just use the same state from the previous
317 // draw. In this case, we won't increment the DS ring index so the next non-split
318 // draw can receive the state.
319 if (isSplitDraw == false)
320 {
321 CopyState(*pCurDrawContext->pState, *pPrevDrawContext->pState);
322
323 // Should have been cleaned up previously
324 SWR_ASSERT(pCurDrawContext->pState->pArena->IsEmpty() == true);
325
326 pCurDrawContext->pState->pPrivateState = nullptr;
327
328 pContext->curStateId++; // Progress state ring index forward.
329 }
330 else
331 {
332 // If its a split draw then just copy the state pointer over
333 // since its the same draw.
334 pCurDrawContext->pState = pPrevDrawContext->pState;
335 SWR_ASSERT(pPrevDrawContext->cleanupState == false);
336 }
337 }
338 else
339 {
340 SWR_ASSERT(pCurDrawContext->pState->pArena->IsEmpty() == true);
341 pContext->curStateId++; // Progress state ring index forward.
342 }
343
344 SWR_ASSERT(pCurDrawContext->pArena->IsEmpty() == true);
345
346 pCurDrawContext->dependent = false;
347 pCurDrawContext->pContext = pContext;
348 pCurDrawContext->isCompute = false; // Dispatch has to set this to true.
349
350 pCurDrawContext->doneFE = false;
351 pCurDrawContext->FeLock = 0;
352 pCurDrawContext->threadsDone = 0;
353 pCurDrawContext->retireCallback.pfnCallbackFunc = nullptr;
354
355 memset(&pCurDrawContext->dynState, 0, sizeof(pCurDrawContext->dynState));
356
357 // Assign unique drawId for this DC
358 pCurDrawContext->drawId = pContext->dcRing.GetHead();
359
360 pCurDrawContext->cleanupState = true;
361 }
362 else
363 {
364 SWR_ASSERT(isSplitDraw == false, "Split draw should only be used when obtaining a new DC");
365 }
366
367 RDTSC_STOP(APIGetDrawContext, 0, 0);
368 return pContext->pCurDrawContext;
369 }
370
371 API_STATE* GetDrawState(SWR_CONTEXT *pContext)
372 {
373 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
374 SWR_ASSERT(pDC->pState != nullptr);
375
376 return &pDC->pState->state;
377 }
378
379 void SWR_API SwrSaveState(
380 HANDLE hContext,
381 void* pOutputStateBlock,
382 size_t memSize)
383 {
384 SWR_CONTEXT *pContext = GetContext(hContext);
385 auto pSrc = GetDrawState(pContext);
386 SWR_ASSERT(pOutputStateBlock && memSize >= sizeof(*pSrc));
387
388 memcpy(pOutputStateBlock, pSrc, sizeof(*pSrc));
389 }
390
391 void SWR_API SwrRestoreState(
392 HANDLE hContext,
393 const void* pStateBlock,
394 size_t memSize)
395 {
396 SWR_CONTEXT *pContext = GetContext(hContext);
397 auto pDst = GetDrawState(pContext);
398 SWR_ASSERT(pStateBlock && memSize >= sizeof(*pDst));
399
400 memcpy(pDst, pStateBlock, sizeof(*pDst));
401 }
402
403 void SetupDefaultState(SWR_CONTEXT *pContext)
404 {
405 API_STATE* pState = GetDrawState(pContext);
406
407 pState->rastState.cullMode = SWR_CULLMODE_NONE;
408 pState->rastState.frontWinding = SWR_FRONTWINDING_CCW;
409 }
410
411 void SwrSync(HANDLE hContext, PFN_CALLBACK_FUNC pfnFunc, uint64_t userData, uint64_t userData2, uint64_t userData3)
412 {
413 RDTSC_START(APISync);
414
415 SWR_ASSERT(pfnFunc != nullptr);
416
417 SWR_CONTEXT *pContext = GetContext(hContext);
418 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
419
420 pDC->FeWork.type = SYNC;
421 pDC->FeWork.pfnWork = ProcessSync;
422
423 // Setup callback function
424 pDC->retireCallback.pfnCallbackFunc = pfnFunc;
425 pDC->retireCallback.userData = userData;
426 pDC->retireCallback.userData2 = userData2;
427 pDC->retireCallback.userData3 = userData3;
428
429 //enqueue
430 QueueDraw(pContext);
431
432 RDTSC_STOP(APISync, 1, 0);
433 }
434
435 void SwrWaitForIdle(HANDLE hContext)
436 {
437 SWR_CONTEXT *pContext = GetContext(hContext);
438
439 RDTSC_START(APIWaitForIdle);
440
441 while (!pContext->dcRing.IsEmpty())
442 {
443 _mm_pause();
444 }
445
446 RDTSC_STOP(APIWaitForIdle, 1, 0);
447 }
448
449 void SwrWaitForIdleFE(HANDLE hContext)
450 {
451 SWR_CONTEXT *pContext = GetContext(hContext);
452
453 RDTSC_START(APIWaitForIdle);
454
455 while (pContext->drawsOutstandingFE > 0)
456 {
457 _mm_pause();
458 }
459
460 RDTSC_STOP(APIWaitForIdle, 1, 0);
461 }
462
463 void SwrSetVertexBuffers(
464 HANDLE hContext,
465 uint32_t numBuffers,
466 const SWR_VERTEX_BUFFER_STATE* pVertexBuffers)
467 {
468 API_STATE* pState = GetDrawState(GetContext(hContext));
469
470 for (uint32_t i = 0; i < numBuffers; ++i)
471 {
472 const SWR_VERTEX_BUFFER_STATE *pVB = &pVertexBuffers[i];
473 pState->vertexBuffers[pVB->index] = *pVB;
474 }
475 }
476
477 void SwrSetIndexBuffer(
478 HANDLE hContext,
479 const SWR_INDEX_BUFFER_STATE* pIndexBuffer)
480 {
481 API_STATE* pState = GetDrawState(GetContext(hContext));
482
483 pState->indexBuffer = *pIndexBuffer;
484 }
485
486 void SwrSetFetchFunc(
487 HANDLE hContext,
488 PFN_FETCH_FUNC pfnFetchFunc)
489 {
490 API_STATE* pState = GetDrawState(GetContext(hContext));
491
492 pState->pfnFetchFunc = pfnFetchFunc;
493 }
494
495 void SwrSetSoFunc(
496 HANDLE hContext,
497 PFN_SO_FUNC pfnSoFunc,
498 uint32_t streamIndex)
499 {
500 API_STATE* pState = GetDrawState(GetContext(hContext));
501
502 SWR_ASSERT(streamIndex < MAX_SO_STREAMS);
503
504 pState->pfnSoFunc[streamIndex] = pfnSoFunc;
505 }
506
507 void SwrSetSoState(
508 HANDLE hContext,
509 SWR_STREAMOUT_STATE* pSoState)
510 {
511 API_STATE* pState = GetDrawState(GetContext(hContext));
512
513 pState->soState = *pSoState;
514 }
515
516 void SwrSetSoBuffers(
517 HANDLE hContext,
518 SWR_STREAMOUT_BUFFER* pSoBuffer,
519 uint32_t slot)
520 {
521 API_STATE* pState = GetDrawState(GetContext(hContext));
522
523 SWR_ASSERT((slot < 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot);
524
525 pState->soBuffer[slot] = *pSoBuffer;
526 }
527
528 void SwrSetVertexFunc(
529 HANDLE hContext,
530 PFN_VERTEX_FUNC pfnVertexFunc)
531 {
532 API_STATE* pState = GetDrawState(GetContext(hContext));
533
534 pState->pfnVertexFunc = pfnVertexFunc;
535 }
536
537 void SwrSetFrontendState(
538 HANDLE hContext,
539 SWR_FRONTEND_STATE *pFEState)
540 {
541 API_STATE* pState = GetDrawState(GetContext(hContext));
542 pState->frontendState = *pFEState;
543 }
544
545 void SwrSetGsState(
546 HANDLE hContext,
547 SWR_GS_STATE *pGSState)
548 {
549 API_STATE* pState = GetDrawState(GetContext(hContext));
550 pState->gsState = *pGSState;
551 }
552
553 void SwrSetGsFunc(
554 HANDLE hContext,
555 PFN_GS_FUNC pfnGsFunc)
556 {
557 API_STATE* pState = GetDrawState(GetContext(hContext));
558 pState->pfnGsFunc = pfnGsFunc;
559 }
560
561 void SwrSetCsFunc(
562 HANDLE hContext,
563 PFN_CS_FUNC pfnCsFunc,
564 uint32_t totalThreadsInGroup,
565 uint32_t totalSpillFillSize)
566 {
567 API_STATE* pState = GetDrawState(GetContext(hContext));
568 pState->pfnCsFunc = pfnCsFunc;
569 pState->totalThreadsInGroup = totalThreadsInGroup;
570 pState->totalSpillFillSize = totalSpillFillSize;
571 }
572
573 void SwrSetTsState(
574 HANDLE hContext,
575 SWR_TS_STATE *pState)
576 {
577 API_STATE* pApiState = GetDrawState(GetContext(hContext));
578 pApiState->tsState = *pState;
579 }
580
581 void SwrSetHsFunc(
582 HANDLE hContext,
583 PFN_HS_FUNC pfnFunc)
584 {
585 API_STATE* pApiState = GetDrawState(GetContext(hContext));
586 pApiState->pfnHsFunc = pfnFunc;
587 }
588
589 void SwrSetDsFunc(
590 HANDLE hContext,
591 PFN_DS_FUNC pfnFunc)
592 {
593 API_STATE* pApiState = GetDrawState(GetContext(hContext));
594 pApiState->pfnDsFunc = pfnFunc;
595 }
596
597 void SwrSetDepthStencilState(
598 HANDLE hContext,
599 SWR_DEPTH_STENCIL_STATE *pDSState)
600 {
601 API_STATE* pState = GetDrawState(GetContext(hContext));
602
603 pState->depthStencilState = *pDSState;
604 }
605
606 void SwrSetBackendState(
607 HANDLE hContext,
608 SWR_BACKEND_STATE *pBEState)
609 {
610 API_STATE* pState = GetDrawState(GetContext(hContext));
611
612 pState->backendState = *pBEState;
613 }
614
615 void SwrSetPixelShaderState(
616 HANDLE hContext,
617 SWR_PS_STATE *pPSState)
618 {
619 API_STATE *pState = GetDrawState(GetContext(hContext));
620 pState->psState = *pPSState;
621 }
622
623 void SwrSetBlendState(
624 HANDLE hContext,
625 SWR_BLEND_STATE *pBlendState)
626 {
627 API_STATE *pState = GetDrawState(GetContext(hContext));
628 memcpy(&pState->blendState, pBlendState, sizeof(SWR_BLEND_STATE));
629 }
630
631 void SwrSetBlendFunc(
632 HANDLE hContext,
633 uint32_t renderTarget,
634 PFN_BLEND_JIT_FUNC pfnBlendFunc)
635 {
636 SWR_ASSERT(renderTarget < SWR_NUM_RENDERTARGETS);
637 API_STATE *pState = GetDrawState(GetContext(hContext));
638 pState->pfnBlendFunc[renderTarget] = pfnBlendFunc;
639 }
640
641 // update guardband multipliers for the viewport
642 void updateGuardband(API_STATE *pState)
643 {
644 // guardband center is viewport center
645 pState->gbState.left = KNOB_GUARDBAND_WIDTH / pState->vp[0].width;
646 pState->gbState.right = KNOB_GUARDBAND_WIDTH / pState->vp[0].width;
647 pState->gbState.top = KNOB_GUARDBAND_HEIGHT / pState->vp[0].height;
648 pState->gbState.bottom = KNOB_GUARDBAND_HEIGHT / pState->vp[0].height;
649 }
650
651 void SwrSetRastState(
652 HANDLE hContext,
653 const SWR_RASTSTATE *pRastState)
654 {
655 SWR_CONTEXT *pContext = GetContext(hContext);
656 API_STATE* pState = GetDrawState(pContext);
657
658 memcpy(&pState->rastState, pRastState, sizeof(SWR_RASTSTATE));
659 }
660
661 void SwrSetViewports(
662 HANDLE hContext,
663 uint32_t numViewports,
664 const SWR_VIEWPORT* pViewports,
665 const SWR_VIEWPORT_MATRICES* pMatrices)
666 {
667 SWR_ASSERT(numViewports <= KNOB_NUM_VIEWPORTS_SCISSORS,
668 "Invalid number of viewports.");
669
670 SWR_CONTEXT *pContext = GetContext(hContext);
671 API_STATE* pState = GetDrawState(pContext);
672
673 memcpy(&pState->vp[0], pViewports, sizeof(SWR_VIEWPORT) * numViewports);
674
675 if (pMatrices != nullptr)
676 {
677 // @todo Faster to copy portions of the SOA or just copy all of it?
678 memcpy(&pState->vpMatrices, pMatrices, sizeof(SWR_VIEWPORT_MATRICES));
679 }
680 else
681 {
682 // Compute default viewport transform.
683 for (uint32_t i = 0; i < numViewports; ++i)
684 {
685 if (pContext->driverType == DX)
686 {
687 pState->vpMatrices.m00[i] = pState->vp[i].width / 2.0f;
688 pState->vpMatrices.m11[i] = -pState->vp[i].height / 2.0f;
689 pState->vpMatrices.m22[i] = pState->vp[i].maxZ - pState->vp[i].minZ;
690 pState->vpMatrices.m30[i] = pState->vp[i].x + pState->vpMatrices.m00[i];
691 pState->vpMatrices.m31[i] = pState->vp[i].y - pState->vpMatrices.m11[i];
692 pState->vpMatrices.m32[i] = pState->vp[i].minZ;
693 }
694 else
695 {
696 // Standard, with the exception that Y is inverted.
697 pState->vpMatrices.m00[i] = (pState->vp[i].width - pState->vp[i].x) / 2.0f;
698 pState->vpMatrices.m11[i] = (pState->vp[i].y - pState->vp[i].height) / 2.0f;
699 pState->vpMatrices.m22[i] = (pState->vp[i].maxZ - pState->vp[i].minZ) / 2.0f;
700 pState->vpMatrices.m30[i] = pState->vp[i].x + pState->vpMatrices.m00[i];
701 pState->vpMatrices.m31[i] = pState->vp[i].height + pState->vpMatrices.m11[i];
702 pState->vpMatrices.m32[i] = pState->vp[i].minZ + pState->vpMatrices.m22[i];
703
704 // Now that the matrix is calculated, clip the view coords to screen size.
705 // OpenGL allows for -ve x,y in the viewport.
706 pState->vp[i].x = std::max(pState->vp[i].x, 0.0f);
707 pState->vp[i].y = std::max(pState->vp[i].y, 0.0f);
708 }
709 }
710 }
711
712 updateGuardband(pState);
713 }
714
715 void SwrSetScissorRects(
716 HANDLE hContext,
717 uint32_t numScissors,
718 const SWR_RECT* pScissors)
719 {
720 SWR_ASSERT(numScissors <= KNOB_NUM_VIEWPORTS_SCISSORS,
721 "Invalid number of scissor rects.");
722
723 API_STATE* pState = GetDrawState(GetContext(hContext));
724 memcpy(&pState->scissorRects[0], pScissors, numScissors * sizeof(pScissors[0]));
725 };
726
727 void SetupMacroTileScissors(DRAW_CONTEXT *pDC)
728 {
729 API_STATE *pState = &pDC->pState->state;
730
731 // Set up scissor dimensions based on scissor or viewport
732 if (pState->rastState.scissorEnable)
733 {
734 pState->scissorInFixedPoint = pState->scissorRects[0];
735 }
736 else
737 {
738 // the vp width and height must be added to origin un-rounded then the result round to -inf.
739 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
740 pState->scissorInFixedPoint.xmin = (int32_t)pState->vp[0].x;
741 pState->scissorInFixedPoint.xmax = (int32_t)(pState->vp[0].x + pState->vp[0].width);
742 pState->scissorInFixedPoint.ymin = (int32_t)pState->vp[0].y;
743 pState->scissorInFixedPoint.ymax = (int32_t)(pState->vp[0].y + pState->vp[0].height);
744 }
745
746 // Clamp to max rect
747 pState->scissorInFixedPoint &= g_MaxScissorRect;
748
749 // Scale to fixed point
750 pState->scissorInFixedPoint.xmin *= FIXED_POINT_SCALE;
751 pState->scissorInFixedPoint.xmax *= FIXED_POINT_SCALE;
752 pState->scissorInFixedPoint.ymin *= FIXED_POINT_SCALE;
753 pState->scissorInFixedPoint.ymax *= FIXED_POINT_SCALE;
754
755 // Make scissor inclusive
756 pState->scissorInFixedPoint.xmax -= 1;
757 pState->scissorInFixedPoint.ymax -= 1;
758 }
759
760 // templated backend function tables
761 extern PFN_BACKEND_FUNC gBackendNullPs[SWR_MULTISAMPLE_TYPE_COUNT];
762 extern PFN_BACKEND_FUNC gBackendSingleSample[SWR_INPUT_COVERAGE_COUNT][2][2];
763 extern PFN_BACKEND_FUNC gBackendPixelRateTable[SWR_MULTISAMPLE_TYPE_COUNT][SWR_MSAA_SAMPLE_PATTERN_COUNT][SWR_INPUT_COVERAGE_COUNT][2][2][2];
764 extern PFN_BACKEND_FUNC gBackendSampleRateTable[SWR_MULTISAMPLE_TYPE_COUNT][SWR_INPUT_COVERAGE_COUNT][2][2];
765 void SetupPipeline(DRAW_CONTEXT *pDC)
766 {
767 DRAW_STATE* pState = pDC->pState;
768 const SWR_RASTSTATE &rastState = pState->state.rastState;
769 const SWR_PS_STATE &psState = pState->state.psState;
770 BACKEND_FUNCS& backendFuncs = pState->backendFuncs;
771 const uint32_t forcedSampleCount = (rastState.forcedSampleCount) ? 1 : 0;
772
773 // setup backend
774 if (psState.pfnPixelShader == nullptr)
775 {
776 backendFuncs.pfnBackend = gBackendNullPs[pState->state.rastState.sampleCount];
777 }
778 else
779 {
780 const bool bMultisampleEnable = ((rastState.sampleCount > SWR_MULTISAMPLE_1X) || rastState.forcedSampleCount) ? 1 : 0;
781 const uint32_t centroid = ((psState.barycentricsMask & SWR_BARYCENTRIC_CENTROID_MASK) > 0) ? 1 : 0;
782 const uint32_t canEarlyZ = (psState.forceEarlyZ || (!psState.writesODepth && !psState.usesSourceDepth && !psState.usesUAV)) ? 1 : 0;
783
784 SWR_BARYCENTRICS_MASK barycentricsMask = (SWR_BARYCENTRICS_MASK)psState.barycentricsMask;
785
786 // select backend function
787 switch(psState.shadingRate)
788 {
789 case SWR_SHADING_RATE_PIXEL:
790 if(bMultisampleEnable)
791 {
792 // always need to generate I & J per sample for Z interpolation
793 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_SAMPLE_MASK);
794 backendFuncs.pfnBackend = gBackendPixelRateTable[rastState.sampleCount][rastState.samplePattern][psState.inputCoverage][centroid][forcedSampleCount][canEarlyZ];
795 }
796 else
797 {
798 // always need to generate I & J per pixel for Z interpolation
799 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_PIXEL_MASK);
800 backendFuncs.pfnBackend = gBackendSingleSample[psState.inputCoverage][centroid][canEarlyZ];
801 }
802 break;
803 case SWR_SHADING_RATE_SAMPLE:
804 SWR_ASSERT(rastState.samplePattern == SWR_MSAA_STANDARD_PATTERN);
805 // always need to generate I & J per sample for Z interpolation
806 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_SAMPLE_MASK);
807 backendFuncs.pfnBackend = gBackendSampleRateTable[rastState.sampleCount][psState.inputCoverage][centroid][canEarlyZ];
808 break;
809 default:
810 SWR_ASSERT(0 && "Invalid shading rate");
811 break;
812 }
813 }
814
815 PFN_PROCESS_PRIMS pfnBinner;
816 switch (pState->state.topology)
817 {
818 case TOP_POINT_LIST:
819 pState->pfnProcessPrims = ClipPoints;
820 pfnBinner = BinPoints;
821 break;
822 case TOP_LINE_LIST:
823 case TOP_LINE_STRIP:
824 case TOP_LINE_LOOP:
825 case TOP_LINE_LIST_ADJ:
826 case TOP_LISTSTRIP_ADJ:
827 pState->pfnProcessPrims = ClipLines;
828 pfnBinner = BinLines;
829 break;
830 default:
831 pState->pfnProcessPrims = ClipTriangles;
832 pfnBinner = GetBinTrianglesFunc((rastState.conservativeRast > 0));
833 break;
834 };
835
836 // disable clipper if viewport transform is disabled
837 if (pState->state.frontendState.vpTransformDisable)
838 {
839 pState->pfnProcessPrims = pfnBinner;
840 }
841
842 if ((pState->state.psState.pfnPixelShader == nullptr) &&
843 (pState->state.depthStencilState.depthTestEnable == FALSE) &&
844 (pState->state.depthStencilState.depthWriteEnable == FALSE) &&
845 (pState->state.depthStencilState.stencilTestEnable == FALSE) &&
846 (pState->state.depthStencilState.stencilWriteEnable == FALSE) &&
847 (pState->state.backendState.numAttributes == 0))
848 {
849 pState->pfnProcessPrims = nullptr;
850 }
851
852 if (pState->state.soState.rasterizerDisable == true)
853 {
854 pState->pfnProcessPrims = nullptr;
855 }
856
857 // set up the frontend attribute count
858 pState->state.feNumAttributes = 0;
859 const SWR_BACKEND_STATE& backendState = pState->state.backendState;
860 if (backendState.swizzleEnable)
861 {
862 // attribute swizzling is enabled, iterate over the map and record the max attribute used
863 for (uint32_t i = 0; i < backendState.numAttributes; ++i)
864 {
865 pState->state.feNumAttributes = std::max(pState->state.feNumAttributes, (uint32_t)backendState.swizzleMap[i].sourceAttrib + 1);
866 }
867 }
868 else
869 {
870 pState->state.feNumAttributes = pState->state.backendState.numAttributes;
871 }
872
873 if (pState->state.soState.soEnable)
874 {
875 uint32_t streamMasks = 0;
876 for (uint32_t i = 0; i < 4; ++i)
877 {
878 streamMasks |= pState->state.soState.streamMasks[i];
879 }
880
881 DWORD maxAttrib;
882 if (_BitScanReverse(&maxAttrib, streamMasks))
883 {
884 pState->state.feNumAttributes = std::max(pState->state.feNumAttributes, (uint32_t)(maxAttrib + 1));
885 }
886 }
887
888 // complicated logic to test for cases where we don't need backing hottile memory for a draw
889 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
890 pState->state.depthHottileEnable = ((!(pState->state.depthStencilState.depthTestEnable &&
891 !pState->state.depthStencilState.depthWriteEnable &&
892 pState->state.depthStencilState.depthTestFunc == ZFUNC_ALWAYS)) &&
893 (pState->state.depthStencilState.depthTestEnable ||
894 pState->state.depthStencilState.depthWriteEnable)) ? true : false;
895
896 pState->state.stencilHottileEnable = (((!(pState->state.depthStencilState.stencilTestEnable &&
897 !pState->state.depthStencilState.stencilWriteEnable &&
898 pState->state.depthStencilState.stencilTestFunc == ZFUNC_ALWAYS)) ||
899 // for stencil we have to check the double sided state as well
900 (!(pState->state.depthStencilState.doubleSidedStencilTestEnable &&
901 !pState->state.depthStencilState.stencilWriteEnable &&
902 pState->state.depthStencilState.backfaceStencilTestFunc == ZFUNC_ALWAYS))) &&
903 (pState->state.depthStencilState.stencilTestEnable ||
904 pState->state.depthStencilState.stencilWriteEnable)) ? true : false;
905
906 uint32_t numRTs = pState->state.psState.numRenderTargets;
907 pState->state.colorHottileEnable = 0;
908 if (psState.pfnPixelShader != nullptr)
909 {
910 for (uint32_t rt = 0; rt < numRTs; ++rt)
911 {
912 pState->state.colorHottileEnable |=
913 (!pState->state.blendState.renderTarget[rt].writeDisableAlpha ||
914 !pState->state.blendState.renderTarget[rt].writeDisableRed ||
915 !pState->state.blendState.renderTarget[rt].writeDisableGreen ||
916 !pState->state.blendState.renderTarget[rt].writeDisableBlue) ? (1 << rt) : 0;
917 }
918 }
919
920 // Setup depth quantization function
921 if (pState->state.depthHottileEnable)
922 {
923 switch (pState->state.rastState.depthFormat)
924 {
925 case R32_FLOAT_X8X24_TYPELESS: pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT_X8X24_TYPELESS > ; break;
926 case R32_FLOAT: pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ; break;
927 case R24_UNORM_X8_TYPELESS: pState->state.pfnQuantizeDepth = QuantizeDepth < R24_UNORM_X8_TYPELESS > ; break;
928 case R16_UNORM: pState->state.pfnQuantizeDepth = QuantizeDepth < R16_UNORM > ; break;
929 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
930 pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ;
931 }
932 }
933 else
934 {
935 // set up pass-through quantize if depth isn't enabled
936 pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ;
937 }
938 }
939
940 //////////////////////////////////////////////////////////////////////////
941 /// @brief InitDraw
942 /// @param pDC - Draw context to initialize for this draw.
943 void InitDraw(
944 DRAW_CONTEXT *pDC,
945 bool isSplitDraw)
946 {
947 // We don't need to re-setup the scissors/pipeline state again for split draw.
948 if (isSplitDraw == false)
949 {
950 SetupMacroTileScissors(pDC);
951 SetupPipeline(pDC);
952 }
953 }
954
955 //////////////////////////////////////////////////////////////////////////
956 /// @brief We can split the draw for certain topologies for better performance.
957 /// @param totalVerts - Total vertices for draw
958 /// @param topology - Topology used for draw
959 uint32_t MaxVertsPerDraw(
960 DRAW_CONTEXT* pDC,
961 uint32_t totalVerts,
962 PRIMITIVE_TOPOLOGY topology)
963 {
964 API_STATE& state = pDC->pState->state;
965
966 uint32_t vertsPerDraw = totalVerts;
967
968 if (state.soState.soEnable)
969 {
970 return totalVerts;
971 }
972
973 switch (topology)
974 {
975 case TOP_POINT_LIST:
976 case TOP_TRIANGLE_LIST:
977 vertsPerDraw = KNOB_MAX_PRIMS_PER_DRAW;
978 break;
979
980 case TOP_PATCHLIST_1:
981 case TOP_PATCHLIST_2:
982 case TOP_PATCHLIST_3:
983 case TOP_PATCHLIST_4:
984 case TOP_PATCHLIST_5:
985 case TOP_PATCHLIST_6:
986 case TOP_PATCHLIST_7:
987 case TOP_PATCHLIST_8:
988 case TOP_PATCHLIST_9:
989 case TOP_PATCHLIST_10:
990 case TOP_PATCHLIST_11:
991 case TOP_PATCHLIST_12:
992 case TOP_PATCHLIST_13:
993 case TOP_PATCHLIST_14:
994 case TOP_PATCHLIST_15:
995 case TOP_PATCHLIST_16:
996 case TOP_PATCHLIST_17:
997 case TOP_PATCHLIST_18:
998 case TOP_PATCHLIST_19:
999 case TOP_PATCHLIST_20:
1000 case TOP_PATCHLIST_21:
1001 case TOP_PATCHLIST_22:
1002 case TOP_PATCHLIST_23:
1003 case TOP_PATCHLIST_24:
1004 case TOP_PATCHLIST_25:
1005 case TOP_PATCHLIST_26:
1006 case TOP_PATCHLIST_27:
1007 case TOP_PATCHLIST_28:
1008 case TOP_PATCHLIST_29:
1009 case TOP_PATCHLIST_30:
1010 case TOP_PATCHLIST_31:
1011 case TOP_PATCHLIST_32:
1012 if (pDC->pState->state.tsState.tsEnable)
1013 {
1014 uint32_t vertsPerPrim = topology - TOP_PATCHLIST_BASE;
1015 vertsPerDraw = vertsPerPrim * KNOB_MAX_TESS_PRIMS_PER_DRAW;
1016 }
1017 break;
1018
1019 // The Primitive Assembly code can only handle 1 RECT at a time.
1020 case TOP_RECT_LIST:
1021 vertsPerDraw = 3;
1022 break;
1023
1024 default:
1025 // We are not splitting up draws for other topologies.
1026 break;
1027 }
1028
1029 return vertsPerDraw;
1030 }
1031
1032
1033 //////////////////////////////////////////////////////////////////////////
1034 /// @brief DrawInstanced
1035 /// @param hContext - Handle passed back from SwrCreateContext
1036 /// @param topology - Specifies topology for draw.
1037 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1038 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1039 /// @param numInstances - How many instances to render.
1040 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1041 void DrawInstanced(
1042 HANDLE hContext,
1043 PRIMITIVE_TOPOLOGY topology,
1044 uint32_t numVertices,
1045 uint32_t startVertex,
1046 uint32_t numInstances = 1,
1047 uint32_t startInstance = 0)
1048 {
1049 if (KNOB_TOSS_DRAW)
1050 {
1051 return;
1052 }
1053
1054 RDTSC_START(APIDraw);
1055
1056 SWR_CONTEXT *pContext = GetContext(hContext);
1057 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1058
1059 uint32_t maxVertsPerDraw = MaxVertsPerDraw(pDC, numVertices, topology);
1060 uint32_t primsPerDraw = GetNumPrims(topology, maxVertsPerDraw);
1061 uint32_t remainingVerts = numVertices;
1062
1063 API_STATE *pState = &pDC->pState->state;
1064 pState->topology = topology;
1065 pState->forceFront = false;
1066
1067 // disable culling for points/lines
1068 uint32_t oldCullMode = pState->rastState.cullMode;
1069 if (topology == TOP_POINT_LIST)
1070 {
1071 pState->rastState.cullMode = SWR_CULLMODE_NONE;
1072 pState->forceFront = true;
1073 }
1074
1075 int draw = 0;
1076 while (remainingVerts)
1077 {
1078 uint32_t numVertsForDraw = (remainingVerts < maxVertsPerDraw) ?
1079 remainingVerts : maxVertsPerDraw;
1080
1081 bool isSplitDraw = (draw > 0) ? true : false;
1082 DRAW_CONTEXT* pDC = GetDrawContext(pContext, isSplitDraw);
1083 InitDraw(pDC, isSplitDraw);
1084
1085 pDC->FeWork.type = DRAW;
1086 pDC->FeWork.pfnWork = GetProcessDrawFunc(
1087 false, // IsIndexed
1088 false, // bEnableCutIndex
1089 pState->tsState.tsEnable,
1090 pState->gsState.gsEnable,
1091 pState->soState.soEnable,
1092 pDC->pState->pfnProcessPrims != nullptr);
1093 pDC->FeWork.desc.draw.numVerts = numVertsForDraw;
1094 pDC->FeWork.desc.draw.startVertex = startVertex;
1095 pDC->FeWork.desc.draw.numInstances = numInstances;
1096 pDC->FeWork.desc.draw.startInstance = startInstance;
1097 pDC->FeWork.desc.draw.startPrimID = draw * primsPerDraw;
1098 pDC->FeWork.desc.draw.startVertexID = draw * maxVertsPerDraw;
1099
1100 pDC->cleanupState = (remainingVerts == numVertsForDraw);
1101
1102 //enqueue DC
1103 QueueDraw(pContext);
1104
1105 remainingVerts -= numVertsForDraw;
1106 draw++;
1107 }
1108
1109 // restore culling state
1110 pDC = GetDrawContext(pContext);
1111 pDC->pState->state.rastState.cullMode = oldCullMode;
1112
1113 RDTSC_STOP(APIDraw, numVertices * numInstances, 0);
1114 }
1115
1116 //////////////////////////////////////////////////////////////////////////
1117 /// @brief SwrDraw
1118 /// @param hContext - Handle passed back from SwrCreateContext
1119 /// @param topology - Specifies topology for draw.
1120 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1121 /// @param primCount - Number of vertices.
1122 void SwrDraw(
1123 HANDLE hContext,
1124 PRIMITIVE_TOPOLOGY topology,
1125 uint32_t startVertex,
1126 uint32_t numVertices)
1127 {
1128 DrawInstanced(hContext, topology, numVertices, startVertex);
1129 }
1130
1131 //////////////////////////////////////////////////////////////////////////
1132 /// @brief SwrDrawInstanced
1133 /// @param hContext - Handle passed back from SwrCreateContext
1134 /// @param topology - Specifies topology for draw.
1135 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1136 /// @param numInstances - How many instances to render.
1137 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1138 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1139 void SwrDrawInstanced(
1140 HANDLE hContext,
1141 PRIMITIVE_TOPOLOGY topology,
1142 uint32_t numVertsPerInstance,
1143 uint32_t numInstances,
1144 uint32_t startVertex,
1145 uint32_t startInstance
1146 )
1147 {
1148 DrawInstanced(hContext, topology, numVertsPerInstance, startVertex, numInstances, startInstance);
1149 }
1150
1151 //////////////////////////////////////////////////////////////////////////
1152 /// @brief DrawIndexedInstanced
1153 /// @param hContext - Handle passed back from SwrCreateContext
1154 /// @param topology - Specifies topology for draw.
1155 /// @param numIndices - Number of indices to read sequentially from index buffer.
1156 /// @param indexOffset - Starting index into index buffer.
1157 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1158 /// @param numInstances - Number of instances to render.
1159 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1160 void DrawIndexedInstance(
1161 HANDLE hContext,
1162 PRIMITIVE_TOPOLOGY topology,
1163 uint32_t numIndices,
1164 uint32_t indexOffset,
1165 int32_t baseVertex,
1166 uint32_t numInstances = 1,
1167 uint32_t startInstance = 0)
1168 {
1169 if (KNOB_TOSS_DRAW)
1170 {
1171 return;
1172 }
1173
1174 RDTSC_START(APIDrawIndexed);
1175
1176 SWR_CONTEXT *pContext = GetContext(hContext);
1177 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1178 API_STATE* pState = &pDC->pState->state;
1179
1180 uint32_t maxIndicesPerDraw = MaxVertsPerDraw(pDC, numIndices, topology);
1181 uint32_t primsPerDraw = GetNumPrims(topology, maxIndicesPerDraw);
1182 uint32_t remainingIndices = numIndices;
1183
1184 uint32_t indexSize = 0;
1185 switch (pState->indexBuffer.format)
1186 {
1187 case R32_UINT: indexSize = sizeof(uint32_t); break;
1188 case R16_UINT: indexSize = sizeof(uint16_t); break;
1189 case R8_UINT: indexSize = sizeof(uint8_t); break;
1190 default:
1191 SWR_ASSERT(0);
1192 }
1193
1194 int draw = 0;
1195 uint8_t *pIB = (uint8_t*)pState->indexBuffer.pIndices;
1196 pIB += (uint64_t)indexOffset * (uint64_t)indexSize;
1197
1198 pState->topology = topology;
1199 pState->forceFront = false;
1200
1201 // disable culling for points/lines
1202 uint32_t oldCullMode = pState->rastState.cullMode;
1203 if (topology == TOP_POINT_LIST)
1204 {
1205 pState->rastState.cullMode = SWR_CULLMODE_NONE;
1206 pState->forceFront = true;
1207 }
1208
1209 while (remainingIndices)
1210 {
1211 uint32_t numIndicesForDraw = (remainingIndices < maxIndicesPerDraw) ?
1212 remainingIndices : maxIndicesPerDraw;
1213
1214 // When breaking up draw, we need to obtain new draw context for each iteration.
1215 bool isSplitDraw = (draw > 0) ? true : false;
1216 pDC = GetDrawContext(pContext, isSplitDraw);
1217 InitDraw(pDC, isSplitDraw);
1218
1219 pDC->FeWork.type = DRAW;
1220 pDC->FeWork.pfnWork = GetProcessDrawFunc(
1221 true, // IsIndexed
1222 pState->frontendState.bEnableCutIndex,
1223 pState->tsState.tsEnable,
1224 pState->gsState.gsEnable,
1225 pState->soState.soEnable,
1226 pDC->pState->pfnProcessPrims != nullptr);
1227 pDC->FeWork.desc.draw.pDC = pDC;
1228 pDC->FeWork.desc.draw.numIndices = numIndicesForDraw;
1229 pDC->FeWork.desc.draw.pIB = (int*)pIB;
1230 pDC->FeWork.desc.draw.type = pDC->pState->state.indexBuffer.format;
1231
1232 pDC->FeWork.desc.draw.numInstances = numInstances;
1233 pDC->FeWork.desc.draw.startInstance = startInstance;
1234 pDC->FeWork.desc.draw.baseVertex = baseVertex;
1235 pDC->FeWork.desc.draw.startPrimID = draw * primsPerDraw;
1236
1237 pDC->cleanupState = (remainingIndices == numIndicesForDraw);
1238
1239 //enqueue DC
1240 QueueDraw(pContext);
1241
1242 pIB += maxIndicesPerDraw * indexSize;
1243 remainingIndices -= numIndicesForDraw;
1244 draw++;
1245 }
1246
1247 // restore culling state
1248 pDC = GetDrawContext(pContext);
1249 pDC->pState->state.rastState.cullMode = oldCullMode;
1250
1251 RDTSC_STOP(APIDrawIndexed, numIndices * numInstances, 0);
1252 }
1253
1254
1255 //////////////////////////////////////////////////////////////////////////
1256 /// @brief DrawIndexed
1257 /// @param hContext - Handle passed back from SwrCreateContext
1258 /// @param topology - Specifies topology for draw.
1259 /// @param numIndices - Number of indices to read sequentially from index buffer.
1260 /// @param indexOffset - Starting index into index buffer.
1261 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1262 void SwrDrawIndexed(
1263 HANDLE hContext,
1264 PRIMITIVE_TOPOLOGY topology,
1265 uint32_t numIndices,
1266 uint32_t indexOffset,
1267 int32_t baseVertex
1268 )
1269 {
1270 DrawIndexedInstance(hContext, topology, numIndices, indexOffset, baseVertex);
1271 }
1272
1273 //////////////////////////////////////////////////////////////////////////
1274 /// @brief SwrDrawIndexedInstanced
1275 /// @param hContext - Handle passed back from SwrCreateContext
1276 /// @param topology - Specifies topology for draw.
1277 /// @param numIndices - Number of indices to read sequentially from index buffer.
1278 /// @param numInstances - Number of instances to render.
1279 /// @param indexOffset - Starting index into index buffer.
1280 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1281 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1282 void SwrDrawIndexedInstanced(
1283 HANDLE hContext,
1284 PRIMITIVE_TOPOLOGY topology,
1285 uint32_t numIndices,
1286 uint32_t numInstances,
1287 uint32_t indexOffset,
1288 int32_t baseVertex,
1289 uint32_t startInstance)
1290 {
1291 DrawIndexedInstance(hContext, topology, numIndices, indexOffset, baseVertex, numInstances, startInstance);
1292 }
1293
1294 //////////////////////////////////////////////////////////////////////////
1295 /// @brief SwrInvalidateTiles
1296 /// @param hContext - Handle passed back from SwrCreateContext
1297 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1298 /// @param invalidateRect - The pixel-coordinate rectangle to invalidate. This will be expanded to
1299 /// be hottile size-aligned.
1300 void SWR_API SwrInvalidateTiles(
1301 HANDLE hContext,
1302 uint32_t attachmentMask,
1303 const SWR_RECT& invalidateRect)
1304 {
1305 if (KNOB_TOSS_DRAW)
1306 {
1307 return;
1308 }
1309
1310 SWR_CONTEXT *pContext = GetContext(hContext);
1311 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1312
1313 pDC->FeWork.type = DISCARDINVALIDATETILES;
1314 pDC->FeWork.pfnWork = ProcessDiscardInvalidateTiles;
1315 pDC->FeWork.desc.discardInvalidateTiles.attachmentMask = attachmentMask;
1316 pDC->FeWork.desc.discardInvalidateTiles.rect = invalidateRect;
1317 pDC->FeWork.desc.discardInvalidateTiles.rect &= g_MaxScissorRect;
1318 pDC->FeWork.desc.discardInvalidateTiles.newTileState = SWR_TILE_INVALID;
1319 pDC->FeWork.desc.discardInvalidateTiles.createNewTiles = false;
1320 pDC->FeWork.desc.discardInvalidateTiles.fullTilesOnly = false;
1321
1322 //enqueue
1323 QueueDraw(pContext);
1324 }
1325
1326 //////////////////////////////////////////////////////////////////////////
1327 /// @brief SwrDiscardRect
1328 /// @param hContext - Handle passed back from SwrCreateContext
1329 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1330 /// @param rect - The pixel-coordinate rectangle to discard. Only fully-covered hottiles will be
1331 /// discarded.
1332 void SWR_API SwrDiscardRect(
1333 HANDLE hContext,
1334 uint32_t attachmentMask,
1335 const SWR_RECT& rect)
1336 {
1337 if (KNOB_TOSS_DRAW)
1338 {
1339 return;
1340 }
1341
1342 SWR_CONTEXT *pContext = GetContext(hContext);
1343 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1344
1345 // Queue a load to the hottile
1346 pDC->FeWork.type = DISCARDINVALIDATETILES;
1347 pDC->FeWork.pfnWork = ProcessDiscardInvalidateTiles;
1348 pDC->FeWork.desc.discardInvalidateTiles.attachmentMask = attachmentMask;
1349 pDC->FeWork.desc.discardInvalidateTiles.rect = rect;
1350 pDC->FeWork.desc.discardInvalidateTiles.rect &= g_MaxScissorRect;
1351 pDC->FeWork.desc.discardInvalidateTiles.newTileState = SWR_TILE_RESOLVED;
1352 pDC->FeWork.desc.discardInvalidateTiles.createNewTiles = true;
1353 pDC->FeWork.desc.discardInvalidateTiles.fullTilesOnly = true;
1354
1355 //enqueue
1356 QueueDraw(pContext);
1357 }
1358
1359 //////////////////////////////////////////////////////////////////////////
1360 /// @brief SwrDispatch
1361 /// @param hContext - Handle passed back from SwrCreateContext
1362 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1363 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1364 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1365 void SwrDispatch(
1366 HANDLE hContext,
1367 uint32_t threadGroupCountX,
1368 uint32_t threadGroupCountY,
1369 uint32_t threadGroupCountZ)
1370 {
1371 if (KNOB_TOSS_DRAW)
1372 {
1373 return;
1374 }
1375
1376 RDTSC_START(APIDispatch);
1377 SWR_CONTEXT *pContext = GetContext(hContext);
1378 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1379
1380 pDC->isCompute = true; // This is a compute context.
1381
1382 COMPUTE_DESC* pTaskData = (COMPUTE_DESC*)pDC->pArena->AllocAligned(sizeof(COMPUTE_DESC), 64);
1383
1384 pTaskData->threadGroupCountX = threadGroupCountX;
1385 pTaskData->threadGroupCountY = threadGroupCountY;
1386 pTaskData->threadGroupCountZ = threadGroupCountZ;
1387
1388 uint32_t totalThreadGroups = threadGroupCountX * threadGroupCountY * threadGroupCountZ;
1389 uint32_t dcIndex = pDC->drawId % KNOB_MAX_DRAWS_IN_FLIGHT;
1390 pDC->pDispatch = &pContext->pDispatchQueueArray[dcIndex];
1391 pDC->pDispatch->initialize(totalThreadGroups, pTaskData);
1392
1393 QueueDispatch(pContext);
1394 RDTSC_STOP(APIDispatch, threadGroupCountX * threadGroupCountY * threadGroupCountZ, 0);
1395 }
1396
1397 // Deswizzles, converts and stores current contents of the hot tiles to surface
1398 // described by pState
1399 void SWR_API SwrStoreTiles(
1400 HANDLE hContext,
1401 SWR_RENDERTARGET_ATTACHMENT attachment,
1402 SWR_TILE_STATE postStoreTileState,
1403 const SWR_RECT& storeRect)
1404 {
1405 if (KNOB_TOSS_DRAW)
1406 {
1407 return;
1408 }
1409
1410 RDTSC_START(APIStoreTiles);
1411
1412 SWR_CONTEXT *pContext = GetContext(hContext);
1413 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1414
1415 pDC->FeWork.type = STORETILES;
1416 pDC->FeWork.pfnWork = ProcessStoreTiles;
1417 pDC->FeWork.desc.storeTiles.attachment = attachment;
1418 pDC->FeWork.desc.storeTiles.postStoreTileState = postStoreTileState;
1419 pDC->FeWork.desc.storeTiles.rect = storeRect;
1420 pDC->FeWork.desc.storeTiles.rect &= g_MaxScissorRect;
1421
1422 //enqueue
1423 QueueDraw(pContext);
1424
1425 RDTSC_STOP(APIStoreTiles, 0, 0);
1426 }
1427
1428 //////////////////////////////////////////////////////////////////////////
1429 /// @brief SwrClearRenderTarget - Clear attached render targets / depth / stencil
1430 /// @param hContext - Handle passed back from SwrCreateContext
1431 /// @param clearMask - combination of SWR_CLEAR_COLOR / SWR_CLEAR_DEPTH / SWR_CLEAR_STENCIL flags (or SWR_CLEAR_NONE)
1432 /// @param clearColor - color use for clearing render targets
1433 /// @param z - depth value use for clearing depth buffer
1434 /// @param stencil - stencil value used for clearing stencil buffer
1435 /// @param clearRect - The pixel-coordinate rectangle to clear in all cleared buffers
1436 void SWR_API SwrClearRenderTarget(
1437 HANDLE hContext,
1438 uint32_t clearMask,
1439 const float clearColor[4],
1440 float z,
1441 uint8_t stencil,
1442 const SWR_RECT& clearRect)
1443 {
1444 if (KNOB_TOSS_DRAW)
1445 {
1446 return;
1447 }
1448
1449 RDTSC_START(APIClearRenderTarget);
1450
1451 SWR_CONTEXT *pContext = GetContext(hContext);
1452 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1453
1454 CLEAR_FLAGS flags;
1455 flags.bits = 0;
1456 flags.mask = clearMask;
1457
1458 pDC->FeWork.type = CLEAR;
1459 pDC->FeWork.pfnWork = ProcessClear;
1460 pDC->FeWork.desc.clear.rect = clearRect;
1461 pDC->FeWork.desc.clear.rect &= g_MaxScissorRect;
1462 pDC->FeWork.desc.clear.flags = flags;
1463 pDC->FeWork.desc.clear.clearDepth = z;
1464 pDC->FeWork.desc.clear.clearRTColor[0] = clearColor[0];
1465 pDC->FeWork.desc.clear.clearRTColor[1] = clearColor[1];
1466 pDC->FeWork.desc.clear.clearRTColor[2] = clearColor[2];
1467 pDC->FeWork.desc.clear.clearRTColor[3] = clearColor[3];
1468 pDC->FeWork.desc.clear.clearStencil = stencil;
1469
1470 // enqueue draw
1471 QueueDraw(pContext);
1472
1473 RDTSC_STOP(APIClearRenderTarget, 0, pDC->drawId);
1474 }
1475
1476 //////////////////////////////////////////////////////////////////////////
1477 /// @brief Returns a pointer to the private context state for the current
1478 /// draw operation. This is used for external componets such as the
1479 /// sampler.
1480 /// SWR is responsible for the allocation of the private context state.
1481 /// @param hContext - Handle passed back from SwrCreateContext
1482 VOID* SwrGetPrivateContextState(
1483 HANDLE hContext)
1484 {
1485 SWR_CONTEXT* pContext = GetContext(hContext);
1486 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1487 DRAW_STATE* pState = pDC->pState;
1488
1489 if (pState->pPrivateState == nullptr)
1490 {
1491 pState->pPrivateState = pState->pArena->AllocAligned(pContext->privateStateSize, KNOB_SIMD_WIDTH*sizeof(float));
1492 }
1493
1494 return pState->pPrivateState;
1495 }
1496
1497 //////////////////////////////////////////////////////////////////////////
1498 /// @brief Clients can use this to allocate memory for draw/dispatch
1499 /// operations. The memory will automatically be freed once operation
1500 /// has completed. Client can use this to allocate binding tables,
1501 /// etc. needed for shader execution.
1502 /// @param hContext - Handle passed back from SwrCreateContext
1503 /// @param size - Size of allocation
1504 /// @param align - Alignment needed for allocation.
1505 VOID* SwrAllocDrawContextMemory(
1506 HANDLE hContext,
1507 uint32_t size,
1508 uint32_t align)
1509 {
1510 SWR_CONTEXT* pContext = GetContext(hContext);
1511 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1512
1513 return pDC->pState->pArena->AllocAligned(size, align);
1514 }
1515
1516 //////////////////////////////////////////////////////////////////////////
1517 /// @brief Enables stats counting
1518 /// @param hContext - Handle passed back from SwrCreateContext
1519 /// @param enable - If true then counts are incremented.
1520 void SwrEnableStats(
1521 HANDLE hContext,
1522 bool enable)
1523 {
1524 SWR_CONTEXT *pContext = GetContext(hContext);
1525 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1526
1527 pDC->pState->state.enableStats = enable;
1528 }
1529
1530 //////////////////////////////////////////////////////////////////////////
1531 /// @brief Mark end of frame - used for performance profiling
1532 /// @param hContext - Handle passed back from SwrCreateContext
1533 void SWR_API SwrEndFrame(
1534 HANDLE hContext)
1535 {
1536 RDTSC_ENDFRAME();
1537 SWR_CONTEXT *pContext = GetContext(hContext);
1538 pContext->frameCount++;
1539 }