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