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"
35 bool disableServer = true;
38 unsigned int minPrimitives = 1;
39 unsigned int maxPrimitives = 1 << 21;
44 extern bool halfIntegerCoordinates; // Pixel centers are not at integer coordinates
45 extern bool symmetricNormalizedDepth; // [-1, 1] instead of [0, 1]
46 extern bool booleanFaceRegister;
47 extern bool fullPixelPositionRegister;
48 extern bool leadingVertexFirst; // Flat shading uses first vertex, else last
49 extern bool secondaryColor; // Specular lighting is applied after texturing
51 extern bool forceWindowed;
52 extern bool complementaryDepthBuffer;
53 extern bool postBlendSRGB;
54 extern bool exactColorRounding;
55 extern TransparencyAntialiasing transparencyAntialiasing;
56 extern bool forceClearRegisters;
58 extern bool precacheVertex;
59 extern bool precacheSetup;
60 extern bool precachePixel;
67 TranscendentalPrecision logPrecision = ACCURATE;
68 TranscendentalPrecision expPrecision = ACCURATE;
69 TranscendentalPrecision rcpPrecision = ACCURATE;
70 TranscendentalPrecision rsqPrecision = ACCURATE;
71 bool perspectiveCorrection = true;
83 vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
87 psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
93 data = (DrawData*)allocate(sizeof(DrawData));
94 data->constants = &constants;
104 Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : context(context), VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), viewport()
106 sw::halfIntegerCoordinates = conventions.halfIntegerCoordinates;
107 sw::symmetricNormalizedDepth = conventions.symmetricNormalizedDepth;
108 sw::booleanFaceRegister = conventions.booleanFaceRegister;
109 sw::fullPixelPositionRegister = conventions.fullPixelPositionRegister;
110 sw::leadingVertexFirst = conventions.leadingVertexFirst;
111 sw::secondaryColor = conventions.secondaryColor;
112 sw::exactColorRounding = exactColorRounding;
114 setRenderTarget(0, 0);
115 clipper = new Clipper();
117 updateViewMatrix = true;
118 updateBaseMatrix = true;
119 updateProjectionMatrix = true;
120 updateClipPlanes = true;
126 for(int i = 0; i < 16; i++)
136 resumeApp = new Event();
144 for(int i = 0; i < 16; i++)
146 triangleBatch[i] = 0;
147 primitiveBatch[i] = 0;
150 for(int draw = 0; draw < DRAW_COUNT; draw++)
152 drawCall[draw] = new DrawCall();
153 drawList[draw] = drawCall[draw];
156 for(int unit = 0; unit < 16; unit++)
158 primitiveProgress[unit].init();
161 for(int cluster = 0; cluster < 16; cluster++)
163 pixelProgress[cluster].init();
168 swiftConfig = new SwiftConfig(disableServer);
169 updateConfiguration(true);
171 sync = new Resource(0);
174 Renderer::~Renderer()
184 for(int draw = 0; draw < DRAW_COUNT; draw++)
186 delete drawCall[draw];
192 void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
194 blitter.clear(pixel, format, dest, dRect, rgbaMask);
197 void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter)
199 blitter.blit(source, sRect, dest, dRect, filter);
202 void Renderer::blit3D(Surface *source, Surface *dest)
204 blitter.blit3D(source, dest);
207 void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
210 if(count < minPrimitives || count > maxPrimitives)
216 context->drawType = drawType;
218 updateConfiguration();
221 int ss = context->getSuperSampleCount();
222 int ms = context->getMultiSampleCount();
224 for(int q = 0; q < ss; q++)
226 int oldMultiSampleMask = context->multiSampleMask;
227 context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
229 if(!context->multiSampleMask)
234 sync->lock(sw::PRIVATE);
236 Routine *vertexRoutine;
237 Routine *setupRoutine;
238 Routine *pixelRoutine;
240 if(update || oldMultiSampleMask != context->multiSampleMask)
242 vertexState = VertexProcessor::update();
243 setupState = SetupProcessor::update();
244 pixelState = PixelProcessor::update();
246 vertexRoutine = VertexProcessor::routine(vertexState);
247 setupRoutine = SetupProcessor::routine(setupState);
248 pixelRoutine = PixelProcessor::routine(pixelState);
251 int batch = batchSize / ms;
253 int (*setupPrimitives)(Renderer *renderer, int batch, int count);
255 if(context->isDrawTriangle())
257 switch(context->fillMode)
260 setupPrimitives = setupSolidTriangles;
263 setupPrimitives = setupWireframeTriangle;
267 setupPrimitives = setupVertexTriangle;
270 default: ASSERT(false);
273 else if(context->isDrawLine())
275 setupPrimitives = setupLines;
279 setupPrimitives = setupPoints;
286 for(int i = 0; i < DRAW_COUNT; i++)
288 if(drawCall[i]->references == -1)
291 drawList[nextDraw % DRAW_COUNT] = draw;
304 DrawData *data = draw->data;
306 if(queries.size() != 0)
308 for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
310 atomicIncrement(&(*query)->reference);
313 draw->queries = new std::list<Query*>(queries);
316 draw->drawType = drawType;
317 draw->batchSize = batch;
319 vertexRoutine->bind();
320 setupRoutine->bind();
321 pixelRoutine->bind();
323 draw->vertexRoutine = vertexRoutine;
324 draw->setupRoutine = setupRoutine;
325 draw->pixelRoutine = pixelRoutine;
326 draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
327 draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
328 draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
329 draw->setupPrimitives = setupPrimitives;
330 draw->setupState = setupState;
332 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
334 draw->vertexStream[i] = context->input[i].resource;
335 data->input[i] = context->input[i].buffer;
336 data->stride[i] = context->input[i].stride;
338 if(draw->vertexStream[i])
340 draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
344 if(context->indexBuffer)
346 data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
349 draw->indexBuffer = context->indexBuffer;
351 for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
353 draw->texture[sampler] = 0;
356 for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
358 if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
360 draw->texture[sampler] = context->texture[sampler];
361 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
363 data->mipmap[sampler] = context->sampler[sampler].getTextureData();
367 if(context->pixelShader)
369 if(draw->psDirtyConstF)
371 memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
372 memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
373 draw->psDirtyConstF = 0;
376 if(draw->psDirtyConstI)
378 memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
379 draw->psDirtyConstI = 0;
382 if(draw->psDirtyConstB)
384 memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
385 draw->psDirtyConstB = 0;
389 if(context->pixelShaderVersion() <= 0x0104)
391 for(int stage = 0; stage < 8; stage++)
393 if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
395 data->textureStage[stage] = context->textureStage[stage].uniforms;
401 if(context->vertexShader)
403 if(context->vertexShader->getVersion() >= 0x0300)
405 for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
407 if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
409 draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
410 draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
412 data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
417 if(draw->vsDirtyConstF)
419 memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
420 draw->vsDirtyConstF = 0;
423 if(draw->vsDirtyConstI)
425 memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
426 draw->vsDirtyConstI = 0;
429 if(draw->vsDirtyConstB)
431 memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
432 draw->vsDirtyConstB = 0;
435 if(context->vertexShader->instanceIdDeclared)
437 data->instanceID = context->instanceID;
444 draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
445 draw->vsDirtyConstI = 16;
446 draw->vsDirtyConstB = 16;
449 if(pixelState.stencilActive)
451 data->stencil[0] = stencil;
452 data->stencil[1] = stencilCCW;
455 if(pixelState.fogActive)
460 if(setupState.isDrawPoint)
465 data->lineWidth = context->lineWidth;
467 data->factor = factor;
469 if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
471 float ref = context->alphaReference * (1.0f / 255.0f);
472 float margin = sw::min(ref, 1.0f - ref);
476 data->a2c0 = replicate(ref - margin * 0.6f);
477 data->a2c1 = replicate(ref - margin * 0.2f);
478 data->a2c2 = replicate(ref + margin * 0.2f);
479 data->a2c3 = replicate(ref + margin * 0.6f);
483 data->a2c0 = replicate(ref - margin * 0.3f);
484 data->a2c1 = replicate(ref + margin * 0.3f);
489 if(pixelState.occlusionEnabled)
491 for(int cluster = 0; cluster < clusterCount; cluster++)
493 data->occlusion[cluster] = 0;
498 for(int cluster = 0; cluster < clusterCount; cluster++)
500 for(int i = 0; i < PERF_TIMERS; i++)
502 data->cycles[i][cluster] = 0;
509 float W = 0.5f * viewport.width;
510 float H = 0.5f * viewport.height;
511 float X0 = viewport.x0 + W;
512 float Y0 = viewport.y0 + H;
513 float N = viewport.minZ;
514 float F = viewport.maxZ;
517 if(context->isDrawTriangle(false))
522 if(complementaryDepthBuffer)
528 static const float X[5][16] = // Fragment offsets
530 {+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
531 {-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
532 {-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
533 {+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
534 {+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
537 static const float Y[5][16] = // Fragment offsets
539 {+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
540 {-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
541 {-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
542 {-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
543 {-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
546 int s = sw::log2(ss);
548 data->Wx16 = replicate(W * 16);
549 data->Hx16 = replicate(H * 16);
550 data->X0x16 = replicate(X0 * 16 - 8);
551 data->Y0x16 = replicate(Y0 * 16 - 8);
552 data->XXXX = replicate(X[s][q] / W);
553 data->YYYY = replicate(Y[s][q] / H);
554 data->halfPixelX = replicate(0.5f / W);
555 data->halfPixelY = replicate(0.5f / H);
556 data->viewportHeight = abs(viewport.height);
557 data->slopeDepthBias = slopeDepthBias;
558 data->depthRange = Z;
560 draw->clipFlags = clipFlags;
564 if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
565 if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
566 if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
567 if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
568 if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
569 if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
575 for(int index = 0; index < RENDERTARGETS; index++)
577 draw->renderTarget[index] = context->renderTarget[index];
579 if(draw->renderTarget[index])
581 data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
582 data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
583 data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
587 draw->depthStencil = context->depthStencil;
589 if(draw->depthStencil)
591 data->depthBuffer = (float*)context->depthStencil->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
592 data->depthPitchB = context->depthStencil->getInternalPitchB();
593 data->depthSliceB = context->depthStencil->getInternalSliceB();
595 data->stencilBuffer = (unsigned char*)context->depthStencil->lockStencil(q * ms, MANAGED);
596 data->stencilPitchB = context->depthStencil->getStencilPitchB();
597 data->stencilSliceB = context->depthStencil->getStencilSliceB();
603 data->scissorX0 = scissor.x0;
604 data->scissorX1 = scissor.x1;
605 data->scissorY0 = scissor.y0;
606 data->scissorY1 = scissor.y1;
612 draw->references = (count + batch - 1) / batch;
614 schedulerMutex.lock();
616 schedulerMutex.unlock();
625 task[0].type = Task::RESUME;
630 else // Use main thread for draw execution
633 task[0].type = Task::RESUME;
640 void Renderer::threadFunction(void *parameters)
642 Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
643 int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
645 if(logPrecision < IEEE)
647 CPUID::setFlushToZero(true);
648 CPUID::setDenormalsAreZero(true);
651 renderer->threadLoop(threadIndex);
654 void Renderer::threadLoop(int threadIndex)
658 taskLoop(threadIndex);
660 suspend[threadIndex]->signal();
661 resume[threadIndex]->wait();
665 void Renderer::taskLoop(int threadIndex)
667 while(task[threadIndex].type != Task::SUSPEND)
669 scheduleTask(threadIndex);
670 executeTask(threadIndex);
674 void Renderer::findAvailableTasks()
677 for(int cluster = 0; cluster < clusterCount; cluster++)
679 if(!pixelProgress[cluster].executing)
681 for(int unit = 0; unit < unitCount; unit++)
683 if(primitiveProgress[unit].references > 0) // Contains processed primitives
685 if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
687 if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
689 Task &task = taskQueue[qHead];
690 task.type = Task::PIXELS;
691 task.primitiveUnit = unit;
692 task.pixelCluster = cluster;
694 pixelProgress[cluster].executing = true;
696 // Commit to the task queue
697 qHead = (qHead + 1) % 32;
708 // Find primitive tasks
709 if(currentDraw == nextDraw)
711 return; // No more primitives to process
714 for(int unit = 0; unit < unitCount; unit++)
716 DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
718 if(draw->primitive >= draw->count)
722 if(currentDraw == nextDraw)
724 return; // No more primitives to process
727 draw = drawList[currentDraw % DRAW_COUNT];
730 if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
732 int primitive = draw->primitive;
733 int count = draw->count;
734 int batch = draw->batchSize;
736 primitiveProgress[unit].drawCall = currentDraw;
737 primitiveProgress[unit].firstPrimitive = primitive;
738 primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
740 draw->primitive += batch;
742 Task &task = taskQueue[qHead];
743 task.type = Task::PRIMITIVES;
744 task.primitiveUnit = unit;
746 primitiveProgress[unit].references = -1;
748 // Commit to the task queue
749 qHead = (qHead + 1) % 32;
755 void Renderer::scheduleTask(int threadIndex)
757 schedulerMutex.lock();
759 if((int)qSize < threadCount - threadsAwake + 1)
761 findAvailableTasks();
766 task[threadIndex] = taskQueue[(qHead - qSize) % 32];
769 if(threadsAwake != threadCount)
771 int wakeup = qSize - threadsAwake + 1;
773 for(int i = 0; i < threadCount && wakeup > 0; i++)
775 if(task[i].type == Task::SUSPEND)
778 task[i].type = Task::RESUME;
789 task[threadIndex].type = Task::SUSPEND;
794 schedulerMutex.unlock();
797 void Renderer::executeTask(int threadIndex)
800 int64_t startTick = Timer::ticks();
803 switch(task[threadIndex].type)
805 case Task::PRIMITIVES:
807 int unit = task[threadIndex].primitiveUnit;
809 int input = primitiveProgress[unit].firstPrimitive;
810 int count = primitiveProgress[unit].primitiveCount;
811 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
812 int (*setupPrimitives)(Renderer *renderer, int batch, int count) = draw->setupPrimitives;
814 processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
817 int64_t time = Timer::ticks();
818 vertexTime[threadIndex] += time - startTick;
822 int visible = setupPrimitives(this, unit, count);
824 primitiveProgress[unit].visible = visible;
825 primitiveProgress[unit].references = clusterCount;
828 setupTime[threadIndex] += Timer::ticks() - startTick;
834 int unit = task[threadIndex].primitiveUnit;
835 int visible = primitiveProgress[unit].visible;
839 int cluster = task[threadIndex].pixelCluster;
840 Primitive *primitive = primitiveBatch[unit];
841 DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
842 DrawData *data = draw->data;
843 PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
845 pixelRoutine(primitive, visible, cluster, data);
848 finishRendering(task[threadIndex]);
851 pixelTime[threadIndex] += Timer::ticks() - startTick;
864 void Renderer::synchronize()
866 sync->lock(sw::PUBLIC);
870 void Renderer::finishRendering(Task &pixelTask)
872 int unit = pixelTask.primitiveUnit;
873 int cluster = pixelTask.pixelCluster;
875 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
876 DrawData &data = *draw.data;
877 int primitive = primitiveProgress[unit].firstPrimitive;
878 int count = primitiveProgress[unit].primitiveCount;
880 pixelProgress[cluster].processedPrimitives = primitive + count;
882 if(pixelProgress[cluster].processedPrimitives >= draw.count)
884 pixelProgress[cluster].drawCall++;
885 pixelProgress[cluster].processedPrimitives = 0;
888 int ref = atomicDecrement(&primitiveProgress[unit].references);
892 ref = atomicDecrement(&draw.references);
897 for(int cluster = 0; cluster < clusterCount; cluster++)
899 for(int i = 0; i < PERF_TIMERS; i++)
901 profiler.cycles[i] += data.cycles[i][cluster];
908 for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
912 for(int cluster = 0; cluster < clusterCount; cluster++)
914 atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
917 atomicDecrement(&query->reference);
924 for(int i = 0; i < RENDERTARGETS; i++)
926 if(draw.renderTarget[i])
928 draw.renderTarget[i]->unlockInternal();
932 if(draw.depthStencil)
934 draw.depthStencil->unlockInternal();
935 draw.depthStencil->unlockStencil();
938 for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
942 draw.texture[i]->unlock();
946 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
948 if(draw.vertexStream[i])
950 draw.vertexStream[i]->unlock();
956 draw.indexBuffer->unlock();
959 draw.vertexRoutine->unbind();
960 draw.setupRoutine->unbind();
961 draw.pixelRoutine->unbind();
965 draw.references = -1;
970 pixelProgress[cluster].executing = false;
973 void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
975 Triangle *triangle = triangleBatch[unit];
976 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
977 DrawData *data = draw->data;
978 VertexTask *task = vertexTask[thread];
980 const void *indices = data->indices;
981 VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
983 if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
985 task->vertexCache.clear();
986 task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
989 unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
991 switch(draw->drawType)
995 unsigned int index = start;
997 for(unsigned int i = 0; i < triangleCount; i++)
1000 batch[i][1] = index;
1001 batch[i][2] = index;
1009 unsigned int index = 2 * start;
1011 for(unsigned int i = 0; i < triangleCount; i++)
1013 batch[i][0] = index + 0;
1014 batch[i][1] = index + 1;
1015 batch[i][2] = index + 1;
1021 case DRAW_LINESTRIP:
1023 unsigned int index = start;
1025 for(unsigned int i = 0; i < triangleCount; i++)
1027 batch[i][0] = index + 0;
1028 batch[i][1] = index + 1;
1029 batch[i][2] = index + 1;
1037 unsigned int index = start;
1039 for(unsigned int i = 0; i < triangleCount; i++)
1041 batch[i][0] = (index + 0) % loop;
1042 batch[i][1] = (index + 1) % loop;
1043 batch[i][2] = (index + 1) % loop;
1049 case DRAW_TRIANGLELIST:
1051 unsigned int index = 3 * 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 + 2;
1063 case DRAW_TRIANGLESTRIP:
1065 unsigned int index = start;
1067 for(unsigned int i = 0; i < triangleCount; i++)
1069 batch[i][0] = index + 0;
1070 batch[i][1] = index + (index & 1) + 1;
1071 batch[i][2] = index + (~index & 1) + 1;
1077 case DRAW_TRIANGLEFAN:
1079 unsigned int index = start;
1081 for(unsigned int i = 0; i < triangleCount; i++)
1083 batch[i][0] = index + 1;
1084 batch[i][1] = index + 2;
1091 case DRAW_INDEXEDPOINTLIST8:
1093 const unsigned char *index = (const unsigned char*)indices + start;
1095 for(unsigned int i = 0; i < triangleCount; i++)
1097 batch[i][0] = *index;
1098 batch[i][1] = *index;
1099 batch[i][2] = *index;
1105 case DRAW_INDEXEDPOINTLIST16:
1107 const unsigned short *index = (const unsigned short*)indices + start;
1109 for(unsigned int i = 0; i < triangleCount; i++)
1111 batch[i][0] = *index;
1112 batch[i][1] = *index;
1113 batch[i][2] = *index;
1119 case DRAW_INDEXEDPOINTLIST32:
1121 const unsigned int *index = (const unsigned int*)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_INDEXEDLINELIST8:
1135 const unsigned char *index = (const unsigned char*)indices + 2 * start;
1137 for(unsigned int i = 0; i < triangleCount; i++)
1139 batch[i][0] = index[0];
1140 batch[i][1] = index[1];
1141 batch[i][2] = index[1];
1147 case DRAW_INDEXEDLINELIST16:
1149 const unsigned short *index = (const unsigned short*)indices + 2 * start;
1151 for(unsigned int i = 0; i < triangleCount; i++)
1153 batch[i][0] = index[0];
1154 batch[i][1] = index[1];
1155 batch[i][2] = index[1];
1161 case DRAW_INDEXEDLINELIST32:
1163 const unsigned int *index = (const unsigned int*)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_INDEXEDLINESTRIP8:
1177 const unsigned char *index = (const unsigned char*)indices + 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_INDEXEDLINESTRIP16:
1191 const unsigned short *index = (const unsigned short*)indices + 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_INDEXEDLINESTRIP32:
1205 const unsigned int *index = (const unsigned int*)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_INDEXEDLINELOOP8:
1219 const unsigned char *index = (const unsigned char*)indices;
1221 for(unsigned int i = 0; i < triangleCount; i++)
1223 batch[i][0] = index[(start + i + 0) % loop];
1224 batch[i][1] = index[(start + i + 1) % loop];
1225 batch[i][2] = index[(start + i + 1) % loop];
1229 case DRAW_INDEXEDLINELOOP16:
1231 const unsigned short *index = (const unsigned short*)indices;
1233 for(unsigned int i = 0; i < triangleCount; i++)
1235 batch[i][0] = index[(start + i + 0) % loop];
1236 batch[i][1] = index[(start + i + 1) % loop];
1237 batch[i][2] = index[(start + i + 1) % loop];
1241 case DRAW_INDEXEDLINELOOP32:
1243 const unsigned int *index = (const unsigned int*)indices;
1245 for(unsigned int i = 0; i < triangleCount; i++)
1247 batch[i][0] = index[(start + i + 0) % loop];
1248 batch[i][1] = index[(start + i + 1) % loop];
1249 batch[i][2] = index[(start + i + 1) % loop];
1253 case DRAW_INDEXEDTRIANGLELIST8:
1255 const unsigned char *index = (const unsigned char*)indices + 3 * start;
1257 for(unsigned int i = 0; i < triangleCount; i++)
1259 batch[i][0] = index[0];
1260 batch[i][1] = index[1];
1261 batch[i][2] = index[2];
1267 case DRAW_INDEXEDTRIANGLELIST16:
1269 const unsigned short *index = (const unsigned short*)indices + 3 * start;
1271 for(unsigned int i = 0; i < triangleCount; i++)
1273 batch[i][0] = index[0];
1274 batch[i][1] = index[1];
1275 batch[i][2] = index[2];
1281 case DRAW_INDEXEDTRIANGLELIST32:
1283 const unsigned int *index = (const unsigned int*)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_INDEXEDTRIANGLESTRIP8:
1297 const unsigned char *index = (const unsigned char*)indices + start;
1299 for(unsigned int i = 0; i < triangleCount; i++)
1301 batch[i][0] = index[0];
1302 batch[i][1] = index[((start + i) & 1) + 1];
1303 batch[i][2] = index[(~(start + i) & 1) + 1];
1309 case DRAW_INDEXEDTRIANGLESTRIP16:
1311 const unsigned short *index = (const unsigned short*)indices + start;
1313 for(unsigned int i = 0; i < triangleCount; i++)
1315 batch[i][0] = index[0];
1316 batch[i][1] = index[((start + i) & 1) + 1];
1317 batch[i][2] = index[(~(start + i) & 1) + 1];
1323 case DRAW_INDEXEDTRIANGLESTRIP32:
1325 const unsigned int *index = (const unsigned int*)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_INDEXEDTRIANGLEFAN8:
1339 const unsigned char *index = (const unsigned char*)indices;
1341 for(unsigned int i = 0; i < triangleCount; i++)
1343 batch[i][0] = index[start + i + 1];
1344 batch[i][1] = index[start + i + 2];
1345 batch[i][2] = index[0];
1349 case DRAW_INDEXEDTRIANGLEFAN16:
1351 const unsigned short *index = (const unsigned short*)indices;
1353 for(unsigned int i = 0; i < triangleCount; i++)
1355 batch[i][0] = index[start + i + 1];
1356 batch[i][1] = index[start + i + 2];
1357 batch[i][2] = index[0];
1361 case DRAW_INDEXEDTRIANGLEFAN32:
1363 const unsigned int *index = (const unsigned int*)indices;
1365 for(unsigned int i = 0; i < triangleCount; i++)
1367 batch[i][0] = index[start + i + 1];
1368 batch[i][1] = index[start + i + 2];
1369 batch[i][2] = index[0];
1375 unsigned int index = 4 * start / 2;
1377 for(unsigned int i = 0; i < triangleCount; i += 2)
1379 batch[i+0][0] = index + 0;
1380 batch[i+0][1] = index + 1;
1381 batch[i+0][2] = index + 2;
1383 batch[i+1][0] = index + 0;
1384 batch[i+1][1] = index + 2;
1385 batch[i+1][2] = index + 3;
1395 task->vertexCount = triangleCount * 3;
1396 vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
1399 int Renderer::setupSolidTriangles(Renderer *renderer, int unit, int count)
1401 Triangle *triangle = renderer->triangleBatch[unit];
1402 Primitive *primitive = renderer->primitiveBatch[unit];
1404 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1405 SetupProcessor::State &state = draw.setupState;
1406 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1408 int ms = state.multiSample;
1409 int pos = state.positionRegister;
1410 const DrawData *data = draw.data;
1413 for(int i = 0; i < count; i++, triangle++)
1415 Vertex &v0 = triangle->v0;
1416 Vertex &v1 = triangle->v1;
1417 Vertex &v2 = triangle->v2;
1419 if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
1421 Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
1423 int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
1425 if(clipFlagsOr != Clipper::CLIP_FINITE)
1427 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1433 if(setupRoutine(primitive, triangle, &polygon, data))
1444 int Renderer::setupWireframeTriangle(Renderer *renderer, int unit, int count)
1446 Triangle *triangle = renderer->triangleBatch[unit];
1447 Primitive *primitive = renderer->primitiveBatch[unit];
1450 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1451 SetupProcessor::State &state = draw.setupState;
1452 SetupProcessor::RoutinePointer setupRoutine = draw.setupPointer;
1454 const Vertex &v0 = triangle[0].v0;
1455 const Vertex &v1 = triangle[0].v1;
1456 const Vertex &v2 = triangle[0].v2;
1458 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;
1460 if(state.cullMode == CULL_CLOCKWISE)
1462 if(d >= 0) return 0;
1464 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1466 if(d <= 0) return 0;
1470 triangle[1].v0 = v1;
1471 triangle[1].v1 = v2;
1472 triangle[2].v0 = v2;
1473 triangle[2].v1 = v0;
1475 if(state.color[0][0].flat) // FIXME
1477 for(int i = 0; i < 2; i++)
1479 triangle[1].v0.C[i] = triangle[0].v0.C[i];
1480 triangle[1].v1.C[i] = triangle[0].v0.C[i];
1481 triangle[2].v0.C[i] = triangle[0].v0.C[i];
1482 triangle[2].v1.C[i] = triangle[0].v0.C[i];
1486 for(int i = 0; i < 3; i++)
1488 if(setupLine(renderer, *primitive, *triangle, draw))
1490 primitive->area = 0.5f * d;
1502 int Renderer::setupVertexTriangle(Renderer *renderer, int unit, int count)
1504 Triangle *triangle = renderer->triangleBatch[unit];
1505 Primitive *primitive = renderer->primitiveBatch[unit];
1508 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1509 SetupProcessor::State &state = draw.setupState;
1511 const Vertex &v0 = triangle[0].v0;
1512 const Vertex &v1 = triangle[0].v1;
1513 const Vertex &v2 = triangle[0].v2;
1515 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;
1517 if(state.cullMode == CULL_CLOCKWISE)
1519 if(d >= 0) return 0;
1521 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1523 if(d <= 0) return 0;
1527 triangle[1].v0 = v1;
1528 triangle[2].v0 = v2;
1530 for(int i = 0; i < 3; i++)
1532 if(setupPoint(renderer, *primitive, *triangle, draw))
1534 primitive->area = 0.5f * d;
1546 int Renderer::setupLines(Renderer *renderer, int unit, int count)
1548 Triangle *triangle = renderer->triangleBatch[unit];
1549 Primitive *primitive = renderer->primitiveBatch[unit];
1552 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1553 SetupProcessor::State &state = draw.setupState;
1555 int ms = state.multiSample;
1557 for(int i = 0; i < count; i++)
1559 if(setupLine(renderer, *primitive, *triangle, draw))
1571 int Renderer::setupPoints(Renderer *renderer, int unit, int count)
1573 Triangle *triangle = renderer->triangleBatch[unit];
1574 Primitive *primitive = renderer->primitiveBatch[unit];
1577 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1578 SetupProcessor::State &state = draw.setupState;
1580 int ms = state.multiSample;
1582 for(int i = 0; i < count; i++)
1584 if(setupPoint(renderer, *primitive, *triangle, draw))
1596 bool Renderer::setupLine(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1598 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1599 const SetupProcessor::State &state = draw.setupState;
1600 const DrawData &data = *draw.data;
1602 float lineWidth = data.lineWidth;
1604 Vertex &v0 = triangle.v0;
1605 Vertex &v1 = triangle.v1;
1607 int pos = state.positionRegister;
1609 const float4 &P0 = v0.v[pos];
1610 const float4 &P1 = v1.v[pos];
1612 if(P0.w <= 0 && P1.w <= 0)
1617 const float W = data.Wx16[0] * (1.0f / 16.0f);
1618 const float H = data.Hx16[0] * (1.0f / 16.0f);
1620 float dx = W * (P1.x / P1.w - P0.x / P0.w);
1621 float dy = H * (P1.y / P1.w - P0.y / P0.w);
1623 if(dx == 0 && dy == 0)
1628 if(false) // Rectangle
1638 float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
1643 float dx0w = dx * P0.w / W;
1644 float dy0h = dy * P0.w / H;
1645 float dx0h = dx * P0.w / H;
1646 float dy0w = dy * P0.w / W;
1648 float dx1w = dx * P1.w / W;
1649 float dy1h = dy * P1.w / H;
1650 float dx1h = dx * P1.w / H;
1651 float dy1w = dy * P1.w / W;
1653 P[0].x += -dy0w + -dx0w;
1654 P[0].y += -dx0h + +dy0h;
1655 C[0] = computeClipFlags(P[0], data);
1657 P[1].x += -dy1w + +dx1w;
1658 P[1].y += -dx1h + +dy1h;
1659 C[1] = computeClipFlags(P[1], data);
1661 P[2].x += +dy1w + +dx1w;
1662 P[2].y += +dx1h + -dy1h;
1663 C[2] = computeClipFlags(P[2], data);
1665 P[3].x += +dy0w + -dx0w;
1666 P[3].y += +dx0h + +dy0h;
1667 C[3] = computeClipFlags(P[3], data);
1669 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1671 Polygon polygon(P, 4);
1673 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1675 if(clipFlagsOr != Clipper::CLIP_FINITE)
1677 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1683 return setupRoutine(&primitive, &triangle, &polygon, &data);
1686 else // Diamond test convention
1700 float dx0 = lineWidth * 0.5f * P0.w / W;
1701 float dy0 = lineWidth * 0.5f * P0.w / H;
1703 float dx1 = lineWidth * 0.5f * P1.w / W;
1704 float dy1 = lineWidth * 0.5f * P1.w / H;
1707 C[0] = computeClipFlags(P[0], data);
1710 C[1] = computeClipFlags(P[1], data);
1713 C[2] = computeClipFlags(P[2], data);
1716 C[3] = computeClipFlags(P[3], data);
1719 C[4] = computeClipFlags(P[4], data);
1722 C[5] = computeClipFlags(P[5], data);
1725 C[6] = computeClipFlags(P[6], data);
1728 C[7] = computeClipFlags(P[7], data);
1730 if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
1736 if(dx > dy) // Right
1777 Polygon polygon(L, 6);
1779 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
1781 if(clipFlagsOr != Clipper::CLIP_FINITE)
1783 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1789 return setupRoutine(&primitive, &triangle, &polygon, &data);
1796 bool Renderer::setupPoint(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1798 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1799 const SetupProcessor::State &state = draw.setupState;
1800 const DrawData &data = *draw.data;
1802 Vertex &v = triangle.v0;
1806 int pts = state.pointSizeRegister;
1808 if(state.pointSizeRegister != 0xF)
1814 pSize = data.point.pointSize[0];
1817 pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
1822 int pos = state.positionRegister;
1829 const float X = pSize * P[0].w * data.halfPixelX[0];
1830 const float Y = pSize * P[0].w * data.halfPixelY[0];
1834 C[0] = computeClipFlags(P[0], data);
1838 C[1] = computeClipFlags(P[1], data);
1842 C[2] = computeClipFlags(P[2], data);
1846 C[3] = computeClipFlags(P[3], data);
1848 triangle.v1 = triangle.v0;
1849 triangle.v2 = triangle.v0;
1851 triangle.v1.X += iround(16 * 0.5f * pSize);
1852 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
1854 Polygon polygon(P, 4);
1856 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1858 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1860 if(clipFlagsOr != Clipper::CLIP_FINITE)
1862 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1868 return setupRoutine(&primitive, &triangle, &polygon, &data);
1874 unsigned int Renderer::computeClipFlags(const float4 &v, const DrawData &data)
1876 return ((v.x > v.w) << 0) |
1877 ((v.y > v.w) << 1) |
1878 ((v.z > v.w) << 2) |
1879 ((v.x < -v.w) << 3) |
1880 ((v.y < -v.w) << 4) |
1882 Clipper::CLIP_FINITE; // FIXME: xyz finite
1885 void Renderer::initializeThreads()
1887 unitCount = ceilPow2(threadCount);
1888 clusterCount = ceilPow2(threadCount);
1890 for(int i = 0; i < unitCount; i++)
1892 triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
1893 primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
1896 for(int i = 0; i < threadCount; i++)
1898 vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
1899 vertexTask[i]->vertexCache.drawCall = -1;
1901 task[i].type = Task::SUSPEND;
1903 resume[i] = new Event();
1904 suspend[i] = new Event();
1906 Parameters parameters;
1907 parameters.threadIndex = i;
1908 parameters.renderer = this;
1910 exitThreads = false;
1911 worker[i] = new Thread(threadFunction, ¶meters);
1914 suspend[i]->signal();
1918 void Renderer::terminateThreads()
1920 while(threadsAwake != 0)
1925 for(int thread = 0; thread < threadCount; thread++)
1930 resume[thread]->signal();
1931 worker[thread]->join();
1933 delete worker[thread];
1935 delete resume[thread];
1937 delete suspend[thread];
1938 suspend[thread] = 0;
1941 deallocate(vertexTask[thread]);
1942 vertexTask[thread] = 0;
1945 for(int i = 0; i < 16; i++)
1947 deallocate(triangleBatch[i]);
1948 triangleBatch[i] = 0;
1950 deallocate(primitiveBatch[i]);
1951 primitiveBatch[i] = 0;
1955 void Renderer::loadConstants(const VertexShader *vertexShader)
1957 if(!vertexShader) return;
1959 size_t count = vertexShader->getLength();
1961 for(size_t i = 0; i < count; i++)
1963 const Shader::Instruction *instruction = vertexShader->getInstruction(i);
1965 if(instruction->opcode == Shader::OPCODE_DEF)
1967 int index = instruction->dst.index;
1970 value[0] = instruction->src[0].value[0];
1971 value[1] = instruction->src[0].value[1];
1972 value[2] = instruction->src[0].value[2];
1973 value[3] = instruction->src[0].value[3];
1975 setVertexShaderConstantF(index, value);
1977 else if(instruction->opcode == Shader::OPCODE_DEFI)
1979 int index = instruction->dst.index;
1982 integer[0] = instruction->src[0].integer[0];
1983 integer[1] = instruction->src[0].integer[1];
1984 integer[2] = instruction->src[0].integer[2];
1985 integer[3] = instruction->src[0].integer[3];
1987 setVertexShaderConstantI(index, integer);
1989 else if(instruction->opcode == Shader::OPCODE_DEFB)
1991 int index = instruction->dst.index;
1992 int boolean = instruction->src[0].boolean[0];
1994 setVertexShaderConstantB(index, &boolean);
1999 void Renderer::loadConstants(const PixelShader *pixelShader)
2001 if(!pixelShader) return;
2003 size_t count = pixelShader->getLength();
2005 for(size_t i = 0; i < count; i++)
2007 const Shader::Instruction *instruction = pixelShader->getInstruction(i);
2009 if(instruction->opcode == Shader::OPCODE_DEF)
2011 int index = instruction->dst.index;
2014 value[0] = instruction->src[0].value[0];
2015 value[1] = instruction->src[0].value[1];
2016 value[2] = instruction->src[0].value[2];
2017 value[3] = instruction->src[0].value[3];
2019 setPixelShaderConstantF(index, value);
2021 else if(instruction->opcode == Shader::OPCODE_DEFI)
2023 int index = instruction->dst.index;
2026 integer[0] = instruction->src[0].integer[0];
2027 integer[1] = instruction->src[0].integer[1];
2028 integer[2] = instruction->src[0].integer[2];
2029 integer[3] = instruction->src[0].integer[3];
2031 setPixelShaderConstantI(index, integer);
2033 else if(instruction->opcode == Shader::OPCODE_DEFB)
2035 int index = instruction->dst.index;
2036 int boolean = instruction->src[0].boolean[0];
2038 setPixelShaderConstantB(index, &boolean);
2043 void Renderer::setIndexBuffer(Resource *indexBuffer)
2045 context->indexBuffer = indexBuffer;
2048 void Renderer::setMultiSampleMask(unsigned int mask)
2050 context->sampleMask = mask;
2053 void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
2055 sw::transparencyAntialiasing = transparencyAntialiasing;
2058 bool Renderer::isReadWriteTexture(int sampler)
2060 for(int index = 0; index < RENDERTARGETS; index++)
2062 if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
2068 if(context->depthStencil && context->texture[sampler] == context->depthStencil->getResource())
2076 void Renderer::updateClipper()
2078 if(updateClipPlanes)
2080 if(VertexProcessor::isFixedFunction()) // User plane in world space
2082 const Matrix &scissorWorld = getViewTransform();
2084 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
2085 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
2086 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
2087 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
2088 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
2089 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
2091 else // User plane in clip space
2093 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
2094 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
2095 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
2096 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
2097 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
2098 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
2101 updateClipPlanes = false;
2105 void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
2107 ASSERT(sampler < TOTAL_IMAGE_UNITS);
2109 context->texture[sampler] = resource;
2112 void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
2114 ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
2116 context->sampler[sampler].setTextureLevel(face, level, surface, type);
2119 void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
2121 if(type == SAMPLER_PIXEL)
2123 PixelProcessor::setTextureFilter(sampler, textureFilter);
2127 VertexProcessor::setTextureFilter(sampler, textureFilter);
2131 void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
2133 if(type == SAMPLER_PIXEL)
2135 PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
2139 VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
2143 void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
2145 if(type == SAMPLER_PIXEL)
2147 PixelProcessor::setGatherEnable(sampler, enable);
2151 VertexProcessor::setGatherEnable(sampler, enable);
2155 void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
2157 if(type == SAMPLER_PIXEL)
2159 PixelProcessor::setAddressingModeU(sampler, addressMode);
2163 VertexProcessor::setAddressingModeU(sampler, addressMode);
2167 void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
2169 if(type == SAMPLER_PIXEL)
2171 PixelProcessor::setAddressingModeV(sampler, addressMode);
2175 VertexProcessor::setAddressingModeV(sampler, addressMode);
2179 void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
2181 if(type == SAMPLER_PIXEL)
2183 PixelProcessor::setAddressingModeW(sampler, addressMode);
2187 VertexProcessor::setAddressingModeW(sampler, addressMode);
2191 void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
2193 if(type == SAMPLER_PIXEL)
2195 PixelProcessor::setReadSRGB(sampler, sRGB);
2199 VertexProcessor::setReadSRGB(sampler, sRGB);
2203 void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
2205 if(type == SAMPLER_PIXEL)
2207 PixelProcessor::setMipmapLOD(sampler, bias);
2211 VertexProcessor::setMipmapLOD(sampler, bias);
2215 void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
2217 if(type == SAMPLER_PIXEL)
2219 PixelProcessor::setBorderColor(sampler, borderColor);
2223 VertexProcessor::setBorderColor(sampler, borderColor);
2227 void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
2229 if(type == SAMPLER_PIXEL)
2231 PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2235 VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2239 void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
2241 if(type == SAMPLER_PIXEL)
2243 PixelProcessor::setSwizzleR(sampler, swizzleR);
2247 VertexProcessor::setSwizzleR(sampler, swizzleR);
2251 void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
2253 if(type == SAMPLER_PIXEL)
2255 PixelProcessor::setSwizzleG(sampler, swizzleG);
2259 VertexProcessor::setSwizzleG(sampler, swizzleG);
2263 void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
2265 if(type == SAMPLER_PIXEL)
2267 PixelProcessor::setSwizzleB(sampler, swizzleB);
2271 VertexProcessor::setSwizzleB(sampler, swizzleB);
2275 void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
2277 if(type == SAMPLER_PIXEL)
2279 PixelProcessor::setSwizzleA(sampler, swizzleA);
2283 VertexProcessor::setSwizzleA(sampler, swizzleA);
2287 void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
2289 context->setPointSpriteEnable(pointSpriteEnable);
2292 void Renderer::setPointScaleEnable(bool pointScaleEnable)
2294 context->setPointScaleEnable(pointScaleEnable);
2297 void Renderer::setLineWidth(float width)
2299 context->lineWidth = width;
2302 void Renderer::setDepthBias(float bias)
2307 void Renderer::setSlopeDepthBias(float slopeBias)
2309 slopeDepthBias = slopeBias;
2312 void Renderer::setPixelShader(const PixelShader *shader)
2314 context->pixelShader = shader;
2316 loadConstants(shader);
2319 void Renderer::setVertexShader(const VertexShader *shader)
2321 context->vertexShader = shader;
2323 loadConstants(shader);
2326 void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
2328 for(int i = 0; i < DRAW_COUNT; i++)
2330 if(drawCall[i]->psDirtyConstF < index + count)
2332 drawCall[i]->psDirtyConstF = index + count;
2336 for(int i = 0; i < count; i++)
2338 PixelProcessor::setFloatConstant(index + i, value);
2343 void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
2345 for(int i = 0; i < DRAW_COUNT; i++)
2347 if(drawCall[i]->psDirtyConstI < index + count)
2349 drawCall[i]->psDirtyConstI = index + count;
2353 for(int i = 0; i < count; i++)
2355 PixelProcessor::setIntegerConstant(index + i, value);
2360 void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
2362 for(int i = 0; i < DRAW_COUNT; i++)
2364 if(drawCall[i]->psDirtyConstB < index + count)
2366 drawCall[i]->psDirtyConstB = index + count;
2370 for(int i = 0; i < count; i++)
2372 PixelProcessor::setBooleanConstant(index + i, *boolean);
2377 void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
2379 for(int i = 0; i < DRAW_COUNT; i++)
2381 if(drawCall[i]->vsDirtyConstF < index + count)
2383 drawCall[i]->vsDirtyConstF = index + count;
2387 for(int i = 0; i < count; i++)
2389 VertexProcessor::setFloatConstant(index + i, value);
2394 void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
2396 for(int i = 0; i < DRAW_COUNT; i++)
2398 if(drawCall[i]->vsDirtyConstI < index + count)
2400 drawCall[i]->vsDirtyConstI = index + count;
2404 for(int i = 0; i < count; i++)
2406 VertexProcessor::setIntegerConstant(index + i, value);
2411 void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
2413 for(int i = 0; i < DRAW_COUNT; i++)
2415 if(drawCall[i]->vsDirtyConstB < index + count)
2417 drawCall[i]->vsDirtyConstB = index + count;
2421 for(int i = 0; i < count; i++)
2423 VertexProcessor::setBooleanConstant(index + i, *boolean);
2428 void Renderer::setModelMatrix(const Matrix &M, int i)
2430 VertexProcessor::setModelMatrix(M, i);
2433 void Renderer::setViewMatrix(const Matrix &V)
2435 VertexProcessor::setViewMatrix(V);
2436 updateClipPlanes = true;
2439 void Renderer::setBaseMatrix(const Matrix &B)
2441 VertexProcessor::setBaseMatrix(B);
2442 updateClipPlanes = true;
2445 void Renderer::setProjectionMatrix(const Matrix &P)
2447 VertexProcessor::setProjectionMatrix(P);
2448 updateClipPlanes = true;
2451 void Renderer::addQuery(Query *query)
2453 queries.push_back(query);
2456 void Renderer::removeQuery(Query *query)
2458 queries.remove(query);
2462 int Renderer::getThreadCount()
2467 int64_t Renderer::getVertexTime(int thread)
2469 return vertexTime[thread];
2472 int64_t Renderer::getSetupTime(int thread)
2474 return setupTime[thread];
2477 int64_t Renderer::getPixelTime(int thread)
2479 return pixelTime[thread];
2482 void Renderer::resetTimers()
2484 for(int thread = 0; thread < threadCount; thread++)
2486 vertexTime[thread] = 0;
2487 setupTime[thread] = 0;
2488 pixelTime[thread] = 0;
2493 void Renderer::setViewport(const Viewport &viewport)
2495 this->viewport = viewport;
2498 void Renderer::setScissor(const Rect &scissor)
2500 this->scissor = scissor;
2503 void Renderer::setClipFlags(int flags)
2505 clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
2508 void Renderer::setClipPlane(unsigned int index, const float plane[4])
2510 if(index < MAX_CLIP_PLANES)
2512 userPlane[index] = plane;
2516 updateClipPlanes = true;
2519 void Renderer::updateConfiguration(bool initialUpdate)
2521 bool newConfiguration = swiftConfig->hasNewConfiguration();
2523 if(newConfiguration || initialUpdate)
2527 SwiftConfig::Configuration configuration = {0};
2528 swiftConfig->getConfiguration(configuration);
2530 precacheVertex = !newConfiguration && configuration.precache;
2531 precacheSetup = !newConfiguration && configuration.precache;
2532 precachePixel = !newConfiguration && configuration.precache;
2534 VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
2535 PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
2536 SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
2538 switch(configuration.textureSampleQuality)
2540 case 0: Sampler::setFilterQuality(FILTER_POINT); break;
2541 case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
2542 case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2543 default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2546 switch(configuration.mipmapQuality)
2548 case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
2549 case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2550 default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2553 setPerspectiveCorrection(configuration.perspectiveCorrection);
2555 switch(configuration.transcendentalPrecision)
2558 logPrecision = APPROXIMATE;
2559 expPrecision = APPROXIMATE;
2560 rcpPrecision = APPROXIMATE;
2561 rsqPrecision = APPROXIMATE;
2564 logPrecision = PARTIAL;
2565 expPrecision = PARTIAL;
2566 rcpPrecision = PARTIAL;
2567 rsqPrecision = PARTIAL;
2570 logPrecision = ACCURATE;
2571 expPrecision = ACCURATE;
2572 rcpPrecision = ACCURATE;
2573 rsqPrecision = ACCURATE;
2576 logPrecision = WHQL;
2577 expPrecision = WHQL;
2578 rcpPrecision = WHQL;
2579 rsqPrecision = WHQL;
2582 logPrecision = IEEE;
2583 expPrecision = IEEE;
2584 rcpPrecision = IEEE;
2585 rsqPrecision = IEEE;
2588 logPrecision = ACCURATE;
2589 expPrecision = ACCURATE;
2590 rcpPrecision = ACCURATE;
2591 rsqPrecision = ACCURATE;
2595 switch(configuration.transparencyAntialiasing)
2597 case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2598 case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
2599 default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2602 switch(configuration.threadCount)
2604 case -1: threadCount = CPUID::coreCount(); break;
2605 case 0: threadCount = CPUID::processAffinity(); break;
2606 default: threadCount = configuration.threadCount; break;
2609 CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
2610 CPUID::setEnableSSSE3(configuration.enableSSSE3);
2611 CPUID::setEnableSSE3(configuration.enableSSE3);
2612 CPUID::setEnableSSE2(configuration.enableSSE2);
2613 CPUID::setEnableSSE(configuration.enableSSE);
2615 for(int pass = 0; pass < 10; pass++)
2617 optimization[pass] = configuration.optimization[pass];
2620 forceWindowed = configuration.forceWindowed;
2621 complementaryDepthBuffer = configuration.complementaryDepthBuffer;
2622 postBlendSRGB = configuration.postBlendSRGB;
2623 exactColorRounding = configuration.exactColorRounding;
2624 forceClearRegisters = configuration.forceClearRegisters;
2627 minPrimitives = configuration.minPrimitives;
2628 maxPrimitives = configuration.maxPrimitives;
2632 if(!initialUpdate && !worker[0])
2634 initializeThreads();