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