wined3d: Handle texture coordinates the same way we handle other vertex attributes.
[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, 2008 Henri Verbeet
9  * Copyright 2007-2008 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 #include <math.h>
34
35 /* Issues the glBegin call for gl given the primitive type and count */
36 static DWORD primitiveToGl(WINED3DPRIMITIVETYPE PrimitiveType,
37                     DWORD            NumPrimitives,
38                     GLenum          *primType)
39 {
40     DWORD   NumVertexes = NumPrimitives;
41
42     switch (PrimitiveType) {
43     case WINED3DPT_POINTLIST:
44         TRACE("POINTS\n");
45         *primType   = GL_POINTS;
46         NumVertexes = NumPrimitives;
47         break;
48
49     case WINED3DPT_LINELIST:
50         TRACE("LINES\n");
51         *primType   = GL_LINES;
52         NumVertexes = NumPrimitives * 2;
53         break;
54
55     case WINED3DPT_LINESTRIP:
56         TRACE("LINE_STRIP\n");
57         *primType   = GL_LINE_STRIP;
58         NumVertexes = NumPrimitives + 1;
59         break;
60
61     case WINED3DPT_TRIANGLELIST:
62         TRACE("TRIANGLES\n");
63         *primType   = GL_TRIANGLES;
64         NumVertexes = NumPrimitives * 3;
65         break;
66
67     case WINED3DPT_TRIANGLESTRIP:
68         TRACE("TRIANGLE_STRIP\n");
69         *primType   = GL_TRIANGLE_STRIP;
70         NumVertexes = NumPrimitives + 2;
71         break;
72
73     case WINED3DPT_TRIANGLEFAN:
74         TRACE("TRIANGLE_FAN\n");
75         *primType   = GL_TRIANGLE_FAN;
76         NumVertexes = NumPrimitives + 2;
77         break;
78
79     default:
80         FIXME("Unhandled primitive\n");
81         *primType    = GL_POINTS;
82         break;
83     }
84     return NumVertexes;
85 }
86
87 static BOOL fixed_get_input(
88     BYTE usage, BYTE usage_idx,
89     unsigned int* regnum) {
90
91     *regnum = -1;
92
93     /* Those positions must have the order in the
94      * named part of the strided data */
95
96     if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 0)
97         *regnum = 0;
98     else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && usage_idx == 0)
99         *regnum = 1;
100     else if (usage == WINED3DDECLUSAGE_BLENDINDICES && usage_idx == 0)
101         *regnum = 2;
102     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 0)
103         *regnum = 3;
104     else if (usage == WINED3DDECLUSAGE_PSIZE && usage_idx == 0)
105         *regnum = 4;
106     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 0)
107         *regnum = 5;
108     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
109         *regnum = 6;
110     else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
111         *regnum = 7 + usage_idx;
112     else if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 1)
113         *regnum = 7 + WINED3DDP_MAXTEXCOORD;
114     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 1)
115         *regnum = 8 + WINED3DDP_MAXTEXCOORD;
116     else if (usage == WINED3DDECLUSAGE_TANGENT && usage_idx == 0)
117         *regnum = 9 + WINED3DDP_MAXTEXCOORD;
118     else if (usage == WINED3DDECLUSAGE_BINORMAL && usage_idx == 0)
119         *regnum = 10 + WINED3DDP_MAXTEXCOORD;
120     else if (usage == WINED3DDECLUSAGE_TESSFACTOR && usage_idx == 0)
121         *regnum = 11 + WINED3DDP_MAXTEXCOORD;
122     else if (usage == WINED3DDECLUSAGE_FOG && usage_idx == 0)
123         *regnum = 12 + WINED3DDP_MAXTEXCOORD;
124     else if (usage == WINED3DDECLUSAGE_DEPTH && usage_idx == 0)
125         *regnum = 13 + WINED3DDP_MAXTEXCOORD;
126     else if (usage == WINED3DDECLUSAGE_SAMPLE && usage_idx == 0)
127         *regnum = 14 + WINED3DDP_MAXTEXCOORD;
128
129     if (*regnum == -1) {
130         FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n",
131             debug_d3ddeclusage(usage), usage_idx);
132         return FALSE;
133     }
134     return TRUE;
135 }
136
137 void primitiveDeclarationConvertToStridedData(
138      IWineD3DDevice *iface,
139      BOOL useVertexShaderFunction,
140      WineDirect3DVertexStridedData *strided,
141      BOOL *fixup) {
142
143      /* We need to deal with frequency data!*/
144
145     BYTE  *data    = NULL;
146     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
147     IWineD3DVertexDeclarationImpl* vertexDeclaration = (IWineD3DVertexDeclarationImpl *)This->stateBlock->vertexDecl;
148     int i;
149     WINED3DVERTEXELEMENT *element;
150     DWORD stride;
151     DWORD numPreloadStreams = This->stateBlock->streamIsUP ? 0 : vertexDeclaration->num_streams;
152     DWORD *streams = vertexDeclaration->streams;
153
154     /* Check for transformed vertices, disable vertex shader if present */
155     strided->u.s.position_transformed = vertexDeclaration->position_transformed;
156     if(vertexDeclaration->position_transformed) {
157         useVertexShaderFunction = FALSE;
158     }
159
160     /* Translate the declaration into strided data */
161     for (i = 0 ; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
162         GLint streamVBO = 0;
163         BOOL stride_used;
164         unsigned int idx;
165
166         element = vertexDeclaration->pDeclarationWine + i;
167         TRACE("%p Element %p (%d of %d)\n", vertexDeclaration->pDeclarationWine,
168             element,  i + 1, vertexDeclaration->declarationWNumElements - 1);
169
170         if (This->stateBlock->streamSource[element->Stream] == NULL)
171             continue;
172
173         stride  = This->stateBlock->streamStride[element->Stream];
174         if (This->stateBlock->streamIsUP) {
175             TRACE("Stream is up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
176             streamVBO = 0;
177             data    = (BYTE *)This->stateBlock->streamSource[element->Stream];
178         } else {
179             TRACE("Stream isn't up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
180             data    = IWineD3DVertexBufferImpl_GetMemory(This->stateBlock->streamSource[element->Stream], 0, &streamVBO);
181
182             /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
183              * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
184              * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
185              * around to some big value. Hope that with the indices, the driver wraps it back internally. If
186              * not, drawStridedSlow is needed, including a vertex buffer path.
187              */
188             if(This->stateBlock->loadBaseVertexIndex < 0) {
189                 WARN("loadBaseVertexIndex is < 0 (%d), not using vbos\n", This->stateBlock->loadBaseVertexIndex);
190                 streamVBO = 0;
191                 data = ((IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[element->Stream])->resource.allocatedMemory;
192                 if((UINT_PTR)data < -This->stateBlock->loadBaseVertexIndex * stride) {
193                     FIXME("System memory vertex data load offset is negative!\n");
194                 }
195             }
196
197             if(fixup) {
198                 if( streamVBO != 0) *fixup = TRUE;
199                 else if(*fixup && !useVertexShaderFunction &&
200                        (element->Usage == WINED3DDECLUSAGE_COLOR ||
201                         element->Usage == WINED3DDECLUSAGE_POSITIONT)) {
202                     static BOOL warned = FALSE;
203                     if(!warned) {
204                         /* This may be bad with the fixed function pipeline */
205                         FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
206                         warned = TRUE;
207                     }
208                 }
209             }
210         }
211         data += element->Offset;
212
213         TRACE("Offset %d Stream %d UsageIndex %d\n", element->Offset, element->Stream, element->UsageIndex);
214
215         if (useVertexShaderFunction)
216             stride_used = vshader_get_input(This->stateBlock->vertexShader,
217                 element->Usage, element->UsageIndex, &idx);
218         else
219             stride_used = fixed_get_input(element->Usage, element->UsageIndex, &idx);
220
221         if (stride_used) {
222             TRACE("Load %s array %u [usage=%s, usage_idx=%u, "
223                     "stream=%u, offset=%u, stride=%u, type=%s, VBO=%u]\n",
224                     useVertexShaderFunction? "shader": "fixed function", idx,
225                     debug_d3ddeclusage(element->Usage), element->UsageIndex,
226                     element->Stream, element->Offset, stride, debug_d3ddecltype(element->Type), streamVBO);
227
228             if (!useVertexShaderFunction && !vertexDeclaration->ffp_valid[i]) {
229                 WARN("Skipping unsupported fixed function element of type %s and usage %s\n",
230                     debug_d3ddecltype(element->Type), debug_d3ddeclusage(element->Usage));
231             } else {
232                 strided->u.input[idx].lpData = data;
233                 strided->u.input[idx].dwType = element->Type;
234                 strided->u.input[idx].dwStride = stride;
235                 strided->u.input[idx].VBO = streamVBO;
236                 strided->u.input[idx].streamNo = element->Stream;
237             }
238         }
239     }
240     /* Now call PreLoad on all the vertex buffers. In the very rare case
241      * that the buffers stopps converting PreLoad will dirtify the VDECL again.
242      * The vertex buffer can now use the strided structure in the device instead of finding its
243      * own again.
244      *
245      * NULL streams won't be recorded in the array, UP streams won't be either. A stream is only
246      * once in there.
247      */
248     for(i=0; i < numPreloadStreams; i++) {
249         IWineD3DVertexBuffer *vb = This->stateBlock->streamSource[streams[i]];
250         if(vb) {
251             IWineD3DVertexBuffer_PreLoad(vb);
252         }
253     }
254 }
255
256 static void drawStridedFast(IWineD3DDevice *iface,UINT numberOfVertices, GLenum glPrimitiveType,
257                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
258     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
259
260     if (idxSize != 0 /* This crashes sometimes!*/) {
261         TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
262         idxData = idxData == (void *)-1 ? NULL : idxData;
263 #if 1
264         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
265                      (const char *)idxData+(idxSize * startIdx));
266         checkGLcall("glDrawElements");
267 #else /* using drawRangeElements may be faster */
268
269         glDrawRangeElements(glPrimitiveType, minIndex, minIndex + numberOfVertices - 1, numberOfVertices,
270                       idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
271                       (const char *)idxData+(idxSize * startIdx));
272         checkGLcall("glDrawRangeElements");
273 #endif
274
275     } else {
276         TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", This, glPrimitiveType, startVertex, numberOfVertices);
277         glDrawArrays(glPrimitiveType, startVertex, numberOfVertices);
278         checkGLcall("glDrawArrays");
279     }
280
281     return;
282 }
283
284 /*
285  * Actually draw using the supplied information.
286  * Slower GL version which extracts info about each vertex in turn
287  */
288
289 static void drawStridedSlow(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd,
290                      UINT NumVertexes, GLenum glPrimType,
291                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
292
293     unsigned int               textureNo    = 0;
294     const WORD                *pIdxBufS     = NULL;
295     const DWORD               *pIdxBufL     = NULL;
296     LONG                       vx_index;
297     DWORD diffuseColor = 0xFFFFFFFF;       /* Diffuse Color              */
298     DWORD specularColor = 0;               /* Specular Color             */
299     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
300     UINT *streamOffset = This->stateBlock->streamOffset;
301     long                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
302     BOOL                      pixelShader = use_ps(This);
303
304     BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
305     BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
306
307     TRACE("Using slow vertex array code\n");
308
309     /* Variable Initialization */
310     if (idxSize != 0) {
311         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
312          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
313          * idxData will be != NULL
314          */
315         if(idxData == NULL) {
316             idxData = ((IWineD3DIndexBufferImpl *) This->stateBlock->pIndexData)->resource.allocatedMemory;
317         }
318
319         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
320         else pIdxBufL = (const DWORD *) idxData;
321     }
322
323     /* Adding the stream offset once is cheaper than doing it every iteration. Do not modify the strided data, it is a pointer
324      * to the strided Data in the device and might be needed intact on the next draw
325      */
326     for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
327         if(sd->u.s.texCoords[textureNo].lpData) {
328             texCoords[textureNo] = sd->u.s.texCoords[textureNo].lpData + streamOffset[sd->u.s.texCoords[textureNo].streamNo];
329         } else {
330             texCoords[textureNo] = NULL;
331         }
332     }
333     if(sd->u.s.diffuse.lpData) {
334         diffuse = sd->u.s.diffuse.lpData + streamOffset[sd->u.s.diffuse.streamNo];
335     }
336     if(sd->u.s.specular.lpData) {
337         specular = sd->u.s.specular.lpData + streamOffset[sd->u.s.specular.streamNo];
338     }
339     if(sd->u.s.normal.lpData) {
340         normal = sd->u.s.normal.lpData + streamOffset[sd->u.s.normal.streamNo];
341     }
342     if(sd->u.s.position.lpData) {
343         position = sd->u.s.position.lpData + streamOffset[sd->u.s.position.streamNo];
344     }
345
346     if(FIXME_ON(d3d_draw)) {
347         if(specular && This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
348            (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position_transformed )&&
349            This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
350             if(GL_SUPPORT(EXT_FOG_COORD) && sd->u.s.specular.dwType != WINED3DDECLTYPE_D3DCOLOR) {
351                 FIXME("Implement fog coordinates from %s\n", debug_d3ddecltype(sd->u.s.specular.dwType));
352             }
353         }
354         if(This->activeContext->num_untracked_materials && sd->u.s.diffuse.dwType != WINED3DDECLTYPE_D3DCOLOR) {
355             FIXME("Implement diffuse color tracking from %s\n", debug_d3ddecltype(sd->u.s.diffuse.dwType));
356         }
357     }
358
359     /* Start drawing in GL */
360     VTRACE(("glBegin(%x)\n", glPrimType));
361     glBegin(glPrimType);
362
363     /* Default settings for data that is not passed */
364     if (sd->u.s.normal.lpData == NULL) {
365         glNormal3f(0, 0, 0);
366     }
367     if(sd->u.s.diffuse.lpData == NULL) {
368         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
369     }
370     if(sd->u.s.specular.lpData == NULL) {
371         if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
372             GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
373         }
374     }
375
376     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
377      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
378      */
379
380     /* For each primitive */
381     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
382
383         /* Initialize diffuse color */
384         diffuseColor = 0xFFFFFFFF;
385
386         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
387          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
388          */
389
390         /* For indexed data, we need to go a few more strides in */
391         if (idxData != NULL) {
392
393             /* Indexed so work out the number of strides to skip */
394             if (idxSize == 2) {
395                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
396                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
397             } else {
398                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
399                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
400             }
401         }
402
403         /* Texture coords --------------------------- */
404         for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
405
406             if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0) {
407                 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
408                 continue ;
409             }
410
411             /* Query tex coords */
412             if (This->stateBlock->textures[textureNo] != NULL || pixelShader) {
413                 int    coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
414                 int texture_idx = This->texUnitMap[textureNo];
415                 void *ptrToCoords;
416
417                 if (coordIdx > 7) {
418                     VTRACE(("tex: %d - Skip tex coords, as being system generated\n", textureNo));
419                     continue;
420                 } else if (coordIdx < 0) {
421                     FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
422                     continue;
423                 }
424
425                 if (texture_idx == -1) continue;
426
427                 if (texCoords[coordIdx] == NULL) {
428                     TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
429                     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
430                         GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
431                     } else {
432                         glTexCoord4f(0, 0, 0, 1);
433                     }
434                     continue;
435                 }
436
437                 ptrToCoords = texCoords[coordIdx] + (SkipnStrides * sd->u.s.texCoords[coordIdx].dwStride);
438                 if (GL_SUPPORT(ARB_MULTITEXTURE))
439                     multi_texcoord_funcs[sd->u.s.texCoords[coordIdx].dwType](GL_TEXTURE0_ARB + texture_idx, ptrToCoords);
440                 else
441                     texcoord_funcs[sd->u.s.texCoords[coordIdx].dwType](ptrToCoords);
442             }
443         } /* End of textures */
444
445         /* Diffuse -------------------------------- */
446         if (diffuse) {
447             DWORD *ptrToCoords = (DWORD *)(diffuse + (SkipnStrides * sd->u.s.diffuse.dwStride));
448
449             diffuse_funcs[sd->u.s.diffuse.dwType]((void *) ptrToCoords);
450             if(This->activeContext->num_untracked_materials) {
451                 unsigned char i;
452                 float color[4];
453
454                 diffuseColor = ptrToCoords[0];
455                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
456                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
457                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
458                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
459
460                 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
461                     glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
462                 }
463             }
464         }
465
466         /* Specular ------------------------------- */
467         if (specular) {
468             DWORD *ptrToCoords = (DWORD *)(specular + (SkipnStrides * sd->u.s.specular.dwStride));
469
470             /* special case where the fog density is stored in the specular alpha channel */
471             if(This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
472               (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position.dwType == WINED3DDECLTYPE_FLOAT4 )&&
473               This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
474                 if(GL_SUPPORT(EXT_FOG_COORD)) {
475                     specularColor = ptrToCoords[0];
476                     GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
477                 } else {
478                     static BOOL warned = FALSE;
479                     if(!warned) {
480                         /* TODO: Use the fog table code from old ddraw */
481                         FIXME("Implement fog for transformed vertices in software\n");
482                         warned = TRUE;
483                     }
484                 }
485             }
486
487             specular_funcs[sd->u.s.specular.dwType]((void *) ptrToCoords);
488         }
489
490         /* Normal -------------------------------- */
491         if (normal != NULL) {
492             float *ptrToCoords = (float *)(normal + (SkipnStrides * sd->u.s.normal.dwStride));
493             normal_funcs[sd->u.s.normal.dwType](ptrToCoords);
494         }
495
496         /* Position -------------------------------- */
497         if (position) {
498             float *ptrToCoords = (float *)(position + (SkipnStrides * sd->u.s.position.dwStride));
499             position_funcs[sd->u.s.position.dwType](ptrToCoords);
500         }
501
502         /* For non indexed mode, step onto next parts */
503         if (idxData == NULL) {
504             ++SkipnStrides;
505         }
506     }
507
508     glEnd();
509     checkGLcall("glEnd and previous calls");
510 }
511
512 static inline void send_attribute(IWineD3DDeviceImpl *This, const DWORD type, const UINT index, const void *ptr) {
513     switch(type) {
514         case WINED3DDECLTYPE_FLOAT1:
515             GL_EXTCALL(glVertexAttrib1fvARB(index, (float *) ptr));
516             break;
517         case WINED3DDECLTYPE_FLOAT2:
518             GL_EXTCALL(glVertexAttrib2fvARB(index, (float *) ptr));
519             break;
520         case WINED3DDECLTYPE_FLOAT3:
521             GL_EXTCALL(glVertexAttrib3fvARB(index, (float *) ptr));
522             break;
523         case WINED3DDECLTYPE_FLOAT4:
524             GL_EXTCALL(glVertexAttrib4fvARB(index, (float *) ptr));
525             break;
526
527         case WINED3DDECLTYPE_UBYTE4:
528             GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
529             break;
530         case WINED3DDECLTYPE_UBYTE4N:
531         case WINED3DDECLTYPE_D3DCOLOR:
532             GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
533             break;
534
535         case WINED3DDECLTYPE_SHORT2:
536             GL_EXTCALL(glVertexAttrib4svARB(index, (GLshort *) ptr));
537             break;
538         case WINED3DDECLTYPE_SHORT4:
539             GL_EXTCALL(glVertexAttrib4svARB(index, (GLshort *) ptr));
540             break;
541
542         case WINED3DDECLTYPE_SHORT2N:
543         {
544             GLshort s[4] = {((short *) ptr)[0], ((short *) ptr)[1], 0, 1};
545             GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
546             break;
547         }
548         case WINED3DDECLTYPE_USHORT2N:
549         {
550             GLushort s[4] = {((unsigned short *) ptr)[0], ((unsigned short *) ptr)[1], 0, 1};
551             GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
552             break;
553         }
554         case WINED3DDECLTYPE_SHORT4N:
555             GL_EXTCALL(glVertexAttrib4NsvARB(index, (GLshort *) ptr));
556             break;
557         case WINED3DDECLTYPE_USHORT4N:
558             GL_EXTCALL(glVertexAttrib4NusvARB(index, (GLushort *) ptr));
559             break;
560
561         case WINED3DDECLTYPE_UDEC3:
562             FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
563             /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
564             break;
565         case WINED3DDECLTYPE_DEC3N:
566             FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
567             /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
568             break;
569
570         case WINED3DDECLTYPE_FLOAT16_2:
571             /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
572              * byte float according to the IEEE standard
573              */
574             if (GL_SUPPORT(NV_HALF_FLOAT)) {
575                 GL_EXTCALL(glVertexAttrib2hvNV(index, (GLhalfNV *)ptr));
576             } else {
577                 float x = float_16_to_32(((unsigned short *) ptr) + 0);
578                 float y = float_16_to_32(((unsigned short *) ptr) + 1);
579                 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
580             }
581             break;
582         case WINED3DDECLTYPE_FLOAT16_4:
583             if (GL_SUPPORT(NV_HALF_FLOAT)) {
584                 GL_EXTCALL(glVertexAttrib4hvNV(index, (GLhalfNV *)ptr));
585             } else {
586                 float x = float_16_to_32(((unsigned short *) ptr) + 0);
587                 float y = float_16_to_32(((unsigned short *) ptr) + 1);
588                 float z = float_16_to_32(((unsigned short *) ptr) + 2);
589                 float w = float_16_to_32(((unsigned short *) ptr) + 3);
590                 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
591             }
592             break;
593
594         case WINED3DDECLTYPE_UNUSED:
595         default:
596             ERR("Unexpected attribute declaration: %d\n", type);
597             break;
598     }
599 }
600
601 static void drawStridedSlowVs(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
602                               GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx,
603                               ULONG startVertex) {
604
605     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
606     long                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
607     const WORD                *pIdxBufS     = NULL;
608     const DWORD               *pIdxBufL     = NULL;
609     LONG                       vx_index;
610     int i;
611     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
612     BYTE *ptr;
613
614     if (idxSize != 0) {
615         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
616          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
617          * idxData will be != NULL
618          */
619         if(idxData == NULL) {
620             idxData = ((IWineD3DIndexBufferImpl *) stateblock->pIndexData)->resource.allocatedMemory;
621         }
622
623         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
624         else pIdxBufL = (const DWORD *) idxData;
625     }
626
627     /* Start drawing in GL */
628     VTRACE(("glBegin(%x)\n", glPrimitiveType));
629     glBegin(glPrimitiveType);
630
631     for (vx_index = 0; vx_index < numberOfVertices; ++vx_index) {
632         if (idxData != NULL) {
633
634             /* Indexed so work out the number of strides to skip */
635             if (idxSize == 2) {
636                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
637                 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
638             } else {
639                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
640                 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
641             }
642         }
643
644         for(i = MAX_ATTRIBS - 1; i >= 0; i--) {
645             if(!sd->u.input[i].lpData) continue;
646
647             ptr = sd->u.input[i].lpData +
648                   sd->u.input[i].dwStride * SkipnStrides +
649                   stateblock->streamOffset[sd->u.input[i].streamNo];
650
651             send_attribute(This, sd->u.input[i].dwType, i, ptr);
652         }
653         SkipnStrides++;
654     }
655
656     glEnd();
657 }
658
659 void depth_blt(IWineD3DDevice *iface, GLuint texture, GLsizei w, GLsizei h) {
660     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
661     GLint old_binding = 0;
662
663     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
664
665     glDisable(GL_CULL_FACE);
666     glEnable(GL_BLEND);
667     glDisable(GL_ALPHA_TEST);
668     glDisable(GL_SCISSOR_TEST);
669     glDisable(GL_STENCIL_TEST);
670     glEnable(GL_DEPTH_TEST);
671     glDepthFunc(GL_ALWAYS);
672     glDepthMask(GL_TRUE);
673     glBlendFunc(GL_ZERO, GL_ONE);
674     glViewport(0, 0, w, h);
675
676     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
677     glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
678     glBindTexture(GL_TEXTURE_2D, texture);
679     glEnable(GL_TEXTURE_2D);
680
681     This->shader_backend->shader_select_depth_blt(iface);
682
683     glBegin(GL_TRIANGLE_STRIP);
684     glVertex2f(-1.0f, -1.0f);
685     glVertex2f(1.0f, -1.0f);
686     glVertex2f(-1.0f, 1.0f);
687     glVertex2f(1.0f, 1.0f);
688     glEnd();
689
690     glBindTexture(GL_TEXTURE_2D, old_binding);
691
692     glPopAttrib();
693
694     This->shader_backend->shader_deselect_depth_blt(iface);
695 }
696
697 static inline void drawStridedInstanced(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
698                                  GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex,
699                                  ULONG startIdx, ULONG startVertex) {
700     UINT numInstances = 0;
701     int numInstancedAttribs = 0, i, j;
702     UINT instancedData[sizeof(sd->u.input) / sizeof(sd->u.input[0]) /* 16 */];
703     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
704     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
705
706     if (idxSize == 0) {
707         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
708          * We don't support this for now
709          *
710          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
711          * But the StreamSourceFreq value has a different meaning in that situation.
712          */
713         FIXME("Non-indexed instanced drawing is not supported\n");
714         return;
715     }
716
717     TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
718     idxData = idxData == (void *)-1 ? NULL : idxData;
719
720     /* First, figure out how many instances we have to draw */
721     for(i = 0; i < MAX_STREAMS; i++) {
722         /* Look at the streams and take the first one which matches */
723         if(((stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) || (stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INDEXEDDATA)) && stateblock->streamSource[i]) {
724             /* D3D9 could set streamFreq 0 with (INSTANCEDATA or INDEXEDDATA) and then it is handled as 1. See d3d9/tests/visual.c-> stream_test() */
725             if(stateblock->streamFreq[i] == 0){
726                 numInstances = 1;
727             } else {
728                 numInstances = stateblock->streamFreq[i]; /* use the specified number of instances from the first matched stream. See d3d9/tests/visual.c-> stream_test() */
729             }
730             break; /* break, because only the first suitable value is interesting */
731         }
732     }
733
734     for(i = 0; i < sizeof(sd->u.input) / sizeof(sd->u.input[0]); i++) {
735         if(stateblock->streamFlags[sd->u.input[i].streamNo] & WINED3DSTREAMSOURCE_INSTANCEDATA) {
736             instancedData[numInstancedAttribs] = i;
737             numInstancedAttribs++;
738         }
739     }
740
741     /* now draw numInstances instances :-) */
742     for(i = 0; i < numInstances; i++) {
743         /* Specify the instanced attributes using immediate mode calls */
744         for(j = 0; j < numInstancedAttribs; j++) {
745             BYTE *ptr = sd->u.input[instancedData[j]].lpData +
746                         sd->u.input[instancedData[j]].dwStride * i +
747                         stateblock->streamOffset[sd->u.input[instancedData[j]].streamNo];
748             if(sd->u.input[instancedData[j]].VBO) {
749                 IWineD3DVertexBufferImpl *vb = (IWineD3DVertexBufferImpl *) stateblock->streamSource[sd->u.input[instancedData[j]].streamNo];
750                 ptr += (long) vb->resource.allocatedMemory;
751             }
752
753             send_attribute(This, sd->u.input[instancedData[j]].dwType, instancedData[j], ptr);
754         }
755
756         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
757                     (const char *)idxData+(idxSize * startIdx));
758         checkGLcall("glDrawElements");
759     }
760 }
761
762 static inline void remove_vbos(IWineD3DDeviceImpl *This, WineDirect3DVertexStridedData *s) {
763     unsigned char i;
764     IWineD3DVertexBufferImpl *vb;
765
766     if(s->u.s.position.VBO) {
767         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position.streamNo];
768         s->u.s.position.VBO = 0;
769         s->u.s.position.lpData = (BYTE *) ((unsigned long) s->u.s.position.lpData + (unsigned long) vb->resource.allocatedMemory);
770     }
771     if(s->u.s.blendWeights.VBO) {
772         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendWeights.streamNo];
773         s->u.s.blendWeights.VBO = 0;
774         s->u.s.blendWeights.lpData = (BYTE *) ((unsigned long) s->u.s.blendWeights.lpData + (unsigned long) vb->resource.allocatedMemory);
775     }
776     if(s->u.s.blendMatrixIndices.VBO) {
777         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendMatrixIndices.streamNo];
778         s->u.s.blendMatrixIndices.VBO = 0;
779         s->u.s.blendMatrixIndices.lpData = (BYTE *) ((unsigned long) s->u.s.blendMatrixIndices.lpData + (unsigned long) vb->resource.allocatedMemory);
780     }
781     if(s->u.s.normal.VBO) {
782         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal.streamNo];
783         s->u.s.normal.VBO = 0;
784         s->u.s.normal.lpData = (BYTE *) ((unsigned long) s->u.s.normal.lpData + (unsigned long) vb->resource.allocatedMemory);
785     }
786     if(s->u.s.pSize.VBO) {
787         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.pSize.streamNo];
788         s->u.s.pSize.VBO = 0;
789         s->u.s.pSize.lpData = (BYTE *) ((unsigned long) s->u.s.pSize.lpData + (unsigned long) vb->resource.allocatedMemory);
790     }
791     if(s->u.s.diffuse.VBO) {
792         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.diffuse.streamNo];
793         s->u.s.diffuse.VBO = 0;
794         s->u.s.diffuse.lpData = (BYTE *) ((unsigned long) s->u.s.diffuse.lpData + (unsigned long) vb->resource.allocatedMemory);
795     }
796     if(s->u.s.specular.VBO) {
797         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.specular.streamNo];
798         s->u.s.specular.VBO = 0;
799         s->u.s.specular.lpData = (BYTE *) ((unsigned long) s->u.s.specular.lpData + (unsigned long) vb->resource.allocatedMemory);
800     }
801     for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) {
802         if(s->u.s.texCoords[i].VBO) {
803             vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.texCoords[i].streamNo];
804             s->u.s.texCoords[i].VBO = 0;
805             s->u.s.texCoords[i].lpData = (BYTE *) ((unsigned long) s->u.s.texCoords[i].lpData + (unsigned long) vb->resource.allocatedMemory);
806         }
807     }
808     if(s->u.s.position2.VBO) {
809         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position2.streamNo];
810         s->u.s.position2.VBO = 0;
811         s->u.s.position2.lpData = (BYTE *) ((unsigned long) s->u.s.position2.lpData + (unsigned long) vb->resource.allocatedMemory);
812     }
813     if(s->u.s.normal2.VBO) {
814         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal2.streamNo];
815         s->u.s.normal2.VBO = 0;
816         s->u.s.normal2.lpData = (BYTE *) ((unsigned long) s->u.s.normal2.lpData + (unsigned long) vb->resource.allocatedMemory);
817     }
818     if(s->u.s.tangent.VBO) {
819         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tangent.streamNo];
820         s->u.s.tangent.VBO = 0;
821         s->u.s.tangent.lpData = (BYTE *) ((unsigned long) s->u.s.tangent.lpData + (unsigned long) vb->resource.allocatedMemory);
822     }
823     if(s->u.s.binormal.VBO) {
824         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.binormal.streamNo];
825         s->u.s.binormal.VBO = 0;
826         s->u.s.binormal.lpData = (BYTE *) ((unsigned long) s->u.s.binormal.lpData + (unsigned long) vb->resource.allocatedMemory);
827     }
828     if(s->u.s.tessFactor.VBO) {
829         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tessFactor.streamNo];
830         s->u.s.tessFactor.VBO = 0;
831         s->u.s.tessFactor.lpData = (BYTE *) ((unsigned long) s->u.s.tessFactor.lpData + (unsigned long) vb->resource.allocatedMemory);
832     }
833     if(s->u.s.fog.VBO) {
834         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.fog.streamNo];
835         s->u.s.fog.VBO = 0;
836         s->u.s.fog.lpData = (BYTE *) ((unsigned long) s->u.s.fog.lpData + (unsigned long) vb->resource.allocatedMemory);
837     }
838     if(s->u.s.depth.VBO) {
839         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.depth.streamNo];
840         s->u.s.depth.VBO = 0;
841         s->u.s.depth.lpData = (BYTE *) ((unsigned long) s->u.s.depth.lpData + (unsigned long) vb->resource.allocatedMemory);
842     }
843     if(s->u.s.sample.VBO) {
844         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.sample.streamNo];
845         s->u.s.sample.VBO = 0;
846         s->u.s.sample.lpData = (BYTE *) ((unsigned long) s->u.s.sample.lpData + (unsigned long) vb->resource.allocatedMemory);
847     }
848 }
849
850 /* Routine common to the draw primitive and draw indexed primitive routines */
851 void drawPrimitive(IWineD3DDevice *iface,
852                    int PrimitiveType,
853                    long NumPrimitives,
854                    /* for Indexed: */
855                    long  StartVertexIndex,
856                    UINT  numberOfVertices,
857                    long  StartIdx,
858                    short idxSize,
859                    const void *idxData,
860                    int   minIndex) {
861
862     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
863     IWineD3DSurfaceImpl          *target;
864     int i;
865
866     if (NumPrimitives == 0) return;
867
868     /* Invalidate the back buffer memory so LockRect will read it the next time */
869     for(i = 0; i < GL_LIMITS(buffers); i++) {
870         target = (IWineD3DSurfaceImpl *) This->render_targets[i];
871         if (target) {
872             IWineD3DSurface_LoadLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, NULL);
873             IWineD3DSurface_ModifyLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, TRUE);
874         }
875     }
876
877     /* Signals other modules that a drawing is in progress and the stateblock finalized */
878     This->isInDraw = TRUE;
879
880     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
881
882     if (This->stencilBufferTarget) {
883         /* Note that this depends on the ActivateContext call above to set
884          * This->render_offscreen properly */
885         DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
886         surface_load_ds_location(This->stencilBufferTarget, location);
887         surface_modify_ds_location(This->stencilBufferTarget, location);
888     }
889
890     /* Ok, we will be updating the screen from here onwards so grab the lock */
891     ENTER_GL();
892     {
893         GLenum glPrimType;
894         BOOL emulation = FALSE;
895         WineDirect3DVertexStridedData *strided = &This->strided_streams;
896         WineDirect3DVertexStridedData stridedlcl;
897         /* Ok, Work out which primitive is requested and how many vertexes that
898            will be                                                              */
899         UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
900         if (numberOfVertices == 0 )
901             numberOfVertices = calculatedNumberOfindices;
902
903         if(!use_vs(This)) {
904             if(!This->strided_streams.u.s.position_transformed && This->activeContext->num_untracked_materials &&
905                 This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
906                 static BOOL first = TRUE;
907                 if(first) {
908                     FIXME("Using software emulation because not all material properties could be tracked\n");
909                     first = FALSE;
910                 } else {
911                     TRACE("Using software emulation because not all material properties could be tracked\n");
912                 }
913                 emulation = TRUE;
914             }
915             else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
916                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
917                  * to a float in the vertex buffer
918                  */
919                 static BOOL first = TRUE;
920                 if(first) {
921                     FIXME("Using software emulation because manual fog coordinates are provided\n");
922                     first = FALSE;
923                 } else {
924                     TRACE("Using software emulation because manual fog coordinates are provided\n");
925                 }
926                 emulation = TRUE;
927             }
928
929             if(emulation) {
930                 strided = &stridedlcl;
931                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
932                 remove_vbos(This, &stridedlcl);
933             }
934         }
935
936         if (This->useDrawStridedSlow || emulation) {
937             /* Immediate mode drawing */
938             if(use_vs(This)) {
939                 static BOOL first = TRUE;
940                 if(first) {
941                     FIXME("Using immediate mode with vertex shaders for half float emulation\n");
942                     first = FALSE;
943                 } else {
944                     TRACE("Using immediate mode with vertex shaders for half float emulation\n");
945                 }
946                 drawStridedSlowVs(iface, strided, calculatedNumberOfindices, glPrimType,
947                                   idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
948             } else {
949                 drawStridedSlow(iface, strided, calculatedNumberOfindices,
950                                 glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
951             }
952         } else if(This->instancedDraw) {
953             /* Instancing emulation with mixing immediate mode and arrays */
954             drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
955                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
956         } else {
957             drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
958                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
959         }
960     }
961
962     /* Finished updating the screen, restore lock */
963     LEAVE_GL();
964     TRACE("Done all gl drawing\n");
965
966     /* Diagnostics */
967 #ifdef SHOW_FRAME_MAKEUP
968     {
969         static long int primCounter = 0;
970         /* NOTE: set primCounter to the value reported by drawprim 
971            before you want to to write frame makeup to /tmp */
972         if (primCounter >= 0) {
973             WINED3DLOCKED_RECT r;
974             char buffer[80];
975             IWineD3DSurface_LockRect(This->render_targets[0], &r, NULL, WINED3DLOCK_READONLY);
976             sprintf(buffer, "/tmp/backbuffer_%ld.tga", primCounter);
977             TRACE("Saving screenshot %s\n", buffer);
978             IWineD3DSurface_SaveSnapshot(This->render_targets[0], buffer);
979             IWineD3DSurface_UnlockRect(This->render_targets[0]);
980
981 #ifdef SHOW_TEXTURE_MAKEUP
982            {
983             IWineD3DSurface *pSur;
984             int textureNo;
985             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
986                 if (This->stateBlock->textures[textureNo] != NULL) {
987                     sprintf(buffer, "/tmp/texture_%p_%ld_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
988                     TRACE("Saving texture %s\n", buffer);
989                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
990                             IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
991                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
992                             IWineD3DSurface_Release(pSur);
993                     } else  {
994                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
995                     }
996                 }
997             }
998            }
999 #endif
1000         }
1001         TRACE("drawprim #%ld\n", primCounter);
1002         ++primCounter;
1003     }
1004 #endif
1005
1006     /* Control goes back to the device, stateblock values may change again */
1007     This->isInDraw = FALSE;
1008 }
1009
1010 static void normalize_normal(float *n) {
1011     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
1012     if(length == 0.0) return;
1013     length = sqrt(length);
1014     n[0] = n[0] / length;
1015     n[1] = n[1] / length;
1016     n[2] = n[2] / length;
1017 }
1018
1019 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
1020  *
1021  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
1022  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
1023  * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
1024  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
1025  * in drawprim.
1026  *
1027  * To read back, the opengl feedback mode is used. This creates a problem because we want
1028  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
1029  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
1030  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
1031  * them to [-1.0;+1.0] and set the viewport up to scale them back.
1032  *
1033  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
1034  * resulting colors back to the normals.
1035  *
1036  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
1037  * does not restore it because normally a draw follows immediately afterwards. The caller is
1038  * responsible of taking care that either the gl states are restored, or the context activated
1039  * for drawing to reset the lastWasBlit flag.
1040  */
1041 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
1042                             struct WineD3DRectPatch *patch) {
1043     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
1044     float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
1045     WineDirect3DVertexStridedData strided;
1046     BYTE *data;
1047     WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
1048     DWORD vtxStride;
1049     GLenum feedback_type;
1050     GLfloat *feedbuffer;
1051
1052     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
1053      * Beware of vbos
1054      */
1055     memset(&strided, 0, sizeof(strided));
1056     primitiveDeclarationConvertToStridedData((IWineD3DDevice *) This, FALSE, &strided, NULL);
1057     if(strided.u.s.position.VBO) {
1058         IWineD3DVertexBufferImpl *vb;
1059         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[strided.u.s.position.streamNo];
1060         strided.u.s.position.lpData = (BYTE *) ((unsigned long) strided.u.s.position.lpData +
1061                                                 (unsigned long) vb->resource.allocatedMemory);
1062     }
1063     vtxStride = strided.u.s.position.dwStride;
1064     data = strided.u.s.position.lpData +
1065            vtxStride * info->Stride * info->StartVertexOffsetHeight +
1066            vtxStride * info->StartVertexOffsetWidth;
1067
1068     /* Not entirely sure about what happens with transformed vertices */
1069     if(strided.u.s.position_transformed) {
1070         FIXME("Transformed position in rectpatch generation\n");
1071     }
1072     if(vtxStride % sizeof(GLfloat)) {
1073         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
1074          * I don't see how the stride could not be a multiple of 4, but make sure
1075          * to check it
1076          */
1077         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
1078     }
1079     if(info->Basis != WINED3DBASIS_BEZIER) {
1080         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
1081     }
1082     if(info->Degree != WINED3DDEGREE_CUBIC) {
1083         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
1084     }
1085
1086     /* First, get the boundary cube of the input data */
1087     for(j = 0; j < info->Height; j++) {
1088         for(i = 0; i < info->Width; i++) {
1089             float *v = (float *) (data + vtxStride * i + vtxStride * info->Stride * j);
1090             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
1091             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
1092             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
1093             if(v[2] < neg_z) neg_z = v[2];
1094         }
1095     }
1096
1097     /* This needs some improvements in the vertex decl code */
1098     FIXME("Cannot find data to generate. Only generating position and normals\n");
1099     patch->has_normals = TRUE;
1100     patch->has_texcoords = FALSE;
1101
1102     /* Simply activate the context for blitting. This disables all the things we don't want and
1103      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
1104      * patch (as opposed to normal draws) will most likely need different changes anyway
1105      */
1106     ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
1107     ENTER_GL();
1108
1109     glMatrixMode(GL_PROJECTION);
1110     checkGLcall("glMatrixMode(GL_PROJECTION)");
1111     glLoadIdentity();
1112     checkGLcall("glLoadIndentity()");
1113     glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
1114     glTranslatef(0, 0, 0.5);
1115     checkGLcall("glScalef");
1116     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
1117     checkGLcall("glViewport");
1118
1119     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
1120      * our feedback buffer parser
1121      */
1122     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1123     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
1124     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
1125     if(patch->has_normals) {
1126         float black[4] = {0, 0, 0, 0};
1127         float red[4]   = {1, 0, 0, 0};
1128         float green[4] = {0, 1, 0, 0};
1129         float blue[4]  = {0, 0, 1, 0};
1130         float white[4] = {1, 1, 1, 1};
1131         glEnable(GL_LIGHTING);
1132         checkGLcall("glEnable(GL_LIGHTING)");
1133         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
1134         checkGLcall("glLightModel for MODEL_AMBIENT");
1135         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
1136
1137         for(i = 3; i < GL_LIMITS(lights); i++) {
1138             glDisable(GL_LIGHT0 + i);
1139             checkGLcall("glDisable(GL_LIGHT0 + i)");
1140             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
1141         }
1142
1143         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
1144         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
1145         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
1146         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
1147         glLightfv(GL_LIGHT0, GL_POSITION, red);
1148         glEnable(GL_LIGHT0);
1149         checkGLcall("Setting up light 1\n");
1150         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
1151         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
1152         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
1153         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
1154         glLightfv(GL_LIGHT1, GL_POSITION, green);
1155         glEnable(GL_LIGHT1);
1156         checkGLcall("Setting up light 2\n");
1157         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
1158         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
1159         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
1160         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
1161         glLightfv(GL_LIGHT2, GL_POSITION, blue);
1162         glEnable(GL_LIGHT2);
1163         checkGLcall("Setting up light 3\n");
1164
1165         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
1166         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
1167         glDisable(GL_COLOR_MATERIAL);
1168         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
1169         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
1170         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
1171         checkGLcall("Setting up materials\n");
1172     }
1173
1174     /* Enable the needed maps.
1175      * GL_MAP2_VERTEX_3 is needed for positional data.
1176      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
1177      * GL_MAP2_TEXTURE_COORD_4 for texture coords
1178      */
1179     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
1180     out_vertex_size = 3 /* position */;
1181     d3d_out_vertex_size = 3;
1182     glEnable(GL_MAP2_VERTEX_3);
1183     if(patch->has_normals && patch->has_texcoords) {
1184         FIXME("Texcoords not handled yet\n");
1185         feedback_type = GL_3D_COLOR_TEXTURE;
1186         out_vertex_size += 8;
1187         d3d_out_vertex_size += 7;
1188         glEnable(GL_AUTO_NORMAL);
1189         glEnable(GL_MAP2_TEXTURE_COORD_4);
1190     } else if(patch->has_texcoords) {
1191         FIXME("Texcoords not handled yet\n");
1192         feedback_type = GL_3D_COLOR_TEXTURE;
1193         out_vertex_size += 7;
1194         d3d_out_vertex_size += 4;
1195         glEnable(GL_MAP2_TEXTURE_COORD_4);
1196     } else if(patch->has_normals) {
1197         feedback_type = GL_3D_COLOR;
1198         out_vertex_size += 4;
1199         d3d_out_vertex_size += 3;
1200         glEnable(GL_AUTO_NORMAL);
1201     } else {
1202         feedback_type = GL_3D;
1203     }
1204     checkGLcall("glEnable vertex attrib generation");
1205
1206     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
1207                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
1208     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
1209
1210     glMap2f(GL_MAP2_VERTEX_3,
1211             0, 1, vtxStride / sizeof(float), info->Width,
1212             0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1213             (float *) data);
1214     checkGLcall("glMap2f");
1215     if(patch->has_texcoords) {
1216         glMap2f(GL_MAP2_TEXTURE_COORD_4,
1217                 0, 1, vtxStride / sizeof(float), info->Width,
1218                 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1219                 (float *) data);
1220         checkGLcall("glMap2f");
1221     }
1222     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
1223     checkGLcall("glMapGrid2f");
1224
1225     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
1226     checkGLcall("glFeedbackBuffer");
1227     glRenderMode(GL_FEEDBACK);
1228
1229     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1230     checkGLcall("glEvalMesh2\n");
1231
1232     i = glRenderMode(GL_RENDER);
1233     if(i == -1) {
1234         LEAVE_GL();
1235         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
1236         Sleep(10000);
1237         HeapFree(GetProcessHeap(), 0, feedbuffer);
1238         return WINED3DERR_DRIVERINTERNALERROR;
1239     } else if(i != buffer_size) {
1240         LEAVE_GL();
1241         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
1242         Sleep(10000);
1243         HeapFree(GetProcessHeap(), 0, feedbuffer);
1244         return WINED3DERR_DRIVERINTERNALERROR;
1245     } else {
1246         TRACE("Got %d elements as expected\n", i);
1247     }
1248
1249     HeapFree(GetProcessHeap(), 0, patch->mem);
1250     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
1251     i = 0;
1252     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1253         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1254             ERR("Unexpected token: %f\n", feedbuffer[j]);
1255             continue;
1256         }
1257         if(feedbuffer[j + 1] != 3) {
1258             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1259             continue;
1260         }
1261         /* Somehow there are different ideas about back / front facing, so fix up the
1262          * vertex order
1263          */
1264         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1265         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1266         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
1267         if(patch->has_normals) {
1268             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1269             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1270             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1271         }
1272         i += d3d_out_vertex_size;
1273
1274         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1275         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1276         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
1277         if(patch->has_normals) {
1278             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1279             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1280             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1281         }
1282         i += d3d_out_vertex_size;
1283
1284         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1285         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1286         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
1287         if(patch->has_normals) {
1288             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1289             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1290             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1291         }
1292         i += d3d_out_vertex_size;
1293     }
1294
1295     if(patch->has_normals) {
1296         /* Now do the same with reverse light directions */
1297         float x[4] = {-1,  0,  0, 0};
1298         float y[4] = { 0, -1,  0, 0};
1299         float z[4] = { 0,  0, -1, 0};
1300         glLightfv(GL_LIGHT0, GL_POSITION, x);
1301         glLightfv(GL_LIGHT1, GL_POSITION, y);
1302         glLightfv(GL_LIGHT2, GL_POSITION, z);
1303         checkGLcall("Setting up reverse light directions\n");
1304
1305         glRenderMode(GL_FEEDBACK);
1306         checkGLcall("glRenderMode(GL_FEEDBACK)");
1307         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1308         checkGLcall("glEvalMesh2\n");
1309         i = glRenderMode(GL_RENDER);
1310         checkGLcall("glRenderMode(GL_RENDER)");
1311
1312         i = 0;
1313         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1314             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1315                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1316                 continue;
1317             }
1318             if(feedbuffer[j + 1] != 3) {
1319                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1320                 continue;
1321             }
1322             if(patch->mem[i + 3] == 0.0)
1323                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1324             if(patch->mem[i + 4] == 0.0)
1325                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1326             if(patch->mem[i + 5] == 0.0)
1327                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1328             normalize_normal(patch->mem + i + 3);
1329             i += d3d_out_vertex_size;
1330
1331             if(patch->mem[i + 3] == 0.0)
1332                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1333             if(patch->mem[i + 4] == 0.0)
1334                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1335             if(patch->mem[i + 5] == 0.0)
1336                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1337             normalize_normal(patch->mem + i + 3);
1338             i += d3d_out_vertex_size;
1339
1340             if(patch->mem[i + 3] == 0.0)
1341                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1342             if(patch->mem[i + 4] == 0.0)
1343                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1344             if(patch->mem[i + 5] == 0.0)
1345                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1346             normalize_normal(patch->mem + i + 3);
1347             i += d3d_out_vertex_size;
1348         }
1349     }
1350
1351     glDisable(GL_MAP2_VERTEX_3);
1352     glDisable(GL_AUTO_NORMAL);
1353     glDisable(GL_MAP2_NORMAL);
1354     glDisable(GL_MAP2_TEXTURE_COORD_4);
1355     checkGLcall("glDisable vertex attrib generation");
1356     LEAVE_GL();
1357
1358     HeapFree(GetProcessHeap(), 0, feedbuffer);
1359
1360     vtxStride = 3 * sizeof(float);
1361     if(patch->has_normals) {
1362         vtxStride += 3 * sizeof(float);
1363     }
1364     if(patch->has_texcoords) {
1365         vtxStride += 4 * sizeof(float);
1366     }
1367     memset(&patch->strided, 0, sizeof(&patch->strided));
1368     patch->strided.u.s.position.lpData = (BYTE *) patch->mem;
1369     patch->strided.u.s.position.dwStride = vtxStride;
1370     patch->strided.u.s.position.dwType = WINED3DDECLTYPE_FLOAT3;
1371     patch->strided.u.s.position.streamNo = 255;
1372
1373     if(patch->has_normals) {
1374         patch->strided.u.s.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1375         patch->strided.u.s.normal.dwStride = vtxStride;
1376         patch->strided.u.s.normal.dwType = WINED3DDECLTYPE_FLOAT3;
1377         patch->strided.u.s.normal.streamNo = 255;
1378     }
1379     if(patch->has_texcoords) {
1380         patch->strided.u.s.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1381         if(patch->has_normals) {
1382             patch->strided.u.s.texCoords[0].lpData += 3 * sizeof(float);
1383         }
1384         patch->strided.u.s.texCoords[0].dwStride = vtxStride;
1385         patch->strided.u.s.texCoords[0].dwType = WINED3DDECLTYPE_FLOAT4;
1386         /* MAX_STREAMS index points to an unused element in stateblock->streamOffsets which
1387          * always remains set to 0. Windows uses stream 255 here, but this is not visible to the
1388          * application.
1389          */
1390         patch->strided.u.s.texCoords[0].streamNo = MAX_STREAMS;
1391     }
1392
1393     return WINED3D_OK;
1394 }