wined3d: Fix various incorrect uses of GL_LIMITS(texture_stages) and GL_LIMITS(sample...
[wine] / dlls / wined3d / drawprim.c
1 /*
2  * WINED3D draw functions
3  *
4  * Copyright 2002-2004 Jason Edmeades
5  * Copyright 2002-2004 Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  * Copyright 2005 Oliver Stieber
8  * Copyright 2006 Henri Verbeet
9  * Copyright 2007 Stefan Dösinger for CodeWeavers
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wined3d_private.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 #include <stdio.h>
33
34 #if 0 /* TODO */
35 extern IWineD3DVertexShaderImpl*            VertexShaders[64];
36 extern IWineD3DVertexDeclarationImpl*       VertexShaderDeclarations[64];
37 extern IWineD3DPixelShaderImpl*             PixelShaders[64];
38
39 #undef GL_VERSION_1_4 /* To be fixed, caused by mesa headers */
40 #endif
41
42 /* Issues the glBegin call for gl given the primitive type and count */
43 static DWORD primitiveToGl(WINED3DPRIMITIVETYPE PrimitiveType,
44                     DWORD            NumPrimitives,
45                     GLenum          *primType)
46 {
47     DWORD   NumVertexes = NumPrimitives;
48
49     switch (PrimitiveType) {
50     case WINED3DPT_POINTLIST:
51         TRACE("POINTS\n");
52         *primType   = GL_POINTS;
53         NumVertexes = NumPrimitives;
54         break;
55
56     case WINED3DPT_LINELIST:
57         TRACE("LINES\n");
58         *primType   = GL_LINES;
59         NumVertexes = NumPrimitives * 2;
60         break;
61
62     case WINED3DPT_LINESTRIP:
63         TRACE("LINE_STRIP\n");
64         *primType   = GL_LINE_STRIP;
65         NumVertexes = NumPrimitives + 1;
66         break;
67
68     case WINED3DPT_TRIANGLELIST:
69         TRACE("TRIANGLES\n");
70         *primType   = GL_TRIANGLES;
71         NumVertexes = NumPrimitives * 3;
72         break;
73
74     case WINED3DPT_TRIANGLESTRIP:
75         TRACE("TRIANGLE_STRIP\n");
76         *primType   = GL_TRIANGLE_STRIP;
77         NumVertexes = NumPrimitives + 2;
78         break;
79
80     case WINED3DPT_TRIANGLEFAN:
81         TRACE("TRIANGLE_FAN\n");
82         *primType   = GL_TRIANGLE_FAN;
83         NumVertexes = NumPrimitives + 2;
84         break;
85
86     default:
87         FIXME("Unhandled primitive\n");
88         *primType    = GL_POINTS;
89         break;
90     }
91     return NumVertexes;
92 }
93
94 static BOOL fixed_get_input(
95     BYTE usage, BYTE usage_idx,
96     unsigned int* regnum) {
97
98     *regnum = -1;
99
100     /* Those positions must have the order in the
101      * named part of the strided data */
102
103     if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 0)
104         *regnum = 0;
105     else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && usage_idx == 0)
106         *regnum = 1;
107     else if (usage == WINED3DDECLUSAGE_BLENDINDICES && usage_idx == 0)
108         *regnum = 2;
109     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 0)
110         *regnum = 3;
111     else if (usage == WINED3DDECLUSAGE_PSIZE && usage_idx == 0)
112         *regnum = 4;
113     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 0)
114         *regnum = 5;
115     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
116         *regnum = 6;
117     else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
118         *regnum = 7 + usage_idx;
119     else if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 1)
120         *regnum = 7 + WINED3DDP_MAXTEXCOORD;
121     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 1)
122         *regnum = 8 + WINED3DDP_MAXTEXCOORD;
123     else if (usage == WINED3DDECLUSAGE_TANGENT && usage_idx == 0)
124         *regnum = 9 + WINED3DDP_MAXTEXCOORD;
125     else if (usage == WINED3DDECLUSAGE_BINORMAL && usage_idx == 0)
126         *regnum = 10 + WINED3DDP_MAXTEXCOORD;
127     else if (usage == WINED3DDECLUSAGE_TESSFACTOR && usage_idx == 0)
128         *regnum = 11 + WINED3DDP_MAXTEXCOORD;
129     else if (usage == WINED3DDECLUSAGE_FOG && usage_idx == 0)
130         *regnum = 12 + WINED3DDP_MAXTEXCOORD;
131     else if (usage == WINED3DDECLUSAGE_DEPTH && usage_idx == 0)
132         *regnum = 13 + WINED3DDP_MAXTEXCOORD;
133     else if (usage == WINED3DDECLUSAGE_SAMPLE && usage_idx == 0)
134         *regnum = 14 + WINED3DDP_MAXTEXCOORD;
135
136     if (*regnum < 0) {
137         FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n",
138             debug_d3ddeclusage(usage), usage_idx);
139         return FALSE;
140     }
141     return TRUE;
142 }
143
144 void primitiveDeclarationConvertToStridedData(
145      IWineD3DDevice *iface,
146      BOOL useVertexShaderFunction,
147      WineDirect3DVertexStridedData *strided,
148      BOOL *fixup) {
149
150      /* We need to deal with frequency data!*/
151
152     BYTE  *data    = NULL;
153     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
154     IWineD3DVertexDeclarationImpl* vertexDeclaration = (IWineD3DVertexDeclarationImpl *)This->stateBlock->vertexDecl;
155     int i;
156     WINED3DVERTEXELEMENT *element;
157     DWORD stride;
158     int reg;
159     char isPreLoaded[MAX_STREAMS];
160     DWORD preLoadStreams[MAX_STREAMS], numPreloadStreams = 0;
161
162     memset(isPreLoaded, 0, sizeof(isPreLoaded));
163
164     /* Check for transformed vertices, disable vertex shader if present */
165     strided->u.s.position_transformed = FALSE;
166     for (i = 0; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
167         element = vertexDeclaration->pDeclarationWine + i;
168
169         if (element->Usage == WINED3DDECLUSAGE_POSITIONT) {
170             strided->u.s.position_transformed = TRUE;
171             useVertexShaderFunction = FALSE;
172         }
173     }
174
175     /* Translate the declaration into strided data */
176     for (i = 0 ; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
177         GLint streamVBO = 0;
178         BOOL stride_used;
179         unsigned int idx;
180
181         element = vertexDeclaration->pDeclarationWine + i;
182         TRACE("%p Element %p (%d of %d)\n", vertexDeclaration->pDeclarationWine,
183             element,  i + 1, vertexDeclaration->declarationWNumElements - 1);
184
185         if (This->stateBlock->streamSource[element->Stream] == NULL)
186             continue;
187
188         if (This->stateBlock->streamIsUP) {
189             TRACE("Stream is up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
190             streamVBO = 0;
191             data    = (BYTE *)This->stateBlock->streamSource[element->Stream];
192         } else {
193             TRACE("Stream isn't up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
194             if(!isPreLoaded[element->Stream]) {
195                 preLoadStreams[numPreloadStreams] = element->Stream;
196                 numPreloadStreams++;
197                 isPreLoaded[element->Stream] = 1;
198             }
199             data    = IWineD3DVertexBufferImpl_GetMemory(This->stateBlock->streamSource[element->Stream], 0, &streamVBO);
200             if(fixup) {
201                 if( streamVBO != 0) *fixup = TRUE;
202                 else if(*fixup && !useVertexShaderFunction) {
203                     /* This may be bad with the fixed function pipeline */
204                     FIXME("Missing fixed and unfixed vertices, expect graphics glitches\n");
205                 }
206             }
207         }
208         stride  = This->stateBlock->streamStride[element->Stream];
209         data += element->Offset;
210         reg = element->Reg;
211
212         TRACE("Offset %d Stream %d UsageIndex %d\n", element->Offset, element->Stream, element->UsageIndex);
213
214         if (useVertexShaderFunction)
215             stride_used = vshader_get_input(This->stateBlock->vertexShader,
216                 element->Usage, element->UsageIndex, &idx);
217         else
218             stride_used = fixed_get_input(element->Usage, element->UsageIndex, &idx);
219
220         if (stride_used) {
221             TRACE("Loaded %s array %u [usage=%s, usage_idx=%u, "
222                     "stream=%u, offset=%u, stride=%u, VBO=%u]\n",
223                     useVertexShaderFunction? "shader": "fixed function", idx,
224                     debug_d3ddeclusage(element->Usage), element->UsageIndex,
225                     element->Stream, element->Offset, stride, streamVBO);
226
227             strided->u.input[idx].lpData = data;
228             strided->u.input[idx].dwType = element->Type;
229             strided->u.input[idx].dwStride = stride;
230             strided->u.input[idx].VBO = streamVBO;
231             strided->u.input[idx].streamNo = element->Stream;
232         }
233     }
234     /* Now call PreLoad on all the vertex buffers. In the very rare case
235      * that the buffers stopps converting PreLoad will dirtify the VDECL again.
236      * The vertex buffer can now use the strided structure in the device instead of finding its
237      * own again.
238      *
239      * NULL streams won't be recorded in the array, UP streams won't be either. A stream is only
240      * once in there.
241      */
242     for(i=0; i < numPreloadStreams; i++) {
243         IWineD3DVertexBuffer_PreLoad(This->stateBlock->streamSource[preLoadStreams[i]]);
244     }
245 }
246
247 static void drawStridedFast(IWineD3DDevice *iface,UINT numberOfVertices, GLenum glPrimitiveType,
248                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
249     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
250
251     if (idxSize != 0 /* This crashes sometimes!*/) {
252         TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
253         idxData = idxData == (void *)-1 ? NULL : idxData;
254 #if 1
255         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
256                      (const char *)idxData+(idxSize * startIdx));
257 #else /* using drawRangeElements may be faster */
258
259         glDrawRangeElements(glPrimitiveType, minIndex, minIndex + numberOfVertices - 1, numberOfVertices,
260                       idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
261                       (const char *)idxData+(idxSize * startIdx));
262 #endif
263         checkGLcall("glDrawRangeElements");
264
265     } else {
266
267         /* Note first is now zero as we shuffled along earlier */
268         TRACE("(%p) : glDrawArrays(%x, 0, %d)\n", This, glPrimitiveType, numberOfVertices);
269         glDrawArrays(glPrimitiveType, startVertex, numberOfVertices);
270         checkGLcall("glDrawArrays");
271
272     }
273
274     return;
275 }
276
277 /*
278  * Actually draw using the supplied information.
279  * Slower GL version which extracts info about each vertex in turn
280  */
281
282 static void drawStridedSlow(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd,
283                      UINT NumVertexes, GLenum glPrimType,
284                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
285
286     unsigned int               textureNo    = 0;
287     const WORD                *pIdxBufS     = NULL;
288     const DWORD               *pIdxBufL     = NULL;
289     LONG                       vx_index;
290     float x  = 0.0f, y  = 0.0f, z = 0.0f;  /* x,y,z coordinates          */
291     float rhw = 0.0f;                      /* rhw                        */
292     DWORD diffuseColor = 0xFFFFFFFF;       /* Diffuse Color              */
293     DWORD specularColor = 0;               /* Specular Color             */
294     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
295     UINT *streamOffset = This->stateBlock->streamOffset;
296     DWORD                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
297
298     BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
299     BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
300
301     TRACE("Using slow vertex array code\n");
302
303     /* Variable Initialization */
304     if (idxSize != 0) {
305         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
306          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
307          * idxData will be != NULL
308          */
309         if(idxData == NULL) {
310             idxData = ((IWineD3DIndexBufferImpl *) This->stateBlock->pIndexData)->resource.allocatedMemory;
311         }
312
313         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
314         else pIdxBufL = (const DWORD *) idxData;
315     }
316
317     /* Adding the stream offset once is cheaper than doing it every iteration. Do not modify the strided data, it is a pointer
318      * to the strided Data in the device and might be needed intact on the next draw
319      */
320     for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
321         if(sd->u.s.texCoords[textureNo].lpData) {
322             texCoords[textureNo] = sd->u.s.texCoords[textureNo].lpData + streamOffset[sd->u.s.texCoords[textureNo].streamNo];
323         } else {
324             texCoords[textureNo] = NULL;
325         }
326     }
327     if(sd->u.s.diffuse.lpData) {
328         diffuse = sd->u.s.diffuse.lpData + streamOffset[sd->u.s.diffuse.streamNo];
329     }
330     if(sd->u.s.specular.lpData) {
331         specular = sd->u.s.specular.lpData + streamOffset[sd->u.s.specular.streamNo];
332     }
333     if(sd->u.s.normal.lpData) {
334         normal = sd->u.s.normal.lpData + streamOffset[sd->u.s.normal.streamNo];
335     }
336     if(sd->u.s.position.lpData) {
337         position = sd->u.s.position.lpData + streamOffset[sd->u.s.position.streamNo];
338     }
339
340     /* Start drawing in GL */
341     VTRACE(("glBegin(%x)\n", glPrimType));
342     glBegin(glPrimType);
343
344     /* Default settings for data that is not passed */
345     if (sd->u.s.normal.lpData == NULL) {
346         glNormal3f(0, 0, 1);
347     }
348     if(sd->u.s.diffuse.lpData == NULL) {
349         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
350     }
351     if(sd->u.s.specular.lpData == NULL) {
352         if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
353             GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
354         }
355     }
356
357     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
358      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
359      */
360
361     /* For each primitive */
362     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
363
364         /* Initialize diffuse color */
365         diffuseColor = 0xFFFFFFFF;
366
367         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
368          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
369          */
370
371         /* For indexed data, we need to go a few more strides in */
372         if (idxData != NULL) {
373
374             /* Indexed so work out the number of strides to skip */
375             if (idxSize == 2) {
376                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
377                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
378             } else {
379                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
380                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
381             }
382         }
383
384         /* Texture coords --------------------------- */
385         for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
386
387             if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0) {
388                 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
389                 continue ;
390             }
391
392             /* Query tex coords */
393             if (This->stateBlock->textures[textureNo] != NULL) {
394
395                 int    coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
396                 float *ptrToCoords = NULL;
397                 float  s = 0.0, t = 0.0, r = 0.0, q = 0.0;
398
399                 if (coordIdx > 7) {
400                     VTRACE(("tex: %d - Skip tex coords, as being system generated\n", textureNo));
401                     continue;
402                 } else if (coordIdx < 0) {
403                     FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
404                     continue;
405                 }
406
407                 ptrToCoords = (float *)(texCoords[coordIdx] + (SkipnStrides * sd->u.s.texCoords[coordIdx].dwStride));
408                 if (texCoords[coordIdx] == NULL) {
409                     TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
410                     continue;
411                 } else {
412                     int texture_idx = This->texUnitMap[textureNo];
413                     int coordsToUse = sd->u.s.texCoords[coordIdx].dwType + 1; /* 0 == WINED3DDECLTYPE_FLOAT1 etc */
414
415                     if (texture_idx == -1) continue;
416
417                     /* The coords to supply depend completely on the fvf / vertex shader */
418                     switch (coordsToUse) {
419                     case 4: q = ptrToCoords[3]; /* drop through */
420                     case 3: r = ptrToCoords[2]; /* drop through */
421                     case 2: t = ptrToCoords[1]; /* drop through */
422                     case 1: s = ptrToCoords[0];
423                     }
424
425                     /* Projected is more 'fun' - Move the last coord to the 'q'
426                           parameter (see comments under WINED3DTSS_TEXTURETRANSFORMFLAGS */
427                     if ((This->stateBlock->textureState[textureNo][WINED3DTSS_TEXTURETRANSFORMFLAGS] != WINED3DTTFF_DISABLE) &&
428                         (This->stateBlock->textureState[textureNo][WINED3DTSS_TEXTURETRANSFORMFLAGS] & WINED3DTTFF_PROJECTED)) {
429
430                         if (This->stateBlock->textureState[textureNo][WINED3DTSS_TEXTURETRANSFORMFLAGS] & WINED3DTTFF_PROJECTED) {
431                             switch (coordsToUse) {
432                             case 0:  /* Drop Through */
433                             case 1:
434                                 FIXME("WINED3DTTFF_PROJECTED but only zero or one coordinate?\n");
435                                 break;
436                             case 2:
437                                 q = t;
438                                 t = 0.0;
439                                 coordsToUse = 4;
440                                 break;
441                             case 3:
442                                 q = r;
443                                 r = 0.0;
444                                 coordsToUse = 4;
445                                 break;
446                             case 4:  /* Nop here */
447                                 break;
448                             default:
449                                 FIXME("Unexpected WINED3DTSS_TEXTURETRANSFORMFLAGS value of %d\n",
450                                       This->stateBlock->textureState[textureNo][WINED3DTSS_TEXTURETRANSFORMFLAGS] & WINED3DTTFF_PROJECTED);
451                             }
452                         }
453                     }
454
455                     switch (coordsToUse) {   /* Supply the provided texture coords */
456                     case WINED3DTTFF_COUNT1:
457                         VTRACE(("tex:%d, s=%f\n", textureNo, s));
458                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
459                             GL_EXTCALL(glMultiTexCoord1fARB(texture_idx, s));
460                         } else {
461                             glTexCoord1f(s);
462                         }
463                         break;
464                     case WINED3DTTFF_COUNT2:
465                         VTRACE(("tex:%d, s=%f, t=%f\n", textureNo, s, t));
466                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
467                             GL_EXTCALL(glMultiTexCoord2fARB(texture_idx, s, t));
468                         } else {
469                             glTexCoord2f(s, t);
470                         }
471                         break;
472                     case WINED3DTTFF_COUNT3:
473                         VTRACE(("tex:%d, s=%f, t=%f, r=%f\n", textureNo, s, t, r));
474                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
475                             GL_EXTCALL(glMultiTexCoord3fARB(texture_idx, s, t, r));
476                         } else {
477                             glTexCoord3f(s, t, r);
478                         }
479                         break;
480                     case WINED3DTTFF_COUNT4:
481                         VTRACE(("tex:%d, s=%f, t=%f, r=%f, q=%f\n", textureNo, s, t, r, q));
482                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
483                             GL_EXTCALL(glMultiTexCoord4fARB(texture_idx, s, t, r, q));
484                         } else {
485                             glTexCoord4f(s, t, r, q);
486                         }
487                         break;
488                     default:
489                         FIXME("Should not get here as coordsToUse is two bits only (%x)!\n", coordsToUse);
490                     }
491                 }
492             }
493         } /* End of textures */
494
495         /* Diffuse -------------------------------- */
496         if (diffuse) {
497             DWORD *ptrToCoords = (DWORD *)(diffuse + (SkipnStrides * sd->u.s.diffuse.dwStride));
498             diffuseColor = ptrToCoords[0];
499             VTRACE(("diffuseColor=%lx\n", diffuseColor));
500
501             glColor4ub(D3DCOLOR_B_R(diffuseColor),
502                      D3DCOLOR_B_G(diffuseColor),
503                      D3DCOLOR_B_B(diffuseColor),
504                      D3DCOLOR_B_A(diffuseColor));
505             VTRACE(("glColor4ub: r,g,b,a=%lu,%lu,%lu,%lu\n", 
506                     D3DCOLOR_B_R(diffuseColor),
507                     D3DCOLOR_B_G(diffuseColor),
508                     D3DCOLOR_B_B(diffuseColor),
509                     D3DCOLOR_B_A(diffuseColor)));
510
511             if(This->activeContext->num_untracked_materials) {
512                 unsigned char i;
513                 float color[4];
514                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
515                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
516                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
517                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
518
519                 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
520                     glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
521                 }
522             }
523         }
524
525         /* Specular ------------------------------- */
526         if (specular) {
527             DWORD *ptrToCoords = (DWORD *)(specular + (SkipnStrides * sd->u.s.specular.dwStride));
528             specularColor = ptrToCoords[0];
529             VTRACE(("specularColor=%lx\n", specularColor));
530
531             /* special case where the fog density is stored in the specular alpha channel */
532             if(This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
533               (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position.dwType == WINED3DDECLTYPE_FLOAT4 )&&
534               This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
535                 if(GL_SUPPORT(EXT_FOG_COORD)) {
536                     GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
537                 } else {
538                     static BOOL warned = FALSE;
539                     if(!warned) {
540                         /* TODO: Use the fog table code from old ddraw */
541                         FIXME("Implement fog for transformed vertices in software\n");
542                         warned = TRUE;
543                     }
544                 }
545             }
546
547             VTRACE(("glSecondaryColor4ub: r,g,b=%lu,%lu,%lu\n", 
548                     D3DCOLOR_B_R(specularColor), 
549                     D3DCOLOR_B_G(specularColor), 
550                     D3DCOLOR_B_B(specularColor)));
551             if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
552                 GL_EXTCALL(glSecondaryColor3ubEXT)(
553                            D3DCOLOR_B_R(specularColor),
554                            D3DCOLOR_B_G(specularColor),
555                            D3DCOLOR_B_B(specularColor));
556             } else {
557                 /* Do not worry if specular colour missing and disable request */
558                 VTRACE(("Specular color extensions not supplied\n"));
559             }
560         }
561
562         /* Normal -------------------------------- */
563         if (normal != NULL) {
564             float *ptrToCoords = (float *)(normal + (SkipnStrides * sd->u.s.normal.dwStride));
565
566             VTRACE(("glNormal:nx,ny,nz=%f,%f,%f\n", ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]));
567             glNormal3f(ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]);
568         }
569
570         /* Position -------------------------------- */
571         if (position) {
572             float *ptrToCoords = (float *)(position + (SkipnStrides * sd->u.s.position.dwStride));
573             x = ptrToCoords[0];
574             y = ptrToCoords[1];
575             z = ptrToCoords[2];
576             rhw = 1.0;
577             VTRACE(("x,y,z=%f,%f,%f\n", x,y,z));
578
579             /* RHW follows, only if transformed, ie 4 floats were provided */
580             if (sd->u.s.position_transformed) {
581                 rhw = ptrToCoords[3];
582                 VTRACE(("rhw=%f\n", rhw));
583             }
584
585             if (1.0f == rhw || ((rhw < eps) && (rhw > -eps))) {
586                 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f\n", x,y,z));
587                 glVertex3f(x, y, z);
588             } else {
589                 GLfloat w = 1.0 / rhw;
590                 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f / rhw=%f\n", x,y,z,rhw));
591                 glVertex4f(x*w, y*w, z*w, w);
592             }
593         }
594
595         /* For non indexed mode, step onto next parts */
596         if (idxData == NULL) {
597             ++SkipnStrides;
598         }
599     }
600
601     glEnd();
602     checkGLcall("glEnd and previous calls");
603 }
604
605 static void depth_blt(IWineD3DDevice *iface, GLuint texture) {
606     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
607     GLint old_binding = 0;
608
609     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
610
611     glDisable(GL_CULL_FACE);
612     glEnable(GL_BLEND);
613     glDisable(GL_ALPHA_TEST);
614     glDisable(GL_SCISSOR_TEST);
615     glDisable(GL_STENCIL_TEST);
616     glEnable(GL_DEPTH_TEST);
617     glDepthFunc(GL_ALWAYS);
618     glBlendFunc(GL_ZERO, GL_ONE);
619
620     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
621     glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
622     glBindTexture(GL_TEXTURE_2D, texture);
623     glEnable(GL_TEXTURE_2D);
624
625     This->shader_backend->shader_select_depth_blt(iface);
626
627     glBegin(GL_TRIANGLE_STRIP);
628     glVertex2f(-1.0f, -1.0f);
629     glVertex2f(1.0f, -1.0f);
630     glVertex2f(-1.0f, 1.0f);
631     glVertex2f(1.0f, 1.0f);
632     glEnd();
633
634     glBindTexture(GL_TEXTURE_2D, old_binding);
635
636     glPopAttrib();
637
638     /* Reselect the old shaders. There doesn't seem to be any glPushAttrib bit for arb shaders,
639      * and this seems easier and more efficient than providing the shader backend with a private
640      * storage to read and restore the old shader settings
641      */
642     This->shader_backend->shader_select(iface, use_ps(This), use_vs(This));
643 }
644
645 static void depth_copy(IWineD3DDevice *iface) {
646     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
647     IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *)This->depthStencilBuffer;
648
649     /* Only copy the depth buffer if there is one. */
650     if (!depth_stencil) return;
651
652     /* TODO: Make this work for modes other than FBO */
653     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
654
655     if (depth_stencil->current_renderbuffer) {
656         FIXME("Not supported with fixed up depth stencil\n");
657         return;
658     }
659
660     if (This->render_offscreen) {
661         static GLuint tmp_texture = 0;
662         GLint old_binding = 0;
663
664         TRACE("Copying onscreen depth buffer to offscreen surface\n");
665
666         if (!tmp_texture) {
667             glGenTextures(1, &tmp_texture);
668         }
669
670         /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
671          * directly on the FBO texture. That's because we need to flip. */
672         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
673         glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
674         glBindTexture(GL_TEXTURE_2D, tmp_texture);
675         glCopyTexImage2D(depth_stencil->glDescription.target,
676                 depth_stencil->glDescription.level,
677                 depth_stencil->glDescription.glFormatInternal,
678                 0,
679                 0,
680                 depth_stencil->currentDesc.Width,
681                 depth_stencil->currentDesc.Height,
682                 0);
683         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
684         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
685         glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
686         glBindTexture(GL_TEXTURE_2D, old_binding);
687
688         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, This->fbo));
689         checkGLcall("glBindFramebuffer()");
690         depth_blt(iface, tmp_texture);
691         checkGLcall("depth_blt");
692     } else {
693         TRACE("Copying offscreen surface to onscreen depth buffer\n");
694
695         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
696         checkGLcall("glBindFramebuffer()");
697         depth_blt(iface, depth_stencil->glDescription.textureName);
698         checkGLcall("depth_blt");
699     }
700 }
701
702 static inline void drawStridedInstanced(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
703                                  GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex,
704                                  ULONG startIdx, ULONG startVertex) {
705     UINT numInstances = 0;
706     int numInstancedAttribs = 0, i, j;
707     UINT instancedData[sizeof(sd->u.input) / sizeof(sd->u.input[0]) /* 16 */];
708     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
709     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
710
711     if (idxSize == 0) {
712         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
713          * We don't support this for now
714          *
715          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
716          * But the StreamSourceFreq value has a different meaning in that situation.
717          */
718         FIXME("Non-indexed instanced drawing is not supported\n");
719         return;
720     }
721
722     TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
723     idxData = idxData == (void *)-1 ? NULL : idxData;
724
725     /* First, figure out how many instances we have to draw */
726     for(i = 0; i < MAX_STREAMS; i++) {
727         /* Look at all non-instanced streams */
728         if(!(stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) &&
729            stateblock->streamSource[i]) {
730             int inst = stateblock->streamFreq[i];
731
732             if(numInstances && inst != numInstances) {
733                 ERR("Two streams specify a different number of instances. Got %d, new is %d\n", numInstances, inst);
734             }
735             numInstances = inst;
736         }
737     }
738
739     for(i = 0; i < sizeof(sd->u.input) / sizeof(sd->u.input[0]); i++) {
740         if(stateblock->streamFlags[sd->u.input[i].streamNo] & WINED3DSTREAMSOURCE_INSTANCEDATA) {
741             instancedData[numInstancedAttribs] = i;
742             numInstancedAttribs++;
743         }
744     }
745
746     /* now draw numInstances instances :-) */
747     for(i = 0; i < numInstances; i++) {
748         /* Specify the instanced attributes using immediate mode calls */
749         for(j = 0; j < numInstancedAttribs; j++) {
750             BYTE *ptr = sd->u.input[instancedData[j]].lpData +
751                         sd->u.input[instancedData[j]].dwStride * i +
752                         stateblock->streamOffset[sd->u.input[instancedData[j]].streamNo];
753             if(sd->u.input[instancedData[j]].VBO) {
754                 IWineD3DVertexBufferImpl *vb = (IWineD3DVertexBufferImpl *) stateblock->streamSource[sd->u.input[instancedData[j]].streamNo];
755                 ptr += (long) vb->resource.allocatedMemory;
756             }
757
758             switch(sd->u.input[instancedData[j]].dwType) {
759                 case WINED3DDECLTYPE_FLOAT1:
760                     GL_EXTCALL(glVertexAttrib1fvARB(instancedData[j], (float *) ptr));
761                     break;
762                 case WINED3DDECLTYPE_FLOAT2:
763                     GL_EXTCALL(glVertexAttrib2fvARB(instancedData[j], (float *) ptr));
764                     break;
765                 case WINED3DDECLTYPE_FLOAT3:
766                     GL_EXTCALL(glVertexAttrib3fvARB(instancedData[j], (float *) ptr));
767                     break;
768                 case WINED3DDECLTYPE_FLOAT4:
769                     GL_EXTCALL(glVertexAttrib4fvARB(instancedData[j], (float *) ptr));
770                     break;
771
772                 case WINED3DDECLTYPE_UBYTE4:
773                     GL_EXTCALL(glVertexAttrib4NubvARB(instancedData[j], ptr));
774                     break;
775                 case WINED3DDECLTYPE_UBYTE4N:
776                 case WINED3DDECLTYPE_D3DCOLOR:
777                     GL_EXTCALL(glVertexAttrib4NubvARB(instancedData[j], ptr));
778                     break;
779
780                 case WINED3DDECLTYPE_SHORT2:
781                     GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
782                     break;
783                 case WINED3DDECLTYPE_SHORT4:
784                     GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
785                     break;
786
787                 case WINED3DDECLTYPE_SHORT2N:
788                 {
789                     GLshort s[4] = {((short *) ptr)[0], ((short *) ptr)[1], 0, 1};
790                     GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], s));
791                     break;
792                 }
793                 case WINED3DDECLTYPE_USHORT2N:
794                 {
795                     GLushort s[4] = {((unsigned short *) ptr)[0], ((unsigned short *) ptr)[1], 0, 1};
796                     GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], s));
797                     break;
798                 }
799                 case WINED3DDECLTYPE_SHORT4N:
800                     GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], (GLshort *) ptr));
801                     break;
802                 case WINED3DDECLTYPE_USHORT4N:
803                     GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], (GLushort *) ptr));
804                     break;
805
806                 case WINED3DDECLTYPE_UDEC3:
807                     FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
808                     /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
809                     break;
810                 case WINED3DDECLTYPE_DEC3N:
811                     FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
812                     /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
813                     break;
814
815                 case WINED3DDECLTYPE_FLOAT16_2:
816                     /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
817                      * byte float according to the IEEE standard
818                      */
819                     FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_2\n");
820                     break;
821                 case WINED3DDECLTYPE_FLOAT16_4:
822                     FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_4\n");
823                     break;
824
825                 case WINED3DDECLTYPE_UNUSED:
826                 default:
827                     ERR("Unexpected declaration in instanced attributes\n");
828                     break;
829             }
830         }
831
832         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
833                     (const char *)idxData+(idxSize * startIdx));
834         checkGLcall("glDrawElements");
835     }
836 }
837
838 struct coords {
839     int x, y, z;
840 };
841
842 void blt_to_drawable(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *surface) {
843     struct coords coords[4];
844     int low_coord;
845
846     /* TODO: This could be supported for lazy unlocking */
847     if(!(surface->Flags & SFLAG_INTEXTURE)) {
848         /* It is ok at init to be nowhere */
849         if(!(surface->Flags & SFLAG_INSYSMEM)) {
850             ERR("Blitting surfaces from sysmem not supported yet\n");
851         }
852         return;
853     }
854
855     ENTER_GL();
856     ActivateContext(This, This->render_targets[0], CTXUSAGE_BLIT);
857
858     if(surface->glDescription.target == GL_TEXTURE_2D) {
859         glBindTexture(GL_TEXTURE_2D, surface->glDescription.textureName);
860         checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
861
862         coords[0].x = 0;    coords[0].y = 0;    coords[0].z = 0;
863         coords[1].x = 0;    coords[1].y = 1;    coords[1].z = 0;
864         coords[2].x = 1;    coords[2].y = 1;    coords[2].z = 0;
865         coords[3].x = 1;    coords[3].y = 0;    coords[3].z = 0;
866
867         low_coord = 0;
868     } else {
869         /* Must be a cube map */
870         glDisable(GL_TEXTURE_2D);
871         checkGLcall("glDisable(GL_TEXTURE_2D)");
872         glEnable(GL_TEXTURE_CUBE_MAP_ARB);
873         checkGLcall("glEnable(surface->glDescription.target)");
874         glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, surface->glDescription.textureName);
875         checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
876
877         switch(surface->glDescription.target) {
878             case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
879                 coords[0].x =  1;   coords[0].y = -1;   coords[0].z =  1;
880                 coords[1].x =  1;   coords[1].y =  1;   coords[1].z =  1;
881                 coords[2].x =  1;   coords[2].y =  1;   coords[2].z = -1;
882                 coords[3].x =  1;   coords[3].y = -1;   coords[3].z = -1;
883                 break;
884
885             case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
886                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
887                 coords[1].x = -1;   coords[1].y =  1;   coords[1].z =  1;
888                 coords[2].x = -1;   coords[2].y =  1;   coords[2].z = -1;
889                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
890                 break;
891
892             case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
893                 coords[0].x = -1;   coords[0].y =  1;   coords[0].z =  1;
894                 coords[1].x =  1;   coords[1].y =  1;   coords[1].z =  1;
895                 coords[2].x =  1;   coords[2].y =  1;   coords[2].z = -1;
896                 coords[3].x = -1;   coords[3].y =  1;   coords[3].z = -1;
897                 break;
898
899             case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
900                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
901                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z =  1;
902                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z = -1;
903                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
904                 break;
905
906             case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
907                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
908                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z =  1;
909                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z =  1;
910                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z =  1;
911                 break;
912
913             case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
914                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z = -1;
915                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z = -1;
916                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z = -1;
917                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
918
919             default:
920                 ERR("Unexpected texture target\n");
921                 LEAVE_GL();
922                 return;
923         }
924
925         low_coord = -1;
926     }
927
928     if(This->render_offscreen) {
929         coords[0].y = coords[0].y == 1 ? low_coord : 1;
930         coords[1].y = coords[1].y == 1 ? low_coord : 1;
931         coords[2].y = coords[2].y == 1 ? low_coord : 1;
932         coords[3].y = coords[3].y == 1 ? low_coord : 1;
933     }
934
935     glBegin(GL_QUADS);
936         glTexCoord3iv((GLint *) &coords[0]);
937         glVertex2i(0, 0);
938
939         glTexCoord3iv((GLint *) &coords[1]);
940         glVertex2i(0, surface->pow2Height);
941
942         glTexCoord3iv((GLint *) &coords[2]);
943         glVertex2i(surface->pow2Width, surface->pow2Height);
944
945         glTexCoord3iv((GLint *) &coords[3]);
946         glVertex2i(surface->pow2Width, 0);
947     glEnd();
948     checkGLcall("glEnd");
949
950     if(surface->glDescription.target != GL_TEXTURE_2D) {
951         glEnable(GL_TEXTURE_2D);
952         checkGLcall("glEnable(GL_TEXTURE_2D)");
953         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
954         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
955     }
956     LEAVE_GL();
957 }
958
959 /* Routine common to the draw primitive and draw indexed primitive routines */
960 void drawPrimitive(IWineD3DDevice *iface,
961                    int PrimitiveType,
962                    long NumPrimitives,
963                    /* for Indexed: */
964                    long  StartVertexIndex,
965                    UINT  numberOfVertices,
966                    long  StartIdx,
967                    short idxSize,
968                    const void *idxData,
969                    int   minIndex) {
970
971     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
972     IWineD3DSwapChain            *swapchain;
973     IWineD3DBaseTexture          *texture = NULL;
974     IWineD3DSurfaceImpl          *target;
975     int i;
976
977     /* Signals other modules that a drawing is in progress and the stateblock finalized */
978     This->isInDraw = TRUE;
979
980     /* Invalidate the back buffer memory so LockRect will read it the next time */
981     for(i = 0; i < GL_LIMITS(buffers); i++) {
982         target = (IWineD3DSurfaceImpl *) This->render_targets[i];
983
984         /* TODO: Only do all that if we're going to change anything
985          * Texture container dirtification does not work quite right yet
986          */
987         if(target /*&& target->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)*/) {
988             swapchain = NULL;
989             texture = NULL;
990
991             if(i == 0) {
992                 IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DSwapChain, (void **)&swapchain);
993
994                 /* Need the surface in the drawable! */
995                 if(!(target->Flags & SFLAG_INDRAWABLE) && (swapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
996                     blt_to_drawable(This, target);
997                 }
998
999                 if(swapchain) {
1000                     /* Onscreen target. Invalidate system memory copy and texture copy */
1001                     target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
1002                     target->Flags |= SFLAG_INDRAWABLE;
1003                     IWineD3DSwapChain_Release(swapchain);
1004                 } else if(wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1005                     /* Non-FBO target: Invalidate system copy, texture copy and dirtify the container */
1006                     IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DBaseTexture, (void **)&texture);
1007
1008                     if(texture) {
1009                         IWineD3DBaseTexture_SetDirty(texture, TRUE);
1010                         IWineD3DTexture_Release(texture);
1011                     }
1012
1013                     target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
1014                     target->Flags |= SFLAG_INDRAWABLE;
1015                 } else {
1016                     /* FBO offscreen target. Invalidate system memory copy */
1017                     target->Flags &= ~SFLAG_INSYSMEM;
1018                 }
1019             } else {
1020                 /* Must be an fbo render target */
1021                 target->Flags &= ~SFLAG_INSYSMEM;
1022                 target->Flags |=  SFLAG_INTEXTURE;
1023             }
1024         }
1025     }
1026
1027     /* Ok, we will be updating the screen from here onwards so grab the lock */
1028     ENTER_GL();
1029
1030     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1031         apply_fbo_state(iface);
1032     }
1033
1034     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
1035
1036     if (This->depth_copy_state == WINED3D_DCS_COPY) {
1037         depth_copy(iface);
1038     }
1039     This->depth_copy_state = WINED3D_DCS_INITIAL;
1040
1041     {
1042         GLenum glPrimType;
1043         BOOL emulation = FALSE;
1044         WineDirect3DVertexStridedData *strided = &This->strided_streams;
1045         WineDirect3DVertexStridedData stridedlcl;
1046         /* Ok, Work out which primitive is requested and how many vertexes that
1047            will be                                                              */
1048         UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
1049         if (numberOfVertices == 0 )
1050             numberOfVertices = calculatedNumberOfindices;
1051
1052         if(!This->strided_streams.u.s.position_transformed && !use_vs(This)) {
1053             if(This->activeContext->num_untracked_materials &&
1054                This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
1055                 IWineD3DVertexBufferImpl *vb;
1056
1057                 FIXME("Using software emulation because not all material properties could be tracked\n");
1058                 emulation = TRUE;
1059
1060                 strided = &stridedlcl;
1061                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
1062
1063 #define FIXVBO(type) \
1064 if(stridedlcl.u.s.type.VBO) { \
1065     vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[stridedlcl.u.s.type.streamNo]; \
1066     stridedlcl.u.s.type.VBO = 0; \
1067     stridedlcl.u.s.type.lpData = (BYTE *) ((unsigned long) stridedlcl.u.s.type.lpData + (unsigned long) vb->resource.allocatedMemory); \
1068 }
1069                 FIXVBO(position);
1070                 FIXVBO(blendWeights);
1071                 FIXVBO(blendMatrixIndices);
1072                 FIXVBO(normal);
1073                 FIXVBO(pSize);
1074                 FIXVBO(diffuse);
1075                 FIXVBO(specular);
1076                 for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) FIXVBO(texCoords[i]);
1077                 FIXVBO(position2);
1078                 FIXVBO(normal2);
1079                 FIXVBO(tangent);
1080                 FIXVBO(binormal);
1081                 FIXVBO(tessFactor);
1082                 FIXVBO(fog);
1083                 FIXVBO(depth);
1084                 FIXVBO(sample);
1085 #undef FIXVBO
1086             }
1087         }
1088
1089         if (This->useDrawStridedSlow || emulation) {
1090             /* Immediate mode drawing */
1091             drawStridedSlow(iface, strided, calculatedNumberOfindices,
1092                             glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1093         } else if(This->instancedDraw) {
1094             /* Instancing emulation with mixing immediate mode and arrays */
1095             drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
1096                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1097         } else {
1098             /* Simple array draw call */
1099             drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
1100                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1101         }
1102     }
1103
1104     /* Finshed updating the screen, restore lock */
1105     LEAVE_GL();
1106     TRACE("Done all gl drawing\n");
1107
1108     /* Diagnostics */
1109 #ifdef SHOW_FRAME_MAKEUP
1110     {
1111         static long int primCounter = 0;
1112         /* NOTE: set primCounter to the value reported by drawprim 
1113            before you want to to write frame makeup to /tmp */
1114         if (primCounter >= 0) {
1115             WINED3DLOCKED_RECT r;
1116             char buffer[80];
1117             IWineD3DSurface_LockRect(This->renderTarget, &r, NULL, WINED3DLOCK_READONLY);
1118             sprintf(buffer, "/tmp/backbuffer_%d.tga", primCounter);
1119             TRACE("Saving screenshot %s\n", buffer);
1120             IWineD3DSurface_SaveSnapshot(This->renderTarget, buffer);
1121             IWineD3DSurface_UnlockRect(This->renderTarget);
1122
1123 #ifdef SHOW_TEXTURE_MAKEUP
1124            {
1125             IWineD3DSurface *pSur;
1126             int textureNo;
1127             for (textureNo = 0; textureNo < MAX_SAMPLERS; ++textureNo) {
1128                 if (This->stateBlock->textures[textureNo] != NULL) {
1129                     sprintf(buffer, "/tmp/texture_%p_%d_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
1130                     TRACE("Saving texture %s\n", buffer);
1131                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
1132                             IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
1133                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
1134                             IWineD3DSurface_Release(pSur);
1135                     } else  {
1136                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
1137                     }
1138                 }
1139             }
1140            }
1141 #endif
1142         }
1143         TRACE("drawprim #%d\n", primCounter);
1144         ++primCounter;
1145     }
1146 #endif
1147
1148     /* Control goes back to the device, stateblock values may change again */
1149     This->isInDraw = FALSE;
1150 }