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