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