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