OSDN Git Service

Transform feedback query implementation
[android-x86/external-swiftshader.git] / src / Renderer / Renderer.cpp
1 // SwiftShader Software Renderer
2 //
3 // Copyright(c) 2005-2012 TransGaming Inc.
4 //
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.
10 //
11
12 #include "Renderer.hpp"
13
14 #include "Clipper.hpp"
15 #include "Math.hpp"
16 #include "FrameBuffer.hpp"
17 #include "Timer.hpp"
18 #include "Surface.hpp"
19 #include "Half.hpp"
20 #include "Primitive.hpp"
21 #include "Polygon.hpp"
22 #include "SwiftConfig.hpp"
23 #include "MutexLock.hpp"
24 #include "CPUID.hpp"
25 #include "Memory.hpp"
26 #include "Resource.hpp"
27 #include "Constants.hpp"
28 #include "Debug.hpp"
29 #include "Reactor/Reactor.hpp"
30
31 #undef max
32
33 bool disableServer = true;
34
35 #ifndef NDEBUG
36 unsigned int minPrimitives = 1;
37 unsigned int maxPrimitives = 1 << 21;
38 #endif
39
40 namespace sw
41 {
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
48
49         extern bool forceWindowed;
50         extern bool complementaryDepthBuffer;
51         extern bool postBlendSRGB;
52         extern bool exactColorRounding;
53         extern TransparencyAntialiasing transparencyAntialiasing;
54         extern bool forceClearRegisters;
55
56         extern bool precacheVertex;
57         extern bool precacheSetup;
58         extern bool precachePixel;
59
60         int batchSize = 128;
61         int threadCount = 1;
62         int unitCount = 1;
63         int clusterCount = 1;
64
65         TranscendentalPrecision logPrecision = ACCURATE;
66         TranscendentalPrecision expPrecision = ACCURATE;
67         TranscendentalPrecision rcpPrecision = ACCURATE;
68         TranscendentalPrecision rsqPrecision = ACCURATE;
69         bool perspectiveCorrection = true;
70
71         struct Parameters
72         {
73                 Renderer *renderer;
74                 int threadIndex;
75         };
76
77         DrawCall::DrawCall()
78         {
79                 queries = 0;
80
81                 vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
82                 vsDirtyConstI = 16;
83                 vsDirtyConstB = 16;
84
85                 psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
86                 psDirtyConstI = 16;
87                 psDirtyConstB = 16;
88
89                 references = -1;
90
91                 data = (DrawData*)allocate(sizeof(DrawData));
92                 data->constants = &constants;
93         }
94
95         DrawCall::~DrawCall()
96         {
97                 delete queries;
98
99                 deallocate(data);
100         }
101
102         Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), context(context), viewport()
103         {
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;
111
112                 setRenderTarget(0, 0);
113                 clipper = new Clipper();
114
115                 updateViewMatrix = true;
116                 updateBaseMatrix = true;
117                 updateProjectionMatrix = true;
118                 updateClipPlanes = true;
119
120                 #if PERF_HUD
121                         resetTimers();
122                 #endif
123
124                 for(int i = 0; i < 16; i++)
125                 {
126                         vertexTask[i] = 0;
127
128                         worker[i] = 0;
129                         resume[i] = 0;
130                         suspend[i] = 0;
131                 }
132
133                 threadsAwake = 0;
134                 resumeApp = new Event();
135
136                 currentDraw = 0;
137                 nextDraw = 0;
138
139                 qHead = 0;
140                 qSize = 0;
141
142                 for(int i = 0; i < 16; i++)
143                 {
144                         triangleBatch[i] = 0;
145                         primitiveBatch[i] = 0;
146                 }
147
148                 for(int draw = 0; draw < DRAW_COUNT; draw++)
149                 {
150                         drawCall[draw] = new DrawCall();
151                         drawList[draw] = drawCall[draw];
152                 }
153
154                 for(int unit = 0; unit < 16; unit++)
155                 {
156                         primitiveProgress[unit].init();
157                 }
158
159                 for(int cluster = 0; cluster < 16; cluster++)
160                 {
161                         pixelProgress[cluster].init();
162                 }
163
164                 clipFlags = 0;
165
166                 swiftConfig = new SwiftConfig(disableServer);
167                 updateConfiguration(true);
168
169                 sync = new Resource(0);
170         }
171
172         Renderer::~Renderer()
173         {
174                 sync->destruct();
175
176                 delete clipper;
177                 clipper = 0;
178
179                 terminateThreads();
180                 delete resumeApp;
181
182                 for(int draw = 0; draw < DRAW_COUNT; draw++)
183                 {
184                         delete drawCall[draw];
185                 }
186
187                 delete swiftConfig;
188         }
189
190         void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
191         {
192                 blitter.clear(pixel, format, dest, dRect, rgbaMask);
193         }
194
195         void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter)
196         {
197                 blitter.blit(source, sRect, dest, dRect, filter);
198         }
199
200         void Renderer::blit3D(Surface *source, Surface *dest)
201         {
202                 blitter.blit3D(source, dest);
203         }
204
205         void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
206         {
207                 #ifndef NDEBUG
208                         if(count < minPrimitives || count > maxPrimitives)
209                         {
210                                 return;
211                         }
212                 #endif
213
214                 context->drawType = drawType;
215
216                 updateConfiguration();
217                 updateClipper();
218
219                 int ss = context->getSuperSampleCount();
220                 int ms = context->getMultiSampleCount();
221
222                 for(int q = 0; q < ss; q++)
223                 {
224                         unsigned int oldMultiSampleMask = context->multiSampleMask;
225                         context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
226
227                         if(!context->multiSampleMask)
228                         {
229                                 continue;
230                         }
231
232                         sync->lock(sw::PRIVATE);
233
234                         Routine *vertexRoutine;
235                         Routine *setupRoutine;
236                         Routine *pixelRoutine;
237
238                         if(update || oldMultiSampleMask != context->multiSampleMask)
239                         {
240                                 vertexState = VertexProcessor::update();
241                                 setupState = SetupProcessor::update();
242                                 pixelState = PixelProcessor::update();
243
244                                 vertexRoutine = VertexProcessor::routine(vertexState);
245                                 setupRoutine = SetupProcessor::routine(setupState);
246                                 pixelRoutine = PixelProcessor::routine(pixelState);
247                         }
248
249                         int batch = batchSize / ms;
250
251                         int (*setupPrimitives)(Renderer *renderer, int batch, int count);
252
253                         if(context->isDrawTriangle())
254                         {
255                                 switch(context->fillMode)
256                                 {
257                                 case FILL_SOLID:
258                                         setupPrimitives = setupSolidTriangles;
259                                         break;
260                                 case FILL_WIREFRAME:
261                                         setupPrimitives = setupWireframeTriangle;
262                                         batch = 1;
263                                         break;
264                                 case FILL_VERTEX:
265                                         setupPrimitives = setupVertexTriangle;
266                                         batch = 1;
267                                         break;
268                                 default: ASSERT(false);
269                                 }
270                         }
271                         else if(context->isDrawLine())
272                         {
273                                 setupPrimitives = setupLines;
274                         }
275                         else   // Point draw
276                         {
277                                 setupPrimitives = setupPoints;
278                         }
279
280                         DrawCall *draw = 0;
281
282                         do
283                         {
284                                 for(int i = 0; i < DRAW_COUNT; i++)
285                                 {
286                                         if(drawCall[i]->references == -1)
287                                         {
288                                                 draw = drawCall[i];
289                                                 drawList[nextDraw % DRAW_COUNT] = draw;
290
291                                                 break;
292                                         }
293                                 }
294
295                                 if(!draw)
296                                 {
297                                         resumeApp->wait();
298                                 }
299                         }
300                         while(!draw);
301
302                         DrawData *data = draw->data;
303
304                         if(queries.size() != 0)
305                         {
306                                 draw->queries = new std::list<Query*>();
307                                 bool includePrimitivesWrittenQueries = vertexState.transformFeedbackQueryEnabled && vertexState.transformFeedbackEnabled;
308                                 for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
309                                 {
310                                         Query* q = *query;
311                                         if(includePrimitivesWrittenQueries || (q->type != Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN))
312                                         {
313                                                 atomicIncrement(&(q->reference));
314                                                 draw->queries->push_back(q);
315                                         }
316                                 }
317                         }
318
319                         draw->drawType = drawType;
320                         draw->batchSize = batch;
321
322                         vertexRoutine->bind();
323                         setupRoutine->bind();
324                         pixelRoutine->bind();
325
326                         draw->vertexRoutine = vertexRoutine;
327                         draw->setupRoutine = setupRoutine;
328                         draw->pixelRoutine = pixelRoutine;
329                         draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
330                         draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
331                         draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
332                         draw->setupPrimitives = setupPrimitives;
333                         draw->setupState = setupState;
334
335                         for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
336                         {
337                                 draw->vertexStream[i] = context->input[i].resource;
338                                 data->input[i] = context->input[i].buffer;
339                                 data->stride[i] = context->input[i].stride;
340
341                                 if(draw->vertexStream[i])
342                                 {
343                                         draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
344                                 }
345                         }
346
347                         if(context->indexBuffer)
348                         {
349                                 data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
350                         }
351
352                         draw->indexBuffer = context->indexBuffer;
353
354                         for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
355                         {
356                                 draw->texture[sampler] = 0;
357                         }
358
359                         for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
360                         {
361                                 if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
362                                 {
363                                         draw->texture[sampler] = context->texture[sampler];
364                                         draw->texture[sampler]->lock(PUBLIC, isReadWriteTexture(sampler) ? MANAGED : PRIVATE);   // If the texure is both read and written, use the same read/write lock as render targets
365
366                                         data->mipmap[sampler] = context->sampler[sampler].getTextureData();
367                                 }
368                         }
369
370                         if(context->pixelShader)
371                         {
372                                 if(draw->psDirtyConstF)
373                                 {
374                                         memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
375                                         memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
376                                         draw->psDirtyConstF = 0;
377                                 }
378
379                                 if(draw->psDirtyConstI)
380                                 {
381                                         memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
382                                         draw->psDirtyConstI = 0;
383                                 }
384
385                                 if(draw->psDirtyConstB)
386                                 {
387                                         memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
388                                         draw->psDirtyConstB = 0;
389                                 }
390
391                                 PixelProcessor::lockUniformBuffers(data->ps.u);
392                         }
393                         
394                         if(context->pixelShaderVersion() <= 0x0104)
395                         {
396                                 for(int stage = 0; stage < 8; stage++)
397                                 {
398                                         if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
399                                         {
400                                                 data->textureStage[stage] = context->textureStage[stage].uniforms;
401                                         }
402                                         else break;
403                                 }
404                         }
405
406                         if(context->vertexShader)
407                         {
408                                 if(context->vertexShader->getVersion() >= 0x0300)
409                                 {
410                                         for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
411                                         {
412                                                 if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
413                                                 {
414                                                         draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
415                                                         draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
416
417                                                         data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
418                                                 }
419                                         }
420                                 }
421
422                                 if(draw->vsDirtyConstF)
423                                 {
424                                         memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
425                                         draw->vsDirtyConstF = 0;
426                                 }
427
428                                 if(draw->vsDirtyConstI)
429                                 {
430                                         memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
431                                         draw->vsDirtyConstI = 0;
432                                 }
433
434                                 if(draw->vsDirtyConstB)
435                                 {
436                                         memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
437                                         draw->vsDirtyConstB = 0;
438                                 }
439
440                                 if(context->vertexShader->instanceIdDeclared)
441                                 {
442                                         data->instanceID = context->instanceID;
443                                 }
444
445                                 VertexProcessor::lockUniformBuffers(data->vs.u);
446                         }
447                         else
448                         {
449                                 data->ff = ff;
450
451                                 draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
452                                 draw->vsDirtyConstI = 16;
453                                 draw->vsDirtyConstB = 16;
454                         }
455
456                         if(pixelState.stencilActive)
457                         {
458                                 data->stencil[0] = stencil;
459                                 data->stencil[1] = stencilCCW;
460                         }
461
462                         if(pixelState.fogActive)
463                         {
464                                 data->fog = fog;
465                         }
466
467                         if(setupState.isDrawPoint)
468                         {
469                                 data->point = point;
470                         }
471
472                         data->lineWidth = context->lineWidth;
473
474                         data->factor = factor;
475
476                         if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
477                         {
478                                 float ref = context->alphaReference * (1.0f / 255.0f);
479                                 float margin = sw::min(ref, 1.0f - ref);
480
481                                 if(ms == 4)
482                                 {
483                                         data->a2c0 = replicate(ref - margin * 0.6f);
484                                         data->a2c1 = replicate(ref - margin * 0.2f);
485                                         data->a2c2 = replicate(ref + margin * 0.2f);
486                                         data->a2c3 = replicate(ref + margin * 0.6f);
487                                 }
488                                 else if(ms == 2)
489                                 {
490                                         data->a2c0 = replicate(ref - margin * 0.3f);
491                                         data->a2c1 = replicate(ref + margin * 0.3f);
492                                 }
493                                 else ASSERT(false);
494                         }
495
496                         if(pixelState.occlusionEnabled)
497                         {
498                                 for(int cluster = 0; cluster < clusterCount; cluster++)
499                                 {
500                                         data->occlusion[cluster] = 0;
501                                 }
502                         }
503
504                         #if PERF_PROFILE
505                                 for(int cluster = 0; cluster < clusterCount; cluster++)
506                                 {
507                                         for(int i = 0; i < PERF_TIMERS; i++)
508                                         {
509                                                 data->cycles[i][cluster] = 0;
510                                         }
511                                 }
512                         #endif
513
514                         // Viewport
515                         {
516                                 float W = 0.5f * viewport.width;
517                                 float H = 0.5f * viewport.height;
518                                 float X0 = viewport.x0 + W;
519                                 float Y0 = viewport.y0 + H;
520                                 float N = viewport.minZ;
521                                 float F = viewport.maxZ;
522                                 float Z = F - N;
523
524                                 if(context->isDrawTriangle(false))
525                                 {
526                                         N += depthBias;
527                                 }
528
529                                 if(complementaryDepthBuffer)
530                                 {
531                                         Z = -Z;
532                                         N = 1 - N;
533                                 }
534
535                                 static const float X[5][16] =   // Fragment offsets
536                                 {
537                                         {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 1 sample
538                                         {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 2 samples
539                                         {-0.3000f, +0.1000f, +0.3000f, -0.1000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 4 samples
540                                         {+0.1875f, -0.3125f, +0.3125f, -0.4375f, -0.0625f, +0.4375f, +0.0625f, -0.1875f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 8 samples
541                                         {+0.2553f, -0.1155f, +0.1661f, -0.1828f, +0.2293f, -0.4132f, -0.1773f, -0.0577f, +0.3891f, -0.4656f, +0.4103f, +0.4248f, -0.2109f, +0.3966f, -0.2664f, -0.3872f}    // 16 samples
542                                 };
543
544                                 static const float Y[5][16] =   // Fragment offsets
545                                 {
546                                         {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 1 sample
547                                         {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 2 samples
548                                         {-0.1000f, -0.3000f, +0.1000f, +0.3000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 4 samples
549                                         {-0.4375f, -0.3125f, -0.1875f, -0.0625f, +0.0625f, +0.1875f, +0.3125f, +0.4375f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f},   // 8 samples
550                                         {-0.4503f, +0.1883f, +0.3684f, -0.4668f, -0.0690f, -0.1315f, +0.4999f, +0.0728f, +0.1070f, -0.3086f, +0.3725f, -0.1547f, -0.1102f, -0.3588f, +0.1789f, +0.0269f}    // 16 samples
551                                 };
552
553                                 int s = sw::log2(ss);
554
555                                 data->Wx16 = replicate(W * 16);
556                                 data->Hx16 = replicate(H * 16);
557                                 data->X0x16 = replicate(X0 * 16 - 8);
558                                 data->Y0x16 = replicate(Y0 * 16 - 8);
559                                 data->XXXX = replicate(X[s][q] / W);
560                                 data->YYYY = replicate(Y[s][q] / H);
561                                 data->halfPixelX = replicate(0.5f / W);
562                                 data->halfPixelY = replicate(0.5f / H);
563                                 data->viewportHeight = abs(viewport.height);
564                                 data->slopeDepthBias = slopeDepthBias;
565                                 data->depthRange = Z;
566                                 data->depthNear = N;
567                                 draw->clipFlags = clipFlags;
568
569                                 if(clipFlags)
570                                 {
571                                         if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
572                                         if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
573                                         if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
574                                         if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
575                                         if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
576                                         if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
577                                 }
578                         }
579
580                         // Target
581                         {
582                                 for(int index = 0; index < RENDERTARGETS; index++)
583                                 {
584                                         draw->renderTarget[index] = context->renderTarget[index];
585
586                                         if(draw->renderTarget[index])
587                                         {
588                                                 data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
589                                                 data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
590                                                 data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
591                                         }
592                                 }
593
594                                 draw->depthStencil = context->depthStencil;
595
596                                 if(draw->depthStencil)
597                                 {
598                                         data->depthBuffer = (float*)context->depthStencil->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
599                                         data->depthPitchB = context->depthStencil->getInternalPitchB();
600                                         data->depthSliceB = context->depthStencil->getInternalSliceB();
601
602                                         data->stencilBuffer = (unsigned char*)context->depthStencil->lockStencil(q * ms, MANAGED);
603                                         data->stencilPitchB = context->depthStencil->getStencilPitchB();
604                                         data->stencilSliceB = context->depthStencil->getStencilSliceB();
605                                 }
606                         }
607
608                         // Scissor
609                         {
610                                 data->scissorX0 = scissor.x0;
611                                 data->scissorX1 = scissor.x1;
612                                 data->scissorY0 = scissor.y0;
613                                 data->scissorY1 = scissor.y1;
614                         }
615
616                         draw->primitive = 0;
617                         draw->count = count;
618
619                         draw->references = (count + batch - 1) / batch;
620
621                         schedulerMutex.lock();
622                         nextDraw++;
623                         schedulerMutex.unlock();
624
625                         if(threadCount > 1)
626                         {
627                                 if(!threadsAwake)
628                                 {
629                                         suspend[0]->wait();
630
631                                         threadsAwake = 1;
632                                         task[0].type = Task::RESUME;
633
634                                         resume[0]->signal();
635                                 }
636                         }
637                         else   // Use main thread for draw execution
638                         {
639                                 threadsAwake = 1;
640                                 task[0].type = Task::RESUME;
641
642                                 taskLoop(0);
643                         }
644                 }
645         }
646
647         void Renderer::threadFunction(void *parameters)
648         {
649                 Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
650                 int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
651
652                 if(logPrecision < IEEE)
653                 {
654                         CPUID::setFlushToZero(true);
655                         CPUID::setDenormalsAreZero(true);
656                 }
657
658                 renderer->threadLoop(threadIndex);
659         }
660
661         void Renderer::threadLoop(int threadIndex)
662         {
663                 while(!exitThreads)
664                 {
665                         taskLoop(threadIndex);
666
667                         suspend[threadIndex]->signal();
668                         resume[threadIndex]->wait();
669                 }
670         }
671
672         void Renderer::taskLoop(int threadIndex)
673         {
674                 while(task[threadIndex].type != Task::SUSPEND)
675                 {
676                         scheduleTask(threadIndex);
677                         executeTask(threadIndex);
678                 }
679         }
680
681         void Renderer::findAvailableTasks()
682         {
683                 // Find pixel tasks
684                 for(int cluster = 0; cluster < clusterCount; cluster++)
685                 {
686                         if(!pixelProgress[cluster].executing)
687                         {
688                                 for(int unit = 0; unit < unitCount; unit++)
689                                 {
690                                         if(primitiveProgress[unit].references > 0)   // Contains processed primitives
691                                         {
692                                                 if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
693                                                 {
694                                                         if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive)   // Previous primitives have been rendered
695                                                         {
696                                                                 Task &task = taskQueue[qHead];
697                                                                 task.type = Task::PIXELS;
698                                                                 task.primitiveUnit = unit;
699                                                                 task.pixelCluster = cluster;
700
701                                                                 pixelProgress[cluster].executing = true;
702
703                                                                 // Commit to the task queue
704                                                                 qHead = (qHead + 1) % 32;
705                                                                 qSize++;
706
707                                                                 break;
708                                                         }
709                                                 }
710                                         }
711                                 }
712                         }
713                 }
714         
715                 // Find primitive tasks
716                 if(currentDraw == nextDraw)
717                 {
718                         return;   // No more primitives to process
719                 }
720
721                 for(int unit = 0; unit < unitCount; unit++)
722                 {
723                         DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
724
725                         if(draw->primitive >= draw->count)
726                         {
727                                 currentDraw++;
728
729                                 if(currentDraw == nextDraw)
730                                 {
731                                         return;   // No more primitives to process
732                                 }
733
734                                 draw = drawList[currentDraw % DRAW_COUNT];
735                         }
736
737                         if(!primitiveProgress[unit].references)   // Task not already being executed and not still in use by a pixel unit
738                         {
739                                 int primitive = draw->primitive;
740                                 int count = draw->count;
741                                 int batch = draw->batchSize;
742
743                                 primitiveProgress[unit].drawCall = currentDraw;
744                                 primitiveProgress[unit].firstPrimitive = primitive;
745                                 primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
746
747                                 draw->primitive += batch;
748
749                                 Task &task = taskQueue[qHead];
750                                 task.type = Task::PRIMITIVES;
751                                 task.primitiveUnit = unit;
752
753                                 primitiveProgress[unit].references = -1;
754
755                                 // Commit to the task queue
756                                 qHead = (qHead + 1) % 32;
757                                 qSize++;
758                         }
759                 }
760         }
761
762         void Renderer::scheduleTask(int threadIndex)
763         {
764                 schedulerMutex.lock();
765
766                 if((int)qSize < threadCount - threadsAwake + 1)
767                 {
768                         findAvailableTasks();
769                 }
770
771                 if(qSize != 0)
772                 {
773                         task[threadIndex] = taskQueue[(qHead - qSize) % 32];
774                         qSize--;
775
776                         if(threadsAwake != threadCount)
777                         {
778                                 int wakeup = qSize - threadsAwake + 1;
779
780                                 for(int i = 0; i < threadCount && wakeup > 0; i++)
781                                 {
782                                         if(task[i].type == Task::SUSPEND)
783                                         {
784                                                 suspend[i]->wait();
785                                                 task[i].type = Task::RESUME;
786                                                 resume[i]->signal();
787
788                                                 threadsAwake++;
789                                                 wakeup--;
790                                         }
791                                 }
792                         }
793                 }
794                 else
795                 {
796                         task[threadIndex].type = Task::SUSPEND;
797
798                         threadsAwake--;
799                 }
800
801                 schedulerMutex.unlock();
802         }
803
804         void Renderer::executeTask(int threadIndex)
805         {
806                 #if PERF_HUD
807                         int64_t startTick = Timer::ticks();
808                 #endif
809
810                 switch(task[threadIndex].type)
811                 {
812                 case Task::PRIMITIVES:
813                         {
814                                 int unit = task[threadIndex].primitiveUnit;
815                                 
816                                 int input = primitiveProgress[unit].firstPrimitive;
817                                 int count = primitiveProgress[unit].primitiveCount;
818                                 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
819                                 int (*setupPrimitives)(Renderer *renderer, int batch, int count) = draw->setupPrimitives;
820
821                                 processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
822
823                                 #if PERF_HUD
824                                         int64_t time = Timer::ticks();
825                                         vertexTime[threadIndex] += time - startTick;
826                                         startTick = time;
827                                 #endif
828
829                                 int visible = draw->setupState.rasterizerDiscard ? 0 : setupPrimitives(this, unit, count);
830
831                                 primitiveProgress[unit].visible = visible;
832                                 primitiveProgress[unit].references = clusterCount;
833
834                                 #if PERF_HUD
835                                         setupTime[threadIndex] += Timer::ticks() - startTick;
836                                 #endif
837                         }
838                         break;
839                 case Task::PIXELS:
840                         {
841                                 int unit = task[threadIndex].primitiveUnit;
842                                 int visible = primitiveProgress[unit].visible;
843
844                                 if(visible > 0)
845                                 {
846                                         int cluster = task[threadIndex].pixelCluster;
847                                         Primitive *primitive = primitiveBatch[unit];
848                                         DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
849                                         DrawData *data = draw->data;
850                                         PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
851
852                                         pixelRoutine(primitive, visible, cluster, data);
853                                 }
854
855                                 finishRendering(task[threadIndex]);
856
857                                 #if PERF_HUD
858                                         pixelTime[threadIndex] += Timer::ticks() - startTick;
859                                 #endif
860                         }
861                         break;
862                 case Task::RESUME:
863                         break;
864                 case Task::SUSPEND:
865                         break;
866                 default:
867                         ASSERT(false);
868                 }
869         }
870
871         void Renderer::synchronize()
872         {
873                 sync->lock(sw::PUBLIC);
874                 sync->unlock();
875         }
876
877         void Renderer::finishRendering(Task &pixelTask)
878         {
879                 int unit = pixelTask.primitiveUnit;
880                 int cluster = pixelTask.pixelCluster;
881
882                 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
883                 DrawData &data = *draw.data;
884                 int primitive = primitiveProgress[unit].firstPrimitive;
885                 int count = primitiveProgress[unit].primitiveCount;
886
887                 pixelProgress[cluster].processedPrimitives = primitive + count;
888
889                 int ref = atomicDecrement(&primitiveProgress[unit].references);
890
891                 if(ref == 0)
892                 {
893                         ref = atomicDecrement(&draw.references);
894
895                         if(ref == 0)
896                         {
897                                 #if PERF_PROFILE
898                                         for(int cluster = 0; cluster < clusterCount; cluster++)
899                                         {
900                                                 for(int i = 0; i < PERF_TIMERS; i++)
901                                                 {
902                                                         profiler.cycles[i] += data.cycles[i][cluster];
903                                                 }
904                                         }
905                                 #endif
906
907                                 if(draw.queries)
908                                 {
909                                         for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
910                                         {
911                                                 Query *query = *q;
912
913                                                 switch(query->type)
914                                                 {
915                                                 case Query::FRAGMENTS_PASSED:
916                                                         for(int cluster = 0; cluster < clusterCount; cluster++)
917                                                         {
918                                                                 atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
919                                                         }
920                                                         break;
921                                                 case Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
922                                                         atomicAdd((volatile int*)&query->data, pixelProgress[cluster].processedPrimitives);
923                                                         break;
924                                                 default:
925                                                         break;
926                                                 }
927
928                                                 atomicDecrement(&query->reference);
929                                         }
930
931                                         delete draw.queries;
932                                         draw.queries = 0;
933                                 }
934
935                                 for(int i = 0; i < RENDERTARGETS; i++)
936                                 {
937                                         if(draw.renderTarget[i])
938                                         {
939                                                 draw.renderTarget[i]->unlockInternal();
940                                         }
941                                 }
942
943                                 if(draw.depthStencil)
944                                 {
945                                         draw.depthStencil->unlockInternal();
946                                         draw.depthStencil->unlockStencil();
947                                 }
948
949                                 for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
950                                 {
951                                         if(draw.texture[i])
952                                         {
953                                                 draw.texture[i]->unlock();
954                                         }
955                                 }
956
957                                 for(int i = 0; i < VERTEX_ATTRIBUTES; i++)
958                                 {
959                                         if(draw.vertexStream[i])
960                                         {
961                                                 draw.vertexStream[i]->unlock();
962                                         }
963                                 }
964
965                                 if(draw.indexBuffer)
966                                 {
967                                         draw.indexBuffer->unlock();
968                                 }
969
970                                 PixelProcessor::unlockUniformBuffers();
971                                 VertexProcessor::unlockUniformBuffers();
972
973                                 draw.vertexRoutine->unbind();
974                                 draw.setupRoutine->unbind();
975                                 draw.pixelRoutine->unbind();
976
977                                 sync->unlock();
978
979                                 draw.references = -1;
980                                 resumeApp->signal();
981                         }
982                 }
983
984                 if(pixelProgress[cluster].processedPrimitives >= draw.count)
985                 {
986                         pixelProgress[cluster].drawCall++;
987                         pixelProgress[cluster].processedPrimitives = 0;
988                 }
989
990                 pixelProgress[cluster].executing = false;
991         }
992
993         void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
994         {
995                 Triangle *triangle = triangleBatch[unit];
996                 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
997                 DrawData *data = draw->data;
998                 VertexTask *task = vertexTask[thread];
999
1000                 const void *indices = data->indices;
1001                 VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
1002
1003                 if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
1004                 {
1005                         task->vertexCache.clear();
1006                         task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
1007                 }
1008
1009                 unsigned int batch[128][3];   // FIXME: Adjust to dynamic batch size
1010
1011                 switch(draw->drawType)
1012                 {
1013                 case DRAW_POINTLIST:
1014                         {
1015                                 unsigned int index = start;
1016
1017                                 for(unsigned int i = 0; i < triangleCount; i++)
1018                                 {
1019                                         batch[i][0] = index;
1020                                         batch[i][1] = index;
1021                                         batch[i][2] = index;
1022
1023                                         index += 1;
1024                                 }
1025                         }
1026                         break;
1027                 case DRAW_LINELIST:
1028                         {
1029                                 unsigned int index = 2 * start;
1030
1031                                 for(unsigned int i = 0; i < triangleCount; i++)
1032                                 {
1033                                         batch[i][0] = index + 0;
1034                                         batch[i][1] = index + 1;
1035                                         batch[i][2] = index + 1;
1036
1037                                         index += 2;
1038                                 }
1039                         }
1040                         break;
1041                 case DRAW_LINESTRIP:
1042                         {
1043                                 unsigned int index = start;
1044
1045                                 for(unsigned int i = 0; i < triangleCount; i++)
1046                                 {
1047                                         batch[i][0] = index + 0;
1048                                         batch[i][1] = index + 1;
1049                                         batch[i][2] = index + 1;
1050
1051                                         index += 1;
1052                                 }
1053                         }
1054                         break;
1055                 case DRAW_LINELOOP:
1056                         {
1057                                 unsigned int index = start;
1058
1059                                 for(unsigned int i = 0; i < triangleCount; i++)
1060                                 {
1061                                         batch[i][0] = (index + 0) % loop;
1062                                         batch[i][1] = (index + 1) % loop;
1063                                         batch[i][2] = (index + 1) % loop;
1064
1065                                         index += 1;
1066                                 }
1067                         }
1068                         break;
1069                 case DRAW_TRIANGLELIST:
1070                         {
1071                                 unsigned int index = 3 * start;
1072
1073                                 for(unsigned int i = 0; i < triangleCount; i++)
1074                                 {
1075                                         batch[i][0] = index + 0;
1076                                         batch[i][1] = index + 1;
1077                                         batch[i][2] = index + 2;
1078
1079                                         index += 3;
1080                                 }
1081                         }
1082                         break;
1083                 case DRAW_TRIANGLESTRIP:
1084                         {
1085                                 unsigned int index = start;
1086
1087                                 for(unsigned int i = 0; i < triangleCount; i++)
1088                                 {
1089                                         batch[i][0] = index + 0;
1090                                         batch[i][1] = index + (index & 1) + 1;
1091                                         batch[i][2] = index + (~index & 1) + 1;
1092
1093                                         index += 1;
1094                                 }
1095                         }
1096                         break;
1097                 case DRAW_TRIANGLEFAN:
1098                         {
1099                                 unsigned int index = start;
1100
1101                                 for(unsigned int i = 0; i < triangleCount; i++)
1102                                 {
1103                                         batch[i][0] = index + 1;
1104                                         batch[i][1] = index + 2;
1105                                         batch[i][2] = 0;
1106
1107                                         index += 1;
1108                                 }
1109                         }
1110                         break;
1111                 case DRAW_INDEXEDPOINTLIST8:
1112                         {
1113                                 const unsigned char *index = (const unsigned char*)indices + start;
1114
1115                                 for(unsigned int i = 0; i < triangleCount; i++)
1116                                 {
1117                                         batch[i][0] = *index;
1118                                         batch[i][1] = *index;
1119                                         batch[i][2] = *index;
1120
1121                                         index += 1;
1122                                 }
1123                         }
1124                         break;
1125                 case DRAW_INDEXEDPOINTLIST16:
1126                         {
1127                                 const unsigned short *index = (const unsigned short*)indices + start;
1128
1129                                 for(unsigned int i = 0; i < triangleCount; i++)
1130                                 {
1131                                         batch[i][0] = *index;
1132                                         batch[i][1] = *index;
1133                                         batch[i][2] = *index;
1134
1135                                         index += 1;
1136                                 }
1137                         }
1138                         break;
1139                 case DRAW_INDEXEDPOINTLIST32:
1140                         {
1141                                 const unsigned int *index = (const unsigned int*)indices + start;
1142
1143                                 for(unsigned int i = 0; i < triangleCount; i++)
1144                                 {
1145                                         batch[i][0] = *index;
1146                                         batch[i][1] = *index;
1147                                         batch[i][2] = *index;
1148
1149                                         index += 1;
1150                                 }
1151                         }
1152                         break;
1153                 case DRAW_INDEXEDLINELIST8:
1154                         {
1155                                 const unsigned char *index = (const unsigned char*)indices + 2 * start;
1156
1157                                 for(unsigned int i = 0; i < triangleCount; i++)
1158                                 {
1159                                         batch[i][0] = index[0];
1160                                         batch[i][1] = index[1];
1161                                         batch[i][2] = index[1];
1162
1163                                         index += 2;
1164                                 }
1165                         }
1166                         break;
1167                 case DRAW_INDEXEDLINELIST16:
1168                         {
1169                                 const unsigned short *index = (const unsigned short*)indices + 2 * start;
1170
1171                                 for(unsigned int i = 0; i < triangleCount; i++)
1172                                 {
1173                                         batch[i][0] = index[0];
1174                                         batch[i][1] = index[1];
1175                                         batch[i][2] = index[1];
1176
1177                                         index += 2;
1178                                 }
1179                         }
1180                         break;
1181                 case DRAW_INDEXEDLINELIST32:
1182                         {
1183                                 const unsigned int *index = (const unsigned int*)indices + 2 * start;
1184
1185                                 for(unsigned int i = 0; i < triangleCount; i++)
1186                                 {
1187                                         batch[i][0] = index[0];
1188                                         batch[i][1] = index[1];
1189                                         batch[i][2] = index[1];
1190
1191                                         index += 2;
1192                                 }
1193                         }
1194                         break;
1195                 case DRAW_INDEXEDLINESTRIP8:
1196                         {
1197                                 const unsigned char *index = (const unsigned char*)indices + start;
1198
1199                                 for(unsigned int i = 0; i < triangleCount; i++)
1200                                 {
1201                                         batch[i][0] = index[0];
1202                                         batch[i][1] = index[1];
1203                                         batch[i][2] = index[1];
1204
1205                                         index += 1;
1206                                 }
1207                         }
1208                         break;
1209                 case DRAW_INDEXEDLINESTRIP16:
1210                         {
1211                                 const unsigned short *index = (const unsigned short*)indices + start;
1212
1213                                 for(unsigned int i = 0; i < triangleCount; i++)
1214                                 {
1215                                         batch[i][0] = index[0];
1216                                         batch[i][1] = index[1];
1217                                         batch[i][2] = index[1];
1218
1219                                         index += 1;
1220                                 }
1221                         }
1222                         break;
1223                 case DRAW_INDEXEDLINESTRIP32:
1224                         {
1225                                 const unsigned int *index = (const unsigned int*)indices + start;
1226
1227                                 for(unsigned int i = 0; i < triangleCount; i++)
1228                                 {
1229                                         batch[i][0] = index[0];
1230                                         batch[i][1] = index[1];
1231                                         batch[i][2] = index[1];
1232
1233                                         index += 1;
1234                                 }
1235                         }
1236                         break;
1237                 case DRAW_INDEXEDLINELOOP8:
1238                         {
1239                                 const unsigned char *index = (const unsigned char*)indices;
1240
1241                                 for(unsigned int i = 0; i < triangleCount; i++)
1242                                 {
1243                                         batch[i][0] = index[(start + i + 0) % loop];
1244                                         batch[i][1] = index[(start + i + 1) % loop];
1245                                         batch[i][2] = index[(start + i + 1) % loop];
1246                                 }
1247                         }
1248                         break;
1249                 case DRAW_INDEXEDLINELOOP16:
1250                         {
1251                                 const unsigned short *index = (const unsigned short*)indices;
1252
1253                                 for(unsigned int i = 0; i < triangleCount; i++)
1254                                 {
1255                                         batch[i][0] = index[(start + i + 0) % loop];
1256                                         batch[i][1] = index[(start + i + 1) % loop];
1257                                         batch[i][2] = index[(start + i + 1) % loop];
1258                                 }
1259                         }
1260                         break;
1261                 case DRAW_INDEXEDLINELOOP32:
1262                         {
1263                                 const unsigned int *index = (const unsigned int*)indices;
1264
1265                                 for(unsigned int i = 0; i < triangleCount; i++)
1266                                 {
1267                                         batch[i][0] = index[(start + i + 0) % loop];
1268                                         batch[i][1] = index[(start + i + 1) % loop];
1269                                         batch[i][2] = index[(start + i + 1) % loop];
1270                                 }
1271                         }
1272                         break;
1273                 case DRAW_INDEXEDTRIANGLELIST8:
1274                         {
1275                                 const unsigned char *index = (const unsigned char*)indices + 3 * start;
1276
1277                                 for(unsigned int i = 0; i < triangleCount; i++)
1278                                 {
1279                                         batch[i][0] = index[0];
1280                                         batch[i][1] = index[1];
1281                                         batch[i][2] = index[2];
1282
1283                                         index += 3;
1284                                 }
1285                         }
1286                         break;
1287                 case DRAW_INDEXEDTRIANGLELIST16:
1288                         {
1289                                 const unsigned short *index = (const unsigned short*)indices + 3 * start;
1290
1291                                 for(unsigned int i = 0; i < triangleCount; i++)
1292                                 {
1293                                         batch[i][0] = index[0];
1294                                         batch[i][1] = index[1];
1295                                         batch[i][2] = index[2];
1296
1297                                         index += 3;
1298                                 }
1299                         }
1300                         break;
1301                 case DRAW_INDEXEDTRIANGLELIST32:
1302                         {
1303                                 const unsigned int *index = (const unsigned int*)indices + 3 * start;
1304
1305                                 for(unsigned int i = 0; i < triangleCount; i++)
1306                                 {
1307                                         batch[i][0] = index[0];
1308                                         batch[i][1] = index[1];
1309                                         batch[i][2] = index[2];
1310
1311                                         index += 3;
1312                                 }
1313                         }
1314                         break;
1315                 case DRAW_INDEXEDTRIANGLESTRIP8:
1316                         {
1317                                 const unsigned char *index = (const unsigned char*)indices + start;
1318
1319                                 for(unsigned int i = 0; i < triangleCount; i++)
1320                                 {
1321                                         batch[i][0] = index[0];
1322                                         batch[i][1] = index[((start + i) & 1) + 1];
1323                                         batch[i][2] = index[(~(start + i) & 1) + 1];
1324
1325                                         index += 1;
1326                                 }
1327                         }
1328                         break;
1329                 case DRAW_INDEXEDTRIANGLESTRIP16:
1330                         {
1331                                 const unsigned short *index = (const unsigned short*)indices + start;
1332
1333                                 for(unsigned int i = 0; i < triangleCount; i++)
1334                                 {
1335                                         batch[i][0] = index[0];
1336                                         batch[i][1] = index[((start + i) & 1) + 1];
1337                                         batch[i][2] = index[(~(start + i) & 1) + 1];
1338
1339                                         index += 1;
1340                                 }
1341                         }
1342                         break;
1343                 case DRAW_INDEXEDTRIANGLESTRIP32:
1344                         {
1345                                 const unsigned int *index = (const unsigned int*)indices + start;
1346
1347                                 for(unsigned int i = 0; i < triangleCount; i++)
1348                                 {
1349                                         batch[i][0] = index[0];
1350                                         batch[i][1] = index[((start + i) & 1) + 1];
1351                                         batch[i][2] = index[(~(start + i) & 1) + 1];
1352
1353                                         index += 1;
1354                                 }
1355                         }
1356                         break;
1357                 case DRAW_INDEXEDTRIANGLEFAN8:
1358                         {
1359                                 const unsigned char *index = (const unsigned char*)indices;
1360
1361                                 for(unsigned int i = 0; i < triangleCount; i++)
1362                                 {
1363                                         batch[i][0] = index[start + i + 1];
1364                                         batch[i][1] = index[start + i + 2];
1365                                         batch[i][2] = index[0];
1366                                 }
1367                         }
1368                         break;
1369                 case DRAW_INDEXEDTRIANGLEFAN16:
1370                         {
1371                                 const unsigned short *index = (const unsigned short*)indices;
1372
1373                                 for(unsigned int i = 0; i < triangleCount; i++)
1374                                 {
1375                                         batch[i][0] = index[start + i + 1];
1376                                         batch[i][1] = index[start + i + 2];
1377                                         batch[i][2] = index[0];
1378                                 }
1379                         }
1380                         break;
1381                 case DRAW_INDEXEDTRIANGLEFAN32:
1382                         {
1383                                 const unsigned int *index = (const unsigned int*)indices;
1384
1385                                 for(unsigned int i = 0; i < triangleCount; i++)
1386                                 {
1387                                         batch[i][0] = index[start + i + 1];
1388                                         batch[i][1] = index[start + i + 2];
1389                                         batch[i][2] = index[0];
1390                                 }
1391                         }
1392                         break;
1393         case DRAW_QUADLIST:
1394                         {
1395                                 unsigned int index = 4 * start / 2;
1396
1397                                 for(unsigned int i = 0; i < triangleCount; i += 2)
1398                                 {
1399                                         batch[i+0][0] = index + 0;
1400                                         batch[i+0][1] = index + 1;
1401                                         batch[i+0][2] = index + 2;
1402
1403                     batch[i+1][0] = index + 0;
1404                                         batch[i+1][1] = index + 2;
1405                                         batch[i+1][2] = index + 3;
1406
1407                                         index += 4;
1408                                 }
1409                         }
1410                         break;
1411                 default:
1412                         ASSERT(false);
1413                         return;
1414                 }
1415
1416                 task->vertexCount = triangleCount * 3;
1417                 vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
1418         }
1419
1420         int Renderer::setupSolidTriangles(Renderer *renderer, int unit, int count)
1421         {
1422                 Triangle *triangle = renderer->triangleBatch[unit];
1423                 Primitive *primitive = renderer->primitiveBatch[unit];
1424
1425                 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1426                 SetupProcessor::State &state = draw.setupState;
1427                 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1428
1429                 int ms = state.multiSample;
1430                 int pos = state.positionRegister;
1431                 const DrawData *data = draw.data;
1432                 int visible = 0;
1433
1434                 for(int i = 0; i < count; i++, triangle++)
1435                 {
1436                         Vertex &v0 = triangle->v0;
1437                         Vertex &v1 = triangle->v1;
1438                         Vertex &v2 = triangle->v2;
1439
1440                         if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
1441                         {
1442                                 Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
1443
1444                                 int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
1445
1446                                 if(clipFlagsOr != Clipper::CLIP_FINITE)
1447                                 {
1448                                         if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1449                                         {
1450                                                 continue;
1451                                         }
1452                                 }
1453
1454                                 if(setupRoutine(primitive, triangle, &polygon, data))
1455                                 {
1456                                         primitive += ms;
1457                                         visible++;
1458                                 }
1459                         }
1460                 }
1461
1462                 return visible;
1463         }
1464
1465         int Renderer::setupWireframeTriangle(Renderer *renderer, int unit, int count)
1466         {
1467                 Triangle *triangle = renderer->triangleBatch[unit];
1468                 Primitive *primitive = renderer->primitiveBatch[unit];
1469                 int visible = 0;
1470
1471                 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1472                 SetupProcessor::State &state = draw.setupState;
1473                 SetupProcessor::RoutinePointer setupRoutine = draw.setupPointer;
1474
1475                 const Vertex &v0 = triangle[0].v0;
1476                 const Vertex &v1 = triangle[0].v1;
1477                 const Vertex &v2 = triangle[0].v2;
1478
1479                 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;
1480
1481                 if(state.cullMode == CULL_CLOCKWISE)
1482                 {
1483                         if(d >= 0) return 0;
1484                 }
1485                 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1486                 {
1487                         if(d <= 0) return 0;
1488                 }
1489
1490                 // Copy attributes
1491                 triangle[1].v0 = v1;
1492                 triangle[1].v1 = v2;
1493                 triangle[2].v0 = v2;
1494                 triangle[2].v1 = v0;
1495
1496                 if(state.color[0][0].flat)   // FIXME
1497                 {
1498                         for(int i = 0; i < 2; i++)
1499                         {
1500                                 triangle[1].v0.C[i] = triangle[0].v0.C[i];
1501                                 triangle[1].v1.C[i] = triangle[0].v0.C[i];
1502                                 triangle[2].v0.C[i] = triangle[0].v0.C[i];
1503                                 triangle[2].v1.C[i] = triangle[0].v0.C[i];
1504                         }
1505                 }
1506
1507                 for(int i = 0; i < 3; i++)
1508                 {
1509                         if(setupLine(renderer, *primitive, *triangle, draw))
1510                         {
1511                                 primitive->area = 0.5f * d;
1512
1513                                 primitive++;
1514                                 visible++;
1515                         }
1516
1517                         triangle++;
1518                 }
1519
1520                 return visible;
1521         }
1522         
1523         int Renderer::setupVertexTriangle(Renderer *renderer, int unit, int count)
1524         {
1525                 Triangle *triangle = renderer->triangleBatch[unit];
1526                 Primitive *primitive = renderer->primitiveBatch[unit];
1527                 int visible = 0;
1528
1529                 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1530                 SetupProcessor::State &state = draw.setupState;
1531
1532                 const Vertex &v0 = triangle[0].v0;
1533                 const Vertex &v1 = triangle[0].v1;
1534                 const Vertex &v2 = triangle[0].v2;
1535
1536                 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;
1537
1538                 if(state.cullMode == CULL_CLOCKWISE)
1539                 {
1540                         if(d >= 0) return 0;
1541                 }
1542                 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1543                 {
1544                         if(d <= 0) return 0;
1545                 }
1546
1547                 // Copy attributes
1548                 triangle[1].v0 = v1;
1549                 triangle[2].v0 = v2;
1550
1551                 for(int i = 0; i < 3; i++)
1552                 {
1553                         if(setupPoint(renderer, *primitive, *triangle, draw))
1554                         {
1555                                 primitive->area = 0.5f * d;
1556
1557                                 primitive++;
1558                                 visible++;
1559                         }
1560
1561                         triangle++;
1562                 }
1563
1564                 return visible;
1565         }
1566
1567         int Renderer::setupLines(Renderer *renderer, int unit, int count)
1568         {
1569                 Triangle *triangle = renderer->triangleBatch[unit];
1570                 Primitive *primitive = renderer->primitiveBatch[unit];
1571                 int visible = 0;
1572
1573                 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1574                 SetupProcessor::State &state = draw.setupState;
1575
1576                 int ms = state.multiSample;
1577
1578                 for(int i = 0; i < count; i++)
1579                 {
1580                         if(setupLine(renderer, *primitive, *triangle, draw))
1581                         {
1582                                 primitive += ms;
1583                                 visible++;
1584                         }
1585
1586                         triangle++;
1587                 }
1588
1589                 return visible;
1590         }
1591
1592         int Renderer::setupPoints(Renderer *renderer, int unit, int count)
1593         {
1594                 Triangle *triangle = renderer->triangleBatch[unit];
1595                 Primitive *primitive = renderer->primitiveBatch[unit];
1596                 int visible = 0;
1597
1598                 DrawCall &draw = *renderer->drawList[renderer->primitiveProgress[unit].drawCall % DRAW_COUNT];
1599                 SetupProcessor::State &state = draw.setupState;
1600
1601                 int ms = state.multiSample;
1602
1603                 for(int i = 0; i < count; i++)
1604                 {
1605                         if(setupPoint(renderer, *primitive, *triangle, draw))
1606                         {
1607                                 primitive += ms;
1608                                 visible++;
1609                         }
1610
1611                         triangle++;
1612                 }
1613
1614                 return visible;
1615         }
1616
1617         bool Renderer::setupLine(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1618         {
1619                 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1620                 const SetupProcessor::State &state = draw.setupState;
1621                 const DrawData &data = *draw.data;
1622
1623                 float lineWidth = data.lineWidth;
1624
1625                 Vertex &v0 = triangle.v0;
1626                 Vertex &v1 = triangle.v1;
1627
1628                 int pos = state.positionRegister;
1629
1630                 const float4 &P0 = v0.v[pos];
1631                 const float4 &P1 = v1.v[pos];
1632
1633                 if(P0.w <= 0 && P1.w <= 0)
1634                 {
1635                         return false;
1636                 }
1637
1638                 const float W = data.Wx16[0] * (1.0f / 16.0f);
1639                 const float H = data.Hx16[0] * (1.0f / 16.0f);
1640
1641                 float dx = W * (P1.x / P1.w - P0.x / P0.w);
1642                 float dy = H * (P1.y / P1.w - P0.y / P0.w);
1643
1644                 if(dx == 0 && dy == 0)
1645                 {
1646                         return false;
1647                 }
1648
1649                 if(false)   // Rectangle
1650                 {
1651                         float4 P[4];
1652                         int C[4];
1653
1654                         P[0] = P0;
1655                         P[1] = P1;
1656                         P[2] = P1;
1657                         P[3] = P0;
1658
1659                         float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
1660
1661                         dx *= scale;
1662                         dy *= scale;
1663
1664                         float dx0w = dx * P0.w / W;
1665                         float dy0h = dy * P0.w / H;
1666                         float dx0h = dx * P0.w / H;
1667                         float dy0w = dy * P0.w / W;
1668
1669                         float dx1w = dx * P1.w / W;
1670                         float dy1h = dy * P1.w / H;
1671                         float dx1h = dx * P1.w / H;
1672                         float dy1w = dy * P1.w / W;
1673
1674                         P[0].x += -dy0w + -dx0w;
1675                         P[0].y += -dx0h + +dy0h;
1676                         C[0] = computeClipFlags(P[0], data);
1677
1678                         P[1].x += -dy1w + +dx1w;
1679                         P[1].y += -dx1h + +dy1h;
1680                         C[1] = computeClipFlags(P[1], data);
1681
1682                         P[2].x += +dy1w + +dx1w;
1683                         P[2].y += +dx1h + -dy1h;
1684                         C[2] = computeClipFlags(P[2], data);
1685
1686                         P[3].x += +dy0w + -dx0w;
1687                         P[3].y += +dx0h + +dy0h;
1688                         C[3] = computeClipFlags(P[3], data);
1689
1690                         if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1691                         {
1692                                 Polygon polygon(P, 4);
1693
1694                                 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1695
1696                                 if(clipFlagsOr != Clipper::CLIP_FINITE)
1697                                 {
1698                                         if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1699                                         {
1700                                                 return false;
1701                                         }
1702                                 }
1703
1704                                 return setupRoutine(&primitive, &triangle, &polygon, &data);
1705                         }
1706                 }
1707                 else   // Diamond test convention
1708                 {
1709                         float4 P[8];
1710                         int C[8];
1711
1712                         P[0] = P0;
1713                         P[1] = P0;
1714                         P[2] = P0;
1715                         P[3] = P0;
1716                         P[4] = P1;
1717                         P[5] = P1;
1718                         P[6] = P1;
1719                         P[7] = P1;
1720
1721                         float dx0 = lineWidth * 0.5f * P0.w / W;
1722                         float dy0 = lineWidth * 0.5f * P0.w / H;
1723
1724                         float dx1 = lineWidth * 0.5f * P1.w / W;
1725                         float dy1 = lineWidth * 0.5f * P1.w / H;
1726
1727                         P[0].x += -dx0;
1728                         C[0] = computeClipFlags(P[0], data);
1729
1730                         P[1].y += +dy0;
1731                         C[1] = computeClipFlags(P[1], data);
1732
1733                         P[2].x += +dx0;
1734                         C[2] = computeClipFlags(P[2], data);
1735
1736                         P[3].y += -dy0;
1737                         C[3] = computeClipFlags(P[3], data);
1738
1739                         P[4].x += -dx1;
1740                         C[4] = computeClipFlags(P[4], data);
1741
1742                         P[5].y += +dy1;
1743                         C[5] = computeClipFlags(P[5], data);
1744
1745                         P[6].x += +dx1;
1746                         C[6] = computeClipFlags(P[6], data);
1747
1748                         P[7].y += -dy1;
1749                         C[7] = computeClipFlags(P[7], data);
1750
1751                         if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
1752                         {
1753                                 float4 L[6];
1754
1755                                 if(dx > -dy)
1756                                 {
1757                                         if(dx > dy)   // Right
1758                                         {
1759                                                 L[0] = P[0];
1760                                                 L[1] = P[1];
1761                                                 L[2] = P[5];
1762                                                 L[3] = P[6];
1763                                                 L[4] = P[7];
1764                                                 L[5] = P[3];
1765                                         }
1766                                         else   // Down
1767                                         {
1768                                                 L[0] = P[0];
1769                                                 L[1] = P[4];
1770                                                 L[2] = P[5];
1771                                                 L[3] = P[6];
1772                                                 L[4] = P[2];
1773                                                 L[5] = P[3];
1774                                         }
1775                                 }
1776                                 else
1777                                 {
1778                                         if(dx > dy)   // Up
1779                                         {
1780                                                 L[0] = P[0];
1781                                                 L[1] = P[1];
1782                                                 L[2] = P[2];
1783                                                 L[3] = P[6];
1784                                                 L[4] = P[7];
1785                                                 L[5] = P[4];
1786                                         }
1787                                         else   // Left
1788                                         {
1789                                                 L[0] = P[1];
1790                                                 L[1] = P[2];
1791                                                 L[2] = P[3];
1792                                                 L[3] = P[7];
1793                                                 L[4] = P[4];
1794                                                 L[5] = P[5];
1795                                         }
1796                                 }
1797
1798                                 Polygon polygon(L, 6);
1799
1800                                 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
1801
1802                                 if(clipFlagsOr != Clipper::CLIP_FINITE)
1803                                 {
1804                                         if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1805                                         {
1806                                                 return false;
1807                                         }
1808                                 }
1809
1810                                 return setupRoutine(&primitive, &triangle, &polygon, &data);
1811                         }
1812                 }
1813
1814                 return false;
1815         }
1816
1817         bool Renderer::setupPoint(Renderer *renderer, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1818         {
1819                 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1820                 const SetupProcessor::State &state = draw.setupState;
1821                 const DrawData &data = *draw.data;
1822
1823                 Vertex &v = triangle.v0;
1824
1825                 float pSize;
1826
1827                 int pts = state.pointSizeRegister;
1828
1829                 if(state.pointSizeRegister != 0xF)
1830                 {
1831                         pSize = v.v[pts].y;
1832                 }
1833                 else
1834                 {
1835                         pSize = data.point.pointSize[0];
1836                 }
1837
1838                 pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
1839
1840                 float4 P[4];
1841                 int C[4];
1842
1843                 int pos = state.positionRegister;
1844
1845                 P[0] = v.v[pos];
1846                 P[1] = v.v[pos];
1847                 P[2] = v.v[pos];
1848                 P[3] = v.v[pos];
1849
1850                 const float X = pSize * P[0].w * data.halfPixelX[0];
1851                 const float Y = pSize * P[0].w * data.halfPixelY[0];
1852
1853                 P[0].x -= X;
1854                 P[0].y += Y;
1855                 C[0] = computeClipFlags(P[0], data);
1856
1857                 P[1].x += X;
1858                 P[1].y += Y;
1859                 C[1] = computeClipFlags(P[1], data);
1860
1861                 P[2].x += X;
1862                 P[2].y -= Y;
1863                 C[2] = computeClipFlags(P[2], data);
1864
1865                 P[3].x -= X;
1866                 P[3].y -= Y;
1867                 C[3] = computeClipFlags(P[3], data);
1868
1869                 triangle.v1 = triangle.v0;
1870                 triangle.v2 = triangle.v0;
1871
1872                 triangle.v1.X += iround(16 * 0.5f * pSize);
1873                 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
1874
1875                 Polygon polygon(P, 4);
1876
1877                 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1878                 {
1879                         int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1880
1881                         if(clipFlagsOr != Clipper::CLIP_FINITE)
1882                         {
1883                                 if(!renderer->clipper->clip(polygon, clipFlagsOr, draw))
1884                                 {
1885                                         return false;
1886                                 }
1887                         }
1888                         
1889                         return setupRoutine(&primitive, &triangle, &polygon, &data);
1890                 }
1891
1892                 return false;
1893         }
1894
1895         unsigned int Renderer::computeClipFlags(const float4 &v, const DrawData &data)
1896         {
1897                 return ((v.x > v.w)  << 0) |
1898                            ((v.y > v.w)  << 1) |
1899                            ((v.z > v.w)  << 2) |
1900                            ((v.x < -v.w) << 3) |
1901                        ((v.y < -v.w) << 4) |
1902                            ((v.z < 0)    << 5) |
1903                            Clipper::CLIP_FINITE;   // FIXME: xyz finite
1904         }
1905
1906         void Renderer::initializeThreads()
1907         {
1908                 unitCount = ceilPow2(threadCount);
1909                 clusterCount = ceilPow2(threadCount);
1910
1911                 for(int i = 0; i < unitCount; i++)
1912                 {
1913                         triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
1914                         primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
1915                 }
1916
1917                 for(int i = 0; i < threadCount; i++)
1918                 {
1919                         vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
1920                         vertexTask[i]->vertexCache.drawCall = -1;
1921
1922                         task[i].type = Task::SUSPEND;
1923
1924                         resume[i] = new Event();
1925                         suspend[i] = new Event();
1926
1927                         Parameters parameters;
1928                         parameters.threadIndex = i;
1929                         parameters.renderer = this;
1930
1931                         exitThreads = false;
1932                         worker[i] = new Thread(threadFunction, &parameters);
1933
1934                         suspend[i]->wait();
1935                         suspend[i]->signal();
1936                 }
1937         }
1938
1939         void Renderer::terminateThreads()
1940         {
1941                 while(threadsAwake != 0)
1942                 {
1943                         Thread::sleep(1);
1944                 }
1945
1946                 for(int thread = 0; thread < threadCount; thread++)
1947                 {
1948                         if(worker[thread])
1949                         {
1950                                 exitThreads = true;
1951                                 resume[thread]->signal();
1952                                 worker[thread]->join();
1953                                 
1954                                 delete worker[thread];
1955                                 worker[thread] = 0;
1956                                 delete resume[thread];
1957                                 resume[thread] = 0;
1958                                 delete suspend[thread];
1959                                 suspend[thread] = 0;
1960                         }
1961                 
1962                         deallocate(vertexTask[thread]);
1963                         vertexTask[thread] = 0;
1964                 }
1965
1966                 for(int i = 0; i < 16; i++)
1967                 {
1968                         deallocate(triangleBatch[i]);
1969                         triangleBatch[i] = 0;
1970
1971                         deallocate(primitiveBatch[i]);
1972                         primitiveBatch[i] = 0;
1973                 }
1974         }
1975
1976         void Renderer::loadConstants(const VertexShader *vertexShader)
1977         {
1978                 if(!vertexShader) return;
1979
1980                 size_t count = vertexShader->getLength();
1981
1982                 for(size_t i = 0; i < count; i++)
1983                 {
1984                         const Shader::Instruction *instruction = vertexShader->getInstruction(i);
1985
1986                         if(instruction->opcode == Shader::OPCODE_DEF)
1987                         {
1988                                 int index = instruction->dst.index;
1989                                 float value[4];
1990
1991                                 value[0] = instruction->src[0].value[0];
1992                                 value[1] = instruction->src[0].value[1];
1993                                 value[2] = instruction->src[0].value[2];
1994                                 value[3] = instruction->src[0].value[3];
1995
1996                                 setVertexShaderConstantF(index, value);
1997                         }
1998                         else if(instruction->opcode == Shader::OPCODE_DEFI)
1999                         {
2000                                 int index = instruction->dst.index;
2001                                 int integer[4];
2002
2003                                 integer[0] = instruction->src[0].integer[0];
2004                                 integer[1] = instruction->src[0].integer[1];
2005                                 integer[2] = instruction->src[0].integer[2];
2006                                 integer[3] = instruction->src[0].integer[3];
2007
2008                                 setVertexShaderConstantI(index, integer);
2009                         }
2010                         else if(instruction->opcode == Shader::OPCODE_DEFB)
2011                         {
2012                                 int index = instruction->dst.index;
2013                                 int boolean = instruction->src[0].boolean[0];
2014
2015                                 setVertexShaderConstantB(index, &boolean);
2016                         }
2017                 }
2018         }
2019
2020         void Renderer::loadConstants(const PixelShader *pixelShader)
2021         {
2022                 if(!pixelShader) return;
2023
2024                 size_t count = pixelShader->getLength();
2025
2026                 for(size_t i = 0; i < count; i++)
2027                 {
2028                         const Shader::Instruction *instruction = pixelShader->getInstruction(i);
2029
2030                         if(instruction->opcode == Shader::OPCODE_DEF)
2031                         {
2032                                 int index = instruction->dst.index;
2033                                 float value[4];
2034
2035                                 value[0] = instruction->src[0].value[0];
2036                                 value[1] = instruction->src[0].value[1];
2037                                 value[2] = instruction->src[0].value[2];
2038                                 value[3] = instruction->src[0].value[3];
2039
2040                                 setPixelShaderConstantF(index, value);
2041                         }
2042                         else if(instruction->opcode == Shader::OPCODE_DEFI)
2043                         {
2044                                 int index = instruction->dst.index;
2045                                 int integer[4];
2046
2047                                 integer[0] = instruction->src[0].integer[0];
2048                                 integer[1] = instruction->src[0].integer[1];
2049                                 integer[2] = instruction->src[0].integer[2];
2050                                 integer[3] = instruction->src[0].integer[3];
2051
2052                                 setPixelShaderConstantI(index, integer);
2053                         }
2054                         else if(instruction->opcode == Shader::OPCODE_DEFB)
2055                         {
2056                                 int index = instruction->dst.index;
2057                                 int boolean = instruction->src[0].boolean[0];
2058
2059                                 setPixelShaderConstantB(index, &boolean);
2060                         }
2061                 }
2062         }
2063
2064         void Renderer::setIndexBuffer(Resource *indexBuffer)
2065         {
2066                 context->indexBuffer = indexBuffer;
2067         }
2068
2069         void Renderer::setMultiSampleMask(unsigned int mask)
2070         {
2071                 context->sampleMask = mask;
2072         }
2073
2074         void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
2075         {
2076                 sw::transparencyAntialiasing = transparencyAntialiasing;
2077         }
2078
2079         bool Renderer::isReadWriteTexture(int sampler)
2080         {
2081                 for(int index = 0; index < RENDERTARGETS; index++)
2082                 {
2083                         if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
2084                         {
2085                                 return true;
2086                         }
2087                 }
2088         
2089                 if(context->depthStencil && context->texture[sampler] == context->depthStencil->getResource())
2090                 {
2091                         return true;
2092                 }
2093
2094                 return false;
2095         }
2096         
2097         void Renderer::updateClipper()
2098         {
2099                 if(updateClipPlanes)
2100                 {
2101                         if(VertexProcessor::isFixedFunction())   // User plane in world space
2102                         {
2103                                 const Matrix &scissorWorld = getViewTransform();
2104
2105                                 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
2106                                 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
2107                                 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
2108                                 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
2109                                 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
2110                                 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
2111                         }
2112                         else   // User plane in clip space
2113                         {
2114                                 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
2115                                 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
2116                                 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
2117                                 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
2118                                 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
2119                                 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
2120                         }
2121
2122                         updateClipPlanes = false;
2123                 }
2124         }
2125
2126         void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
2127         {
2128                 ASSERT(sampler < TOTAL_IMAGE_UNITS);
2129
2130                 context->texture[sampler] = resource;
2131         }
2132
2133         void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
2134         {
2135                 ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
2136                 
2137                 context->sampler[sampler].setTextureLevel(face, level, surface, type);
2138         }
2139
2140         void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
2141         {
2142                 if(type == SAMPLER_PIXEL)
2143                 {
2144                         PixelProcessor::setTextureFilter(sampler, textureFilter);
2145                 }
2146                 else
2147                 {
2148                         VertexProcessor::setTextureFilter(sampler, textureFilter);
2149                 }
2150         }
2151
2152         void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
2153         {
2154                 if(type == SAMPLER_PIXEL)
2155                 {
2156                         PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
2157                 }
2158                 else
2159                 {
2160                         VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
2161                 }
2162         }
2163
2164         void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
2165         {
2166                 if(type == SAMPLER_PIXEL)
2167                 {
2168                         PixelProcessor::setGatherEnable(sampler, enable);
2169                 }
2170                 else
2171                 {
2172                         VertexProcessor::setGatherEnable(sampler, enable);
2173                 }
2174         }
2175
2176         void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
2177         {
2178                 if(type == SAMPLER_PIXEL)
2179                 {
2180                         PixelProcessor::setAddressingModeU(sampler, addressMode);
2181                 }
2182                 else
2183                 {
2184                         VertexProcessor::setAddressingModeU(sampler, addressMode);
2185                 }
2186         }
2187
2188         void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
2189         {
2190                 if(type == SAMPLER_PIXEL)
2191                 {
2192                         PixelProcessor::setAddressingModeV(sampler, addressMode);
2193                 }
2194                 else
2195                 {
2196                         VertexProcessor::setAddressingModeV(sampler, addressMode);
2197                 }
2198         }
2199
2200         void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
2201         {
2202                 if(type == SAMPLER_PIXEL)
2203                 {
2204                         PixelProcessor::setAddressingModeW(sampler, addressMode);
2205                 }
2206                 else
2207                 {
2208                         VertexProcessor::setAddressingModeW(sampler, addressMode);
2209                 }
2210         }
2211
2212         void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
2213         {
2214                 if(type == SAMPLER_PIXEL)
2215                 {
2216                         PixelProcessor::setReadSRGB(sampler, sRGB);
2217                 }
2218                 else
2219                 {
2220                         VertexProcessor::setReadSRGB(sampler, sRGB);
2221                 }
2222         }
2223
2224         void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
2225         {
2226                 if(type == SAMPLER_PIXEL)
2227                 {
2228                         PixelProcessor::setMipmapLOD(sampler, bias);
2229                 }
2230                 else
2231                 {
2232                         VertexProcessor::setMipmapLOD(sampler, bias);
2233                 }
2234         }
2235
2236         void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
2237         {
2238                 if(type == SAMPLER_PIXEL)
2239                 {
2240                         PixelProcessor::setBorderColor(sampler, borderColor);
2241                 }
2242                 else
2243                 {
2244                         VertexProcessor::setBorderColor(sampler, borderColor);
2245                 }
2246         }
2247
2248         void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
2249         {
2250                 if(type == SAMPLER_PIXEL)
2251                 {
2252                         PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2253                 }
2254                 else
2255                 {
2256                         VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2257                 }
2258         }
2259
2260         void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
2261         {
2262                 if(type == SAMPLER_PIXEL)
2263                 {
2264                         PixelProcessor::setSwizzleR(sampler, swizzleR);
2265                 }
2266                 else
2267                 {
2268                         VertexProcessor::setSwizzleR(sampler, swizzleR);
2269                 }
2270         }
2271
2272         void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
2273         {
2274                 if(type == SAMPLER_PIXEL)
2275                 {
2276                         PixelProcessor::setSwizzleG(sampler, swizzleG);
2277                 }
2278                 else
2279                 {
2280                         VertexProcessor::setSwizzleG(sampler, swizzleG);
2281                 }
2282         }
2283
2284         void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
2285         {
2286                 if(type == SAMPLER_PIXEL)
2287                 {
2288                         PixelProcessor::setSwizzleB(sampler, swizzleB);
2289                 }
2290                 else
2291                 {
2292                         VertexProcessor::setSwizzleB(sampler, swizzleB);
2293                 }
2294         }
2295
2296         void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
2297         {
2298                 if(type == SAMPLER_PIXEL)
2299                 {
2300                         PixelProcessor::setSwizzleA(sampler, swizzleA);
2301                 }
2302                 else
2303                 {
2304                         VertexProcessor::setSwizzleA(sampler, swizzleA);
2305                 }
2306         }
2307
2308         void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
2309         {
2310                 context->setPointSpriteEnable(pointSpriteEnable);
2311         }
2312
2313         void Renderer::setPointScaleEnable(bool pointScaleEnable)
2314         {
2315                 context->setPointScaleEnable(pointScaleEnable);
2316         }
2317
2318         void Renderer::setLineWidth(float width)
2319         {
2320                 context->lineWidth = width;
2321         }
2322
2323         void Renderer::setDepthBias(float bias)
2324         {
2325                 depthBias = bias;
2326         }
2327
2328         void Renderer::setSlopeDepthBias(float slopeBias)
2329         {
2330                 slopeDepthBias = slopeBias;
2331         }
2332
2333         void Renderer::setRasterizerDiscard(bool rasterizerDiscard)
2334         {
2335                 context->rasterizerDiscard = rasterizerDiscard;
2336         }
2337
2338         void Renderer::setPixelShader(const PixelShader *shader)
2339         {
2340                 context->pixelShader = shader;
2341
2342                 loadConstants(shader);
2343         }
2344
2345         void Renderer::setVertexShader(const VertexShader *shader)
2346         {
2347                 context->vertexShader = shader;
2348
2349                 loadConstants(shader);
2350         }
2351
2352         void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
2353         {
2354                 for(int i = 0; i < DRAW_COUNT; i++)
2355                 {
2356                         if(drawCall[i]->psDirtyConstF < index + count)
2357                         {
2358                                 drawCall[i]->psDirtyConstF = index + count;
2359                         }
2360                 }
2361
2362                 for(int i = 0; i < count; i++)
2363                 {
2364                         PixelProcessor::setFloatConstant(index + i, value);
2365                         value += 4;
2366                 }
2367         }
2368
2369         void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
2370         {
2371                 for(int i = 0; i < DRAW_COUNT; i++)
2372                 {
2373                         if(drawCall[i]->psDirtyConstI < index + count)
2374                         {
2375                                 drawCall[i]->psDirtyConstI = index + count;
2376                         }
2377                 }
2378
2379                 for(int i = 0; i < count; i++)
2380                 {
2381                         PixelProcessor::setIntegerConstant(index + i, value);
2382                         value += 4;
2383                 }
2384         }
2385
2386         void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
2387         {
2388                 for(int i = 0; i < DRAW_COUNT; i++)
2389                 {
2390                         if(drawCall[i]->psDirtyConstB < index + count)
2391                         {
2392                                 drawCall[i]->psDirtyConstB = index + count;
2393                         }
2394                 }
2395
2396                 for(int i = 0; i < count; i++)
2397                 {
2398                         PixelProcessor::setBooleanConstant(index + i, *boolean);
2399                         boolean++;
2400                 }
2401         }
2402
2403         void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
2404         {
2405                 for(int i = 0; i < DRAW_COUNT; i++)
2406                 {
2407                         if(drawCall[i]->vsDirtyConstF < index + count)
2408                         {
2409                                 drawCall[i]->vsDirtyConstF = index + count;
2410                         }
2411                 }
2412
2413                 for(int i = 0; i < count; i++)
2414                 {
2415                         VertexProcessor::setFloatConstant(index + i, value);
2416                         value += 4;
2417                 }
2418         }
2419
2420         void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
2421         {
2422                 for(int i = 0; i < DRAW_COUNT; i++)
2423                 {
2424                         if(drawCall[i]->vsDirtyConstI < index + count)
2425                         {
2426                                 drawCall[i]->vsDirtyConstI = index + count;
2427                         }
2428                 }
2429
2430                 for(int i = 0; i < count; i++)
2431                 {
2432                         VertexProcessor::setIntegerConstant(index + i, value);
2433                         value += 4;
2434                 }
2435         }
2436
2437         void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
2438         {
2439                 for(int i = 0; i < DRAW_COUNT; i++)
2440                 {
2441                         if(drawCall[i]->vsDirtyConstB < index + count)
2442                         {
2443                                 drawCall[i]->vsDirtyConstB = index + count;
2444                         }
2445                 }
2446
2447                 for(int i = 0; i < count; i++)
2448                 {
2449                         VertexProcessor::setBooleanConstant(index + i, *boolean);
2450                         boolean++;
2451                 }
2452         }
2453
2454         void Renderer::setModelMatrix(const Matrix &M, int i)
2455         {
2456                 VertexProcessor::setModelMatrix(M, i);
2457         }
2458
2459         void Renderer::setViewMatrix(const Matrix &V)
2460         {
2461                 VertexProcessor::setViewMatrix(V);
2462                 updateClipPlanes = true;
2463         }
2464
2465         void Renderer::setBaseMatrix(const Matrix &B)
2466         {
2467                 VertexProcessor::setBaseMatrix(B);
2468                 updateClipPlanes = true;
2469         }
2470
2471         void Renderer::setProjectionMatrix(const Matrix &P)
2472         {
2473                 VertexProcessor::setProjectionMatrix(P);
2474                 updateClipPlanes = true;
2475         }
2476
2477         void Renderer::addQuery(Query *query)
2478         {
2479                 queries.push_back(query);
2480         }
2481         
2482         void Renderer::removeQuery(Query *query)
2483         {
2484                 queries.remove(query);
2485         }
2486
2487         #if PERF_HUD
2488                 int Renderer::getThreadCount()
2489                 {
2490                         return threadCount;
2491                 }
2492                 
2493                 int64_t Renderer::getVertexTime(int thread)
2494                 {
2495                         return vertexTime[thread];
2496                 }
2497
2498                 int64_t Renderer::getSetupTime(int thread)
2499                 {
2500                         return setupTime[thread];
2501                 }
2502                         
2503                 int64_t Renderer::getPixelTime(int thread)
2504                 {
2505                         return pixelTime[thread];
2506                 }
2507
2508                 void Renderer::resetTimers()
2509                 {
2510                         for(int thread = 0; thread < threadCount; thread++)
2511                         {
2512                                 vertexTime[thread] = 0;
2513                                 setupTime[thread] = 0;
2514                                 pixelTime[thread] = 0;
2515                         }
2516                 }
2517         #endif
2518
2519         void Renderer::setViewport(const Viewport &viewport)
2520         {
2521                 this->viewport = viewport;
2522         }
2523
2524         void Renderer::setScissor(const Rect &scissor)
2525         {
2526                 this->scissor = scissor;
2527         }
2528
2529         void Renderer::setClipFlags(int flags)
2530         {
2531                 clipFlags = flags << 8;   // Bottom 8 bits used by legacy frustum
2532         }
2533
2534         void Renderer::setClipPlane(unsigned int index, const float plane[4])
2535         {
2536                 if(index < MAX_CLIP_PLANES)
2537                 {
2538                         userPlane[index] = plane;
2539                 }
2540                 else ASSERT(false);
2541
2542                 updateClipPlanes = true;
2543         }
2544
2545         void Renderer::updateConfiguration(bool initialUpdate)
2546         {
2547                 bool newConfiguration = swiftConfig->hasNewConfiguration();
2548
2549                 if(newConfiguration || initialUpdate)
2550                 {
2551                         terminateThreads();
2552
2553                         SwiftConfig::Configuration configuration = {};
2554                         swiftConfig->getConfiguration(configuration);
2555
2556                         precacheVertex = !newConfiguration && configuration.precache;
2557                         precacheSetup = !newConfiguration && configuration.precache;
2558                         precachePixel = !newConfiguration && configuration.precache;
2559
2560                         VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
2561                         PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
2562                         SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
2563
2564                         switch(configuration.textureSampleQuality)
2565                         {
2566                         case 0:  Sampler::setFilterQuality(FILTER_POINT);       break;
2567                         case 1:  Sampler::setFilterQuality(FILTER_LINEAR);      break;
2568                         case 2:  Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2569                         default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2570                         }
2571
2572                         switch(configuration.mipmapQuality)
2573                         {
2574                         case 0:  Sampler::setMipmapQuality(MIPMAP_POINT);  break;
2575                         case 1:  Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2576                         default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2577                         }
2578
2579                         setPerspectiveCorrection(configuration.perspectiveCorrection);
2580
2581                         switch(configuration.transcendentalPrecision)
2582                         {
2583                         case 0:
2584                                 logPrecision = APPROXIMATE;
2585                                 expPrecision = APPROXIMATE;
2586                                 rcpPrecision = APPROXIMATE;
2587                                 rsqPrecision = APPROXIMATE;
2588                                 break;
2589                         case 1:
2590                                 logPrecision = PARTIAL;
2591                                 expPrecision = PARTIAL;
2592                                 rcpPrecision = PARTIAL;
2593                                 rsqPrecision = PARTIAL;
2594                                 break;
2595                         case 2:
2596                                 logPrecision = ACCURATE;
2597                                 expPrecision = ACCURATE;
2598                                 rcpPrecision = ACCURATE;
2599                                 rsqPrecision = ACCURATE;
2600                                 break;
2601                         case 3:
2602                                 logPrecision = WHQL;
2603                                 expPrecision = WHQL;
2604                                 rcpPrecision = WHQL;
2605                                 rsqPrecision = WHQL;
2606                                 break;
2607                         case 4:
2608                                 logPrecision = IEEE;
2609                                 expPrecision = IEEE;
2610                                 rcpPrecision = IEEE;
2611                                 rsqPrecision = IEEE;
2612                                 break;
2613                         default:
2614                                 logPrecision = ACCURATE;
2615                                 expPrecision = ACCURATE;
2616                                 rcpPrecision = ACCURATE;
2617                                 rsqPrecision = ACCURATE;
2618                                 break;
2619                         }
2620
2621                         switch(configuration.transparencyAntialiasing)
2622                         {
2623                         case 0:  transparencyAntialiasing = TRANSPARENCY_NONE;              break;
2624                         case 1:  transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
2625                         default: transparencyAntialiasing = TRANSPARENCY_NONE;              break;
2626                         }
2627
2628                         switch(configuration.threadCount)
2629                         {
2630                         case -1: threadCount = CPUID::coreCount();        break;
2631                         case 0:  threadCount = CPUID::processAffinity();  break;
2632                         default: threadCount = configuration.threadCount; break;
2633                         }
2634
2635                         CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
2636                         CPUID::setEnableSSSE3(configuration.enableSSSE3);
2637                         CPUID::setEnableSSE3(configuration.enableSSE3);
2638                         CPUID::setEnableSSE2(configuration.enableSSE2);
2639                         CPUID::setEnableSSE(configuration.enableSSE);
2640
2641                         for(int pass = 0; pass < 10; pass++)
2642                         {
2643                                 optimization[pass] = configuration.optimization[pass];
2644                         }
2645
2646                         forceWindowed = configuration.forceWindowed;
2647                         complementaryDepthBuffer = configuration.complementaryDepthBuffer;
2648                         postBlendSRGB = configuration.postBlendSRGB;
2649                         exactColorRounding = configuration.exactColorRounding;
2650                         forceClearRegisters = configuration.forceClearRegisters;
2651
2652                 #ifndef NDEBUG
2653                         minPrimitives = configuration.minPrimitives;
2654                         maxPrimitives = configuration.maxPrimitives;
2655                 #endif
2656                 }
2657
2658                 if(!initialUpdate && !worker[0])
2659                 {
2660                         initializeThreads();
2661                 }
2662         }
2663 }