comctl32: We can now store binary files in the repository.
[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     DWORD numPreloadStreams = This->stateBlock->streamIsUP ? 0 : vertexDeclaration->num_streams;
160     DWORD *streams = vertexDeclaration->streams;
161
162     /* Check for transformed vertices, disable vertex shader if present */
163     strided->u.s.position_transformed = vertexDeclaration->position_transformed;
164     if(vertexDeclaration->position_transformed) {
165         useVertexShaderFunction = FALSE;
166     }
167
168     /* Translate the declaration into strided data */
169     for (i = 0 ; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
170         GLint streamVBO = 0;
171         BOOL stride_used;
172         unsigned int idx;
173
174         element = vertexDeclaration->pDeclarationWine + i;
175         TRACE("%p Element %p (%d of %d)\n", vertexDeclaration->pDeclarationWine,
176             element,  i + 1, vertexDeclaration->declarationWNumElements - 1);
177
178         if (This->stateBlock->streamSource[element->Stream] == NULL)
179             continue;
180
181         stride  = This->stateBlock->streamStride[element->Stream];
182         if (This->stateBlock->streamIsUP) {
183             TRACE("Stream is up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
184             streamVBO = 0;
185             data    = (BYTE *)This->stateBlock->streamSource[element->Stream];
186         } else {
187             TRACE("Stream isn't up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
188             data    = IWineD3DVertexBufferImpl_GetMemory(This->stateBlock->streamSource[element->Stream], 0, &streamVBO);
189
190             /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
191              * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
192              * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
193              * around to some big value. Hope that with the indices, the driver wraps it back internally. If
194              * not, drawStridedSlow is needed, including a vertex buffer path.
195              */
196             if(This->stateBlock->loadBaseVertexIndex < 0) {
197                 WARN("loadBaseVertexIndex is < 0 (%d), not using vbos\n", This->stateBlock->loadBaseVertexIndex);
198                 streamVBO = 0;
199                 data = ((IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[element->Stream])->resource.allocatedMemory;
200                 if(data + This->stateBlock->loadBaseVertexIndex * stride < 0) {
201                     FIXME("System memory vertex data load offset is negative!\n");
202                 }
203             }
204
205             if(fixup) {
206                 if( streamVBO != 0) *fixup = TRUE;
207                 else if(*fixup && !useVertexShaderFunction &&
208                        (element->Usage == WINED3DDECLUSAGE_COLOR ||
209                         element->Usage == WINED3DDECLUSAGE_POSITIONT)) {
210                     /* This may be bad with the fixed function pipeline */
211                     FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
212                 }
213             }
214         }
215         data += element->Offset;
216         reg = element->Reg;
217
218         TRACE("Offset %d Stream %d UsageIndex %d\n", element->Offset, element->Stream, element->UsageIndex);
219
220         if (useVertexShaderFunction)
221             stride_used = vshader_get_input(This->stateBlock->vertexShader,
222                 element->Usage, element->UsageIndex, &idx);
223         else
224             stride_used = fixed_get_input(element->Usage, element->UsageIndex, &idx);
225
226         if (stride_used) {
227             TRACE("Loaded %s array %u [usage=%s, usage_idx=%u, "
228                     "stream=%u, offset=%u, stride=%u, type=%s, VBO=%u]\n",
229                     useVertexShaderFunction? "shader": "fixed function", idx,
230                     debug_d3ddeclusage(element->Usage), element->UsageIndex,
231                     element->Stream, element->Offset, stride, debug_d3ddecltype(element->Type), streamVBO);
232
233             strided->u.input[idx].lpData = data;
234             strided->u.input[idx].dwType = element->Type;
235             strided->u.input[idx].dwStride = stride;
236             strided->u.input[idx].VBO = streamVBO;
237             strided->u.input[idx].streamNo = element->Stream;
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_PreLoad(This->stateBlock->streamSource[streams[i]]);
250     }
251 }
252
253 static void drawStridedFast(IWineD3DDevice *iface,UINT numberOfVertices, GLenum glPrimitiveType,
254                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
255     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
256
257     if (idxSize != 0 /* This crashes sometimes!*/) {
258         TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
259         idxData = idxData == (void *)-1 ? NULL : idxData;
260 #if 1
261         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
262                      (const char *)idxData+(idxSize * startIdx));
263         checkGLcall("glDrawElements");
264 #else /* using drawRangeElements may be faster */
265
266         glDrawRangeElements(glPrimitiveType, minIndex, minIndex + numberOfVertices - 1, numberOfVertices,
267                       idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
268                       (const char *)idxData+(idxSize * startIdx));
269         checkGLcall("glDrawRangeElements");
270 #endif
271
272     } else {
273
274         /* Note first is now zero as we shuffled along earlier */
275         TRACE("(%p) : glDrawArrays(%x, 0, %d)\n", This, glPrimitiveType, numberOfVertices);
276         glDrawArrays(glPrimitiveType, startVertex, numberOfVertices);
277         checkGLcall("glDrawArrays");
278
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     float x  = 0.0f, y  = 0.0f, z = 0.0f;  /* x,y,z coordinates          */
298     float rhw = 0.0f;                      /* rhw                        */
299     DWORD diffuseColor = 0xFFFFFFFF;       /* Diffuse Color              */
300     DWORD specularColor = 0;               /* Specular Color             */
301     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
302     UINT *streamOffset = This->stateBlock->streamOffset;
303     long                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
304     BOOL                      pixelShader = use_ps(This);
305
306     BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
307     BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
308
309     TRACE("Using slow vertex array code\n");
310
311     /* Variable Initialization */
312     if (idxSize != 0) {
313         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
314          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
315          * idxData will be != NULL
316          */
317         if(idxData == NULL) {
318             idxData = ((IWineD3DIndexBufferImpl *) This->stateBlock->pIndexData)->resource.allocatedMemory;
319         }
320
321         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
322         else pIdxBufL = (const DWORD *) idxData;
323     }
324
325     /* Adding the stream offset once is cheaper than doing it every iteration. Do not modify the strided data, it is a pointer
326      * to the strided Data in the device and might be needed intact on the next draw
327      */
328     for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
329         if(sd->u.s.texCoords[textureNo].lpData) {
330             texCoords[textureNo] = sd->u.s.texCoords[textureNo].lpData + streamOffset[sd->u.s.texCoords[textureNo].streamNo];
331         } else {
332             texCoords[textureNo] = NULL;
333         }
334     }
335     if(sd->u.s.diffuse.lpData) {
336         diffuse = sd->u.s.diffuse.lpData + streamOffset[sd->u.s.diffuse.streamNo];
337     }
338     if(sd->u.s.specular.lpData) {
339         specular = sd->u.s.specular.lpData + streamOffset[sd->u.s.specular.streamNo];
340     }
341     if(sd->u.s.normal.lpData) {
342         normal = sd->u.s.normal.lpData + streamOffset[sd->u.s.normal.streamNo];
343     }
344     if(sd->u.s.position.lpData) {
345         position = sd->u.s.position.lpData + streamOffset[sd->u.s.position.streamNo];
346     }
347
348     /* Start drawing in GL */
349     VTRACE(("glBegin(%x)\n", glPrimType));
350     glBegin(glPrimType);
351
352     /* Default settings for data that is not passed */
353     if (sd->u.s.normal.lpData == NULL) {
354         glNormal3f(0, 0, 0);
355     }
356     if(sd->u.s.diffuse.lpData == NULL) {
357         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
358     }
359     if(sd->u.s.specular.lpData == NULL) {
360         if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
361             GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
362         }
363     }
364
365     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
366      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
367      */
368
369     /* For each primitive */
370     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
371
372         /* Initialize diffuse color */
373         diffuseColor = 0xFFFFFFFF;
374
375         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
376          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
377          */
378
379         /* For indexed data, we need to go a few more strides in */
380         if (idxData != NULL) {
381
382             /* Indexed so work out the number of strides to skip */
383             if (idxSize == 2) {
384                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
385                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
386             } else {
387                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
388                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
389             }
390         }
391
392         /* Texture coords --------------------------- */
393         for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
394
395             if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0) {
396                 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
397                 continue ;
398             }
399
400             /* Query tex coords */
401             if (This->stateBlock->textures[textureNo] != NULL || pixelShader) {
402
403                 int    coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
404                 int texture_idx = This->texUnitMap[textureNo];
405                 float *ptrToCoords = NULL;
406                 float  s = 0.0, t = 0.0, r = 0.0, q = 0.0;
407
408                 if (coordIdx > 7) {
409                     VTRACE(("tex: %d - Skip tex coords, as being system generated\n", textureNo));
410                     continue;
411                 } else if (coordIdx < 0) {
412                     FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
413                     continue;
414                 }
415
416                 ptrToCoords = (float *)(texCoords[coordIdx] + (SkipnStrides * sd->u.s.texCoords[coordIdx].dwStride));
417                 if (texCoords[coordIdx] == NULL) {
418                     TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
419                     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
420                         GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
421                     } else {
422                         glTexCoord4f(0, 0, 0, 1);
423                     }
424                     continue;
425                 } else {
426                     int coordsToUse = sd->u.s.texCoords[coordIdx].dwType + 1; /* 0 == WINED3DDECLTYPE_FLOAT1 etc */
427
428                     if (texture_idx == -1) continue;
429
430                     /* The coords to supply depend completely on the fvf / vertex shader */
431                     switch (coordsToUse) {
432                     case 4: q = ptrToCoords[3]; /* drop through */
433                     case 3: r = ptrToCoords[2]; /* drop through */
434                     case 2: t = ptrToCoords[1]; /* drop through */
435                     case 1: s = ptrToCoords[0];
436                     }
437
438                     switch (coordsToUse) {   /* Supply the provided texture coords */
439                     case WINED3DTTFF_COUNT1:
440                         VTRACE(("tex:%d, s=%f\n", textureNo, s));
441                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
442                             GL_EXTCALL(glMultiTexCoord1fARB(GL_TEXTURE0_ARB + texture_idx, s));
443                         } else {
444                             glTexCoord1f(s);
445                         }
446                         break;
447                     case WINED3DTTFF_COUNT2:
448                         VTRACE(("tex:%d, s=%f, t=%f\n", textureNo, s, t));
449                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
450                             GL_EXTCALL(glMultiTexCoord2fARB(GL_TEXTURE0_ARB + texture_idx, s, t));
451                         } else {
452                             glTexCoord2f(s, t);
453                         }
454                         break;
455                     case WINED3DTTFF_COUNT3:
456                         VTRACE(("tex:%d, s=%f, t=%f, r=%f\n", textureNo, s, t, r));
457                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
458                             GL_EXTCALL(glMultiTexCoord3fARB(GL_TEXTURE0_ARB + texture_idx, s, t, r));
459                         } else {
460                             glTexCoord3f(s, t, r);
461                         }
462                         break;
463                     case WINED3DTTFF_COUNT4:
464                         VTRACE(("tex:%d, s=%f, t=%f, r=%f, q=%f\n", textureNo, s, t, r, q));
465                         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
466                             GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, s, t, r, q));
467                         } else {
468                             glTexCoord4f(s, t, r, q);
469                         }
470                         break;
471                     default:
472                         FIXME("Should not get here as coordsToUse is two bits only (%x)!\n", coordsToUse);
473                     }
474                 }
475             }
476         } /* End of textures */
477
478         /* Diffuse -------------------------------- */
479         if (diffuse) {
480             DWORD *ptrToCoords = (DWORD *)(diffuse + (SkipnStrides * sd->u.s.diffuse.dwStride));
481             diffuseColor = ptrToCoords[0];
482             VTRACE(("diffuseColor=%lx\n", diffuseColor));
483
484             glColor4ub(D3DCOLOR_B_R(diffuseColor),
485                      D3DCOLOR_B_G(diffuseColor),
486                      D3DCOLOR_B_B(diffuseColor),
487                      D3DCOLOR_B_A(diffuseColor));
488             VTRACE(("glColor4ub: r,g,b,a=%lu,%lu,%lu,%lu\n", 
489                     D3DCOLOR_B_R(diffuseColor),
490                     D3DCOLOR_B_G(diffuseColor),
491                     D3DCOLOR_B_B(diffuseColor),
492                     D3DCOLOR_B_A(diffuseColor)));
493
494             if(This->activeContext->num_untracked_materials) {
495                 unsigned char i;
496                 float color[4];
497                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
498                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
499                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
500                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
501
502                 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
503                     glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
504                 }
505             }
506         }
507
508         /* Specular ------------------------------- */
509         if (specular) {
510             DWORD *ptrToCoords = (DWORD *)(specular + (SkipnStrides * sd->u.s.specular.dwStride));
511             specularColor = ptrToCoords[0];
512             VTRACE(("specularColor=%lx\n", specularColor));
513
514             /* special case where the fog density is stored in the specular alpha channel */
515             if(This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
516               (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position.dwType == WINED3DDECLTYPE_FLOAT4 )&&
517               This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
518                 if(GL_SUPPORT(EXT_FOG_COORD)) {
519                     GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
520                 } else {
521                     static BOOL warned = FALSE;
522                     if(!warned) {
523                         /* TODO: Use the fog table code from old ddraw */
524                         FIXME("Implement fog for transformed vertices in software\n");
525                         warned = TRUE;
526                     }
527                 }
528             }
529
530             VTRACE(("glSecondaryColor4ub: r,g,b=%lu,%lu,%lu\n", 
531                     D3DCOLOR_B_R(specularColor), 
532                     D3DCOLOR_B_G(specularColor), 
533                     D3DCOLOR_B_B(specularColor)));
534             if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
535                 GL_EXTCALL(glSecondaryColor3ubEXT)(
536                            D3DCOLOR_B_R(specularColor),
537                            D3DCOLOR_B_G(specularColor),
538                            D3DCOLOR_B_B(specularColor));
539             } else {
540                 /* Do not worry if specular colour missing and disable request */
541                 VTRACE(("Specular color extensions not supplied\n"));
542             }
543         }
544
545         /* Normal -------------------------------- */
546         if (normal != NULL) {
547             float *ptrToCoords = (float *)(normal + (SkipnStrides * sd->u.s.normal.dwStride));
548
549             VTRACE(("glNormal:nx,ny,nz=%f,%f,%f\n", ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]));
550             glNormal3f(ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]);
551         }
552
553         /* Position -------------------------------- */
554         if (position) {
555             float *ptrToCoords = (float *)(position + (SkipnStrides * sd->u.s.position.dwStride));
556             x = ptrToCoords[0];
557             y = ptrToCoords[1];
558             z = ptrToCoords[2];
559             rhw = 1.0;
560             VTRACE(("x,y,z=%f,%f,%f\n", x,y,z));
561
562             /* RHW follows, only if transformed, ie 4 floats were provided */
563             if (sd->u.s.position_transformed) {
564                 rhw = ptrToCoords[3];
565                 VTRACE(("rhw=%f\n", rhw));
566             }
567
568             if (1.0f == rhw || ((rhw < eps) && (rhw > -eps))) {
569                 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f\n", x,y,z));
570                 glVertex3f(x, y, z);
571             } else {
572                 GLfloat w = 1.0 / rhw;
573                 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f / rhw=%f\n", x,y,z,rhw));
574                 glVertex4f(x*w, y*w, z*w, w);
575             }
576         }
577
578         /* For non indexed mode, step onto next parts */
579         if (idxData == NULL) {
580             ++SkipnStrides;
581         }
582     }
583
584     glEnd();
585     checkGLcall("glEnd and previous calls");
586 }
587
588 static void depth_blt(IWineD3DDevice *iface, GLuint texture) {
589     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
590     GLint old_binding = 0;
591
592     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
593
594     glDisable(GL_CULL_FACE);
595     glEnable(GL_BLEND);
596     glDisable(GL_ALPHA_TEST);
597     glDisable(GL_SCISSOR_TEST);
598     glDisable(GL_STENCIL_TEST);
599     glEnable(GL_DEPTH_TEST);
600     glDepthFunc(GL_ALWAYS);
601     glBlendFunc(GL_ZERO, GL_ONE);
602
603     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
604     glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
605     glBindTexture(GL_TEXTURE_2D, texture);
606     glEnable(GL_TEXTURE_2D);
607
608     This->shader_backend->shader_select_depth_blt(iface);
609
610     glBegin(GL_TRIANGLE_STRIP);
611     glVertex2f(-1.0f, -1.0f);
612     glVertex2f(1.0f, -1.0f);
613     glVertex2f(-1.0f, 1.0f);
614     glVertex2f(1.0f, 1.0f);
615     glEnd();
616
617     glBindTexture(GL_TEXTURE_2D, old_binding);
618
619     glPopAttrib();
620
621     /* Reselect the old shaders. There doesn't seem to be any glPushAttrib bit for arb shaders,
622      * and this seems easier and more efficient than providing the shader backend with a private
623      * storage to read and restore the old shader settings
624      */
625     This->shader_backend->shader_select(iface, use_ps(This), use_vs(This));
626 }
627
628 static void depth_copy(IWineD3DDevice *iface) {
629     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
630     IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *)This->depthStencilBuffer;
631
632     /* Only copy the depth buffer if there is one. */
633     if (!depth_stencil) return;
634
635     /* TODO: Make this work for modes other than FBO */
636     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
637
638     if (depth_stencil->current_renderbuffer) {
639         FIXME("Not supported with fixed up depth stencil\n");
640         return;
641     }
642
643     if (This->render_offscreen) {
644         static GLuint tmp_texture = 0;
645         GLint old_binding = 0;
646
647         TRACE("Copying onscreen depth buffer to offscreen surface\n");
648
649         if (!tmp_texture) {
650             glGenTextures(1, &tmp_texture);
651         }
652
653         /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
654          * directly on the FBO texture. That's because we need to flip. */
655         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
656         glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
657         glBindTexture(GL_TEXTURE_2D, tmp_texture);
658         glCopyTexImage2D(depth_stencil->glDescription.target,
659                 depth_stencil->glDescription.level,
660                 depth_stencil->glDescription.glFormatInternal,
661                 0,
662                 0,
663                 depth_stencil->currentDesc.Width,
664                 depth_stencil->currentDesc.Height,
665                 0);
666         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
667         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
668         glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
669         glBindTexture(GL_TEXTURE_2D, old_binding);
670
671         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, This->fbo));
672         checkGLcall("glBindFramebuffer()");
673         depth_blt(iface, tmp_texture);
674         checkGLcall("depth_blt");
675     } else {
676         TRACE("Copying offscreen surface to onscreen depth buffer\n");
677
678         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
679         checkGLcall("glBindFramebuffer()");
680         depth_blt(iface, depth_stencil->glDescription.textureName);
681         checkGLcall("depth_blt");
682     }
683 }
684
685 static inline void drawStridedInstanced(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
686                                  GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex,
687                                  ULONG startIdx, ULONG startVertex) {
688     UINT numInstances = 0;
689     int numInstancedAttribs = 0, i, j;
690     UINT instancedData[sizeof(sd->u.input) / sizeof(sd->u.input[0]) /* 16 */];
691     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
692     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
693
694     if (idxSize == 0) {
695         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
696          * We don't support this for now
697          *
698          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
699          * But the StreamSourceFreq value has a different meaning in that situation.
700          */
701         FIXME("Non-indexed instanced drawing is not supported\n");
702         return;
703     }
704
705     TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
706     idxData = idxData == (void *)-1 ? NULL : idxData;
707
708     /* First, figure out how many instances we have to draw */
709     for(i = 0; i < MAX_STREAMS; i++) {
710         /* Look at all non-instanced streams */
711         if(!(stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) &&
712            stateblock->streamSource[i]) {
713             int inst = stateblock->streamFreq[i];
714
715             if(numInstances && inst != numInstances) {
716                 ERR("Two streams specify a different number of instances. Got %d, new is %d\n", numInstances, inst);
717             }
718             numInstances = inst;
719         }
720     }
721
722     for(i = 0; i < sizeof(sd->u.input) / sizeof(sd->u.input[0]); i++) {
723         if(stateblock->streamFlags[sd->u.input[i].streamNo] & WINED3DSTREAMSOURCE_INSTANCEDATA) {
724             instancedData[numInstancedAttribs] = i;
725             numInstancedAttribs++;
726         }
727     }
728
729     /* now draw numInstances instances :-) */
730     for(i = 0; i < numInstances; i++) {
731         /* Specify the instanced attributes using immediate mode calls */
732         for(j = 0; j < numInstancedAttribs; j++) {
733             BYTE *ptr = sd->u.input[instancedData[j]].lpData +
734                         sd->u.input[instancedData[j]].dwStride * i +
735                         stateblock->streamOffset[sd->u.input[instancedData[j]].streamNo];
736             if(sd->u.input[instancedData[j]].VBO) {
737                 IWineD3DVertexBufferImpl *vb = (IWineD3DVertexBufferImpl *) stateblock->streamSource[sd->u.input[instancedData[j]].streamNo];
738                 ptr += (long) vb->resource.allocatedMemory;
739             }
740
741             switch(sd->u.input[instancedData[j]].dwType) {
742                 case WINED3DDECLTYPE_FLOAT1:
743                     GL_EXTCALL(glVertexAttrib1fvARB(instancedData[j], (float *) ptr));
744                     break;
745                 case WINED3DDECLTYPE_FLOAT2:
746                     GL_EXTCALL(glVertexAttrib2fvARB(instancedData[j], (float *) ptr));
747                     break;
748                 case WINED3DDECLTYPE_FLOAT3:
749                     GL_EXTCALL(glVertexAttrib3fvARB(instancedData[j], (float *) ptr));
750                     break;
751                 case WINED3DDECLTYPE_FLOAT4:
752                     GL_EXTCALL(glVertexAttrib4fvARB(instancedData[j], (float *) ptr));
753                     break;
754
755                 case WINED3DDECLTYPE_UBYTE4:
756                     GL_EXTCALL(glVertexAttrib4ubvARB(instancedData[j], ptr));
757                     break;
758                 case WINED3DDECLTYPE_UBYTE4N:
759                 case WINED3DDECLTYPE_D3DCOLOR:
760                     GL_EXTCALL(glVertexAttrib4NubvARB(instancedData[j], ptr));
761                     break;
762
763                 case WINED3DDECLTYPE_SHORT2:
764                     GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
765                     break;
766                 case WINED3DDECLTYPE_SHORT4:
767                     GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
768                     break;
769
770                 case WINED3DDECLTYPE_SHORT2N:
771                 {
772                     GLshort s[4] = {((short *) ptr)[0], ((short *) ptr)[1], 0, 1};
773                     GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], s));
774                     break;
775                 }
776                 case WINED3DDECLTYPE_USHORT2N:
777                 {
778                     GLushort s[4] = {((unsigned short *) ptr)[0], ((unsigned short *) ptr)[1], 0, 1};
779                     GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], s));
780                     break;
781                 }
782                 case WINED3DDECLTYPE_SHORT4N:
783                     GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], (GLshort *) ptr));
784                     break;
785                 case WINED3DDECLTYPE_USHORT4N:
786                     GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], (GLushort *) ptr));
787                     break;
788
789                 case WINED3DDECLTYPE_UDEC3:
790                     FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
791                     /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
792                     break;
793                 case WINED3DDECLTYPE_DEC3N:
794                     FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
795                     /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
796                     break;
797
798                 case WINED3DDECLTYPE_FLOAT16_2:
799                     /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
800                      * byte float according to the IEEE standard
801                      */
802                     if (GL_SUPPORT(NV_HALF_FLOAT)) {
803                         GL_EXTCALL(glVertexAttrib2hvNV(instancedData[j], (GLhalfNV *)ptr));
804                     } else {
805                         FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_2\n");
806                     }
807                     break;
808                 case WINED3DDECLTYPE_FLOAT16_4:
809                     if (GL_SUPPORT(NV_HALF_FLOAT)) {
810                         GL_EXTCALL(glVertexAttrib4hvNV(instancedData[j], (GLhalfNV *)ptr));
811                     } else {
812                         FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_4\n");
813                     }
814                     break;
815
816                 case WINED3DDECLTYPE_UNUSED:
817                 default:
818                     ERR("Unexpected declaration in instanced attributes\n");
819                     break;
820             }
821         }
822
823         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
824                     (const char *)idxData+(idxSize * startIdx));
825         checkGLcall("glDrawElements");
826     }
827 }
828
829 struct coords {
830     int x, y, z;
831 };
832
833 void blt_to_drawable(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *surface) {
834     struct coords coords[4];
835     int low_coord;
836
837     /* TODO: This could be supported for lazy unlocking */
838     if(!(surface->Flags & SFLAG_INTEXTURE)) {
839         /* It is ok at init to be nowhere */
840         if(!(surface->Flags & SFLAG_INSYSMEM)) {
841             ERR("Blitting surfaces from sysmem not supported yet\n");
842         }
843         return;
844     }
845
846     ActivateContext(This, This->render_targets[0], CTXUSAGE_BLIT);
847     ENTER_GL();
848
849     if(surface->glDescription.target == GL_TEXTURE_2D) {
850         glBindTexture(GL_TEXTURE_2D, surface->glDescription.textureName);
851         checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
852
853         coords[0].x = 0;    coords[0].y = 0;    coords[0].z = 0;
854         coords[1].x = 0;    coords[1].y = 1;    coords[1].z = 0;
855         coords[2].x = 1;    coords[2].y = 1;    coords[2].z = 0;
856         coords[3].x = 1;    coords[3].y = 0;    coords[3].z = 0;
857
858         low_coord = 0;
859     } else {
860         /* Must be a cube map */
861         glDisable(GL_TEXTURE_2D);
862         checkGLcall("glDisable(GL_TEXTURE_2D)");
863         glEnable(GL_TEXTURE_CUBE_MAP_ARB);
864         checkGLcall("glEnable(surface->glDescription.target)");
865         glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, surface->glDescription.textureName);
866         checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
867
868         switch(surface->glDescription.target) {
869             case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
870                 coords[0].x =  1;   coords[0].y = -1;   coords[0].z =  1;
871                 coords[1].x =  1;   coords[1].y =  1;   coords[1].z =  1;
872                 coords[2].x =  1;   coords[2].y =  1;   coords[2].z = -1;
873                 coords[3].x =  1;   coords[3].y = -1;   coords[3].z = -1;
874                 break;
875
876             case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
877                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
878                 coords[1].x = -1;   coords[1].y =  1;   coords[1].z =  1;
879                 coords[2].x = -1;   coords[2].y =  1;   coords[2].z = -1;
880                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
881                 break;
882
883             case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
884                 coords[0].x = -1;   coords[0].y =  1;   coords[0].z =  1;
885                 coords[1].x =  1;   coords[1].y =  1;   coords[1].z =  1;
886                 coords[2].x =  1;   coords[2].y =  1;   coords[2].z = -1;
887                 coords[3].x = -1;   coords[3].y =  1;   coords[3].z = -1;
888                 break;
889
890             case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
891                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
892                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z =  1;
893                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z = -1;
894                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
895                 break;
896
897             case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
898                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z =  1;
899                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z =  1;
900                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z =  1;
901                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z =  1;
902                 break;
903
904             case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
905                 coords[0].x = -1;   coords[0].y = -1;   coords[0].z = -1;
906                 coords[1].x =  1;   coords[1].y = -1;   coords[1].z = -1;
907                 coords[2].x =  1;   coords[2].y = -1;   coords[2].z = -1;
908                 coords[3].x = -1;   coords[3].y = -1;   coords[3].z = -1;
909
910             default:
911                 ERR("Unexpected texture target\n");
912                 LEAVE_GL();
913                 return;
914         }
915
916         low_coord = -1;
917     }
918
919     if(This->render_offscreen) {
920         coords[0].y = coords[0].y == 1 ? low_coord : 1;
921         coords[1].y = coords[1].y == 1 ? low_coord : 1;
922         coords[2].y = coords[2].y == 1 ? low_coord : 1;
923         coords[3].y = coords[3].y == 1 ? low_coord : 1;
924     }
925
926     glBegin(GL_QUADS);
927         glTexCoord3iv((GLint *) &coords[0]);
928         glVertex2i(0, 0);
929
930         glTexCoord3iv((GLint *) &coords[1]);
931         glVertex2i(0, surface->pow2Height);
932
933         glTexCoord3iv((GLint *) &coords[2]);
934         glVertex2i(surface->pow2Width, surface->pow2Height);
935
936         glTexCoord3iv((GLint *) &coords[3]);
937         glVertex2i(surface->pow2Width, 0);
938     glEnd();
939     checkGLcall("glEnd");
940
941     if(surface->glDescription.target != GL_TEXTURE_2D) {
942         glEnable(GL_TEXTURE_2D);
943         checkGLcall("glEnable(GL_TEXTURE_2D)");
944         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
945         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
946     }
947     LEAVE_GL();
948 }
949
950 static inline void remove_vbos(IWineD3DDeviceImpl *This, WineDirect3DVertexStridedData *s) {
951     unsigned char i;
952     IWineD3DVertexBufferImpl *vb;
953
954     if(s->u.s.position.VBO) {
955         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position.streamNo];
956         s->u.s.position.VBO = 0;
957         s->u.s.position.lpData = (BYTE *) ((unsigned long) s->u.s.position.lpData + (unsigned long) vb->resource.allocatedMemory);
958     }
959     if(s->u.s.blendWeights.VBO) {
960         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendWeights.streamNo];
961         s->u.s.blendWeights.VBO = 0;
962         s->u.s.blendWeights.lpData = (BYTE *) ((unsigned long) s->u.s.blendWeights.lpData + (unsigned long) vb->resource.allocatedMemory);
963     }
964     if(s->u.s.blendMatrixIndices.VBO) {
965         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendMatrixIndices.streamNo];
966         s->u.s.blendMatrixIndices.VBO = 0;
967         s->u.s.blendMatrixIndices.lpData = (BYTE *) ((unsigned long) s->u.s.blendMatrixIndices.lpData + (unsigned long) vb->resource.allocatedMemory);
968     }
969     if(s->u.s.normal.VBO) {
970         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal.streamNo];
971         s->u.s.normal.VBO = 0;
972         s->u.s.normal.lpData = (BYTE *) ((unsigned long) s->u.s.normal.lpData + (unsigned long) vb->resource.allocatedMemory);
973     }
974     if(s->u.s.pSize.VBO) {
975         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.pSize.streamNo];
976         s->u.s.pSize.VBO = 0;
977         s->u.s.pSize.lpData = (BYTE *) ((unsigned long) s->u.s.pSize.lpData + (unsigned long) vb->resource.allocatedMemory);
978     }
979     if(s->u.s.diffuse.VBO) {
980         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.diffuse.streamNo];
981         s->u.s.diffuse.VBO = 0;
982         s->u.s.diffuse.lpData = (BYTE *) ((unsigned long) s->u.s.diffuse.lpData + (unsigned long) vb->resource.allocatedMemory);
983     }
984     if(s->u.s.specular.VBO) {
985         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.specular.streamNo];
986         s->u.s.specular.VBO = 0;
987         s->u.s.specular.lpData = (BYTE *) ((unsigned long) s->u.s.specular.lpData + (unsigned long) vb->resource.allocatedMemory);
988     }
989     for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) {
990         if(s->u.s.texCoords[i].VBO) {
991             vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.texCoords[i].streamNo];
992             s->u.s.texCoords[i].VBO = 0;
993             s->u.s.texCoords[i].lpData = (BYTE *) ((unsigned long) s->u.s.texCoords[i].lpData + (unsigned long) vb->resource.allocatedMemory);
994         }
995     }
996     if(s->u.s.position2.VBO) {
997         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position2.streamNo];
998         s->u.s.position2.VBO = 0;
999         s->u.s.position2.lpData = (BYTE *) ((unsigned long) s->u.s.position2.lpData + (unsigned long) vb->resource.allocatedMemory);
1000     }
1001     if(s->u.s.normal2.VBO) {
1002         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal2.streamNo];
1003         s->u.s.normal2.VBO = 0;
1004         s->u.s.normal2.lpData = (BYTE *) ((unsigned long) s->u.s.normal2.lpData + (unsigned long) vb->resource.allocatedMemory);
1005     }
1006     if(s->u.s.tangent.VBO) {
1007         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tangent.streamNo];
1008         s->u.s.tangent.VBO = 0;
1009         s->u.s.tangent.lpData = (BYTE *) ((unsigned long) s->u.s.tangent.lpData + (unsigned long) vb->resource.allocatedMemory);
1010     }
1011     if(s->u.s.binormal.VBO) {
1012         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.binormal.streamNo];
1013         s->u.s.binormal.VBO = 0;
1014         s->u.s.binormal.lpData = (BYTE *) ((unsigned long) s->u.s.binormal.lpData + (unsigned long) vb->resource.allocatedMemory);
1015     }
1016     if(s->u.s.tessFactor.VBO) {
1017         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tessFactor.streamNo];
1018         s->u.s.tessFactor.VBO = 0;
1019         s->u.s.tessFactor.lpData = (BYTE *) ((unsigned long) s->u.s.tessFactor.lpData + (unsigned long) vb->resource.allocatedMemory);
1020     }
1021     if(s->u.s.fog.VBO) {
1022         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.fog.streamNo];
1023         s->u.s.fog.VBO = 0;
1024         s->u.s.fog.lpData = (BYTE *) ((unsigned long) s->u.s.fog.lpData + (unsigned long) vb->resource.allocatedMemory);
1025     }
1026     if(s->u.s.depth.VBO) {
1027         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.depth.streamNo];
1028         s->u.s.depth.VBO = 0;
1029         s->u.s.depth.lpData = (BYTE *) ((unsigned long) s->u.s.depth.lpData + (unsigned long) vb->resource.allocatedMemory);
1030     }
1031     if(s->u.s.sample.VBO) {
1032         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.sample.streamNo];
1033         s->u.s.sample.VBO = 0;
1034         s->u.s.sample.lpData = (BYTE *) ((unsigned long) s->u.s.sample.lpData + (unsigned long) vb->resource.allocatedMemory);
1035     }
1036 }
1037
1038 /* Routine common to the draw primitive and draw indexed primitive routines */
1039 void drawPrimitive(IWineD3DDevice *iface,
1040                    int PrimitiveType,
1041                    long NumPrimitives,
1042                    /* for Indexed: */
1043                    long  StartVertexIndex,
1044                    UINT  numberOfVertices,
1045                    long  StartIdx,
1046                    short idxSize,
1047                    const void *idxData,
1048                    int   minIndex) {
1049
1050     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
1051     IWineD3DSwapChain            *swapchain;
1052     IWineD3DBaseTexture          *texture = NULL;
1053     IWineD3DSurfaceImpl          *target;
1054     int i;
1055
1056     /* Signals other modules that a drawing is in progress and the stateblock finalized */
1057     This->isInDraw = TRUE;
1058
1059     /* Invalidate the back buffer memory so LockRect will read it the next time */
1060     for(i = 0; i < GL_LIMITS(buffers); i++) {
1061         target = (IWineD3DSurfaceImpl *) This->render_targets[i];
1062
1063         /* TODO: Only do all that if we're going to change anything
1064          * Texture container dirtification does not work quite right yet
1065          */
1066         if(target /*&& target->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)*/) {
1067             swapchain = NULL;
1068             texture = NULL;
1069
1070             if(i == 0) {
1071                 IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1072
1073                 /* Need the surface in the drawable! */
1074                 if(!(target->Flags & SFLAG_INDRAWABLE) && (swapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
1075                     blt_to_drawable(This, target);
1076                 }
1077
1078                 if(swapchain) {
1079                     /* Onscreen target. Invalidate system memory copy and texture copy */
1080                     target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
1081                     target->Flags |= SFLAG_INDRAWABLE;
1082                     IWineD3DSwapChain_Release(swapchain);
1083                 } else if(wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1084                     /* Non-FBO target: Invalidate system copy, texture copy and dirtify the container */
1085                     IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DBaseTexture, (void **)&texture);
1086
1087                     if(texture) {
1088                         IWineD3DBaseTexture_SetDirty(texture, TRUE);
1089                         IWineD3DTexture_Release(texture);
1090                     }
1091
1092                     target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
1093                     target->Flags |= SFLAG_INDRAWABLE;
1094                 } else {
1095                     /* FBO offscreen target. Invalidate system memory copy */
1096                     target->Flags &= ~SFLAG_INSYSMEM;
1097                 }
1098             } else {
1099                 /* Must be an fbo render target */
1100                 target->Flags &= ~SFLAG_INSYSMEM;
1101                 target->Flags |=  SFLAG_INTEXTURE;
1102             }
1103         }
1104     }
1105
1106     /* Ok, we will be updating the screen from here onwards so grab the lock */
1107
1108     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1109         ENTER_GL();
1110         apply_fbo_state(iface);
1111         LEAVE_GL();
1112     }
1113
1114     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
1115     ENTER_GL();
1116
1117     if (This->depth_copy_state == WINED3D_DCS_COPY) {
1118         depth_copy(iface);
1119     }
1120     This->depth_copy_state = WINED3D_DCS_INITIAL;
1121
1122     {
1123         GLenum glPrimType;
1124         BOOL emulation = FALSE;
1125         WineDirect3DVertexStridedData *strided = &This->strided_streams;
1126         WineDirect3DVertexStridedData stridedlcl;
1127         /* Ok, Work out which primitive is requested and how many vertexes that
1128            will be                                                              */
1129         UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
1130         if (numberOfVertices == 0 )
1131             numberOfVertices = calculatedNumberOfindices;
1132
1133         if(!use_vs(This)) {
1134             if(!This->strided_streams.u.s.position_transformed && This->activeContext->num_untracked_materials &&
1135                 This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
1136                 FIXME("Using software emulation because not all material properties could be tracked\n");
1137                 emulation = TRUE;
1138             }
1139             else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
1140                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
1141                  * to a float in the vertex buffer
1142                  */
1143                 FIXME("Using software emulation because manual fog coordinates are provided\n");
1144                 emulation = TRUE;
1145             }
1146
1147             if(emulation) {
1148                 strided = &stridedlcl;
1149                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
1150                 remove_vbos(This, &stridedlcl);
1151             }
1152         }
1153
1154         if (This->useDrawStridedSlow || emulation) {
1155             /* Immediate mode drawing */
1156             drawStridedSlow(iface, strided, calculatedNumberOfindices,
1157                             glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1158         } else if(This->instancedDraw) {
1159             /* Instancing emulation with mixing immediate mode and arrays */
1160             drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
1161                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1162         } else {
1163             /* Simple array draw call */
1164             drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
1165                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1166         }
1167     }
1168
1169     /* Finshed updating the screen, restore lock */
1170     LEAVE_GL();
1171     TRACE("Done all gl drawing\n");
1172
1173     /* Diagnostics */
1174 #ifdef SHOW_FRAME_MAKEUP
1175     {
1176         static long int primCounter = 0;
1177         /* NOTE: set primCounter to the value reported by drawprim 
1178            before you want to to write frame makeup to /tmp */
1179         if (primCounter >= 0) {
1180             WINED3DLOCKED_RECT r;
1181             char buffer[80];
1182             IWineD3DSurface_LockRect(This->renderTarget, &r, NULL, WINED3DLOCK_READONLY);
1183             sprintf(buffer, "/tmp/backbuffer_%d.tga", primCounter);
1184             TRACE("Saving screenshot %s\n", buffer);
1185             IWineD3DSurface_SaveSnapshot(This->renderTarget, buffer);
1186             IWineD3DSurface_UnlockRect(This->renderTarget);
1187
1188 #ifdef SHOW_TEXTURE_MAKEUP
1189            {
1190             IWineD3DSurface *pSur;
1191             int textureNo;
1192             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
1193                 if (This->stateBlock->textures[textureNo] != NULL) {
1194                     sprintf(buffer, "/tmp/texture_%p_%d_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
1195                     TRACE("Saving texture %s\n", buffer);
1196                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
1197                             IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
1198                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
1199                             IWineD3DSurface_Release(pSur);
1200                     } else  {
1201                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
1202                     }
1203                 }
1204             }
1205            }
1206 #endif
1207         }
1208         TRACE("drawprim #%d\n", primCounter);
1209         ++primCounter;
1210     }
1211 #endif
1212
1213     /* Control goes back to the device, stateblock values may change again */
1214     This->isInDraw = FALSE;
1215 }
1216
1217 static void normalize_normal(float *n) {
1218     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
1219     if(length == 0.0) return;
1220     length = sqrt(length);
1221     n[0] = n[0] / length;
1222     n[1] = n[1] / length;
1223     n[2] = n[2] / length;
1224 }
1225
1226 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
1227  *
1228  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
1229  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
1230  * to chache the patches in a vertex buffer. But more importantly, gl can't bind generated
1231  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
1232  * in drawprim.
1233  *
1234  * To read back, the opengl feedback mode is used. This creates a proplem because we want
1235  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
1236  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
1237  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
1238  * them to [-1.0;+1.0] and set the viewport up to scale them back.
1239  *
1240  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
1241  * resulting colors back to the normals.
1242  *
1243  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
1244  * does not restore it because normally a draw follows immediately afterwards. The caller is
1245  * responsible of taking care that either the gl states are restored, or the context activated
1246  * for drawing to reset the lastWasBlit flag.
1247  */
1248 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
1249                             struct WineD3DRectPatch *patch) {
1250     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
1251     float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
1252     WineDirect3DVertexStridedData strided;
1253     BYTE *data;
1254     WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
1255     DWORD vtxStride;
1256     GLenum feedback_type;
1257     GLfloat *feedbuffer;
1258
1259     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
1260      * Beware of vbos
1261      */
1262     memset(&strided, 0, sizeof(strided));
1263     primitiveDeclarationConvertToStridedData((IWineD3DDevice *) This, FALSE, &strided, NULL);
1264     if(strided.u.s.position.VBO) {
1265         IWineD3DVertexBufferImpl *vb;
1266         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[strided.u.s.position.streamNo];
1267         strided.u.s.position.lpData = (BYTE *) ((unsigned long) strided.u.s.position.lpData +
1268                                                 (unsigned long) vb->resource.allocatedMemory);
1269     }
1270     vtxStride = strided.u.s.position.dwStride;
1271     data = strided.u.s.position.lpData +
1272            vtxStride * info->Stride * info->StartVertexOffsetHeight +
1273            vtxStride * info->StartVertexOffsetWidth;
1274
1275     /* Not entirely sure about what happens with transformed vertices */
1276     if(strided.u.s.position_transformed) {
1277         FIXME("Transformed position in rectpatch generation\n");
1278     }
1279     if(vtxStride % sizeof(GLfloat)) {
1280         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
1281          * I don't see how the stride could not be a multiple of 4, but make sure
1282          * to check it
1283          */
1284         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
1285     }
1286     if(info->Basis != WINED3DBASIS_BEZIER) {
1287         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
1288     }
1289     if(info->Degree != WINED3DDEGREE_CUBIC) {
1290         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
1291     }
1292
1293     /* First, get the boundary cube of the input data */
1294     for(j = 0; j < info->Height; j++) {
1295         for(i = 0; i < info->Width; i++) {
1296             float *v = (float *) (data + vtxStride * i + vtxStride * info->Stride * j);
1297             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
1298             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
1299             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
1300             if(v[2] < neg_z) neg_z = v[2];
1301         }
1302     }
1303
1304     /* This needs some improvements in the vertex decl code */
1305     FIXME("Cannot find data to generate. Only generating position and normals\n");
1306     patch->has_normals = TRUE;
1307     patch->has_texcoords = FALSE;
1308
1309     /* Simply activate the context for blitting. This disables all the things we don't want and
1310      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
1311      * patch (as opposed to normal draws) will most likely need different changes anyway
1312      */
1313     ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
1314     ENTER_GL();
1315
1316     glMatrixMode(GL_PROJECTION);
1317     checkGLcall("glMatrixMode(GL_PROJECTION)");
1318     glLoadIdentity();
1319     checkGLcall("glLoadIndentity()");
1320     glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
1321     glTranslatef(0, 0, 0.5);
1322     checkGLcall("glScalef");
1323     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
1324     checkGLcall("glViewport");
1325
1326     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
1327      * our feedback buffer parser
1328      */
1329     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1330     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
1331     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
1332     if(patch->has_normals) {
1333         float black[4] = {0, 0, 0, 0};
1334         float red[4]   = {1, 0, 0, 0};
1335         float green[4] = {0, 1, 0, 0};
1336         float blue[4]  = {0, 0, 1, 0};
1337         float white[4] = {1, 1, 1, 1};
1338         glEnable(GL_LIGHTING);
1339         checkGLcall("glEnable(GL_LIGHTING)");
1340         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
1341         checkGLcall("glLightModel for MODEL_AMBIENT");
1342         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
1343
1344         for(i = 3; i < GL_LIMITS(lights); i++) {
1345             glDisable(GL_LIGHT0 + i);
1346             checkGLcall("glDisable(GL_LIGHT0 + i)");
1347             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
1348         }
1349
1350         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
1351         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
1352         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
1353         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
1354         glLightfv(GL_LIGHT0, GL_POSITION, red);
1355         glEnable(GL_LIGHT0);
1356         checkGLcall("Setting up light 1\n");
1357         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
1358         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
1359         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
1360         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
1361         glLightfv(GL_LIGHT1, GL_POSITION, green);
1362         glEnable(GL_LIGHT1);
1363         checkGLcall("Setting up light 2\n");
1364         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
1365         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
1366         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
1367         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
1368         glLightfv(GL_LIGHT2, GL_POSITION, blue);
1369         glEnable(GL_LIGHT2);
1370         checkGLcall("Setting up light 3\n");
1371
1372         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
1373         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
1374         glDisable(GL_COLOR_MATERIAL);
1375         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
1376         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
1377         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
1378         checkGLcall("Setting up materials\n");
1379     }
1380
1381     /* Enable the needed maps.
1382      * GL_MAP2_VERTEX_3 is needed for positional data.
1383      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
1384      * GL_MAP2_TEXTURE_COORD_4 for texture coords
1385      */
1386     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
1387     out_vertex_size = 3 /* position */;
1388     d3d_out_vertex_size = 3;
1389     glEnable(GL_MAP2_VERTEX_3);
1390     if(patch->has_normals && patch->has_texcoords) {
1391         FIXME("Texcoords not handled yet\n");
1392         feedback_type = GL_3D_COLOR_TEXTURE;
1393         out_vertex_size += 8;
1394         d3d_out_vertex_size += 7;
1395         glEnable(GL_AUTO_NORMAL);
1396         glEnable(GL_MAP2_TEXTURE_COORD_4);
1397     } else if(patch->has_texcoords) {
1398         FIXME("Texcoords not handled yet\n");
1399         feedback_type = GL_3D_COLOR_TEXTURE;
1400         out_vertex_size += 7;
1401         d3d_out_vertex_size += 4;
1402         glEnable(GL_MAP2_TEXTURE_COORD_4);
1403     } else if(patch->has_normals) {
1404         feedback_type = GL_3D_COLOR;
1405         out_vertex_size += 4;
1406         d3d_out_vertex_size += 3;
1407         glEnable(GL_AUTO_NORMAL);
1408     } else {
1409         feedback_type = GL_3D;
1410     }
1411     checkGLcall("glEnable vertex attrib generation");
1412
1413     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
1414                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
1415     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
1416
1417     glMap2f(GL_MAP2_VERTEX_3,
1418             0, 1, vtxStride / sizeof(float), info->Width,
1419             0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1420             (float *) data);
1421     checkGLcall("glMap2f");
1422     if(patch->has_texcoords) {
1423         glMap2f(GL_MAP2_TEXTURE_COORD_4,
1424                 0, 1, vtxStride / sizeof(float), info->Width,
1425                 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1426                 (float *) data);
1427         checkGLcall("glMap2f");
1428     }
1429     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
1430     checkGLcall("glMapGrid2f");
1431
1432     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
1433     checkGLcall("glFeedbackBuffer");
1434     glRenderMode(GL_FEEDBACK);
1435
1436     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1437     checkGLcall("glEvalMesh2\n");
1438
1439     i = glRenderMode(GL_RENDER);
1440     if(i == -1) {
1441         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
1442         Sleep(10000);
1443         HeapFree(GetProcessHeap(), 0, feedbuffer);
1444         return WINED3DERR_DRIVERINTERNALERROR;
1445     } else if(i != buffer_size) {
1446         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
1447         Sleep(10000);
1448         HeapFree(GetProcessHeap(), 0, feedbuffer);
1449         return WINED3DERR_DRIVERINTERNALERROR;
1450     } else {
1451         TRACE("Got %d elements as expected\n", i);
1452     }
1453
1454     HeapFree(GetProcessHeap(), 0, patch->mem);
1455     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
1456     i = 0;
1457     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1458         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1459             ERR("Unexpected token: %f\n", feedbuffer[j]);
1460             continue;
1461         }
1462         if(feedbuffer[j + 1] != 3) {
1463             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1464             continue;
1465         }
1466         /* Somehow there are different ideas about back / front facing, so fix up the
1467          * vertex order
1468          */
1469         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1470         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1471         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
1472         if(patch->has_normals) {
1473             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1474             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1475             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1476         }
1477         i += d3d_out_vertex_size;
1478
1479         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1480         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1481         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
1482         if(patch->has_normals) {
1483             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1484             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1485             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1486         }
1487         i += d3d_out_vertex_size;
1488
1489         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1490         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1491         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
1492         if(patch->has_normals) {
1493             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1494             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1495             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1496         }
1497         i += d3d_out_vertex_size;
1498     }
1499
1500     if(patch->has_normals) {
1501         /* Now do the same with reverse light directions */
1502         float x[4] = {-1,  0,  0, 0};
1503         float y[4] = { 0, -1,  0, 0};
1504         float z[4] = { 0,  0, -1, 0};
1505         glLightfv(GL_LIGHT0, GL_POSITION, x);
1506         glLightfv(GL_LIGHT1, GL_POSITION, y);
1507         glLightfv(GL_LIGHT2, GL_POSITION, z);
1508         checkGLcall("Setting up reverse light directions\n");
1509
1510         glRenderMode(GL_FEEDBACK);
1511         checkGLcall("glRenderMode(GL_FEEDBACK)");
1512         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1513         checkGLcall("glEvalMesh2\n");
1514         i = glRenderMode(GL_RENDER);
1515         checkGLcall("glRenderMode(GL_RENDER)");
1516
1517         i = 0;
1518         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1519             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1520                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1521                 continue;
1522             }
1523             if(feedbuffer[j + 1] != 3) {
1524                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1525                 continue;
1526             }
1527             if(patch->mem[i + 3] == 0.0)
1528                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1529             if(patch->mem[i + 4] == 0.0)
1530                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1531             if(patch->mem[i + 5] == 0.0)
1532                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1533             normalize_normal(patch->mem + i + 3);
1534             i += d3d_out_vertex_size;
1535
1536             if(patch->mem[i + 3] == 0.0)
1537                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1538             if(patch->mem[i + 4] == 0.0)
1539                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1540             if(patch->mem[i + 5] == 0.0)
1541                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1542             normalize_normal(patch->mem + i + 3);
1543             i += d3d_out_vertex_size;
1544
1545             if(patch->mem[i + 3] == 0.0)
1546                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1547             if(patch->mem[i + 4] == 0.0)
1548                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1549             if(patch->mem[i + 5] == 0.0)
1550                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1551             normalize_normal(patch->mem + i + 3);
1552             i += d3d_out_vertex_size;
1553         }
1554     }
1555
1556     glDisable(GL_MAP2_VERTEX_3);
1557     glDisable(GL_AUTO_NORMAL);
1558     glDisable(GL_MAP2_NORMAL);
1559     glDisable(GL_MAP2_TEXTURE_COORD_4);
1560     checkGLcall("glDisable vertex attrib generation");
1561     LEAVE_GL();
1562
1563     HeapFree(GetProcessHeap(), 0, feedbuffer);
1564
1565     vtxStride = 3 * sizeof(float);
1566     if(patch->has_normals) {
1567         vtxStride += 3 * sizeof(float);
1568     }
1569     if(patch->has_texcoords) {
1570         vtxStride += 4 * sizeof(float);
1571     }
1572     memset(&patch->strided, 0, sizeof(&patch->strided));
1573     patch->strided.u.s.position.lpData = (BYTE *) patch->mem;
1574     patch->strided.u.s.position.dwStride = vtxStride;
1575     patch->strided.u.s.position.dwType = WINED3DDECLTYPE_FLOAT3;
1576     patch->strided.u.s.position.streamNo = 255;
1577
1578     if(patch->has_normals) {
1579         patch->strided.u.s.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1580         patch->strided.u.s.normal.dwStride = vtxStride;
1581         patch->strided.u.s.normal.dwType = WINED3DDECLTYPE_FLOAT3;
1582         patch->strided.u.s.normal.streamNo = 255;
1583     }
1584     if(patch->has_texcoords) {
1585         patch->strided.u.s.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1586         if(patch->has_normals) {
1587             patch->strided.u.s.texCoords[0].lpData += 3 * sizeof(float);
1588         }
1589         patch->strided.u.s.texCoords[0].dwStride = vtxStride;
1590         patch->strided.u.s.texCoords[0].dwType = WINED3DDECLTYPE_FLOAT4;
1591         /* MAX_STREAMS index points to an unused element in stateblock->streamOffsets which
1592          * always remains set to 0. Windows uses stream 255 here, but this is not visible to the
1593          * application.
1594          */
1595         patch->strided.u.s.texCoords[0].streamNo = MAX_STREAMS;
1596     }
1597
1598     return WINED3D_OK;
1599 }