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