1 // SwiftShader Software Renderer
3 // Copyright(c) 2005-2012 TransGaming Inc.
5 // All rights reserved. No part of this software may be copied, distributed, transmitted,
6 // transcribed, stored in a retrieval system, translated into any human or computer
7 // language by any means, or disclosed to third parties without the explicit written
8 // agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
9 // or implied, including but not limited to any patent rights, are granted to you.
12 #include "Renderer.hpp"
14 #include "Clipper.hpp"
16 #include "FrameBuffer.hpp"
18 #include "Surface.hpp"
20 #include "Primitive.hpp"
21 #include "Polygon.hpp"
22 #include "SwiftConfig.hpp"
23 #include "MutexLock.hpp"
26 #include "Resource.hpp"
27 #include "Constants.hpp"
29 #include "Reactor/Reactor.hpp"
33 bool disableServer = true;
36 unsigned int minPrimitives = 1;
37 unsigned int maxPrimitives = 1 << 21;
42 extern bool halfIntegerCoordinates; // Pixel centers are not at integer coordinates
43 extern bool symmetricNormalizedDepth; // [-1, 1] instead of [0, 1]
44 extern bool booleanFaceRegister;
45 extern bool fullPixelPositionRegister;
46 extern bool leadingVertexFirst; // Flat shading uses first vertex, else last
47 extern bool secondaryColor; // Specular lighting is applied after texturing
49 extern bool forceWindowed;
50 extern bool complementaryDepthBuffer;
51 extern bool postBlendSRGB;
52 extern bool exactColorRounding;
53 extern TransparencyAntialiasing transparencyAntialiasing;
54 extern bool forceClearRegisters;
56 extern bool precacheVertex;
57 extern bool precacheSetup;
58 extern bool precachePixel;
65 TranscendentalPrecision logPrecision = ACCURATE;
66 TranscendentalPrecision expPrecision = ACCURATE;
67 TranscendentalPrecision rcpPrecision = ACCURATE;
68 TranscendentalPrecision rsqPrecision = ACCURATE;
69 bool perspectiveCorrection = true;
81 vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
85 psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
91 data = (DrawData*)allocate(sizeof(DrawData));
92 data->constants = &constants;
102 Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), context(context), viewport()
104 sw::halfIntegerCoordinates = conventions.halfIntegerCoordinates;
105 sw::symmetricNormalizedDepth = conventions.symmetricNormalizedDepth;
106 sw::booleanFaceRegister = conventions.booleanFaceRegister;
107 sw::fullPixelPositionRegister = conventions.fullPixelPositionRegister;
108 sw::leadingVertexFirst = conventions.leadingVertexFirst;
109 sw::secondaryColor = conventions.secondaryColor;
110 sw::exactColorRounding = exactColorRounding;
112 setRenderTarget(0, 0);
113 clipper = new Clipper();
115 updateViewMatrix = true;
116 updateBaseMatrix = true;
117 updateProjectionMatrix = true;
118 updateClipPlanes = true;
124 for(int i = 0; i < 16; i++)
134 resumeApp = new Event();
142 for(int i = 0; i < 16; i++)
144 triangleBatch[i] = 0;
145 primitiveBatch[i] = 0;
148 for(int draw = 0; draw < DRAW_COUNT; draw++)
150 drawCall[draw] = new DrawCall();
151 drawList[draw] = drawCall[draw];
154 for(int unit = 0; unit < 16; unit++)
156 primitiveProgress[unit].init();
159 for(int cluster = 0; cluster < 16; cluster++)
161 pixelProgress[cluster].init();
166 swiftConfig = new SwiftConfig(disableServer);
167 updateConfiguration(true);
169 sync = new Resource(0);
172 Renderer::~Renderer()
182 for(int draw = 0; draw < DRAW_COUNT; draw++)
184 delete drawCall[draw];
190 void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
192 blitter.clear(pixel, format, dest, dRect, rgbaMask);
195 void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter)
197 blitter.blit(source, sRect, dest, dRect, filter);
200 void Renderer::blit3D(Surface *source, Surface *dest)
202 blitter.blit3D(source, dest);
205 void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
208 if(count < minPrimitives || count > maxPrimitives)
214 context->drawType = drawType;
216 updateConfiguration();
219 int ss = context->getSuperSampleCount();
220 int ms = context->getMultiSampleCount();
222 for(int q = 0; q < ss; q++)
224 unsigned int oldMultiSampleMask = context->multiSampleMask;
225 context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
227 if(!context->multiSampleMask)
232 sync->lock(sw::PRIVATE);
234 Routine *vertexRoutine;
235 Routine *setupRoutine;
236 Routine *pixelRoutine;
238 if(update || oldMultiSampleMask != context->multiSampleMask)
240 vertexState = VertexProcessor::update();
241 setupState = SetupProcessor::update();
242 pixelState = PixelProcessor::update();
244 vertexRoutine = VertexProcessor::routine(vertexState);
245 setupRoutine = SetupProcessor::routine(setupState);
246 pixelRoutine = PixelProcessor::routine(pixelState);
249 int batch = batchSize / ms;
251 int (*setupPrimitives)(Renderer *renderer, int batch, int count);
253 if(context->isDrawTriangle())
255 switch(context->fillMode)
258 setupPrimitives = setupSolidTriangles;
261 setupPrimitives = setupWireframeTriangle;
265 setupPrimitives = setupVertexTriangle;
268 default: ASSERT(false);
271 else if(context->isDrawLine())
273 setupPrimitives = setupLines;
277 setupPrimitives = setupPoints;
284 for(int i = 0; i < DRAW_COUNT; i++)
286 if(drawCall[i]->references == -1)
289 drawList[nextDraw % DRAW_COUNT] = draw;
302 DrawData *data = draw->data;
304 if(queries.size() != 0)
306 draw->queries = new std::list<Query*>();
307 bool includePrimitivesWrittenQueries = vertexState.transformFeedbackQueryEnabled && vertexState.transformFeedbackEnabled;
308 for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
311 if(includePrimitivesWrittenQueries || (q->type != Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN))
313 atomicIncrement(&(q->reference));
314 draw->queries->push_back(q);
319 draw->drawType = drawType;
320 draw->batchSize = batch;
322 vertexRoutine->bind();
323 setupRoutine->bind();
324 pixelRoutine->bind();
326 draw->vertexRoutine = vertexRoutine;
327 draw->setupRoutine = setupRoutine;
328 draw->pixelRoutine = pixelRoutine;
329 draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
330 draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
331 draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
332 draw->setupPrimitives = setupPrimitives;
333 draw->setupState = setupState;
335 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
337 draw->vertexStream[i] = context->input[i].resource;
338 data->input[i] = context->input[i].buffer;
339 data->stride[i] = context->input[i].stride;
341 if(draw->vertexStream[i])
343 draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
347 if(context->indexBuffer)
349 data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
352 draw->indexBuffer = context->indexBuffer;
354 for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
356 draw->texture[sampler] = 0;
359 for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
361 if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
363 draw->texture[sampler] = context->texture[sampler];
364 draw->texture[sampler]->lock(PUBLIC, isReadWriteTexture(sampler) ? MANAGED : PRIVATE); // If the texure is both read and written, use the same read/write lock as render targets
366 data->mipmap[sampler] = context->sampler[sampler].getTextureData();
370 if(context->pixelShader)
372 if(draw->psDirtyConstF)
374 memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
375 memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
376 draw->psDirtyConstF = 0;
379 if(draw->psDirtyConstI)
381 memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
382 draw->psDirtyConstI = 0;
385 if(draw->psDirtyConstB)
387 memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
388 draw->psDirtyConstB = 0;
391 PixelProcessor::lockUniformBuffers(data->ps.u);
394 if(context->pixelShaderVersion() <= 0x0104)
396 for(int stage = 0; stage < 8; stage++)
398 if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
400 data->textureStage[stage] = context->textureStage[stage].uniforms;
406 if(context->vertexShader)
408 if(context->vertexShader->getVersion() >= 0x0300)
410 for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
412 if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
414 draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
415 draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
417 data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
422 if(draw->vsDirtyConstF)
424 memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
425 draw->vsDirtyConstF = 0;
428 if(draw->vsDirtyConstI)
430 memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
431 draw->vsDirtyConstI = 0;
434 if(draw->vsDirtyConstB)
436 memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
437 draw->vsDirtyConstB = 0;
440 if(context->vertexShader->instanceIdDeclared)
442 data->instanceID = context->instanceID;
445 VertexProcessor::lockUniformBuffers(data->vs.u);
451 draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
452 draw->vsDirtyConstI = 16;
453 draw->vsDirtyConstB = 16;
456 if(pixelState.stencilActive)
458 data->stencil[0] = stencil;
459 data->stencil[1] = stencilCCW;
462 if(pixelState.fogActive)
467 if(setupState.isDrawPoint)
472 data->lineWidth = context->lineWidth;
474 data->factor = factor;
476 if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
478 float ref = context->alphaReference * (1.0f / 255.0f);
479 float margin = sw::min(ref, 1.0f - ref);
483 data->a2c0 = replicate(ref - margin * 0.6f);
484 data->a2c1 = replicate(ref - margin * 0.2f);
485 data->a2c2 = replicate(ref + margin * 0.2f);
486 data->a2c3 = replicate(ref + margin * 0.6f);
490 data->a2c0 = replicate(ref - margin * 0.3f);
491 data->a2c1 = replicate(ref + margin * 0.3f);
496 if(pixelState.occlusionEnabled)
498 for(int cluster = 0; cluster < clusterCount; cluster++)
500 data->occlusion[cluster] = 0;
505 for(int cluster = 0; cluster < clusterCount; cluster++)
507 for(int i = 0; i < PERF_TIMERS; i++)
509 data->cycles[i][cluster] = 0;
516 float W = 0.5f * viewport.width;
517 float H = 0.5f * viewport.height;
518 float X0 = viewport.x0 + W;
519 float Y0 = viewport.y0 + H;
520 float N = viewport.minZ;
521 float F = viewport.maxZ;
524 if(context->isDrawTriangle(false))
529 if(complementaryDepthBuffer)
535 static const float X[5][16] = // Fragment offsets
537 {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
538 {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
539 {-0.3000f, +0.1000f, +0.3000f, -0.1000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
540 {+0.1875f, -0.3125f, +0.3125f, -0.4375f, -0.0625f, +0.4375f, +0.0625f, -0.1875f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
541 {+0.2553f, -0.1155f, +0.1661f, -0.1828f, +0.2293f, -0.4132f, -0.1773f, -0.0577f, +0.3891f, -0.4656f, +0.4103f, +0.4248f, -0.2109f, +0.3966f, -0.2664f, -0.3872f} // 16 samples
544 static const float Y[5][16] = // Fragment offsets
546 {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
547 {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
548 {-0.1000f, -0.3000f, +0.1000f, +0.3000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
549 {-0.4375f, -0.3125f, -0.1875f, -0.0625f, +0.0625f, +0.1875f, +0.3125f, +0.4375f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
550 {-0.4503f, +0.1883f, +0.3684f, -0.4668f, -0.0690f, -0.1315f, +0.4999f, +0.0728f, +0.1070f, -0.3086f, +0.3725f, -0.1547f, -0.1102f, -0.3588f, +0.1789f, +0.0269f} // 16 samples
553 int s = sw::log2(ss);
555 data->Wx16 = replicate(W * 16);
556 data->Hx16 = replicate(H * 16);
557 data->X0x16 = replicate(X0 * 16 - 8);
558 data->Y0x16 = replicate(Y0 * 16 - 8);
559 data->XXXX = replicate(X[s][q] / W);
560 data->YYYY = replicate(Y[s][q] / H);
561 data->halfPixelX = replicate(0.5f / W);
562 data->halfPixelY = replicate(0.5f / H);
563 data->viewportHeight = abs(viewport.height);
564 data->slopeDepthBias = slopeDepthBias;
565 data->depthRange = Z;
567 draw->clipFlags = clipFlags;
571 if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
572 if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
573 if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
574 if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
575 if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
576 if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
582 for(int index = 0; index < RENDERTARGETS; index++)
584 draw->renderTarget[index] = context->renderTarget[index];
586 if(draw->renderTarget[index])
588 data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
589 data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
590 data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
594 draw->depthBuffer = context->depthBuffer;
595 draw->stencilBuffer = context->stencilBuffer;
597 if(draw->depthBuffer)
599 data->depthBuffer = (float*)context->depthBuffer->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
600 data->depthPitchB = context->depthBuffer->getInternalPitchB();
601 data->depthSliceB = context->depthBuffer->getInternalSliceB();
604 if(draw->stencilBuffer)
606 data->stencilBuffer = (unsigned char*)context->stencilBuffer->lockStencil(q * ms, MANAGED);
607 data->stencilPitchB = context->stencilBuffer->getStencilPitchB();
608 data->stencilSliceB = context->stencilBuffer->getStencilSliceB();
614 data->scissorX0 = scissor.x0;
615 data->scissorX1 = scissor.x1;
616 data->scissorY0 = scissor.y0;
617 data->scissorY1 = scissor.y1;
623 draw->references = (count + batch - 1) / batch;
625 schedulerMutex.lock();
627 schedulerMutex.unlock();
636 task[0].type = Task::RESUME;
641 else // Use main thread for draw execution
644 task[0].type = Task::RESUME;
651 void Renderer::threadFunction(void *parameters)
653 Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
654 int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
656 if(logPrecision < IEEE)
658 CPUID::setFlushToZero(true);
659 CPUID::setDenormalsAreZero(true);
662 renderer->threadLoop(threadIndex);
665 void Renderer::threadLoop(int threadIndex)
669 taskLoop(threadIndex);
671 suspend[threadIndex]->signal();
672 resume[threadIndex]->wait();
676 void Renderer::taskLoop(int threadIndex)
678 while(task[threadIndex].type != Task::SUSPEND)
680 scheduleTask(threadIndex);
681 executeTask(threadIndex);
685 void Renderer::findAvailableTasks()
688 for(int cluster = 0; cluster < clusterCount; cluster++)
690 if(!pixelProgress[cluster].executing)
692 for(int unit = 0; unit < unitCount; unit++)
694 if(primitiveProgress[unit].references > 0) // Contains processed primitives
696 if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
698 if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
700 Task &task = taskQueue[qHead];
701 task.type = Task::PIXELS;
702 task.primitiveUnit = unit;
703 task.pixelCluster = cluster;
705 pixelProgress[cluster].executing = true;
707 // Commit to the task queue
708 qHead = (qHead + 1) % 32;
719 // Find primitive tasks
720 if(currentDraw == nextDraw)
722 return; // No more primitives to process
725 for(int unit = 0; unit < unitCount; unit++)
727 DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
729 if(draw->primitive >= draw->count)
733 if(currentDraw == nextDraw)
735 return; // No more primitives to process
738 draw = drawList[currentDraw % DRAW_COUNT];
741 if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
743 int primitive = draw->primitive;
744 int count = draw->count;
745 int batch = draw->batchSize;
747 primitiveProgress[unit].drawCall = currentDraw;
748 primitiveProgress[unit].firstPrimitive = primitive;
749 primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
751 draw->primitive += batch;
753 Task &task = taskQueue[qHead];
754 task.type = Task::PRIMITIVES;
755 task.primitiveUnit = unit;
757 primitiveProgress[unit].references = -1;
759 // Commit to the task queue
760 qHead = (qHead + 1) % 32;
766 void Renderer::scheduleTask(int threadIndex)
768 schedulerMutex.lock();
770 if((int)qSize < threadCount - threadsAwake + 1)
772 findAvailableTasks();
777 task[threadIndex] = taskQueue[(qHead - qSize) % 32];
780 if(threadsAwake != threadCount)
782 int wakeup = qSize - threadsAwake + 1;
784 for(int i = 0; i < threadCount && wakeup > 0; i++)
786 if(task[i].type == Task::SUSPEND)
789 task[i].type = Task::RESUME;
800 task[threadIndex].type = Task::SUSPEND;
805 schedulerMutex.unlock();
808 void Renderer::executeTask(int threadIndex)
811 int64_t startTick = Timer::ticks();
814 switch(task[threadIndex].type)
816 case Task::PRIMITIVES:
818 int unit = task[threadIndex].primitiveUnit;
820 int input = primitiveProgress[unit].firstPrimitive;
821 int count = primitiveProgress[unit].primitiveCount;
822 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
823 int (*setupPrimitives)(Renderer *renderer, int batch, int count) = draw->setupPrimitives;
825 processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
828 int64_t time = Timer::ticks();
829 vertexTime[threadIndex] += time - startTick;
833 int visible = draw->setupState.rasterizerDiscard ? 0 : setupPrimitives(this, unit, count);
835 primitiveProgress[unit].visible = visible;
836 primitiveProgress[unit].references = clusterCount;
839 setupTime[threadIndex] += Timer::ticks() - startTick;
845 int unit = task[threadIndex].primitiveUnit;
846 int visible = primitiveProgress[unit].visible;
850 int cluster = task[threadIndex].pixelCluster;
851 Primitive *primitive = primitiveBatch[unit];
852 DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
853 DrawData *data = draw->data;
854 PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
856 pixelRoutine(primitive, visible, cluster, data);
859 finishRendering(task[threadIndex]);
862 pixelTime[threadIndex] += Timer::ticks() - startTick;
875 void Renderer::synchronize()
877 sync->lock(sw::PUBLIC);
881 void Renderer::finishRendering(Task &pixelTask)
883 int unit = pixelTask.primitiveUnit;
884 int cluster = pixelTask.pixelCluster;
886 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
887 DrawData &data = *draw.data;
888 int primitive = primitiveProgress[unit].firstPrimitive;
889 int count = primitiveProgress[unit].primitiveCount;
891 pixelProgress[cluster].processedPrimitives = primitive + count;
893 if(pixelProgress[cluster].processedPrimitives >= draw.count)
895 pixelProgress[cluster].drawCall++;
896 pixelProgress[cluster].processedPrimitives = 0;
899 int ref = atomicDecrement(&primitiveProgress[unit].references);
903 ref = atomicDecrement(&draw.references);
908 for(int cluster = 0; cluster < clusterCount; cluster++)
910 for(int i = 0; i < PERF_TIMERS; i++)
912 profiler.cycles[i] += data.cycles[i][cluster];
919 for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
925 case Query::FRAGMENTS_PASSED:
926 for(int cluster = 0; cluster < clusterCount; cluster++)
928 atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
931 case Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
932 atomicAdd((volatile int*)&query->data, pixelProgress[cluster].processedPrimitives);
938 atomicDecrement(&query->reference);
945 for(int i = 0; i < RENDERTARGETS; i++)
947 if(draw.renderTarget[i])
949 draw.renderTarget[i]->unlockInternal();
955 draw.depthBuffer->unlockInternal();
958 if(draw.stencilBuffer)
960 draw.stencilBuffer->unlockStencil();
963 for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
967 draw.texture[i]->unlock();
971 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
973 if(draw.vertexStream[i])
975 draw.vertexStream[i]->unlock();
981 draw.indexBuffer->unlock();
984 PixelProcessor::unlockUniformBuffers();
985 VertexProcessor::unlockUniformBuffers();
987 draw.vertexRoutine->unbind();
988 draw.setupRoutine->unbind();
989 draw.pixelRoutine->unbind();
993 draw.references = -1;
998 pixelProgress[cluster].executing = false;
1001 void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
1003 Triangle *triangle = triangleBatch[unit];
1004 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1005 DrawData *data = draw->data;
1006 VertexTask *task = vertexTask[thread];
1008 const void *indices = data->indices;
1009 VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
1011 if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
1013 task->vertexCache.clear();
1014 task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
1017 unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
1019 switch(draw->drawType)
1021 case DRAW_POINTLIST:
1023 unsigned int index = start;
1025 for(unsigned int i = 0; i < triangleCount; i++)
1027 batch[i][0] = index;
1028 batch[i][1] = index;
1029 batch[i][2] = index;
1037 unsigned int index = 2 * start;
1039 for(unsigned int i = 0; i < triangleCount; i++)
1041 batch[i][0] = index + 0;
1042 batch[i][1] = index + 1;
1043 batch[i][2] = index + 1;
1049 case DRAW_LINESTRIP:
1051 unsigned int index = start;
1053 for(unsigned int i = 0; i < triangleCount; i++)
1055 batch[i][0] = index + 0;
1056 batch[i][1] = index + 1;
1057 batch[i][2] = index + 1;
1065 unsigned int index = start;
1067 for(unsigned int i = 0; i < triangleCount; i++)
1069 batch[i][0] = (index + 0) % loop;
1070 batch[i][1] = (index + 1) % loop;
1071 batch[i][2] = (index + 1) % loop;
1077 case DRAW_TRIANGLELIST:
1079 unsigned int index = 3 * start;
1081 for(unsigned int i = 0; i < triangleCount; i++)
1083 batch[i][0] = index + 0;
1084 batch[i][1] = index + 1;
1085 batch[i][2] = index + 2;
1091 case DRAW_TRIANGLESTRIP:
1093 unsigned int index = start;
1095 for(unsigned int i = 0; i < triangleCount; i++)
1097 batch[i][0] = index + 0;
1098 batch[i][1] = index + (index & 1) + 1;
1099 batch[i][2] = index + (~index & 1) + 1;
1105 case DRAW_TRIANGLEFAN:
1107 unsigned int index = start;
1109 for(unsigned int i = 0; i < triangleCount; i++)
1111 batch[i][0] = index + 1;
1112 batch[i][1] = index + 2;
1119 case DRAW_INDEXEDPOINTLIST8:
1121 const unsigned char *index = (const unsigned char*)indices + start;
1123 for(unsigned int i = 0; i < triangleCount; i++)
1125 batch[i][0] = *index;
1126 batch[i][1] = *index;
1127 batch[i][2] = *index;
1133 case DRAW_INDEXEDPOINTLIST16:
1135 const unsigned short *index = (const unsigned short*)indices + start;
1137 for(unsigned int i = 0; i < triangleCount; i++)
1139 batch[i][0] = *index;
1140 batch[i][1] = *index;
1141 batch[i][2] = *index;
1147 case DRAW_INDEXEDPOINTLIST32:
1149 const unsigned int *index = (const unsigned int*)indices + start;
1151 for(unsigned int i = 0; i < triangleCount; i++)
1153 batch[i][0] = *index;
1154 batch[i][1] = *index;
1155 batch[i][2] = *index;
1161 case DRAW_INDEXEDLINELIST8:
1163 const unsigned char *index = (const unsigned char*)indices + 2 * start;
1165 for(unsigned int i = 0; i < triangleCount; i++)
1167 batch[i][0] = index[0];
1168 batch[i][1] = index[1];
1169 batch[i][2] = index[1];
1175 case DRAW_INDEXEDLINELIST16:
1177 const unsigned short *index = (const unsigned short*)indices + 2 * start;
1179 for(unsigned int i = 0; i < triangleCount; i++)
1181 batch[i][0] = index[0];
1182 batch[i][1] = index[1];
1183 batch[i][2] = index[1];
1189 case DRAW_INDEXEDLINELIST32:
1191 const unsigned int *index = (const unsigned int*)indices + 2 * start;
1193 for(unsigned int i = 0; i < triangleCount; i++)
1195 batch[i][0] = index[0];
1196 batch[i][1] = index[1];
1197 batch[i][2] = index[1];
1203 case DRAW_INDEXEDLINESTRIP8:
1205 const unsigned char *index = (const unsigned char*)indices + start;
1207 for(unsigned int i = 0; i < triangleCount; i++)
1209 batch[i][0] = index[0];
1210 batch[i][1] = index[1];
1211 batch[i][2] = index[1];
1217 case DRAW_INDEXEDLINESTRIP16:
1219 const unsigned short *index = (const unsigned short*)indices + start;
1221 for(unsigned int i = 0; i < triangleCount; i++)
1223 batch[i][0] = index[0];
1224 batch[i][1] = index[1];
1225 batch[i][2] = index[1];
1231 case DRAW_INDEXEDLINESTRIP32:
1233 const unsigned int *index = (const unsigned int*)indices + start;
1235 for(unsigned int i = 0; i < triangleCount; i++)
1237 batch[i][0] = index[0];
1238 batch[i][1] = index[1];
1239 batch[i][2] = index[1];
1245 case DRAW_INDEXEDLINELOOP8:
1247 const unsigned char *index = (const unsigned char*)indices;
1249 for(unsigned int i = 0; i < triangleCount; i++)
1251 batch[i][0] = index[(start + i + 0) % loop];
1252 batch[i][1] = index[(start + i + 1) % loop];
1253 batch[i][2] = index[(start + i + 1) % loop];
1257 case DRAW_INDEXEDLINELOOP16:
1259 const unsigned short *index = (const unsigned short*)indices;
1261 for(unsigned int i = 0; i < triangleCount; i++)
1263 batch[i][0] = index[(start + i + 0) % loop];
1264 batch[i][1] = index[(start + i + 1) % loop];
1265 batch[i][2] = index[(start + i + 1) % loop];
1269 case DRAW_INDEXEDLINELOOP32:
1271 const unsigned int *index = (const unsigned int*)indices;
1273 for(unsigned int i = 0; i < triangleCount; i++)
1275 batch[i][0] = index[(start + i + 0) % loop];
1276 batch[i][1] = index[(start + i + 1) % loop];
1277 batch[i][2] = index[(start + i + 1) % loop];
1281 case DRAW_INDEXEDTRIANGLELIST8:
1283 const unsigned char *index = (const unsigned char*)indices + 3 * start;
1285 for(unsigned int i = 0; i < triangleCount; i++)
1287 batch[i][0] = index[0];
1288 batch[i][1] = index[1];
1289 batch[i][2] = index[2];
1295 case DRAW_INDEXEDTRIANGLELIST16:
1297 const unsigned short *index = (const unsigned short*)indices + 3 * start;
1299 for(unsigned int i = 0; i < triangleCount; i++)
1301 batch[i][0] = index[0];
1302 batch[i][1] = index[1];
1303 batch[i][2] = index[2];
1309 case DRAW_INDEXEDTRIANGLELIST32:
1311 const unsigned int *index = (const unsigned int*)indices + 3 * start;
1313 for(unsigned int i = 0; i < triangleCount; i++)
1315 batch[i][0] = index[0];
1316 batch[i][1] = index[1];
1317 batch[i][2] = index[2];
1323 case DRAW_INDEXEDTRIANGLESTRIP8:
1325 const unsigned char *index = (const unsigned char*)indices + start;
1327 for(unsigned int i = 0; i < triangleCount; i++)
1329 batch[i][0] = index[0];
1330 batch[i][1] = index[((start + i) & 1) + 1];
1331 batch[i][2] = index[(~(start + i) & 1) + 1];
1337 case DRAW_INDEXEDTRIANGLESTRIP16:
1339 const unsigned short *index = (const unsigned short*)indices + start;
1341 for(unsigned int i = 0; i < triangleCount; i++)
1343 batch[i][0] = index[0];
1344 batch[i][1] = index[((start + i) & 1) + 1];
1345 batch[i][2] = index[(~(start + i) & 1) + 1];
1351 case DRAW_INDEXEDTRIANGLESTRIP32:
1353 const unsigned int *index = (const unsigned int*)indices + start;
1355 for(unsigned int i = 0; i < triangleCount; i++)
1357 batch[i][0] = index[0];
1358 batch[i][1] = index[((start + i) & 1) + 1];
1359 batch[i][2] = index[(~(start + i) & 1) + 1];
1365 case DRAW_INDEXEDTRIANGLEFAN8:
1367 const unsigned char *index = (const unsigned char*)indices;
1369 for(unsigned int i = 0; i < triangleCount; i++)
1371 batch[i][0] = index[start + i + 1];
1372 batch[i][1] = index[start + i + 2];
1373 batch[i][2] = index[0];
1377 case DRAW_INDEXEDTRIANGLEFAN16:
1379 const unsigned short *index = (const unsigned short*)indices;
1381 for(unsigned int i = 0; i < triangleCount; i++)
1383 batch[i][0] = index[start + i + 1];
1384 batch[i][1] = index[start + i + 2];
1385 batch[i][2] = index[0];
1389 case DRAW_INDEXEDTRIANGLEFAN32:
1391 const unsigned int *index = (const unsigned int*)indices;
1393 for(unsigned int i = 0; i < triangleCount; i++)
1395 batch[i][0] = index[start + i + 1];
1396 batch[i][1] = index[start + i + 2];
1397 batch[i][2] = index[0];
1403 unsigned int index = 4 * start / 2;
1405 for(unsigned int i = 0; i < triangleCount; i += 2)
1407 batch[i+0][0] = index + 0;
1408 batch[i+0][1] = index + 1;
1409 batch[i+0][2] = index + 2;
1411 batch[i+1][0] = index + 0;
1412 batch[i+1][1] = index + 2;
1413 batch[i+1][2] = index + 3;
1424 task->vertexCount = triangleCount * 3;
1425 vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
1428 int Renderer::setupSolidTriangles(Renderer *renderer, int unit, int count)
1430 Triangle *triangle = renderer->triangleBatch[unit];
1431 Primitive *primitive = renderer->primitiveBatch[unit];
1433 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1434 SetupProcessor::State &state = draw.setupState;
1435 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1437 int ms = state.multiSample;
1438 int pos = state.positionRegister;
1439 const DrawData *data = draw.data;
1442 for(int i = 0; i < count; i++, triangle++)
1444 Vertex &v0 = triangle->v0;
1445 Vertex &v1 = triangle->v1;
1446 Vertex &v2 = triangle->v2;
1448 if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
1450 Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
1452 int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
1454 if(clipFlagsOr != Clipper::CLIP_FINITE)
1456 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1462 if(setupRoutine(primitive, triangle, &polygon, data))
1473 int Renderer::setupWireframeTriangle(Renderer *renderer, int unit, int count)
1475 Triangle *triangle = renderer->triangleBatch[unit];
1476 Primitive *primitive = renderer->primitiveBatch[unit];
1479 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1480 SetupProcessor::State &state = draw.setupState;
1481 SetupProcessor::RoutinePointer setupRoutine = draw.setupPointer;
1483 const Vertex &v0 = triangle[0].v0;
1484 const Vertex &v1 = triangle[0].v1;
1485 const Vertex &v2 = triangle[0].v2;
1487 float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
1489 if(state.cullMode == CULL_CLOCKWISE)
1491 if(d >= 0) return 0;
1493 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1495 if(d <= 0) return 0;
1499 triangle[1].v0 = v1;
1500 triangle[1].v1 = v2;
1501 triangle[2].v0 = v2;
1502 triangle[2].v1 = v0;
1504 if(state.color[0][0].flat) // FIXME
1506 for(int i = 0; i < 2; i++)
1508 triangle[1].v0.C[i] = triangle[0].v0.C[i];
1509 triangle[1].v1.C[i] = triangle[0].v0.C[i];
1510 triangle[2].v0.C[i] = triangle[0].v0.C[i];
1511 triangle[2].v1.C[i] = triangle[0].v0.C[i];
1515 for(int i = 0; i < 3; i++)
1517 if(setupLine(renderer, *primitive, *triangle, draw))
1519 primitive->area = 0.5f * d;
1531 int Renderer::setupVertexTriangle(Renderer *renderer, int unit, int count)
1533 Triangle *triangle = renderer->triangleBatch[unit];
1534 Primitive *primitive = renderer->primitiveBatch[unit];
1537 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1538 SetupProcessor::State &state = draw.setupState;
1540 const Vertex &v0 = triangle[0].v0;
1541 const Vertex &v1 = triangle[0].v1;
1542 const Vertex &v2 = triangle[0].v2;
1544 float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
1546 if(state.cullMode == CULL_CLOCKWISE)
1548 if(d >= 0) return 0;
1550 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1552 if(d <= 0) return 0;
1556 triangle[1].v0 = v1;
1557 triangle[2].v0 = v2;
1559 for(int i = 0; i < 3; i++)
1561 if(setupPoint(renderer, *primitive, *triangle, draw))
1563 primitive->area = 0.5f * d;
1575 int Renderer::setupLines(Renderer *renderer, int unit, int count)
1577 Triangle *triangle = renderer->triangleBatch[unit];
1578 Primitive *primitive = renderer->primitiveBatch[unit];
1581 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1582 SetupProcessor::State &state = draw.setupState;
1584 int ms = state.multiSample;
1586 for(int i = 0; i < count; i++)
1588 if(setupLine(renderer, *primitive, *triangle, draw))
1600 int Renderer::setupPoints(Renderer *renderer, int unit, int count)
1602 Triangle *triangle = renderer->triangleBatch[unit];
1603 Primitive *primitive = renderer->primitiveBatch[unit];
1606 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1607 SetupProcessor::State &state = draw.setupState;
1609 int ms = state.multiSample;
1611 for(int i = 0; i < count; i++)
1613 if(setupPoint(renderer, *primitive, *triangle, draw))
1625 bool Renderer::setupLine(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1627 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1628 const SetupProcessor::State &state = draw.setupState;
1629 const DrawData &data = *draw.data;
1631 float lineWidth = data.lineWidth;
1633 Vertex &v0 = triangle.v0;
1634 Vertex &v1 = triangle.v1;
1636 int pos = state.positionRegister;
1638 const float4 &P0 = v0.v[pos];
1639 const float4 &P1 = v1.v[pos];
1641 if(P0.w <= 0 && P1.w <= 0)
1646 const float W = data.Wx16[0] * (1.0f / 16.0f);
1647 const float H = data.Hx16[0] * (1.0f / 16.0f);
1649 float dx = W * (P1.x / P1.w - P0.x / P0.w);
1650 float dy = H * (P1.y / P1.w - P0.y / P0.w);
1652 if(dx == 0 && dy == 0)
1657 if(false) // Rectangle
1667 float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
1672 float dx0w = dx * P0.w / W;
1673 float dy0h = dy * P0.w / H;
1674 float dx0h = dx * P0.w / H;
1675 float dy0w = dy * P0.w / W;
1677 float dx1w = dx * P1.w / W;
1678 float dy1h = dy * P1.w / H;
1679 float dx1h = dx * P1.w / H;
1680 float dy1w = dy * P1.w / W;
1682 P[0].x += -dy0w + -dx0w;
1683 P[0].y += -dx0h + +dy0h;
1684 C[0] = computeClipFlags(P[0], data);
1686 P[1].x += -dy1w + +dx1w;
1687 P[1].y += -dx1h + +dy1h;
1688 C[1] = computeClipFlags(P[1], data);
1690 P[2].x += +dy1w + +dx1w;
1691 P[2].y += +dx1h + -dy1h;
1692 C[2] = computeClipFlags(P[2], data);
1694 P[3].x += +dy0w + -dx0w;
1695 P[3].y += +dx0h + +dy0h;
1696 C[3] = computeClipFlags(P[3], data);
1698 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1700 Polygon polygon(P, 4);
1702 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1704 if(clipFlagsOr != Clipper::CLIP_FINITE)
1706 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1712 return setupRoutine(&primitive, &triangle, &polygon, &data);
1715 else // Diamond test convention
1729 float dx0 = lineWidth * 0.5f * P0.w / W;
1730 float dy0 = lineWidth * 0.5f * P0.w / H;
1732 float dx1 = lineWidth * 0.5f * P1.w / W;
1733 float dy1 = lineWidth * 0.5f * P1.w / H;
1736 C[0] = computeClipFlags(P[0], data);
1739 C[1] = computeClipFlags(P[1], data);
1742 C[2] = computeClipFlags(P[2], data);
1745 C[3] = computeClipFlags(P[3], data);
1748 C[4] = computeClipFlags(P[4], data);
1751 C[5] = computeClipFlags(P[5], data);
1754 C[6] = computeClipFlags(P[6], data);
1757 C[7] = computeClipFlags(P[7], data);
1759 if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
1765 if(dx > dy) // Right
1806 Polygon polygon(L, 6);
1808 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
1810 if(clipFlagsOr != Clipper::CLIP_FINITE)
1812 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1818 return setupRoutine(&primitive, &triangle, &polygon, &data);
1825 bool Renderer::setupPoint(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1827 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1828 const SetupProcessor::State &state = draw.setupState;
1829 const DrawData &data = *draw.data;
1831 Vertex &v = triangle.v0;
1835 int pts = state.pointSizeRegister;
1837 if(state.pointSizeRegister != 0xF)
1843 pSize = data.point.pointSize[0];
1846 pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
1851 int pos = state.positionRegister;
1858 const float X = pSize * P[0].w * data.halfPixelX[0];
1859 const float Y = pSize * P[0].w * data.halfPixelY[0];
1863 C[0] = computeClipFlags(P[0], data);
1867 C[1] = computeClipFlags(P[1], data);
1871 C[2] = computeClipFlags(P[2], data);
1875 C[3] = computeClipFlags(P[3], data);
1877 triangle.v1 = triangle.v0;
1878 triangle.v2 = triangle.v0;
1880 triangle.v1.X += iround(16 * 0.5f * pSize);
1881 triangle.v2.Y -= iround(16 * 0.5f * pSize) * (data.Hx16[0] > 0.0f ? 1 : -1); // Both Direct3D and OpenGL expect (0, 0) in the top-left corner
1883 Polygon polygon(P, 4);
1885 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1887 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1889 if(clipFlagsOr != Clipper::CLIP_FINITE)
1891 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1897 return setupRoutine(&primitive, &triangle, &polygon, &data);
1903 unsigned int Renderer::computeClipFlags(const float4 &v, const DrawData &data)
1905 return ((v.x > v.w) << 0) |
1906 ((v.y > v.w) << 1) |
1907 ((v.z > v.w) << 2) |
1908 ((v.x < -v.w) << 3) |
1909 ((v.y < -v.w) << 4) |
1911 Clipper::CLIP_FINITE; // FIXME: xyz finite
1914 void Renderer::initializeThreads()
1916 unitCount = ceilPow2(threadCount);
1917 clusterCount = ceilPow2(threadCount);
1919 for(int i = 0; i < unitCount; i++)
1921 triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
1922 primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
1925 for(int i = 0; i < threadCount; i++)
1927 vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
1928 vertexTask[i]->vertexCache.drawCall = -1;
1930 task[i].type = Task::SUSPEND;
1932 resume[i] = new Event();
1933 suspend[i] = new Event();
1935 Parameters parameters;
1936 parameters.threadIndex = i;
1937 parameters.renderer = this;
1939 exitThreads = false;
1940 worker[i] = new Thread(threadFunction, ¶meters);
1943 suspend[i]->signal();
1947 void Renderer::terminateThreads()
1949 while(threadsAwake != 0)
1954 for(int thread = 0; thread < threadCount; thread++)
1959 resume[thread]->signal();
1960 worker[thread]->join();
1962 delete worker[thread];
1964 delete resume[thread];
1966 delete suspend[thread];
1967 suspend[thread] = 0;
1970 deallocate(vertexTask[thread]);
1971 vertexTask[thread] = 0;
1974 for(int i = 0; i < 16; i++)
1976 deallocate(triangleBatch[i]);
1977 triangleBatch[i] = 0;
1979 deallocate(primitiveBatch[i]);
1980 primitiveBatch[i] = 0;
1984 void Renderer::loadConstants(const VertexShader *vertexShader)
1986 if(!vertexShader) return;
1988 size_t count = vertexShader->getLength();
1990 for(size_t i = 0; i < count; i++)
1992 const Shader::Instruction *instruction = vertexShader->getInstruction(i);
1994 if(instruction->opcode == Shader::OPCODE_DEF)
1996 int index = instruction->dst.index;
1999 value[0] = instruction->src[0].value[0];
2000 value[1] = instruction->src[0].value[1];
2001 value[2] = instruction->src[0].value[2];
2002 value[3] = instruction->src[0].value[3];
2004 setVertexShaderConstantF(index, value);
2006 else if(instruction->opcode == Shader::OPCODE_DEFI)
2008 int index = instruction->dst.index;
2011 integer[0] = instruction->src[0].integer[0];
2012 integer[1] = instruction->src[0].integer[1];
2013 integer[2] = instruction->src[0].integer[2];
2014 integer[3] = instruction->src[0].integer[3];
2016 setVertexShaderConstantI(index, integer);
2018 else if(instruction->opcode == Shader::OPCODE_DEFB)
2020 int index = instruction->dst.index;
2021 int boolean = instruction->src[0].boolean[0];
2023 setVertexShaderConstantB(index, &boolean);
2028 void Renderer::loadConstants(const PixelShader *pixelShader)
2030 if(!pixelShader) return;
2032 size_t count = pixelShader->getLength();
2034 for(size_t i = 0; i < count; i++)
2036 const Shader::Instruction *instruction = pixelShader->getInstruction(i);
2038 if(instruction->opcode == Shader::OPCODE_DEF)
2040 int index = instruction->dst.index;
2043 value[0] = instruction->src[0].value[0];
2044 value[1] = instruction->src[0].value[1];
2045 value[2] = instruction->src[0].value[2];
2046 value[3] = instruction->src[0].value[3];
2048 setPixelShaderConstantF(index, value);
2050 else if(instruction->opcode == Shader::OPCODE_DEFI)
2052 int index = instruction->dst.index;
2055 integer[0] = instruction->src[0].integer[0];
2056 integer[1] = instruction->src[0].integer[1];
2057 integer[2] = instruction->src[0].integer[2];
2058 integer[3] = instruction->src[0].integer[3];
2060 setPixelShaderConstantI(index, integer);
2062 else if(instruction->opcode == Shader::OPCODE_DEFB)
2064 int index = instruction->dst.index;
2065 int boolean = instruction->src[0].boolean[0];
2067 setPixelShaderConstantB(index, &boolean);
2072 void Renderer::setIndexBuffer(Resource *indexBuffer)
2074 context->indexBuffer = indexBuffer;
2077 void Renderer::setMultiSampleMask(unsigned int mask)
2079 context->sampleMask = mask;
2082 void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
2084 sw::transparencyAntialiasing = transparencyAntialiasing;
2087 bool Renderer::isReadWriteTexture(int sampler)
2089 for(int index = 0; index < RENDERTARGETS; index++)
2091 if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
2097 if(context->depthBuffer && context->texture[sampler] == context->depthBuffer->getResource())
2105 void Renderer::updateClipper()
2107 if(updateClipPlanes)
2109 if(VertexProcessor::isFixedFunction()) // User plane in world space
2111 const Matrix &scissorWorld = getViewTransform();
2113 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
2114 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
2115 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
2116 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
2117 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
2118 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
2120 else // User plane in clip space
2122 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
2123 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
2124 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
2125 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
2126 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
2127 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
2130 updateClipPlanes = false;
2134 void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
2136 ASSERT(sampler < TOTAL_IMAGE_UNITS);
2138 context->texture[sampler] = resource;
2141 void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
2143 ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
2145 context->sampler[sampler].setTextureLevel(face, level, surface, type);
2148 void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
2150 if(type == SAMPLER_PIXEL)
2152 PixelProcessor::setTextureFilter(sampler, textureFilter);
2156 VertexProcessor::setTextureFilter(sampler, textureFilter);
2160 void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
2162 if(type == SAMPLER_PIXEL)
2164 PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
2168 VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
2172 void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
2174 if(type == SAMPLER_PIXEL)
2176 PixelProcessor::setGatherEnable(sampler, enable);
2180 VertexProcessor::setGatherEnable(sampler, enable);
2184 void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
2186 if(type == SAMPLER_PIXEL)
2188 PixelProcessor::setAddressingModeU(sampler, addressMode);
2192 VertexProcessor::setAddressingModeU(sampler, addressMode);
2196 void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
2198 if(type == SAMPLER_PIXEL)
2200 PixelProcessor::setAddressingModeV(sampler, addressMode);
2204 VertexProcessor::setAddressingModeV(sampler, addressMode);
2208 void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
2210 if(type == SAMPLER_PIXEL)
2212 PixelProcessor::setAddressingModeW(sampler, addressMode);
2216 VertexProcessor::setAddressingModeW(sampler, addressMode);
2220 void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
2222 if(type == SAMPLER_PIXEL)
2224 PixelProcessor::setReadSRGB(sampler, sRGB);
2228 VertexProcessor::setReadSRGB(sampler, sRGB);
2232 void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
2234 if(type == SAMPLER_PIXEL)
2236 PixelProcessor::setMipmapLOD(sampler, bias);
2240 VertexProcessor::setMipmapLOD(sampler, bias);
2244 void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
2246 if(type == SAMPLER_PIXEL)
2248 PixelProcessor::setBorderColor(sampler, borderColor);
2252 VertexProcessor::setBorderColor(sampler, borderColor);
2256 void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
2258 if(type == SAMPLER_PIXEL)
2260 PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2264 VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2268 void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
2270 if(type == SAMPLER_PIXEL)
2272 PixelProcessor::setSwizzleR(sampler, swizzleR);
2276 VertexProcessor::setSwizzleR(sampler, swizzleR);
2280 void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
2282 if(type == SAMPLER_PIXEL)
2284 PixelProcessor::setSwizzleG(sampler, swizzleG);
2288 VertexProcessor::setSwizzleG(sampler, swizzleG);
2292 void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
2294 if(type == SAMPLER_PIXEL)
2296 PixelProcessor::setSwizzleB(sampler, swizzleB);
2300 VertexProcessor::setSwizzleB(sampler, swizzleB);
2304 void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
2306 if(type == SAMPLER_PIXEL)
2308 PixelProcessor::setSwizzleA(sampler, swizzleA);
2312 VertexProcessor::setSwizzleA(sampler, swizzleA);
2316 void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
2318 context->setPointSpriteEnable(pointSpriteEnable);
2321 void Renderer::setPointScaleEnable(bool pointScaleEnable)
2323 context->setPointScaleEnable(pointScaleEnable);
2326 void Renderer::setLineWidth(float width)
2328 context->lineWidth = width;
2331 void Renderer::setDepthBias(float bias)
2336 void Renderer::setSlopeDepthBias(float slopeBias)
2338 slopeDepthBias = slopeBias;
2341 void Renderer::setRasterizerDiscard(bool rasterizerDiscard)
2343 context->rasterizerDiscard = rasterizerDiscard;
2346 void Renderer::setPixelShader(const PixelShader *shader)
2348 context->pixelShader = shader;
2350 loadConstants(shader);
2353 void Renderer::setVertexShader(const VertexShader *shader)
2355 context->vertexShader = shader;
2357 loadConstants(shader);
2360 void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
2362 for(int i = 0; i < DRAW_COUNT; i++)
2364 if(drawCall[i]->psDirtyConstF < index + count)
2366 drawCall[i]->psDirtyConstF = index + count;
2370 for(int i = 0; i < count; i++)
2372 PixelProcessor::setFloatConstant(index + i, value);
2377 void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
2379 for(int i = 0; i < DRAW_COUNT; i++)
2381 if(drawCall[i]->psDirtyConstI < index + count)
2383 drawCall[i]->psDirtyConstI = index + count;
2387 for(int i = 0; i < count; i++)
2389 PixelProcessor::setIntegerConstant(index + i, value);
2394 void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
2396 for(int i = 0; i < DRAW_COUNT; i++)
2398 if(drawCall[i]->psDirtyConstB < index + count)
2400 drawCall[i]->psDirtyConstB = index + count;
2404 for(int i = 0; i < count; i++)
2406 PixelProcessor::setBooleanConstant(index + i, *boolean);
2411 void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
2413 for(int i = 0; i < DRAW_COUNT; i++)
2415 if(drawCall[i]->vsDirtyConstF < index + count)
2417 drawCall[i]->vsDirtyConstF = index + count;
2421 for(int i = 0; i < count; i++)
2423 VertexProcessor::setFloatConstant(index + i, value);
2428 void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
2430 for(int i = 0; i < DRAW_COUNT; i++)
2432 if(drawCall[i]->vsDirtyConstI < index + count)
2434 drawCall[i]->vsDirtyConstI = index + count;
2438 for(int i = 0; i < count; i++)
2440 VertexProcessor::setIntegerConstant(index + i, value);
2445 void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
2447 for(int i = 0; i < DRAW_COUNT; i++)
2449 if(drawCall[i]->vsDirtyConstB < index + count)
2451 drawCall[i]->vsDirtyConstB = index + count;
2455 for(int i = 0; i < count; i++)
2457 VertexProcessor::setBooleanConstant(index + i, *boolean);
2462 void Renderer::setModelMatrix(const Matrix &M, int i)
2464 VertexProcessor::setModelMatrix(M, i);
2467 void Renderer::setViewMatrix(const Matrix &V)
2469 VertexProcessor::setViewMatrix(V);
2470 updateClipPlanes = true;
2473 void Renderer::setBaseMatrix(const Matrix &B)
2475 VertexProcessor::setBaseMatrix(B);
2476 updateClipPlanes = true;
2479 void Renderer::setProjectionMatrix(const Matrix &P)
2481 VertexProcessor::setProjectionMatrix(P);
2482 updateClipPlanes = true;
2485 void Renderer::addQuery(Query *query)
2487 queries.push_back(query);
2490 void Renderer::removeQuery(Query *query)
2492 queries.remove(query);
2496 int Renderer::getThreadCount()
2501 int64_t Renderer::getVertexTime(int thread)
2503 return vertexTime[thread];
2506 int64_t Renderer::getSetupTime(int thread)
2508 return setupTime[thread];
2511 int64_t Renderer::getPixelTime(int thread)
2513 return pixelTime[thread];
2516 void Renderer::resetTimers()
2518 for(int thread = 0; thread < threadCount; thread++)
2520 vertexTime[thread] = 0;
2521 setupTime[thread] = 0;
2522 pixelTime[thread] = 0;
2527 void Renderer::setViewport(const Viewport &viewport)
2529 this->viewport = viewport;
2532 void Renderer::setScissor(const Rect &scissor)
2534 this->scissor = scissor;
2537 void Renderer::setClipFlags(int flags)
2539 clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
2542 void Renderer::setClipPlane(unsigned int index, const float plane[4])
2544 if(index < MAX_CLIP_PLANES)
2546 userPlane[index] = plane;
2550 updateClipPlanes = true;
2553 void Renderer::updateConfiguration(bool initialUpdate)
2555 bool newConfiguration = swiftConfig->hasNewConfiguration();
2557 if(newConfiguration || initialUpdate)
2561 SwiftConfig::Configuration configuration = {};
2562 swiftConfig->getConfiguration(configuration);
2564 precacheVertex = !newConfiguration && configuration.precache;
2565 precacheSetup = !newConfiguration && configuration.precache;
2566 precachePixel = !newConfiguration && configuration.precache;
2568 VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
2569 PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
2570 SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
2572 switch(configuration.textureSampleQuality)
2574 case 0: Sampler::setFilterQuality(FILTER_POINT); break;
2575 case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
2576 case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2577 default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2580 switch(configuration.mipmapQuality)
2582 case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
2583 case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2584 default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2587 setPerspectiveCorrection(configuration.perspectiveCorrection);
2589 switch(configuration.transcendentalPrecision)
2592 logPrecision = APPROXIMATE;
2593 expPrecision = APPROXIMATE;
2594 rcpPrecision = APPROXIMATE;
2595 rsqPrecision = APPROXIMATE;
2598 logPrecision = PARTIAL;
2599 expPrecision = PARTIAL;
2600 rcpPrecision = PARTIAL;
2601 rsqPrecision = PARTIAL;
2604 logPrecision = ACCURATE;
2605 expPrecision = ACCURATE;
2606 rcpPrecision = ACCURATE;
2607 rsqPrecision = ACCURATE;
2610 logPrecision = WHQL;
2611 expPrecision = WHQL;
2612 rcpPrecision = WHQL;
2613 rsqPrecision = WHQL;
2616 logPrecision = IEEE;
2617 expPrecision = IEEE;
2618 rcpPrecision = IEEE;
2619 rsqPrecision = IEEE;
2622 logPrecision = ACCURATE;
2623 expPrecision = ACCURATE;
2624 rcpPrecision = ACCURATE;
2625 rsqPrecision = ACCURATE;
2629 switch(configuration.transparencyAntialiasing)
2631 case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2632 case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
2633 default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2636 switch(configuration.threadCount)
2638 case -1: threadCount = CPUID::coreCount(); break;
2639 case 0: threadCount = CPUID::processAffinity(); break;
2640 default: threadCount = configuration.threadCount; break;
2643 CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
2644 CPUID::setEnableSSSE3(configuration.enableSSSE3);
2645 CPUID::setEnableSSE3(configuration.enableSSE3);
2646 CPUID::setEnableSSE2(configuration.enableSSE2);
2647 CPUID::setEnableSSE(configuration.enableSSE);
2649 for(int pass = 0; pass < 10; pass++)
2651 optimization[pass] = configuration.optimization[pass];
2654 forceWindowed = configuration.forceWindowed;
2655 complementaryDepthBuffer = configuration.complementaryDepthBuffer;
2656 postBlendSRGB = configuration.postBlendSRGB;
2657 exactColorRounding = configuration.exactColorRounding;
2658 forceClearRegisters = configuration.forceClearRegisters;
2661 minPrimitives = configuration.minPrimitives;
2662 maxPrimitives = configuration.maxPrimitives;
2666 if(!initialUpdate && !worker[0])
2668 initializeThreads();