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