d3dx9_36: Find, store and enable retreival of CTAB comment data in shader (based...
[wine] / dlls / wined3d / drawprim.c
1 /*
2  * WINED3D draw functions
3  *
4  * Copyright 2002-2004 Jason Edmeades
5  * Copyright 2002-2004 Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  * Copyright 2005 Oliver Stieber
8  * Copyright 2006, 2008 Henri Verbeet
9  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
10  * Copyright 2009 Henri Verbeet for CodeWeavers
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25  */
26
27 #include "config.h"
28 #include "wined3d_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
31 #define GLINFO_LOCATION This->adapter->gl_info
32
33 #include <stdio.h>
34 #include <math.h>
35
36 /* GL locking is done by the caller */
37 static void drawStridedFast(IWineD3DDevice *iface, GLenum primitive_type,
38         UINT count, UINT idx_size, const void *idx_data, UINT start_idx)
39 {
40     if (idx_size)
41     {
42         TRACE("(%p) : glElements(%x, %d, ...)\n", iface, primitive_type, count);
43
44         glDrawElements(primitive_type, count,
45                 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
46                 (const char *)idx_data + (idx_size * start_idx));
47         checkGLcall("glDrawElements");
48     }
49     else
50     {
51         TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", iface, primitive_type, start_idx, count);
52
53         glDrawArrays(primitive_type, start_idx, count);
54         checkGLcall("glDrawArrays");
55     }
56 }
57
58 /*
59  * Actually draw using the supplied information.
60  * Slower GL version which extracts info about each vertex in turn
61  */
62
63 /* GL locking is done by the caller */
64 static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_context *context,
65         const struct wined3d_stream_info *si, UINT NumVertexes, GLenum glPrimType,
66         const void *idxData, UINT idxSize, UINT startIdx)
67 {
68     unsigned int               textureNo    = 0;
69     const WORD                *pIdxBufS     = NULL;
70     const DWORD               *pIdxBufL     = NULL;
71     UINT vx_index;
72     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
73     const UINT *streamOffset = This->stateBlock->streamOffset;
74     long                      SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
75     BOOL                      pixelShader = use_ps(This->stateBlock);
76     BOOL specular_fog = FALSE;
77     const BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
78     const BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
79     const struct wined3d_gl_info *gl_info = context->gl_info;
80     UINT texture_stages = gl_info->limits.texture_stages;
81     const struct wined3d_stream_info_element *element;
82     UINT num_untracked_materials;
83     DWORD tex_mask = 0;
84
85     TRACE("Using slow vertex array code\n");
86
87     /* Variable Initialization */
88     if (idxSize != 0) {
89         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
90          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
91          * idxData will be != NULL
92          */
93         if(idxData == NULL) {
94             idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
95         }
96
97         if (idxSize == 2) pIdxBufS = idxData;
98         else pIdxBufL = idxData;
99     } else if (idxData) {
100         ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
101         return;
102     }
103
104     /* Start drawing in GL */
105     VTRACE(("glBegin(%x)\n", glPrimType));
106     glBegin(glPrimType);
107
108     if (si->use_map & (1 << WINED3D_FFP_POSITION))
109     {
110         element = &si->elements[WINED3D_FFP_POSITION];
111         position = element->data + streamOffset[element->stream_idx];
112     }
113
114     if (si->use_map & (1 << WINED3D_FFP_NORMAL))
115     {
116         element = &si->elements[WINED3D_FFP_NORMAL];
117         normal = element->data + streamOffset[element->stream_idx];
118     }
119     else
120     {
121         glNormal3f(0, 0, 0);
122     }
123
124     num_untracked_materials = context->num_untracked_materials;
125     if (si->use_map & (1 << WINED3D_FFP_DIFFUSE))
126     {
127         element = &si->elements[WINED3D_FFP_DIFFUSE];
128         diffuse = element->data + streamOffset[element->stream_idx];
129
130         if (num_untracked_materials && element->format_desc->format != WINED3DFMT_B8G8R8A8_UNORM)
131             FIXME("Implement diffuse color tracking from %s\n", debug_d3dformat(element->format_desc->format));
132     }
133     else
134     {
135         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
136     }
137
138     if (si->use_map & (1 << WINED3D_FFP_SPECULAR))
139     {
140         element = &si->elements[WINED3D_FFP_SPECULAR];
141         specular = element->data + streamOffset[element->stream_idx];
142
143         /* special case where the fog density is stored in the specular alpha channel */
144         if (This->stateBlock->renderState[WINED3DRS_FOGENABLE]
145                 && (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE
146                     || si->elements[WINED3D_FFP_POSITION].format_desc->format == WINED3DFMT_R32G32B32A32_FLOAT)
147                 && This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE)
148         {
149             if (gl_info->supported[EXT_FOG_COORD])
150             {
151                 if (element->format_desc->format == WINED3DFMT_B8G8R8A8_UNORM) specular_fog = TRUE;
152                 else FIXME("Implement fog coordinates from %s\n", debug_d3dformat(element->format_desc->format));
153             }
154             else
155             {
156                 static BOOL warned;
157
158                 if (!warned)
159                 {
160                     /* TODO: Use the fog table code from old ddraw */
161                     FIXME("Implement fog for transformed vertices in software\n");
162                     warned = TRUE;
163                 }
164             }
165         }
166     }
167     else if (gl_info->supported[EXT_SECONDARY_COLOR])
168     {
169         GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
170     }
171
172     for (textureNo = 0; textureNo < texture_stages; ++textureNo)
173     {
174         int coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
175         DWORD texture_idx = This->texUnitMap[textureNo];
176
177         if (!gl_info->supported[ARB_MULTITEXTURE] && textureNo > 0)
178         {
179             FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
180             continue;
181         }
182
183         if (!pixelShader && !This->stateBlock->textures[textureNo]) continue;
184
185         if (texture_idx == WINED3D_UNMAPPED_STAGE) continue;
186
187         if (coordIdx > 7)
188         {
189             TRACE("tex: %d - Skip tex coords, as being system generated\n", textureNo);
190             continue;
191         }
192         else if (coordIdx < 0)
193         {
194             FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
195             continue;
196         }
197
198         if (si->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + coordIdx)))
199         {
200             element = &si->elements[WINED3D_FFP_TEXCOORD0 + coordIdx];
201             texCoords[coordIdx] = element->data + streamOffset[element->stream_idx];
202             tex_mask |= (1 << textureNo);
203         }
204         else
205         {
206             TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
207             if (gl_info->supported[ARB_MULTITEXTURE])
208                 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
209             else
210                 glTexCoord4f(0, 0, 0, 1);
211         }
212     }
213
214     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
215      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
216      */
217
218     /* For each primitive */
219     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
220         UINT texture, tmp_tex_mask;
221         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
222          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
223          */
224
225         /* For indexed data, we need to go a few more strides in */
226         if (idxData != NULL) {
227
228             /* Indexed so work out the number of strides to skip */
229             if (idxSize == 2) {
230                 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufS[startIdx+vx_index]));
231                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
232             } else {
233                 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufL[startIdx+vx_index]));
234                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
235             }
236         }
237
238         tmp_tex_mask = tex_mask;
239         for (texture = 0; tmp_tex_mask; tmp_tex_mask >>= 1, ++texture)
240         {
241             int coord_idx;
242             const void *ptr;
243             DWORD texture_idx;
244
245             if (!(tmp_tex_mask & 1)) continue;
246
247             coord_idx = This->stateBlock->textureState[texture][WINED3DTSS_TEXCOORDINDEX];
248             ptr = texCoords[coord_idx] + (SkipnStrides * si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].stride);
249
250             texture_idx = This->texUnitMap[texture];
251             multi_texcoord_funcs[si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].format_desc->emit_idx](
252                     GL_TEXTURE0_ARB + texture_idx, ptr);
253         }
254
255         /* Diffuse -------------------------------- */
256         if (diffuse) {
257             const void *ptrToCoords = diffuse + SkipnStrides * si->elements[WINED3D_FFP_DIFFUSE].stride;
258
259             diffuse_funcs[si->elements[WINED3D_FFP_DIFFUSE].format_desc->emit_idx](ptrToCoords);
260             if (num_untracked_materials)
261             {
262                 DWORD diffuseColor = ((const DWORD *)ptrToCoords)[0];
263                 unsigned char i;
264                 float color[4];
265
266                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0f;
267                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0f;
268                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0f;
269                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0f;
270
271                 for (i = 0; i < num_untracked_materials; ++i)
272                 {
273                     glMaterialfv(GL_FRONT_AND_BACK, context->untracked_materials[i], color);
274                 }
275             }
276         }
277
278         /* Specular ------------------------------- */
279         if (specular) {
280             const void *ptrToCoords = specular + SkipnStrides * si->elements[WINED3D_FFP_SPECULAR].stride;
281
282             specular_funcs[si->elements[WINED3D_FFP_SPECULAR].format_desc->emit_idx](ptrToCoords);
283
284             if (specular_fog)
285             {
286                 DWORD specularColor = *(const DWORD *)ptrToCoords;
287                 GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
288             }
289         }
290
291         /* Normal -------------------------------- */
292         if (normal != NULL) {
293             const void *ptrToCoords = normal + SkipnStrides * si->elements[WINED3D_FFP_NORMAL].stride;
294             normal_funcs[si->elements[WINED3D_FFP_NORMAL].format_desc->emit_idx](ptrToCoords);
295         }
296
297         /* Position -------------------------------- */
298         if (position) {
299             const void *ptrToCoords = position + SkipnStrides * si->elements[WINED3D_FFP_POSITION].stride;
300             position_funcs[si->elements[WINED3D_FFP_POSITION].format_desc->emit_idx](ptrToCoords);
301         }
302
303         /* For non indexed mode, step onto next parts */
304         if (idxData == NULL) {
305             ++SkipnStrides;
306         }
307     }
308
309     glEnd();
310     checkGLcall("glEnd and previous calls");
311 }
312
313 /* GL locking is done by the caller */
314 static inline void send_attribute(IWineD3DDeviceImpl *This, WINED3DFORMAT format, const UINT index, const void *ptr)
315 {
316     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
317
318     switch(format)
319     {
320         case WINED3DFMT_R32_FLOAT:
321             GL_EXTCALL(glVertexAttrib1fvARB(index, ptr));
322             break;
323         case WINED3DFMT_R32G32_FLOAT:
324             GL_EXTCALL(glVertexAttrib2fvARB(index, ptr));
325             break;
326         case WINED3DFMT_R32G32B32_FLOAT:
327             GL_EXTCALL(glVertexAttrib3fvARB(index, ptr));
328             break;
329         case WINED3DFMT_R32G32B32A32_FLOAT:
330             GL_EXTCALL(glVertexAttrib4fvARB(index, ptr));
331             break;
332
333         case WINED3DFMT_R8G8B8A8_UINT:
334             GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
335             break;
336         case WINED3DFMT_B8G8R8A8_UNORM:
337             if (gl_info->supported[ARB_VERTEX_ARRAY_BGRA])
338             {
339                 const DWORD *src = ptr;
340                 DWORD c = *src & 0xff00ff00;
341                 c |= (*src & 0xff0000) >> 16;
342                 c |= (*src & 0xff) << 16;
343                 GL_EXTCALL(glVertexAttrib4NubvARB(index, (GLubyte *)&c));
344                 break;
345             }
346             /* else fallthrough */
347         case WINED3DFMT_R8G8B8A8_UNORM:
348             GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
349             break;
350
351         case WINED3DFMT_R16G16_SINT:
352             GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
353             break;
354         case WINED3DFMT_R16G16B16A16_SINT:
355             GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
356             break;
357
358         case WINED3DFMT_R16G16_SNORM:
359         {
360             GLshort s[4] = {((const GLshort *)ptr)[0], ((const GLshort *)ptr)[1], 0, 1};
361             GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
362             break;
363         }
364         case WINED3DFMT_R16G16_UNORM:
365         {
366             GLushort s[4] = {((const GLushort *)ptr)[0], ((const GLushort *)ptr)[1], 0, 1};
367             GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
368             break;
369         }
370         case WINED3DFMT_R16G16B16A16_SNORM:
371             GL_EXTCALL(glVertexAttrib4NsvARB(index, ptr));
372             break;
373         case WINED3DFMT_R16G16B16A16_UNORM:
374             GL_EXTCALL(glVertexAttrib4NusvARB(index, ptr));
375             break;
376
377         case WINED3DFMT_R10G10B10A2_UINT:
378             FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
379             /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
380             break;
381         case WINED3DFMT_R10G10B10A2_SNORM:
382             FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
383             /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
384             break;
385
386         case WINED3DFMT_R16G16_FLOAT:
387             /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
388              * byte float according to the IEEE standard
389              */
390             if (gl_info->supported[NV_HALF_FLOAT])
391             {
392                 /* Not supported by GL_ARB_half_float_vertex */
393                 GL_EXTCALL(glVertexAttrib2hvNV(index, ptr));
394             }
395             else
396             {
397                 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
398                 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
399                 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
400             }
401             break;
402         case WINED3DFMT_R16G16B16A16_FLOAT:
403             if (gl_info->supported[NV_HALF_FLOAT])
404             {
405                 /* Not supported by GL_ARB_half_float_vertex */
406                 GL_EXTCALL(glVertexAttrib4hvNV(index, ptr));
407             }
408             else
409             {
410                 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
411                 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
412                 float z = float_16_to_32(((const unsigned short *)ptr) + 2);
413                 float w = float_16_to_32(((const unsigned short *)ptr) + 3);
414                 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
415             }
416             break;
417
418         default:
419             ERR("Unexpected attribute format: %s\n", debug_d3dformat(format));
420             break;
421     }
422 }
423
424 /* GL locking is done by the caller */
425 static void drawStridedSlowVs(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT numberOfVertices,
426         GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT startIdx)
427 {
428     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
429     long                      SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
430     const WORD                *pIdxBufS     = NULL;
431     const DWORD               *pIdxBufL     = NULL;
432     UINT vx_index;
433     int i;
434     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
435     const BYTE *ptr;
436
437     if (idxSize != 0) {
438         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
439          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
440          * idxData will be != NULL
441          */
442         if(idxData == NULL) {
443             idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
444         }
445
446         if (idxSize == 2) pIdxBufS = idxData;
447         else pIdxBufL = idxData;
448     } else if (idxData) {
449         ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
450         return;
451     }
452
453     /* Start drawing in GL */
454     VTRACE(("glBegin(%x)\n", glPrimitiveType));
455     glBegin(glPrimitiveType);
456
457     for (vx_index = 0; vx_index < numberOfVertices; ++vx_index) {
458         if (idxData != NULL) {
459
460             /* Indexed so work out the number of strides to skip */
461             if (idxSize == 2) {
462                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
463                 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
464             } else {
465                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
466                 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
467             }
468         }
469
470         for (i = MAX_ATTRIBS - 1; i >= 0; i--)
471         {
472             if (!(si->use_map & (1 << i))) continue;
473
474             ptr = si->elements[i].data +
475                   si->elements[i].stride * SkipnStrides +
476                   stateblock->streamOffset[si->elements[i].stream_idx];
477
478             send_attribute(This, si->elements[i].format_desc->format, i, ptr);
479         }
480         SkipnStrides++;
481     }
482
483     glEnd();
484 }
485
486 /* GL locking is done by the caller */
487 static inline void drawStridedInstanced(IWineD3DDevice *iface, const struct wined3d_stream_info *si,
488         UINT numberOfVertices, GLenum glPrimitiveType, const void *idxData, UINT idxSize,
489         UINT startIdx)
490 {
491     UINT numInstances = 0, i;
492     int numInstancedAttribs = 0, j;
493     UINT instancedData[sizeof(si->elements) / sizeof(*si->elements) /* 16 */];
494     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
495     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
496
497     if (idxSize == 0) {
498         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
499          * We don't support this for now
500          *
501          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
502          * But the StreamSourceFreq value has a different meaning in that situation.
503          */
504         FIXME("Non-indexed instanced drawing is not supported\n");
505         return;
506     }
507
508     TRACE("(%p) : glElements(%x, %d, ...)\n", This, glPrimitiveType, numberOfVertices);
509
510     /* First, figure out how many instances we have to draw */
511     for(i = 0; i < MAX_STREAMS; i++) {
512         /* Look at the streams and take the first one which matches */
513         if(((stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) || (stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INDEXEDDATA)) && stateblock->streamSource[i]) {
514             /* D3D9 could set streamFreq 0 with (INSTANCEDATA or INDEXEDDATA) and then it is handled as 1. See d3d9/tests/visual.c-> stream_test() */
515             if(stateblock->streamFreq[i] == 0){
516                 numInstances = 1;
517             } else {
518                 numInstances = stateblock->streamFreq[i]; /* use the specified number of instances from the first matched stream. See d3d9/tests/visual.c-> stream_test() */
519             }
520             break; /* break, because only the first suitable value is interesting */
521         }
522     }
523
524     for (i = 0; i < sizeof(si->elements) / sizeof(*si->elements); ++i)
525     {
526         if (!(si->use_map & (1 << i))) continue;
527
528         if (stateblock->streamFlags[si->elements[i].stream_idx] & WINED3DSTREAMSOURCE_INSTANCEDATA)
529         {
530             instancedData[numInstancedAttribs] = i;
531             numInstancedAttribs++;
532         }
533     }
534
535     /* now draw numInstances instances :-) */
536     for(i = 0; i < numInstances; i++) {
537         /* Specify the instanced attributes using immediate mode calls */
538         for(j = 0; j < numInstancedAttribs; j++) {
539             const BYTE *ptr = si->elements[instancedData[j]].data +
540                         si->elements[instancedData[j]].stride * i +
541                         stateblock->streamOffset[si->elements[instancedData[j]].stream_idx];
542             if (si->elements[instancedData[j]].buffer_object)
543             {
544                 struct wined3d_buffer *vb =
545                         (struct wined3d_buffer *)stateblock->streamSource[si->elements[instancedData[j]].stream_idx];
546                 ptr += (long) buffer_get_sysmem(vb);
547             }
548
549             send_attribute(This, si->elements[instancedData[j]].format_desc->format, instancedData[j], ptr);
550         }
551
552         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
553                     (const char *)idxData+(idxSize * startIdx));
554         checkGLcall("glDrawElements");
555     }
556 }
557
558 static inline void remove_vbos(IWineD3DDeviceImpl *This, struct wined3d_stream_info *s)
559 {
560     unsigned int i;
561
562     for (i = 0; i < (sizeof(s->elements) / sizeof(*s->elements)); ++i)
563     {
564         struct wined3d_stream_info_element *e;
565
566         if (!(s->use_map & (1 << i))) continue;
567
568         e = &s->elements[i];
569         if (e->buffer_object)
570         {
571             struct wined3d_buffer *vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
572             e->buffer_object = 0;
573             e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
574         }
575     }
576 }
577
578 /* Routine common to the draw primitive and draw indexed primitive routines */
579 void drawPrimitive(IWineD3DDevice *iface, UINT index_count, UINT StartIdx, UINT idxSize, const void *idxData)
580 {
581
582     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
583     IWineD3DSurfaceImpl          *target;
584     struct wined3d_context *context;
585     unsigned int i;
586
587     if (!index_count) return;
588
589     if (This->stateBlock->renderState[WINED3DRS_COLORWRITEENABLE])
590     {
591         /* Invalidate the back buffer memory so LockRect will read it the next time */
592         for (i = 0; i < This->adapter->gl_info.limits.buffers; ++i)
593         {
594             target = (IWineD3DSurfaceImpl *)This->render_targets[i];
595             if (target)
596             {
597                 IWineD3DSurface_LoadLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, NULL);
598                 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, TRUE);
599             }
600         }
601     }
602
603     /* Signals other modules that a drawing is in progress and the stateblock finalized */
604     This->isInDraw = TRUE;
605
606     context = context_acquire(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
607
608     if (This->stencilBufferTarget) {
609         /* Note that this depends on the context_acquire() call above to set
610          * This->render_offscreen properly. We don't currently take the
611          * Z-compare function into account, but we could skip loading the
612          * depthstencil for D3DCMP_NEVER and D3DCMP_ALWAYS as well. Also note
613          * that we never copy the stencil data.*/
614         DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
615         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE]
616                 || This->stateBlock->renderState[WINED3DRS_ZENABLE])
617             surface_load_ds_location(This->stencilBufferTarget, context, location);
618         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE])
619             surface_modify_ds_location(This->stencilBufferTarget, location);
620     }
621
622     /* Ok, we will be updating the screen from here onwards so grab the lock */
623     ENTER_GL();
624     {
625         GLenum glPrimType = This->stateBlock->gl_primitive_type;
626         BOOL emulation = FALSE;
627         const struct wined3d_stream_info *stream_info = &This->strided_streams;
628         struct wined3d_stream_info stridedlcl;
629
630         if (!use_vs(This->stateBlock))
631         {
632             if (!This->strided_streams.position_transformed && context->num_untracked_materials
633                     && This->stateBlock->renderState[WINED3DRS_LIGHTING])
634             {
635                 static BOOL warned;
636                 if (!warned) {
637                     FIXME("Using software emulation because not all material properties could be tracked\n");
638                     warned = TRUE;
639                 } else {
640                     TRACE("Using software emulation because not all material properties could be tracked\n");
641                 }
642                 emulation = TRUE;
643             }
644             else if (context->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE])
645             {
646                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
647                  * to a float in the vertex buffer
648                  */
649                 static BOOL warned;
650                 if (!warned) {
651                     FIXME("Using software emulation because manual fog coordinates are provided\n");
652                     warned = TRUE;
653                 } else {
654                     TRACE("Using software emulation because manual fog coordinates are provided\n");
655                 }
656                 emulation = TRUE;
657             }
658
659             if(emulation) {
660                 stream_info = &stridedlcl;
661                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
662                 remove_vbos(This, &stridedlcl);
663             }
664         }
665
666         if (This->useDrawStridedSlow || emulation) {
667             /* Immediate mode drawing */
668             if (use_vs(This->stateBlock))
669             {
670                 static BOOL warned;
671                 if (!warned) {
672                     FIXME("Using immediate mode with vertex shaders for half float emulation\n");
673                     warned = TRUE;
674                 } else {
675                     TRACE("Using immediate mode with vertex shaders for half float emulation\n");
676                 }
677                 drawStridedSlowVs(iface, stream_info, index_count, glPrimType, idxData, idxSize, StartIdx);
678             } else {
679                 drawStridedSlow(iface, context, stream_info, index_count,
680                         glPrimType, idxData, idxSize, StartIdx);
681             }
682         } else if(This->instancedDraw) {
683             /* Instancing emulation with mixing immediate mode and arrays */
684             drawStridedInstanced(iface, &This->strided_streams, index_count,
685                     glPrimType, idxData, idxSize, StartIdx);
686         } else {
687             drawStridedFast(iface, glPrimType, index_count, idxSize, idxData, StartIdx);
688         }
689     }
690
691     /* Finished updating the screen, restore lock */
692     LEAVE_GL();
693
694     wglFlush(); /* Flush to ensure ordering across contexts. */
695
696     context_release(context);
697
698     TRACE("Done all gl drawing\n");
699
700     /* Diagnostics */
701 #ifdef SHOW_FRAME_MAKEUP
702     {
703         static long int primCounter = 0;
704         /* NOTE: set primCounter to the value reported by drawprim
705            before you want to to write frame makeup to /tmp */
706         if (primCounter >= 0) {
707             WINED3DLOCKED_RECT r;
708             char buffer[80];
709             IWineD3DSurface_LockRect(This->render_targets[0], &r, NULL, WINED3DLOCK_READONLY);
710             sprintf(buffer, "/tmp/backbuffer_%ld.tga", primCounter);
711             TRACE("Saving screenshot %s\n", buffer);
712             IWineD3DSurface_SaveSnapshot(This->render_targets[0], buffer);
713             IWineD3DSurface_UnlockRect(This->render_targets[0]);
714
715 #ifdef SHOW_TEXTURE_MAKEUP
716            {
717             IWineD3DSurface *pSur;
718             int textureNo;
719             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
720                 if (This->stateBlock->textures[textureNo] != NULL) {
721                     sprintf(buffer, "/tmp/texture_%p_%ld_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
722                     TRACE("Saving texture %s\n", buffer);
723                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
724                             IWineD3DTexture_GetSurfaceLevel(This->stateBlock->textures[textureNo], 0, &pSur);
725                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
726                             IWineD3DSurface_Release(pSur);
727                     } else  {
728                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
729                     }
730                 }
731             }
732            }
733 #endif
734         }
735         TRACE("drawprim #%ld\n", primCounter);
736         ++primCounter;
737     }
738 #endif
739
740     /* Control goes back to the device, stateblock values may change again */
741     This->isInDraw = FALSE;
742 }
743
744 static void normalize_normal(float *n) {
745     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
746     if (length == 0.0f) return;
747     length = sqrt(length);
748     n[0] = n[0] / length;
749     n[1] = n[1] / length;
750     n[2] = n[2] / length;
751 }
752
753 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
754  *
755  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
756  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
757  * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
758  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
759  * in drawprim.
760  *
761  * To read back, the opengl feedback mode is used. This creates a problem because we want
762  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
763  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
764  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
765  * them to [-1.0;+1.0] and set the viewport up to scale them back.
766  *
767  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
768  * resulting colors back to the normals.
769  *
770  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
771  * does not restore it because normally a draw follows immediately afterwards. The caller is
772  * responsible of taking care that either the gl states are restored, or the context activated
773  * for drawing to reset the lastWasBlit flag.
774  */
775 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
776                             struct WineD3DRectPatch *patch) {
777     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
778     float max_x = 0.0f, max_y = 0.0f, max_z = 0.0f, neg_z = 0.0f;
779     struct wined3d_stream_info stream_info;
780     struct wined3d_stream_info_element *e;
781     struct wined3d_context *context;
782     const BYTE *data;
783     const WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
784     DWORD vtxStride;
785     GLenum feedback_type;
786     GLfloat *feedbuffer;
787
788     /* Simply activate the context for blitting. This disables all the things we don't want and
789      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
790      * patch (as opposed to normal draws) will most likely need different changes anyway. */
791     context = context_acquire(This, NULL, CTXUSAGE_BLIT);
792
793     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
794      * Beware of vbos
795      */
796     device_stream_info_from_declaration(This, FALSE, &stream_info, NULL);
797
798     e = &stream_info.elements[WINED3D_FFP_POSITION];
799     if (e->buffer_object)
800     {
801         struct wined3d_buffer *vb;
802         vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
803         e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
804     }
805     vtxStride = e->stride;
806     data = e->data +
807            vtxStride * info->Stride * info->StartVertexOffsetHeight +
808            vtxStride * info->StartVertexOffsetWidth;
809
810     /* Not entirely sure about what happens with transformed vertices */
811     if (stream_info.position_transformed) FIXME("Transformed position in rectpatch generation\n");
812
813     if(vtxStride % sizeof(GLfloat)) {
814         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
815          * I don't see how the stride could not be a multiple of 4, but make sure
816          * to check it
817          */
818         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
819     }
820     if(info->Basis != WINED3DBASIS_BEZIER) {
821         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
822     }
823     if(info->Degree != WINED3DDEGREE_CUBIC) {
824         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
825     }
826
827     /* First, get the boundary cube of the input data */
828     for(j = 0; j < info->Height; j++) {
829         for(i = 0; i < info->Width; i++) {
830             const float *v = (const float *)(data + vtxStride * i + vtxStride * info->Stride * j);
831             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
832             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
833             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
834             if(v[2] < neg_z) neg_z = v[2];
835         }
836     }
837
838     /* This needs some improvements in the vertex decl code */
839     FIXME("Cannot find data to generate. Only generating position and normals\n");
840     patch->has_normals = TRUE;
841     patch->has_texcoords = FALSE;
842
843     ENTER_GL();
844
845     glMatrixMode(GL_PROJECTION);
846     checkGLcall("glMatrixMode(GL_PROJECTION)");
847     glLoadIdentity();
848     checkGLcall("glLoadIndentity()");
849     glScalef(1.0f / (max_x), 1.0f / (max_y), max_z == 0.0f ? 1.0f : 1.0f / (2.0f * max_z));
850     glTranslatef(0.0f, 0.0f, 0.5f);
851     checkGLcall("glScalef");
852     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
853     checkGLcall("glViewport");
854
855     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
856      * our feedback buffer parser
857      */
858     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
859     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
860     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
861     if(patch->has_normals) {
862         static const GLfloat black[] = {0.0f, 0.0f, 0.0f, 0.0f};
863         static const GLfloat red[]   = {1.0f, 0.0f, 0.0f, 0.0f};
864         static const GLfloat green[] = {0.0f, 1.0f, 0.0f, 0.0f};
865         static const GLfloat blue[]  = {0.0f, 0.0f, 1.0f, 0.0f};
866         static const GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
867         glEnable(GL_LIGHTING);
868         checkGLcall("glEnable(GL_LIGHTING)");
869         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
870         checkGLcall("glLightModel for MODEL_AMBIENT");
871         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
872
873         for (i = 3; i < context->gl_info->limits.lights; ++i)
874         {
875             glDisable(GL_LIGHT0 + i);
876             checkGLcall("glDisable(GL_LIGHT0 + i)");
877             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
878         }
879
880         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
881         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
882         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
883         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
884         glLightfv(GL_LIGHT0, GL_POSITION, red);
885         glEnable(GL_LIGHT0);
886         checkGLcall("Setting up light 1");
887         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
888         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
889         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
890         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
891         glLightfv(GL_LIGHT1, GL_POSITION, green);
892         glEnable(GL_LIGHT1);
893         checkGLcall("Setting up light 2");
894         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
895         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
896         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
897         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
898         glLightfv(GL_LIGHT2, GL_POSITION, blue);
899         glEnable(GL_LIGHT2);
900         checkGLcall("Setting up light 3");
901
902         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
903         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
904         glDisable(GL_COLOR_MATERIAL);
905         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
906         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
907         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
908         checkGLcall("Setting up materials");
909     }
910
911     /* Enable the needed maps.
912      * GL_MAP2_VERTEX_3 is needed for positional data.
913      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
914      * GL_MAP2_TEXTURE_COORD_4 for texture coords
915      */
916     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
917     out_vertex_size = 3 /* position */;
918     d3d_out_vertex_size = 3;
919     glEnable(GL_MAP2_VERTEX_3);
920     if(patch->has_normals && patch->has_texcoords) {
921         FIXME("Texcoords not handled yet\n");
922         feedback_type = GL_3D_COLOR_TEXTURE;
923         out_vertex_size += 8;
924         d3d_out_vertex_size += 7;
925         glEnable(GL_AUTO_NORMAL);
926         glEnable(GL_MAP2_TEXTURE_COORD_4);
927     } else if(patch->has_texcoords) {
928         FIXME("Texcoords not handled yet\n");
929         feedback_type = GL_3D_COLOR_TEXTURE;
930         out_vertex_size += 7;
931         d3d_out_vertex_size += 4;
932         glEnable(GL_MAP2_TEXTURE_COORD_4);
933     } else if(patch->has_normals) {
934         feedback_type = GL_3D_COLOR;
935         out_vertex_size += 4;
936         d3d_out_vertex_size += 3;
937         glEnable(GL_AUTO_NORMAL);
938     } else {
939         feedback_type = GL_3D;
940     }
941     checkGLcall("glEnable vertex attrib generation");
942
943     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
944                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
945     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
946
947     glMap2f(GL_MAP2_VERTEX_3,
948             0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
949             0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
950             (const GLfloat *)data);
951     checkGLcall("glMap2f");
952     if(patch->has_texcoords) {
953         glMap2f(GL_MAP2_TEXTURE_COORD_4,
954                 0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
955                 0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
956                 (const GLfloat *)data);
957         checkGLcall("glMap2f");
958     }
959     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0f, 1.0f, ceilf(patch->numSegs[1]), 0.0f, 1.0f);
960     checkGLcall("glMapGrid2f");
961
962     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
963     checkGLcall("glFeedbackBuffer");
964     glRenderMode(GL_FEEDBACK);
965
966     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
967     checkGLcall("glEvalMesh2");
968
969     i = glRenderMode(GL_RENDER);
970     if(i == -1) {
971         LEAVE_GL();
972         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
973         HeapFree(GetProcessHeap(), 0, feedbuffer);
974         context_release(context);
975         return WINED3DERR_DRIVERINTERNALERROR;
976     } else if(i != buffer_size) {
977         LEAVE_GL();
978         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
979         HeapFree(GetProcessHeap(), 0, feedbuffer);
980         context_release(context);
981         return WINED3DERR_DRIVERINTERNALERROR;
982     } else {
983         TRACE("Got %d elements as expected\n", i);
984     }
985
986     HeapFree(GetProcessHeap(), 0, patch->mem);
987     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
988     i = 0;
989     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
990         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
991             ERR("Unexpected token: %f\n", feedbuffer[j]);
992             continue;
993         }
994         if(feedbuffer[j + 1] != 3) {
995             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
996             continue;
997         }
998         /* Somehow there are different ideas about back / front facing, so fix up the
999          * vertex order
1000          */
1001         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1002         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1003         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 3 */
1004         if(patch->has_normals) {
1005             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1006             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1007             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1008         }
1009         i += d3d_out_vertex_size;
1010
1011         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1012         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1013         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 2 */
1014         if(patch->has_normals) {
1015             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1016             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1017             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1018         }
1019         i += d3d_out_vertex_size;
1020
1021         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1022         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1023         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 1 */
1024         if(patch->has_normals) {
1025             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1026             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1027             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1028         }
1029         i += d3d_out_vertex_size;
1030     }
1031
1032     if(patch->has_normals) {
1033         /* Now do the same with reverse light directions */
1034         static const GLfloat x[] = {-1.0f,  0.0f,  0.0f, 0.0f};
1035         static const GLfloat y[] = { 0.0f, -1.0f,  0.0f, 0.0f};
1036         static const GLfloat z[] = { 0.0f,  0.0f, -1.0f, 0.0f};
1037         glLightfv(GL_LIGHT0, GL_POSITION, x);
1038         glLightfv(GL_LIGHT1, GL_POSITION, y);
1039         glLightfv(GL_LIGHT2, GL_POSITION, z);
1040         checkGLcall("Setting up reverse light directions");
1041
1042         glRenderMode(GL_FEEDBACK);
1043         checkGLcall("glRenderMode(GL_FEEDBACK)");
1044         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1045         checkGLcall("glEvalMesh2");
1046         i = glRenderMode(GL_RENDER);
1047         checkGLcall("glRenderMode(GL_RENDER)");
1048
1049         i = 0;
1050         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1051             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1052                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1053                 continue;
1054             }
1055             if(feedbuffer[j + 1] != 3) {
1056                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1057                 continue;
1058             }
1059             if(patch->mem[i + 3] == 0.0f)
1060                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1061             if(patch->mem[i + 4] == 0.0f)
1062                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1063             if(patch->mem[i + 5] == 0.0f)
1064                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1065             normalize_normal(patch->mem + i + 3);
1066             i += d3d_out_vertex_size;
1067
1068             if(patch->mem[i + 3] == 0.0f)
1069                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1070             if(patch->mem[i + 4] == 0.0f)
1071                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1072             if(patch->mem[i + 5] == 0.0f)
1073                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1074             normalize_normal(patch->mem + i + 3);
1075             i += d3d_out_vertex_size;
1076
1077             if(patch->mem[i + 3] == 0.0f)
1078                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1079             if(patch->mem[i + 4] == 0.0f)
1080                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1081             if(patch->mem[i + 5] == 0.0f)
1082                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1083             normalize_normal(patch->mem + i + 3);
1084             i += d3d_out_vertex_size;
1085         }
1086     }
1087
1088     glDisable(GL_MAP2_VERTEX_3);
1089     glDisable(GL_AUTO_NORMAL);
1090     glDisable(GL_MAP2_NORMAL);
1091     glDisable(GL_MAP2_TEXTURE_COORD_4);
1092     checkGLcall("glDisable vertex attrib generation");
1093     LEAVE_GL();
1094
1095     context_release(context);
1096
1097     HeapFree(GetProcessHeap(), 0, feedbuffer);
1098
1099     vtxStride = 3 * sizeof(float);
1100     if(patch->has_normals) {
1101         vtxStride += 3 * sizeof(float);
1102     }
1103     if(patch->has_texcoords) {
1104         vtxStride += 4 * sizeof(float);
1105     }
1106     memset(&patch->strided, 0, sizeof(patch->strided));
1107     patch->strided.position.format = WINED3DFMT_R32G32B32_FLOAT;
1108     patch->strided.position.lpData = (BYTE *) patch->mem;
1109     patch->strided.position.dwStride = vtxStride;
1110
1111     if(patch->has_normals) {
1112         patch->strided.normal.format = WINED3DFMT_R32G32B32_FLOAT;
1113         patch->strided.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1114         patch->strided.normal.dwStride = vtxStride;
1115     }
1116     if(patch->has_texcoords) {
1117         patch->strided.texCoords[0].format = WINED3DFMT_R32G32B32A32_FLOAT;
1118         patch->strided.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1119         if(patch->has_normals) {
1120             patch->strided.texCoords[0].lpData += 3 * sizeof(float);
1121         }
1122         patch->strided.texCoords[0].dwStride = vtxStride;
1123     }
1124
1125     return WINED3D_OK;
1126 }