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 for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
308 atomicIncrement(&(*query)->reference);
311 draw->queries = new std::list<Query*>(queries);
314 draw->drawType = drawType;
315 draw->batchSize = batch;
317 vertexRoutine->bind();
318 setupRoutine->bind();
319 pixelRoutine->bind();
321 draw->vertexRoutine = vertexRoutine;
322 draw->setupRoutine = setupRoutine;
323 draw->pixelRoutine = pixelRoutine;
324 draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
325 draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
326 draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
327 draw->setupPrimitives = setupPrimitives;
328 draw->setupState = setupState;
330 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
332 draw->vertexStream[i] = context->input[i].resource;
333 data->input[i] = context->input[i].buffer;
334 data->stride[i] = context->input[i].stride;
336 if(draw->vertexStream[i])
338 draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
342 if(context->indexBuffer)
344 data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
347 draw->indexBuffer = context->indexBuffer;
349 for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
351 draw->texture[sampler] = 0;
354 for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
356 if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
358 draw->texture[sampler] = context->texture[sampler];
359 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
361 data->mipmap[sampler] = context->sampler[sampler].getTextureData();
365 if(context->pixelShader)
367 if(draw->psDirtyConstF)
369 memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
370 memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
371 draw->psDirtyConstF = 0;
374 if(draw->psDirtyConstI)
376 memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
377 draw->psDirtyConstI = 0;
380 if(draw->psDirtyConstB)
382 memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
383 draw->psDirtyConstB = 0;
387 if(context->pixelShaderVersion() <= 0x0104)
389 for(int stage = 0; stage < 8; stage++)
391 if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
393 data->textureStage[stage] = context->textureStage[stage].uniforms;
399 if(context->vertexShader)
401 if(context->vertexShader->getVersion() >= 0x0300)
403 for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
405 if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
407 draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
408 draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
410 data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
415 if(draw->vsDirtyConstF)
417 memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
418 draw->vsDirtyConstF = 0;
421 if(draw->vsDirtyConstI)
423 memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
424 draw->vsDirtyConstI = 0;
427 if(draw->vsDirtyConstB)
429 memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
430 draw->vsDirtyConstB = 0;
433 if(context->vertexShader->instanceIdDeclared)
435 data->instanceID = context->instanceID;
442 draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
443 draw->vsDirtyConstI = 16;
444 draw->vsDirtyConstB = 16;
447 if(pixelState.stencilActive)
449 data->stencil[0] = stencil;
450 data->stencil[1] = stencilCCW;
453 if(pixelState.fogActive)
458 if(setupState.isDrawPoint)
463 data->lineWidth = context->lineWidth;
465 data->factor = factor;
467 if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
469 float ref = context->alphaReference * (1.0f / 255.0f);
470 float margin = sw::min(ref, 1.0f - ref);
474 data->a2c0 = replicate(ref - margin * 0.6f);
475 data->a2c1 = replicate(ref - margin * 0.2f);
476 data->a2c2 = replicate(ref + margin * 0.2f);
477 data->a2c3 = replicate(ref + margin * 0.6f);
481 data->a2c0 = replicate(ref - margin * 0.3f);
482 data->a2c1 = replicate(ref + margin * 0.3f);
487 if(pixelState.occlusionEnabled)
489 for(int cluster = 0; cluster < clusterCount; cluster++)
491 data->occlusion[cluster] = 0;
496 for(int cluster = 0; cluster < clusterCount; cluster++)
498 for(int i = 0; i < PERF_TIMERS; i++)
500 data->cycles[i][cluster] = 0;
507 float W = 0.5f * viewport.width;
508 float H = 0.5f * viewport.height;
509 float X0 = viewport.x0 + W;
510 float Y0 = viewport.y0 + H;
511 float N = viewport.minZ;
512 float F = viewport.maxZ;
515 if(context->isDrawTriangle(false))
520 if(complementaryDepthBuffer)
526 static const float X[5][16] = // Fragment offsets
528 {+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
529 {-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
530 {-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
531 {+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
532 {+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
535 static const float Y[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.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
540 {-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
541 {-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
544 int s = sw::log2(ss);
546 data->Wx16 = replicate(W * 16);
547 data->Hx16 = replicate(H * 16);
548 data->X0x16 = replicate(X0 * 16 - 8);
549 data->Y0x16 = replicate(Y0 * 16 - 8);
550 data->XXXX = replicate(X[s][q] / W);
551 data->YYYY = replicate(Y[s][q] / H);
552 data->halfPixelX = replicate(0.5f / W);
553 data->halfPixelY = replicate(0.5f / H);
554 data->viewportHeight = abs(viewport.height);
555 data->slopeDepthBias = slopeDepthBias;
556 data->depthRange = Z;
558 draw->clipFlags = clipFlags;
562 if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
563 if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
564 if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
565 if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
566 if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
567 if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
573 for(int index = 0; index < RENDERTARGETS; index++)
575 draw->renderTarget[index] = context->renderTarget[index];
577 if(draw->renderTarget[index])
579 data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
580 data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
581 data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
585 draw->depthStencil = context->depthStencil;
587 if(draw->depthStencil)
589 data->depthBuffer = (float*)context->depthStencil->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
590 data->depthPitchB = context->depthStencil->getInternalPitchB();
591 data->depthSliceB = context->depthStencil->getInternalSliceB();
593 data->stencilBuffer = (unsigned char*)context->depthStencil->lockStencil(q * ms, MANAGED);
594 data->stencilPitchB = context->depthStencil->getStencilPitchB();
595 data->stencilSliceB = context->depthStencil->getStencilSliceB();
601 data->scissorX0 = scissor.x0;
602 data->scissorX1 = scissor.x1;
603 data->scissorY0 = scissor.y0;
604 data->scissorY1 = scissor.y1;
610 draw->references = (count + batch - 1) / batch;
612 schedulerMutex.lock();
614 schedulerMutex.unlock();
623 task[0].type = Task::RESUME;
628 else // Use main thread for draw execution
631 task[0].type = Task::RESUME;
638 void Renderer::threadFunction(void *parameters)
640 Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
641 int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
643 if(logPrecision < IEEE)
645 CPUID::setFlushToZero(true);
646 CPUID::setDenormalsAreZero(true);
649 renderer->threadLoop(threadIndex);
652 void Renderer::threadLoop(int threadIndex)
656 taskLoop(threadIndex);
658 suspend[threadIndex]->signal();
659 resume[threadIndex]->wait();
663 void Renderer::taskLoop(int threadIndex)
665 while(task[threadIndex].type != Task::SUSPEND)
667 scheduleTask(threadIndex);
668 executeTask(threadIndex);
672 void Renderer::findAvailableTasks()
675 for(int cluster = 0; cluster < clusterCount; cluster++)
677 if(!pixelProgress[cluster].executing)
679 for(int unit = 0; unit < unitCount; unit++)
681 if(primitiveProgress[unit].references > 0) // Contains processed primitives
683 if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
685 if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
687 Task &task = taskQueue[qHead];
688 task.type = Task::PIXELS;
689 task.primitiveUnit = unit;
690 task.pixelCluster = cluster;
692 pixelProgress[cluster].executing = true;
694 // Commit to the task queue
695 qHead = (qHead + 1) % 32;
706 // Find primitive tasks
707 if(currentDraw == nextDraw)
709 return; // No more primitives to process
712 for(int unit = 0; unit < unitCount; unit++)
714 DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
716 if(draw->primitive >= draw->count)
720 if(currentDraw == nextDraw)
722 return; // No more primitives to process
725 draw = drawList[currentDraw % DRAW_COUNT];
728 if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
730 int primitive = draw->primitive;
731 int count = draw->count;
732 int batch = draw->batchSize;
734 primitiveProgress[unit].drawCall = currentDraw;
735 primitiveProgress[unit].firstPrimitive = primitive;
736 primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
738 draw->primitive += batch;
740 Task &task = taskQueue[qHead];
741 task.type = Task::PRIMITIVES;
742 task.primitiveUnit = unit;
744 primitiveProgress[unit].references = -1;
746 // Commit to the task queue
747 qHead = (qHead + 1) % 32;
753 void Renderer::scheduleTask(int threadIndex)
755 schedulerMutex.lock();
757 if((int)qSize < threadCount - threadsAwake + 1)
759 findAvailableTasks();
764 task[threadIndex] = taskQueue[(qHead - qSize) % 32];
767 if(threadsAwake != threadCount)
769 int wakeup = qSize - threadsAwake + 1;
771 for(int i = 0; i < threadCount && wakeup > 0; i++)
773 if(task[i].type == Task::SUSPEND)
776 task[i].type = Task::RESUME;
787 task[threadIndex].type = Task::SUSPEND;
792 schedulerMutex.unlock();
795 void Renderer::executeTask(int threadIndex)
798 int64_t startTick = Timer::ticks();
801 switch(task[threadIndex].type)
803 case Task::PRIMITIVES:
805 int unit = task[threadIndex].primitiveUnit;
807 int input = primitiveProgress[unit].firstPrimitive;
808 int count = primitiveProgress[unit].primitiveCount;
809 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
810 int (*setupPrimitives)(Renderer *renderer, int batch, int count) = draw->setupPrimitives;
812 processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
815 int64_t time = Timer::ticks();
816 vertexTime[threadIndex] += time - startTick;
820 int visible = setupPrimitives(this, unit, count);
822 primitiveProgress[unit].visible = visible;
823 primitiveProgress[unit].references = clusterCount;
826 setupTime[threadIndex] += Timer::ticks() - startTick;
832 int unit = task[threadIndex].primitiveUnit;
833 int visible = primitiveProgress[unit].visible;
837 int cluster = task[threadIndex].pixelCluster;
838 Primitive *primitive = primitiveBatch[unit];
839 DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
840 DrawData *data = draw->data;
841 PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
843 pixelRoutine(primitive, visible, cluster, data);
846 finishRendering(task[threadIndex]);
849 pixelTime[threadIndex] += Timer::ticks() - startTick;
862 void Renderer::synchronize()
864 sync->lock(sw::PUBLIC);
868 void Renderer::finishRendering(Task &pixelTask)
870 int unit = pixelTask.primitiveUnit;
871 int cluster = pixelTask.pixelCluster;
873 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
874 DrawData &data = *draw.data;
875 int primitive = primitiveProgress[unit].firstPrimitive;
876 int count = primitiveProgress[unit].primitiveCount;
878 pixelProgress[cluster].processedPrimitives = primitive + count;
880 if(pixelProgress[cluster].processedPrimitives >= draw.count)
882 pixelProgress[cluster].drawCall++;
883 pixelProgress[cluster].processedPrimitives = 0;
886 int ref = atomicDecrement(&primitiveProgress[unit].references);
890 ref = atomicDecrement(&draw.references);
895 for(int cluster = 0; cluster < clusterCount; cluster++)
897 for(int i = 0; i < PERF_TIMERS; i++)
899 profiler.cycles[i] += data.cycles[i][cluster];
906 for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
910 for(int cluster = 0; cluster < clusterCount; cluster++)
912 atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
915 atomicDecrement(&query->reference);
922 for(int i = 0; i < RENDERTARGETS; i++)
924 if(draw.renderTarget[i])
926 draw.renderTarget[i]->unlockInternal();
930 if(draw.depthStencil)
932 draw.depthStencil->unlockInternal();
933 draw.depthStencil->unlockStencil();
936 for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
940 draw.texture[i]->unlock();
944 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
946 if(draw.vertexStream[i])
948 draw.vertexStream[i]->unlock();
954 draw.indexBuffer->unlock();
957 draw.vertexRoutine->unbind();
958 draw.setupRoutine->unbind();
959 draw.pixelRoutine->unbind();
963 draw.references = -1;
968 pixelProgress[cluster].executing = false;
971 void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
973 Triangle *triangle = triangleBatch[unit];
974 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
975 DrawData *data = draw->data;
976 VertexTask *task = vertexTask[thread];
978 const void *indices = data->indices;
979 VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
981 if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
983 task->vertexCache.clear();
984 task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
987 unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
989 switch(draw->drawType)
993 unsigned int index = start;
995 for(unsigned int i = 0; i < triangleCount; i++)
1007 unsigned int index = 2 * start;
1009 for(unsigned int i = 0; i < triangleCount; i++)
1011 batch[i][0] = index + 0;
1012 batch[i][1] = index + 1;
1013 batch[i][2] = index + 1;
1019 case DRAW_LINESTRIP:
1021 unsigned int index = start;
1023 for(unsigned int i = 0; i < triangleCount; i++)
1025 batch[i][0] = index + 0;
1026 batch[i][1] = index + 1;
1027 batch[i][2] = index + 1;
1035 unsigned int index = start;
1037 for(unsigned int i = 0; i < triangleCount; i++)
1039 batch[i][0] = (index + 0) % loop;
1040 batch[i][1] = (index + 1) % loop;
1041 batch[i][2] = (index + 1) % loop;
1047 case DRAW_TRIANGLELIST:
1049 unsigned int index = 3 * start;
1051 for(unsigned int i = 0; i < triangleCount; i++)
1053 batch[i][0] = index + 0;
1054 batch[i][1] = index + 1;
1055 batch[i][2] = index + 2;
1061 case DRAW_TRIANGLESTRIP:
1063 unsigned int index = start;
1065 for(unsigned int i = 0; i < triangleCount; i++)
1067 batch[i][0] = index + 0;
1068 batch[i][1] = index + (index & 1) + 1;
1069 batch[i][2] = index + (~index & 1) + 1;
1075 case DRAW_TRIANGLEFAN:
1077 unsigned int index = start;
1079 for(unsigned int i = 0; i < triangleCount; i++)
1081 batch[i][0] = index + 1;
1082 batch[i][1] = index + 2;
1089 case DRAW_INDEXEDPOINTLIST8:
1091 const unsigned char *index = (const unsigned char*)indices + start;
1093 for(unsigned int i = 0; i < triangleCount; i++)
1095 batch[i][0] = *index;
1096 batch[i][1] = *index;
1097 batch[i][2] = *index;
1103 case DRAW_INDEXEDPOINTLIST16:
1105 const unsigned short *index = (const unsigned short*)indices + start;
1107 for(unsigned int i = 0; i < triangleCount; i++)
1109 batch[i][0] = *index;
1110 batch[i][1] = *index;
1111 batch[i][2] = *index;
1117 case DRAW_INDEXEDPOINTLIST32:
1119 const unsigned int *index = (const unsigned int*)indices + start;
1121 for(unsigned int i = 0; i < triangleCount; i++)
1123 batch[i][0] = *index;
1124 batch[i][1] = *index;
1125 batch[i][2] = *index;
1131 case DRAW_INDEXEDLINELIST8:
1133 const unsigned char *index = (const unsigned char*)indices + 2 * start;
1135 for(unsigned int i = 0; i < triangleCount; i++)
1137 batch[i][0] = index[0];
1138 batch[i][1] = index[1];
1139 batch[i][2] = index[1];
1145 case DRAW_INDEXEDLINELIST16:
1147 const unsigned short *index = (const unsigned short*)indices + 2 * start;
1149 for(unsigned int i = 0; i < triangleCount; i++)
1151 batch[i][0] = index[0];
1152 batch[i][1] = index[1];
1153 batch[i][2] = index[1];
1159 case DRAW_INDEXEDLINELIST32:
1161 const unsigned int *index = (const unsigned int*)indices + 2 * start;
1163 for(unsigned int i = 0; i < triangleCount; i++)
1165 batch[i][0] = index[0];
1166 batch[i][1] = index[1];
1167 batch[i][2] = index[1];
1173 case DRAW_INDEXEDLINESTRIP8:
1175 const unsigned char *index = (const unsigned char*)indices + start;
1177 for(unsigned int i = 0; i < triangleCount; i++)
1179 batch[i][0] = index[0];
1180 batch[i][1] = index[1];
1181 batch[i][2] = index[1];
1187 case DRAW_INDEXEDLINESTRIP16:
1189 const unsigned short *index = (const unsigned short*)indices + start;
1191 for(unsigned int i = 0; i < triangleCount; i++)
1193 batch[i][0] = index[0];
1194 batch[i][1] = index[1];
1195 batch[i][2] = index[1];
1201 case DRAW_INDEXEDLINESTRIP32:
1203 const unsigned int *index = (const unsigned int*)indices + start;
1205 for(unsigned int i = 0; i < triangleCount; i++)
1207 batch[i][0] = index[0];
1208 batch[i][1] = index[1];
1209 batch[i][2] = index[1];
1215 case DRAW_INDEXEDLINELOOP8:
1217 const unsigned char *index = (const unsigned char*)indices;
1219 for(unsigned int i = 0; i < triangleCount; i++)
1221 batch[i][0] = index[(start + i + 0) % loop];
1222 batch[i][1] = index[(start + i + 1) % loop];
1223 batch[i][2] = index[(start + i + 1) % loop];
1227 case DRAW_INDEXEDLINELOOP16:
1229 const unsigned short *index = (const unsigned short*)indices;
1231 for(unsigned int i = 0; i < triangleCount; i++)
1233 batch[i][0] = index[(start + i + 0) % loop];
1234 batch[i][1] = index[(start + i + 1) % loop];
1235 batch[i][2] = index[(start + i + 1) % loop];
1239 case DRAW_INDEXEDLINELOOP32:
1241 const unsigned int *index = (const unsigned int*)indices;
1243 for(unsigned int i = 0; i < triangleCount; i++)
1245 batch[i][0] = index[(start + i + 0) % loop];
1246 batch[i][1] = index[(start + i + 1) % loop];
1247 batch[i][2] = index[(start + i + 1) % loop];
1251 case DRAW_INDEXEDTRIANGLELIST8:
1253 const unsigned char *index = (const unsigned char*)indices + 3 * start;
1255 for(unsigned int i = 0; i < triangleCount; i++)
1257 batch[i][0] = index[0];
1258 batch[i][1] = index[1];
1259 batch[i][2] = index[2];
1265 case DRAW_INDEXEDTRIANGLELIST16:
1267 const unsigned short *index = (const unsigned short*)indices + 3 * start;
1269 for(unsigned int i = 0; i < triangleCount; i++)
1271 batch[i][0] = index[0];
1272 batch[i][1] = index[1];
1273 batch[i][2] = index[2];
1279 case DRAW_INDEXEDTRIANGLELIST32:
1281 const unsigned int *index = (const unsigned int*)indices + 3 * start;
1283 for(unsigned int i = 0; i < triangleCount; i++)
1285 batch[i][0] = index[0];
1286 batch[i][1] = index[1];
1287 batch[i][2] = index[2];
1293 case DRAW_INDEXEDTRIANGLESTRIP8:
1295 const unsigned char *index = (const unsigned char*)indices + start;
1297 for(unsigned int i = 0; i < triangleCount; i++)
1299 batch[i][0] = index[0];
1300 batch[i][1] = index[((start + i) & 1) + 1];
1301 batch[i][2] = index[(~(start + i) & 1) + 1];
1307 case DRAW_INDEXEDTRIANGLESTRIP16:
1309 const unsigned short *index = (const unsigned short*)indices + start;
1311 for(unsigned int i = 0; i < triangleCount; i++)
1313 batch[i][0] = index[0];
1314 batch[i][1] = index[((start + i) & 1) + 1];
1315 batch[i][2] = index[(~(start + i) & 1) + 1];
1321 case DRAW_INDEXEDTRIANGLESTRIP32:
1323 const unsigned int *index = (const unsigned int*)indices + start;
1325 for(unsigned int i = 0; i < triangleCount; i++)
1327 batch[i][0] = index[0];
1328 batch[i][1] = index[((start + i) & 1) + 1];
1329 batch[i][2] = index[(~(start + i) & 1) + 1];
1335 case DRAW_INDEXEDTRIANGLEFAN8:
1337 const unsigned char *index = (const unsigned char*)indices;
1339 for(unsigned int i = 0; i < triangleCount; i++)
1341 batch[i][0] = index[start + i + 1];
1342 batch[i][1] = index[start + i + 2];
1343 batch[i][2] = index[0];
1347 case DRAW_INDEXEDTRIANGLEFAN16:
1349 const unsigned short *index = (const unsigned short*)indices;
1351 for(unsigned int i = 0; i < triangleCount; i++)
1353 batch[i][0] = index[start + i + 1];
1354 batch[i][1] = index[start + i + 2];
1355 batch[i][2] = index[0];
1359 case DRAW_INDEXEDTRIANGLEFAN32:
1361 const unsigned int *index = (const unsigned int*)indices;
1363 for(unsigned int i = 0; i < triangleCount; i++)
1365 batch[i][0] = index[start + i + 1];
1366 batch[i][1] = index[start + i + 2];
1367 batch[i][2] = index[0];
1373 unsigned int index = 4 * start / 2;
1375 for(unsigned int i = 0; i < triangleCount; i += 2)
1377 batch[i+0][0] = index + 0;
1378 batch[i+0][1] = index + 1;
1379 batch[i+0][2] = index + 2;
1381 batch[i+1][0] = index + 0;
1382 batch[i+1][1] = index + 2;
1383 batch[i+1][2] = index + 3;
1394 task->vertexCount = triangleCount * 3;
1395 vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
1398 int Renderer::setupSolidTriangles(Renderer *renderer, int unit, int count)
1400 Triangle *triangle = renderer->triangleBatch[unit];
1401 Primitive *primitive = renderer->primitiveBatch[unit];
1403 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1404 SetupProcessor::State &state = draw.setupState;
1405 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1407 int ms = state.multiSample;
1408 int pos = state.positionRegister;
1409 const DrawData *data = draw.data;
1412 for(int i = 0; i < count; i++, triangle++)
1414 Vertex &v0 = triangle->v0;
1415 Vertex &v1 = triangle->v1;
1416 Vertex &v2 = triangle->v2;
1418 if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
1420 Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
1422 int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
1424 if(clipFlagsOr != Clipper::CLIP_FINITE)
1426 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1432 if(setupRoutine(primitive, triangle, &polygon, data))
1443 int Renderer::setupWireframeTriangle(Renderer *renderer, int unit, int count)
1445 Triangle *triangle = renderer->triangleBatch[unit];
1446 Primitive *primitive = renderer->primitiveBatch[unit];
1449 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1450 SetupProcessor::State &state = draw.setupState;
1451 SetupProcessor::RoutinePointer setupRoutine = draw.setupPointer;
1453 const Vertex &v0 = triangle[0].v0;
1454 const Vertex &v1 = triangle[0].v1;
1455 const Vertex &v2 = triangle[0].v2;
1457 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;
1459 if(state.cullMode == CULL_CLOCKWISE)
1461 if(d >= 0) return 0;
1463 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1465 if(d <= 0) return 0;
1469 triangle[1].v0 = v1;
1470 triangle[1].v1 = v2;
1471 triangle[2].v0 = v2;
1472 triangle[2].v1 = v0;
1474 if(state.color[0][0].flat) // FIXME
1476 for(int i = 0; i < 2; i++)
1478 triangle[1].v0.C[i] = triangle[0].v0.C[i];
1479 triangle[1].v1.C[i] = triangle[0].v0.C[i];
1480 triangle[2].v0.C[i] = triangle[0].v0.C[i];
1481 triangle[2].v1.C[i] = triangle[0].v0.C[i];
1485 for(int i = 0; i < 3; i++)
1487 if(setupLine(renderer, *primitive, *triangle, draw))
1489 primitive->area = 0.5f * d;
1501 int Renderer::setupVertexTriangle(Renderer *renderer, int unit, int count)
1503 Triangle *triangle = renderer->triangleBatch[unit];
1504 Primitive *primitive = renderer->primitiveBatch[unit];
1507 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1508 SetupProcessor::State &state = draw.setupState;
1510 const Vertex &v0 = triangle[0].v0;
1511 const Vertex &v1 = triangle[0].v1;
1512 const Vertex &v2 = triangle[0].v2;
1514 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;
1516 if(state.cullMode == CULL_CLOCKWISE)
1518 if(d >= 0) return 0;
1520 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1522 if(d <= 0) return 0;
1526 triangle[1].v0 = v1;
1527 triangle[2].v0 = v2;
1529 for(int i = 0; i < 3; i++)
1531 if(setupPoint(renderer, *primitive, *triangle, draw))
1533 primitive->area = 0.5f * d;
1545 int Renderer::setupLines(Renderer *renderer, int unit, int count)
1547 Triangle *triangle = renderer->triangleBatch[unit];
1548 Primitive *primitive = renderer->primitiveBatch[unit];
1551 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1552 SetupProcessor::State &state = draw.setupState;
1554 int ms = state.multiSample;
1556 for(int i = 0; i < count; i++)
1558 if(setupLine(renderer, *primitive, *triangle, draw))
1570 int Renderer::setupPoints(Renderer *renderer, int unit, int count)
1572 Triangle *triangle = renderer->triangleBatch[unit];
1573 Primitive *primitive = renderer->primitiveBatch[unit];
1576 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1577 SetupProcessor::State &state = draw.setupState;
1579 int ms = state.multiSample;
1581 for(int i = 0; i < count; i++)
1583 if(setupPoint(renderer, *primitive, *triangle, draw))
1595 bool Renderer::setupLine(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1597 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1598 const SetupProcessor::State &state = draw.setupState;
1599 const DrawData &data = *draw.data;
1601 float lineWidth = data.lineWidth;
1603 Vertex &v0 = triangle.v0;
1604 Vertex &v1 = triangle.v1;
1606 int pos = state.positionRegister;
1608 const float4 &P0 = v0.v[pos];
1609 const float4 &P1 = v1.v[pos];
1611 if(P0.w <= 0 && P1.w <= 0)
1616 const float W = data.Wx16[0] * (1.0f / 16.0f);
1617 const float H = data.Hx16[0] * (1.0f / 16.0f);
1619 float dx = W * (P1.x / P1.w - P0.x / P0.w);
1620 float dy = H * (P1.y / P1.w - P0.y / P0.w);
1622 if(dx == 0 && dy == 0)
1627 if(false) // Rectangle
1637 float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
1642 float dx0w = dx * P0.w / W;
1643 float dy0h = dy * P0.w / H;
1644 float dx0h = dx * P0.w / H;
1645 float dy0w = dy * P0.w / W;
1647 float dx1w = dx * P1.w / W;
1648 float dy1h = dy * P1.w / H;
1649 float dx1h = dx * P1.w / H;
1650 float dy1w = dy * P1.w / W;
1652 P[0].x += -dy0w + -dx0w;
1653 P[0].y += -dx0h + +dy0h;
1654 C[0] = computeClipFlags(P[0], data);
1656 P[1].x += -dy1w + +dx1w;
1657 P[1].y += -dx1h + +dy1h;
1658 C[1] = computeClipFlags(P[1], data);
1660 P[2].x += +dy1w + +dx1w;
1661 P[2].y += +dx1h + -dy1h;
1662 C[2] = computeClipFlags(P[2], data);
1664 P[3].x += +dy0w + -dx0w;
1665 P[3].y += +dx0h + +dy0h;
1666 C[3] = computeClipFlags(P[3], data);
1668 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1670 Polygon polygon(P, 4);
1672 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1674 if(clipFlagsOr != Clipper::CLIP_FINITE)
1676 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1682 return setupRoutine(&primitive, &triangle, &polygon, &data);
1685 else // Diamond test convention
1699 float dx0 = lineWidth * 0.5f * P0.w / W;
1700 float dy0 = lineWidth * 0.5f * P0.w / H;
1702 float dx1 = lineWidth * 0.5f * P1.w / W;
1703 float dy1 = lineWidth * 0.5f * P1.w / H;
1706 C[0] = computeClipFlags(P[0], data);
1709 C[1] = computeClipFlags(P[1], data);
1712 C[2] = computeClipFlags(P[2], data);
1715 C[3] = computeClipFlags(P[3], data);
1718 C[4] = computeClipFlags(P[4], data);
1721 C[5] = computeClipFlags(P[5], data);
1724 C[6] = computeClipFlags(P[6], data);
1727 C[7] = computeClipFlags(P[7], data);
1729 if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
1735 if(dx > dy) // Right
1776 Polygon polygon(L, 6);
1778 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
1780 if(clipFlagsOr != Clipper::CLIP_FINITE)
1782 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1788 return setupRoutine(&primitive, &triangle, &polygon, &data);
1795 bool Renderer::setupPoint(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1797 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1798 const SetupProcessor::State &state = draw.setupState;
1799 const DrawData &data = *draw.data;
1801 Vertex &v = triangle.v0;
1805 int pts = state.pointSizeRegister;
1807 if(state.pointSizeRegister != 0xF)
1813 pSize = data.point.pointSize[0];
1816 pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
1821 int pos = state.positionRegister;
1828 const float X = pSize * P[0].w * data.halfPixelX[0];
1829 const float Y = pSize * P[0].w * data.halfPixelY[0];
1833 C[0] = computeClipFlags(P[0], data);
1837 C[1] = computeClipFlags(P[1], data);
1841 C[2] = computeClipFlags(P[2], data);
1845 C[3] = computeClipFlags(P[3], data);
1847 triangle.v1 = triangle.v0;
1848 triangle.v2 = triangle.v0;
1850 triangle.v1.X += iround(16 * 0.5f * pSize);
1851 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
1853 Polygon polygon(P, 4);
1855 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1857 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1859 if(clipFlagsOr != Clipper::CLIP_FINITE)
1861 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1867 return setupRoutine(&primitive, &triangle, &polygon, &data);
1873 unsigned int Renderer::computeClipFlags(const float4 &v, const DrawData &data)
1875 return ((v.x > v.w) << 0) |
1876 ((v.y > v.w) << 1) |
1877 ((v.z > v.w) << 2) |
1878 ((v.x < -v.w) << 3) |
1879 ((v.y < -v.w) << 4) |
1881 Clipper::CLIP_FINITE; // FIXME: xyz finite
1884 void Renderer::initializeThreads()
1886 unitCount = ceilPow2(threadCount);
1887 clusterCount = ceilPow2(threadCount);
1889 for(int i = 0; i < unitCount; i++)
1891 triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
1892 primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
1895 for(int i = 0; i < threadCount; i++)
1897 vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
1898 vertexTask[i]->vertexCache.drawCall = -1;
1900 task[i].type = Task::SUSPEND;
1902 resume[i] = new Event();
1903 suspend[i] = new Event();
1905 Parameters parameters;
1906 parameters.threadIndex = i;
1907 parameters.renderer = this;
1909 exitThreads = false;
1910 worker[i] = new Thread(threadFunction, ¶meters);
1913 suspend[i]->signal();
1917 void Renderer::terminateThreads()
1919 while(threadsAwake != 0)
1924 for(int thread = 0; thread < threadCount; thread++)
1929 resume[thread]->signal();
1930 worker[thread]->join();
1932 delete worker[thread];
1934 delete resume[thread];
1936 delete suspend[thread];
1937 suspend[thread] = 0;
1940 deallocate(vertexTask[thread]);
1941 vertexTask[thread] = 0;
1944 for(int i = 0; i < 16; i++)
1946 deallocate(triangleBatch[i]);
1947 triangleBatch[i] = 0;
1949 deallocate(primitiveBatch[i]);
1950 primitiveBatch[i] = 0;
1954 void Renderer::loadConstants(const VertexShader *vertexShader)
1956 if(!vertexShader) return;
1958 size_t count = vertexShader->getLength();
1960 for(size_t i = 0; i < count; i++)
1962 const Shader::Instruction *instruction = vertexShader->getInstruction(i);
1964 if(instruction->opcode == Shader::OPCODE_DEF)
1966 int index = instruction->dst.index;
1969 value[0] = instruction->src[0].value[0];
1970 value[1] = instruction->src[0].value[1];
1971 value[2] = instruction->src[0].value[2];
1972 value[3] = instruction->src[0].value[3];
1974 setVertexShaderConstantF(index, value);
1976 else if(instruction->opcode == Shader::OPCODE_DEFI)
1978 int index = instruction->dst.index;
1981 integer[0] = instruction->src[0].integer[0];
1982 integer[1] = instruction->src[0].integer[1];
1983 integer[2] = instruction->src[0].integer[2];
1984 integer[3] = instruction->src[0].integer[3];
1986 setVertexShaderConstantI(index, integer);
1988 else if(instruction->opcode == Shader::OPCODE_DEFB)
1990 int index = instruction->dst.index;
1991 int boolean = instruction->src[0].boolean[0];
1993 setVertexShaderConstantB(index, &boolean);
1998 void Renderer::loadConstants(const PixelShader *pixelShader)
2000 if(!pixelShader) return;
2002 size_t count = pixelShader->getLength();
2004 for(size_t i = 0; i < count; i++)
2006 const Shader::Instruction *instruction = pixelShader->getInstruction(i);
2008 if(instruction->opcode == Shader::OPCODE_DEF)
2010 int index = instruction->dst.index;
2013 value[0] = instruction->src[0].value[0];
2014 value[1] = instruction->src[0].value[1];
2015 value[2] = instruction->src[0].value[2];
2016 value[3] = instruction->src[0].value[3];
2018 setPixelShaderConstantF(index, value);
2020 else if(instruction->opcode == Shader::OPCODE_DEFI)
2022 int index = instruction->dst.index;
2025 integer[0] = instruction->src[0].integer[0];
2026 integer[1] = instruction->src[0].integer[1];
2027 integer[2] = instruction->src[0].integer[2];
2028 integer[3] = instruction->src[0].integer[3];
2030 setPixelShaderConstantI(index, integer);
2032 else if(instruction->opcode == Shader::OPCODE_DEFB)
2034 int index = instruction->dst.index;
2035 int boolean = instruction->src[0].boolean[0];
2037 setPixelShaderConstantB(index, &boolean);
2042 void Renderer::setIndexBuffer(Resource *indexBuffer)
2044 context->indexBuffer = indexBuffer;
2047 void Renderer::setMultiSampleMask(unsigned int mask)
2049 context->sampleMask = mask;
2052 void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
2054 sw::transparencyAntialiasing = transparencyAntialiasing;
2057 bool Renderer::isReadWriteTexture(int sampler)
2059 for(int index = 0; index < RENDERTARGETS; index++)
2061 if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
2067 if(context->depthStencil && context->texture[sampler] == context->depthStencil->getResource())
2075 void Renderer::updateClipper()
2077 if(updateClipPlanes)
2079 if(VertexProcessor::isFixedFunction()) // User plane in world space
2081 const Matrix &scissorWorld = getViewTransform();
2083 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
2084 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
2085 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
2086 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
2087 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
2088 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
2090 else // User plane in clip space
2092 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
2093 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
2094 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
2095 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
2096 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
2097 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
2100 updateClipPlanes = false;
2104 void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
2106 ASSERT(sampler < TOTAL_IMAGE_UNITS);
2108 context->texture[sampler] = resource;
2111 void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
2113 ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
2115 context->sampler[sampler].setTextureLevel(face, level, surface, type);
2118 void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
2120 if(type == SAMPLER_PIXEL)
2122 PixelProcessor::setTextureFilter(sampler, textureFilter);
2126 VertexProcessor::setTextureFilter(sampler, textureFilter);
2130 void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
2132 if(type == SAMPLER_PIXEL)
2134 PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
2138 VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
2142 void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
2144 if(type == SAMPLER_PIXEL)
2146 PixelProcessor::setGatherEnable(sampler, enable);
2150 VertexProcessor::setGatherEnable(sampler, enable);
2154 void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
2156 if(type == SAMPLER_PIXEL)
2158 PixelProcessor::setAddressingModeU(sampler, addressMode);
2162 VertexProcessor::setAddressingModeU(sampler, addressMode);
2166 void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
2168 if(type == SAMPLER_PIXEL)
2170 PixelProcessor::setAddressingModeV(sampler, addressMode);
2174 VertexProcessor::setAddressingModeV(sampler, addressMode);
2178 void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
2180 if(type == SAMPLER_PIXEL)
2182 PixelProcessor::setAddressingModeW(sampler, addressMode);
2186 VertexProcessor::setAddressingModeW(sampler, addressMode);
2190 void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
2192 if(type == SAMPLER_PIXEL)
2194 PixelProcessor::setReadSRGB(sampler, sRGB);
2198 VertexProcessor::setReadSRGB(sampler, sRGB);
2202 void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
2204 if(type == SAMPLER_PIXEL)
2206 PixelProcessor::setMipmapLOD(sampler, bias);
2210 VertexProcessor::setMipmapLOD(sampler, bias);
2214 void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
2216 if(type == SAMPLER_PIXEL)
2218 PixelProcessor::setBorderColor(sampler, borderColor);
2222 VertexProcessor::setBorderColor(sampler, borderColor);
2226 void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
2228 if(type == SAMPLER_PIXEL)
2230 PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2234 VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2238 void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
2240 if(type == SAMPLER_PIXEL)
2242 PixelProcessor::setSwizzleR(sampler, swizzleR);
2246 VertexProcessor::setSwizzleR(sampler, swizzleR);
2250 void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
2252 if(type == SAMPLER_PIXEL)
2254 PixelProcessor::setSwizzleG(sampler, swizzleG);
2258 VertexProcessor::setSwizzleG(sampler, swizzleG);
2262 void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
2264 if(type == SAMPLER_PIXEL)
2266 PixelProcessor::setSwizzleB(sampler, swizzleB);
2270 VertexProcessor::setSwizzleB(sampler, swizzleB);
2274 void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
2276 if(type == SAMPLER_PIXEL)
2278 PixelProcessor::setSwizzleA(sampler, swizzleA);
2282 VertexProcessor::setSwizzleA(sampler, swizzleA);
2286 void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
2288 context->setPointSpriteEnable(pointSpriteEnable);
2291 void Renderer::setPointScaleEnable(bool pointScaleEnable)
2293 context->setPointScaleEnable(pointScaleEnable);
2296 void Renderer::setLineWidth(float width)
2298 context->lineWidth = width;
2301 void Renderer::setDepthBias(float bias)
2306 void Renderer::setSlopeDepthBias(float slopeBias)
2308 slopeDepthBias = slopeBias;
2311 void Renderer::setPixelShader(const PixelShader *shader)
2313 context->pixelShader = shader;
2315 loadConstants(shader);
2318 void Renderer::setVertexShader(const VertexShader *shader)
2320 context->vertexShader = shader;
2322 loadConstants(shader);
2325 void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
2327 for(int i = 0; i < DRAW_COUNT; i++)
2329 if(drawCall[i]->psDirtyConstF < index + count)
2331 drawCall[i]->psDirtyConstF = index + count;
2335 for(int i = 0; i < count; i++)
2337 PixelProcessor::setFloatConstant(index + i, value);
2342 void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
2344 for(int i = 0; i < DRAW_COUNT; i++)
2346 if(drawCall[i]->psDirtyConstI < index + count)
2348 drawCall[i]->psDirtyConstI = index + count;
2352 for(int i = 0; i < count; i++)
2354 PixelProcessor::setIntegerConstant(index + i, value);
2359 void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
2361 for(int i = 0; i < DRAW_COUNT; i++)
2363 if(drawCall[i]->psDirtyConstB < index + count)
2365 drawCall[i]->psDirtyConstB = index + count;
2369 for(int i = 0; i < count; i++)
2371 PixelProcessor::setBooleanConstant(index + i, *boolean);
2376 void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
2378 for(int i = 0; i < DRAW_COUNT; i++)
2380 if(drawCall[i]->vsDirtyConstF < index + count)
2382 drawCall[i]->vsDirtyConstF = index + count;
2386 for(int i = 0; i < count; i++)
2388 VertexProcessor::setFloatConstant(index + i, value);
2393 void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
2395 for(int i = 0; i < DRAW_COUNT; i++)
2397 if(drawCall[i]->vsDirtyConstI < index + count)
2399 drawCall[i]->vsDirtyConstI = index + count;
2403 for(int i = 0; i < count; i++)
2405 VertexProcessor::setIntegerConstant(index + i, value);
2410 void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
2412 for(int i = 0; i < DRAW_COUNT; i++)
2414 if(drawCall[i]->vsDirtyConstB < index + count)
2416 drawCall[i]->vsDirtyConstB = index + count;
2420 for(int i = 0; i < count; i++)
2422 VertexProcessor::setBooleanConstant(index + i, *boolean);
2427 void Renderer::setModelMatrix(const Matrix &M, int i)
2429 VertexProcessor::setModelMatrix(M, i);
2432 void Renderer::setViewMatrix(const Matrix &V)
2434 VertexProcessor::setViewMatrix(V);
2435 updateClipPlanes = true;
2438 void Renderer::setBaseMatrix(const Matrix &B)
2440 VertexProcessor::setBaseMatrix(B);
2441 updateClipPlanes = true;
2444 void Renderer::setProjectionMatrix(const Matrix &P)
2446 VertexProcessor::setProjectionMatrix(P);
2447 updateClipPlanes = true;
2450 void Renderer::addQuery(Query *query)
2452 queries.push_back(query);
2455 void Renderer::removeQuery(Query *query)
2457 queries.remove(query);
2461 int Renderer::getThreadCount()
2466 int64_t Renderer::getVertexTime(int thread)
2468 return vertexTime[thread];
2471 int64_t Renderer::getSetupTime(int thread)
2473 return setupTime[thread];
2476 int64_t Renderer::getPixelTime(int thread)
2478 return pixelTime[thread];
2481 void Renderer::resetTimers()
2483 for(int thread = 0; thread < threadCount; thread++)
2485 vertexTime[thread] = 0;
2486 setupTime[thread] = 0;
2487 pixelTime[thread] = 0;
2492 void Renderer::setViewport(const Viewport &viewport)
2494 this->viewport = viewport;
2497 void Renderer::setScissor(const Rect &scissor)
2499 this->scissor = scissor;
2502 void Renderer::setClipFlags(int flags)
2504 clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
2507 void Renderer::setClipPlane(unsigned int index, const float plane[4])
2509 if(index < MAX_CLIP_PLANES)
2511 userPlane[index] = plane;
2515 updateClipPlanes = true;
2518 void Renderer::updateConfiguration(bool initialUpdate)
2520 bool newConfiguration = swiftConfig->hasNewConfiguration();
2522 if(newConfiguration || initialUpdate)
2526 SwiftConfig::Configuration configuration = {};
2527 swiftConfig->getConfiguration(configuration);
2529 precacheVertex = !newConfiguration && configuration.precache;
2530 precacheSetup = !newConfiguration && configuration.precache;
2531 precachePixel = !newConfiguration && configuration.precache;
2533 VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
2534 PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
2535 SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
2537 switch(configuration.textureSampleQuality)
2539 case 0: Sampler::setFilterQuality(FILTER_POINT); break;
2540 case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
2541 case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2542 default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2545 switch(configuration.mipmapQuality)
2547 case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
2548 case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2549 default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2552 setPerspectiveCorrection(configuration.perspectiveCorrection);
2554 switch(configuration.transcendentalPrecision)
2557 logPrecision = APPROXIMATE;
2558 expPrecision = APPROXIMATE;
2559 rcpPrecision = APPROXIMATE;
2560 rsqPrecision = APPROXIMATE;
2563 logPrecision = PARTIAL;
2564 expPrecision = PARTIAL;
2565 rcpPrecision = PARTIAL;
2566 rsqPrecision = PARTIAL;
2569 logPrecision = ACCURATE;
2570 expPrecision = ACCURATE;
2571 rcpPrecision = ACCURATE;
2572 rsqPrecision = ACCURATE;
2575 logPrecision = WHQL;
2576 expPrecision = WHQL;
2577 rcpPrecision = WHQL;
2578 rsqPrecision = WHQL;
2581 logPrecision = IEEE;
2582 expPrecision = IEEE;
2583 rcpPrecision = IEEE;
2584 rsqPrecision = IEEE;
2587 logPrecision = ACCURATE;
2588 expPrecision = ACCURATE;
2589 rcpPrecision = ACCURATE;
2590 rsqPrecision = ACCURATE;
2594 switch(configuration.transparencyAntialiasing)
2596 case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2597 case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
2598 default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2601 switch(configuration.threadCount)
2603 case -1: threadCount = CPUID::coreCount(); break;
2604 case 0: threadCount = CPUID::processAffinity(); break;
2605 default: threadCount = configuration.threadCount; break;
2608 CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
2609 CPUID::setEnableSSSE3(configuration.enableSSSE3);
2610 CPUID::setEnableSSE3(configuration.enableSSE3);
2611 CPUID::setEnableSSE2(configuration.enableSSE2);
2612 CPUID::setEnableSSE(configuration.enableSSE);
2614 for(int pass = 0; pass < 10; pass++)
2616 optimization[pass] = configuration.optimization[pass];
2619 forceWindowed = configuration.forceWindowed;
2620 complementaryDepthBuffer = configuration.complementaryDepthBuffer;
2621 postBlendSRGB = configuration.postBlendSRGB;
2622 exactColorRounding = configuration.exactColorRounding;
2623 forceClearRegisters = configuration.forceClearRegisters;
2626 minPrimitives = configuration.minPrimitives;
2627 maxPrimitives = configuration.maxPrimitives;
2631 if(!initialUpdate && !worker[0])
2633 initializeThreads();