spoolss: Implement GetPrinterDriverDirectoryW.
[wine] / dlls / wined3d / glsl_shader.c
1 /*
2  * GLSL pixel and vertex shader implementation
3  *
4  * Copyright 2006 Jason Green 
5  * Copyright 2006-2007 Henri Verbeet
6  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /*
24  * D3D shader asm has swizzles on source parameters, and write masks for
25  * destination parameters. GLSL uses swizzles for both. The result of this is
26  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
27  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
28  * mask for the destination parameter into account.
29  */
30
31 #include "config.h"
32 #include <limits.h>
33 #include <stdio.h>
34 #include "wined3d_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d);
40
41 #define GLINFO_LOCATION      (*gl_info)
42
43 typedef struct {
44     char reg_name[150];
45     char mask_str[6];
46 } glsl_dst_param_t;
47
48 typedef struct {
49     char reg_name[150];
50     char param_str[100];
51 } glsl_src_param_t;
52
53 typedef struct {
54     const char *name;
55     DWORD coord_mask;
56 } glsl_sample_function_t;
57
58 enum heap_node_op
59 {
60     HEAP_NODE_TRAVERSE_LEFT,
61     HEAP_NODE_TRAVERSE_RIGHT,
62     HEAP_NODE_POP,
63 };
64
65 struct constant_entry
66 {
67     unsigned int idx;
68     unsigned int version;
69 };
70
71 struct constant_heap
72 {
73     struct constant_entry *entries;
74     unsigned int *positions;
75     unsigned int size;
76 };
77
78 /* GLSL shader private data */
79 struct shader_glsl_priv {
80     struct hash_table_t *glsl_program_lookup;
81     struct glsl_shader_prog_link *glsl_program;
82     struct constant_heap vconst_heap;
83     struct constant_heap pconst_heap;
84     unsigned char *stack;
85     GLhandleARB depth_blt_program[tex_type_count];
86     UINT next_constant_version;
87 };
88
89 /* Struct to maintain data about a linked GLSL program */
90 struct glsl_shader_prog_link {
91     struct list                 vshader_entry;
92     struct list                 pshader_entry;
93     GLhandleARB                 programId;
94     GLhandleARB                 *vuniformF_locations;
95     GLhandleARB                 *puniformF_locations;
96     GLhandleARB                 vuniformI_locations[MAX_CONST_I];
97     GLhandleARB                 puniformI_locations[MAX_CONST_I];
98     GLhandleARB                 posFixup_location;
99     GLhandleARB                 bumpenvmat_location[MAX_TEXTURES];
100     GLhandleARB                 luminancescale_location[MAX_TEXTURES];
101     GLhandleARB                 luminanceoffset_location[MAX_TEXTURES];
102     GLhandleARB                 ycorrection_location;
103     GLenum                      vertex_color_clamp;
104     IWineD3DVertexShader        *vshader;
105     IWineD3DPixelShader         *pshader;
106     struct vs_compile_args      vs_args;
107     struct ps_compile_args      ps_args;
108     UINT                        constant_version;
109 };
110
111 typedef struct {
112     IWineD3DVertexShader        *vshader;
113     IWineD3DPixelShader         *pshader;
114     struct ps_compile_args      ps_args;
115     struct vs_compile_args      vs_args;
116 } glsl_program_key_t;
117
118
119 /** Prints the GLSL info log which will contain error messages if they exist */
120 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
121 {
122     int infologLength = 0;
123     char *infoLog;
124     unsigned int i;
125     BOOL is_spam;
126
127     static const char * const spam[] =
128     {
129         "Vertex shader was successfully compiled to run on hardware.\n",    /* fglrx          */
130         "Fragment shader was successfully compiled to run on hardware.\n",  /* fglrx          */
131         "Fragment shader(s) linked, vertex shader(s) linked. \n ",          /* fglrx, with \n */
132         "Fragment shader(s) linked, vertex shader(s) linked.",              /* fglrx, no \n   */
133         "Vertex shader(s) linked, no fragment shader(s) defined. \n ",      /* fglrx, with \n */
134         "Vertex shader(s) linked, no fragment shader(s) defined.",          /* fglrx, no \n   */
135         "Fragment shader was successfully compiled to run on hardware.\n"
136         "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
137         "Fragment shader(s) linked, no vertex shader(s) defined.",          /* fglrx, no \n   */
138         "Fragment shader(s) linked, no vertex shader(s) defined. \n ",      /* fglrx, with \n */
139         "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n"  /* MacOS ati      */
140     };
141
142     if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
143
144     GL_EXTCALL(glGetObjectParameterivARB(obj,
145                GL_OBJECT_INFO_LOG_LENGTH_ARB,
146                &infologLength));
147
148     /* A size of 1 is just a null-terminated string, so the log should be bigger than
149      * that if there are errors. */
150     if (infologLength > 1)
151     {
152         /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
153          * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
154          */
155         infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
156         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
157         is_spam = FALSE;
158
159         for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
160             if(strcmp(infoLog, spam[i]) == 0) {
161                 is_spam = TRUE;
162                 break;
163             }
164         }
165         if(is_spam) {
166             TRACE("Spam received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
167         } else {
168             FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
169         }
170         HeapFree(GetProcessHeap(), 0, infoLog);
171     }
172 }
173
174 /**
175  * Loads (pixel shader) samplers
176  */
177 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, IWineD3DStateBlock *iface, GLhandleARB programId)
178 {
179     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
180     GLhandleARB name_loc;
181     int i;
182     char sampler_name[20];
183
184     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
185         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
186         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
187         if (name_loc != -1) {
188             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
189             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
190                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
191                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
192                 checkGLcall("glUniform1iARB");
193             } else {
194                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
195             }
196         }
197     }
198 }
199
200 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, IWineD3DStateBlock *iface, GLhandleARB programId)
201 {
202     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
203     GLhandleARB name_loc;
204     char sampler_name[20];
205     int i;
206
207     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
208         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
209         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
210         if (name_loc != -1) {
211             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
212             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
213                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
214                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
215                 checkGLcall("glUniform1iARB");
216             } else {
217                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
218             }
219         }
220     }
221 }
222
223 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
224         const GLhandleARB *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
225 {
226     int stack_idx = 0;
227     unsigned int heap_idx = 1;
228     unsigned int idx;
229
230     if (heap->entries[heap_idx].version <= version) return;
231
232     idx = heap->entries[heap_idx].idx;
233     if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
234     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
235
236     while (stack_idx >= 0)
237     {
238         /* Note that we fall through to the next case statement. */
239         switch(stack[stack_idx])
240         {
241             case HEAP_NODE_TRAVERSE_LEFT:
242             {
243                 unsigned int left_idx = heap_idx << 1;
244                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
245                 {
246                     heap_idx = left_idx;
247                     idx = heap->entries[heap_idx].idx;
248                     if (constant_locations[idx] != -1)
249                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
250
251                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
252                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
253                     break;
254                 }
255             }
256
257             case HEAP_NODE_TRAVERSE_RIGHT:
258             {
259                 unsigned int right_idx = (heap_idx << 1) + 1;
260                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
261                 {
262                     heap_idx = right_idx;
263                     idx = heap->entries[heap_idx].idx;
264                     if (constant_locations[idx] != -1)
265                         GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
266
267                     stack[stack_idx++] = HEAP_NODE_POP;
268                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
269                     break;
270                 }
271             }
272
273             case HEAP_NODE_POP:
274             {
275                 heap_idx >>= 1;
276                 --stack_idx;
277                 break;
278             }
279         }
280     }
281     checkGLcall("walk_constant_heap()");
282 }
283
284 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
285 {
286     GLfloat clamped_constant[4];
287
288     if (location == -1) return;
289
290     clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
291     clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
292     clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
293     clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
294
295     GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
296 }
297
298 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
299         const GLhandleARB *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
300 {
301     int stack_idx = 0;
302     unsigned int heap_idx = 1;
303     unsigned int idx;
304
305     if (heap->entries[heap_idx].version <= version) return;
306
307     idx = heap->entries[heap_idx].idx;
308     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
309     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
310
311     while (stack_idx >= 0)
312     {
313         /* Note that we fall through to the next case statement. */
314         switch(stack[stack_idx])
315         {
316             case HEAP_NODE_TRAVERSE_LEFT:
317             {
318                 unsigned int left_idx = heap_idx << 1;
319                 if (left_idx < heap->size && heap->entries[left_idx].version > version)
320                 {
321                     heap_idx = left_idx;
322                     idx = heap->entries[heap_idx].idx;
323                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
324
325                     stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
326                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
327                     break;
328                 }
329             }
330
331             case HEAP_NODE_TRAVERSE_RIGHT:
332             {
333                 unsigned int right_idx = (heap_idx << 1) + 1;
334                 if (right_idx < heap->size && heap->entries[right_idx].version > version)
335                 {
336                     heap_idx = right_idx;
337                     idx = heap->entries[heap_idx].idx;
338                     apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
339
340                     stack[stack_idx++] = HEAP_NODE_POP;
341                     stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
342                     break;
343                 }
344             }
345
346             case HEAP_NODE_POP:
347             {
348                 heap_idx >>= 1;
349                 --stack_idx;
350                 break;
351             }
352         }
353     }
354     checkGLcall("walk_constant_heap_clamped()");
355 }
356
357 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
358 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
359         const float *constants, const GLhandleARB *constant_locations, const struct constant_heap *heap,
360         unsigned char *stack, UINT version)
361 {
362     const local_constant *lconst;
363
364     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
365     if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.reg_maps.shader_version) == 1
366             && shader_is_pshader_version(This->baseShader.reg_maps.shader_version))
367         walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
368     else
369         walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
370
371     if (!This->baseShader.load_local_constsF)
372     {
373         TRACE("No need to load local float constants for this shader\n");
374         return;
375     }
376
377     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
378     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
379     {
380         GLhandleARB location = constant_locations[lconst->idx];
381         /* We found this uniform name in the program - go ahead and send the data */
382         if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
383     }
384     checkGLcall("glUniform4fvARB()");
385 }
386
387 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
388 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
389         const GLhandleARB locations[MAX_CONST_I], const int *constants, WORD constants_set)
390 {
391     unsigned int i;
392     struct list* ptr;
393
394     for (i = 0; constants_set; constants_set >>= 1, ++i)
395     {
396         if (!(constants_set & 1)) continue;
397
398         TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
399                 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
400
401         /* We found this uniform name in the program - go ahead and send the data */
402         GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
403         checkGLcall("glUniform4ivARB");
404     }
405
406     /* Load immediate constants */
407     ptr = list_head(&This->baseShader.constantsI);
408     while (ptr) {
409         const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
410         unsigned int idx = lconst->idx;
411         const GLint *values = (const GLint *)lconst->value;
412
413         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
414             values[0], values[1], values[2], values[3]);
415
416         /* We found this uniform name in the program - go ahead and send the data */
417         GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
418         checkGLcall("glUniform4ivARB");
419         ptr = list_next(&This->baseShader.constantsI, ptr);
420     }
421 }
422
423 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
424 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
425         GLhandleARB programId, const BOOL *constants, WORD constants_set)
426 {
427     GLhandleARB tmp_loc;
428     unsigned int i;
429     char tmp_name[8];
430     char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
431     const char* prefix = is_pshader? "PB":"VB";
432     struct list* ptr;
433
434     /* TODO: Benchmark and see if it would be beneficial to store the
435      * locations of the constants to avoid looking up each time */
436     for (i = 0; constants_set; constants_set >>= 1, ++i)
437     {
438         if (!(constants_set & 1)) continue;
439
440         TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
441
442         /* TODO: Benchmark and see if it would be beneficial to store the
443          * locations of the constants to avoid looking up each time */
444         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
445         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
446         if (tmp_loc != -1)
447         {
448             /* We found this uniform name in the program - go ahead and send the data */
449             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
450             checkGLcall("glUniform1ivARB");
451         }
452     }
453
454     /* Load immediate constants */
455     ptr = list_head(&This->baseShader.constantsB);
456     while (ptr) {
457         const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
458         unsigned int idx = lconst->idx;
459         const GLint *values = (const GLint *)lconst->value;
460
461         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
462
463         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
464         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
465         if (tmp_loc != -1) {
466             /* We found this uniform name in the program - go ahead and send the data */
467             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
468             checkGLcall("glUniform1ivARB");
469         }
470         ptr = list_next(&This->baseShader.constantsB, ptr);
471     }
472 }
473
474 static void reset_program_constant_version(void *value, void *context)
475 {
476     struct glsl_shader_prog_link *entry = value;
477     entry->constant_version = 0;
478 }
479
480 /**
481  * Loads the app-supplied constants into the currently set GLSL program.
482  */
483 static void shader_glsl_load_constants(
484     IWineD3DDevice* device,
485     char usePixelShader,
486     char useVertexShader) {
487    
488     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
489     struct shader_glsl_priv *priv = deviceImpl->shader_priv;
490     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
491     const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
492
493     GLhandleARB programId;
494     struct glsl_shader_prog_link *prog = priv->glsl_program;
495     UINT constant_version;
496     int i;
497
498     if (!prog) {
499         /* No GLSL program set - nothing to do. */
500         return;
501     }
502     programId = prog->programId;
503     constant_version = prog->constant_version;
504
505     if (useVertexShader) {
506         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
507
508         /* Load DirectX 9 float constants/uniforms for vertex shader */
509         shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
510                 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
511
512         /* Load DirectX 9 integer constants/uniforms for vertex shader */
513         if(vshader->baseShader.uses_int_consts) {
514             shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations,
515                     stateBlock->vertexShaderConstantI, stateBlock->changed.vertexShaderConstantsI);
516         }
517
518         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
519         if(vshader->baseShader.uses_bool_consts) {
520             shader_glsl_load_constantsB(vshader, gl_info, programId,
521                     stateBlock->vertexShaderConstantB, stateBlock->changed.vertexShaderConstantsB);
522         }
523
524         /* Upload the position fixup params */
525         GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
526         checkGLcall("glUniform4fvARB");
527     }
528
529     if (usePixelShader) {
530
531         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
532
533         /* Load DirectX 9 float constants/uniforms for pixel shader */
534         shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
535                 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
536
537         /* Load DirectX 9 integer constants/uniforms for pixel shader */
538         if(pshader->baseShader.uses_int_consts) {
539             shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations,
540                     stateBlock->pixelShaderConstantI, stateBlock->changed.pixelShaderConstantsI);
541         }
542
543         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
544         if(pshader->baseShader.uses_bool_consts) {
545             shader_glsl_load_constantsB(pshader, gl_info, programId,
546                     stateBlock->pixelShaderConstantB, stateBlock->changed.pixelShaderConstantsB);
547         }
548
549         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
550          * It can't be 0 for a valid texbem instruction.
551          */
552         for(i = 0; i < ((IWineD3DPixelShaderImpl *) pshader)->numbumpenvmatconsts; i++) {
553             IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pshader;
554             int stage = ps->luminanceconst[i].texunit;
555
556             const float *data = (const float *)&stateBlock->textureState[(int)ps->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
557             GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
558             checkGLcall("glUniformMatrix2fvARB");
559
560             /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
561              * is set too, so we can check that in the needsbumpmat check
562              */
563             if(ps->baseShader.reg_maps.luminanceparams[stage]) {
564                 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
565                 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
566
567                 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
568                 checkGLcall("glUniform1fvARB");
569                 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
570                 checkGLcall("glUniform1fvARB");
571             }
572         }
573
574         if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
575             float correction_params[4];
576             if(deviceImpl->render_offscreen) {
577                 correction_params[0] = 0.0;
578                 correction_params[1] = 1.0;
579             } else {
580                 /* position is window relative, not viewport relative */
581                 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
582                 correction_params[1] = -1.0;
583             }
584             GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
585         }
586     }
587
588     if (priv->next_constant_version == UINT_MAX)
589     {
590         TRACE("Max constant version reached, resetting to 0.\n");
591         hash_table_for_each_entry(priv->glsl_program_lookup, reset_program_constant_version, NULL);
592         priv->next_constant_version = 1;
593     }
594     else
595     {
596         prog->constant_version = priv->next_constant_version++;
597     }
598 }
599
600 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
601         unsigned int heap_idx, DWORD new_version)
602 {
603     struct constant_entry *entries = heap->entries;
604     unsigned int *positions = heap->positions;
605     unsigned int parent_idx;
606
607     while (heap_idx > 1)
608     {
609         parent_idx = heap_idx >> 1;
610
611         if (new_version <= entries[parent_idx].version) break;
612
613         entries[heap_idx] = entries[parent_idx];
614         positions[entries[parent_idx].idx] = heap_idx;
615         heap_idx = parent_idx;
616     }
617
618     entries[heap_idx].version = new_version;
619     entries[heap_idx].idx = idx;
620     positions[idx] = heap_idx;
621 }
622
623 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
624 {
625     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
626     struct shader_glsl_priv *priv = This->shader_priv;
627     struct constant_heap *heap = &priv->vconst_heap;
628     UINT i;
629
630     for (i = start; i < count + start; ++i)
631     {
632         if (!This->stateBlock->changed.vertexShaderConstantsF[i])
633             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
634         else
635             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
636     }
637 }
638
639 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
640 {
641     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
642     struct shader_glsl_priv *priv = This->shader_priv;
643     struct constant_heap *heap = &priv->pconst_heap;
644     UINT i;
645
646     for (i = start; i < count + start; ++i)
647     {
648         if (!This->stateBlock->changed.pixelShaderConstantsF[i])
649             update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
650         else
651             update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
652     }
653 }
654
655 /** Generate the variable & register declarations for the GLSL output target */
656 static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
657         SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info,
658         const struct ps_compile_args *ps_args)
659 {
660     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
661     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
662     DWORD shader_version = reg_maps->shader_version;
663     unsigned int i, extra_constants_needed = 0;
664     const local_constant *lconst;
665
666     /* There are some minor differences between pixel and vertex shaders */
667     char pshader = shader_is_pshader_version(shader_version);
668     char prefix = pshader ? 'P' : 'V';
669
670     /* Prototype the subroutines */
671     for (i = 0; i < This->baseShader.limits.label; i++) {
672         if (reg_maps->labels[i])
673             shader_addline(buffer, "void subroutine%u();\n", i);
674     }
675
676     /* Declare the constants (aka uniforms) */
677     if (This->baseShader.limits.constant_float > 0) {
678         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
679                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
680         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
681     }
682
683     if (This->baseShader.limits.constant_int > 0)
684         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
685
686     if (This->baseShader.limits.constant_bool > 0)
687         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
688
689     if(!pshader) {
690         shader_addline(buffer, "uniform vec4 posFixup;\n");
691         /* Predeclaration; This function is added at link time based on the pixel shader.
692          * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
693          * that. We know the input to the reorder function at vertex shader compile time, so
694          * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
695          * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
696          * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
697          * it will write to the varying array. Here we depend on the shader optimizer on sorting that
698          * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
699          * inout.
700          */
701         if (shader_version >= WINED3DVS_VERSION(3, 0))
702         {
703             shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
704         } else {
705             shader_addline(buffer, "void order_ps_input();\n");
706         }
707     } else {
708         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
709
710         ps_impl->numbumpenvmatconsts = 0;
711         for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
712             if(!reg_maps->bumpmat[i]) {
713                 continue;
714             }
715
716             ps_impl->bumpenvmatconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
717             shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
718
719             if(reg_maps->luminanceparams) {
720                 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
721                 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
722                 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
723                 extra_constants_needed++;
724             } else {
725                 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = -1;
726             }
727
728             extra_constants_needed++;
729             ps_impl->numbumpenvmatconsts++;
730         }
731
732         if(ps_args->srgb_correction) {
733             shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
734                             srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
735             shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
736                             srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
737         }
738         if(reg_maps->vpos || reg_maps->usesdsy) {
739             if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
740                 shader_addline(buffer, "uniform vec4 ycorrection;\n");
741                 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
742                 extra_constants_needed++;
743             } else {
744                 /* This happens because we do not have proper tracking of the constant registers that are
745                  * actually used, only the max limit of the shader version
746                  */
747                 FIXME("Cannot find a free uniform for vpos correction params\n");
748                 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
749                                device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
750                                device->render_offscreen ? 1.0 : -1.0);
751             }
752             shader_addline(buffer, "vec4 vpos;\n");
753         }
754     }
755
756     /* Declare texture samplers */ 
757     for (i = 0; i < This->baseShader.limits.sampler; i++) {
758         if (reg_maps->samplers[i]) {
759
760             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
761             switch (stype) {
762
763                 case WINED3DSTT_1D:
764                     shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
765                     break;
766                 case WINED3DSTT_2D:
767                     if(device->stateBlock->textures[i] &&
768                        IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
769                         shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
770                     } else {
771                         shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
772                     }
773                     break;
774                 case WINED3DSTT_CUBE:
775                     shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
776                     break;
777                 case WINED3DSTT_VOLUME:
778                     shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
779                     break;
780                 default:
781                     shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
782                     FIXME("Unrecognized sampler type: %#x\n", stype);
783                     break;
784             }
785         }
786     }
787     
788     /* Declare address variables */
789     for (i = 0; i < This->baseShader.limits.address; i++) {
790         if (reg_maps->address[i])
791             shader_addline(buffer, "ivec4 A%d;\n", i);
792     }
793
794     /* Declare texture coordinate temporaries and initialize them */
795     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
796         if (reg_maps->texcoord[i]) 
797             shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
798     }
799
800     /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
801      * helper function shader that is linked in at link time
802      */
803     if (pshader && shader_version >= WINED3DPS_VERSION(3, 0))
804     {
805         if (use_vs(device->stateBlock))
806         {
807             shader_addline(buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
808         } else {
809             /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
810              * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
811              * pixel shader that reads the fixed function color into the packed input registers.
812              */
813             shader_addline(buffer, "vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
814         }
815     }
816
817     /* Declare output register temporaries */
818     if(This->baseShader.limits.packed_output) {
819         shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
820     }
821
822     /* Declare temporary variables */
823     for(i = 0; i < This->baseShader.limits.temporary; i++) {
824         if (reg_maps->temporary[i])
825             shader_addline(buffer, "vec4 R%u;\n", i);
826     }
827
828     /* Declare attributes */
829     for (i = 0; i < This->baseShader.limits.attributes; i++) {
830         if (reg_maps->attributes[i])
831             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
832     }
833
834     /* Declare loop registers aLx */
835     for (i = 0; i < reg_maps->loop_depth; i++) {
836         shader_addline(buffer, "int aL%u;\n", i);
837         shader_addline(buffer, "int tmpInt%u;\n", i);
838     }
839
840     /* Temporary variables for matrix operations */
841     shader_addline(buffer, "vec4 tmp0;\n");
842     shader_addline(buffer, "vec4 tmp1;\n");
843
844     /* Local constants use a different name so they can be loaded once at shader link time
845      * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
846      * float -> string conversion can cause precision loss.
847      */
848     if(!This->baseShader.load_local_constsF) {
849         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
850             shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
851         }
852     }
853
854     /* Start the main program */
855     shader_addline(buffer, "void main() {\n");
856     if(pshader && reg_maps->vpos) {
857         /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
858          * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
859          * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
860          * precision troubles when we just substract 0.5.
861          *
862          * To deal with that just floor() the position. This will eliminate the fraction on all cards.
863          *
864          * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
865          *
866          * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
867          * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
868          * coordinates specify the pixel centers instead of the pixel corners. This code will behave
869          * correctly on drivers that returns integer values.
870          */
871         shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
872     }
873 }
874
875 /*****************************************************************************
876  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
877  *
878  * For more information, see http://wiki.winehq.org/DirectX-Shaders
879  ****************************************************************************/
880
881 /* Prototypes */
882 static void shader_glsl_add_src_param(const SHADER_OPCODE_ARG *arg, const DWORD param,
883         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
884
885 /** Used for opcode modifiers - They multiply the result by the specified amount */
886 static const char * const shift_glsl_tab[] = {
887     "",           /*  0 (none) */ 
888     "2.0 * ",     /*  1 (x2)   */ 
889     "4.0 * ",     /*  2 (x4)   */ 
890     "8.0 * ",     /*  3 (x8)   */ 
891     "16.0 * ",    /*  4 (x16)  */ 
892     "32.0 * ",    /*  5 (x32)  */ 
893     "",           /*  6 (x64)  */ 
894     "",           /*  7 (x128) */ 
895     "",           /*  8 (d256) */ 
896     "",           /*  9 (d128) */ 
897     "",           /* 10 (d64)  */ 
898     "",           /* 11 (d32)  */ 
899     "0.0625 * ",  /* 12 (d16)  */ 
900     "0.125 * ",   /* 13 (d8)   */ 
901     "0.25 * ",    /* 14 (d4)   */ 
902     "0.5 * "      /* 15 (d2)   */ 
903 };
904
905 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
906 static void shader_glsl_gen_modifier (
907     const DWORD instr,
908     const char *in_reg,
909     const char *in_regswizzle,
910     char *out_str) {
911
912     out_str[0] = 0;
913     
914     if (instr == WINED3DSIO_TEXKILL)
915         return;
916
917     switch (instr & WINED3DSP_SRCMOD_MASK) {
918     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
919     case WINED3DSPSM_DW:
920     case WINED3DSPSM_NONE:
921         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
922         break;
923     case WINED3DSPSM_NEG:
924         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
925         break;
926     case WINED3DSPSM_NOT:
927         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
928         break;
929     case WINED3DSPSM_BIAS:
930         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
931         break;
932     case WINED3DSPSM_BIASNEG:
933         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
934         break;
935     case WINED3DSPSM_SIGN:
936         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
937         break;
938     case WINED3DSPSM_SIGNNEG:
939         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
940         break;
941     case WINED3DSPSM_COMP:
942         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
943         break;
944     case WINED3DSPSM_X2:
945         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
946         break;
947     case WINED3DSPSM_X2NEG:
948         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
949         break;
950     case WINED3DSPSM_ABS:
951         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
952         break;
953     case WINED3DSPSM_ABSNEG:
954         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
955         break;
956     default:
957         FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
958         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
959     }
960 }
961
962 /** Writes the GLSL variable name that corresponds to the register that the
963  * DX opcode parameter is trying to access */
964 static void shader_glsl_get_register_name(const DWORD param, const DWORD addr_token,
965         char *regstr, BOOL *is_color, const SHADER_OPCODE_ARG *arg)
966 {
967     /* oPos, oFog and oPts in D3D */
968     static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
969
970     DWORD reg = param & WINED3DSP_REGNUM_MASK;
971     DWORD regtype = shader_get_regtype(param);
972     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
973     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
974     const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
975     DWORD shader_version = This->baseShader.reg_maps.shader_version;
976     char pshader = shader_is_pshader_version(shader_version);
977     char tmpStr[150];
978
979     *is_color = FALSE;   
980  
981     switch (regtype) {
982     case WINED3DSPR_TEMP:
983         sprintf(tmpStr, "R%u", reg);
984     break;
985     case WINED3DSPR_INPUT:
986         if (pshader) {
987             /* Pixel shaders >= 3.0 */
988             if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3)
989             {
990                 DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
991
992                 if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
993                     glsl_src_param_t rel_param;
994                     shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
995
996                     /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
997                      * operation there
998                      */
999                     if(((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]) {
1000                         if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1001                             sprintf(tmpStr, "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1002                                     rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg], in_count - 1,
1003                                     rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg], in_count,
1004                                     rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg]);
1005                         } else {
1006                             sprintf(tmpStr, "IN[%s + %u]", rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg]);
1007                         }
1008                     } else {
1009                         if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1010                             sprintf(tmpStr, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1011                                     rel_param.param_str, in_count - 1,
1012                                     rel_param.param_str, in_count,
1013                                     rel_param.param_str);
1014                         } else {
1015                             sprintf(tmpStr, "IN[%s]", rel_param.param_str);
1016                         }
1017                     }
1018                 } else {
1019                     DWORD idx = ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg];
1020                     if (idx == in_count) {
1021                         sprintf(tmpStr, "gl_Color");
1022                     } else if (idx == in_count + 1) {
1023                         sprintf(tmpStr, "gl_SecondaryColor");
1024                     } else {
1025                         sprintf(tmpStr, "IN[%u]", idx);
1026                     }
1027                 }
1028             } else {
1029                 if (reg==0)
1030                     strcpy(tmpStr, "gl_Color");
1031                 else
1032                     strcpy(tmpStr, "gl_SecondaryColor");
1033             }
1034         } else {
1035             if (((IWineD3DVertexShaderImpl *)This)->cur_args->swizzle_map & (1 << reg)) *is_color = TRUE;
1036             sprintf(tmpStr, "attrib%u", reg);
1037         } 
1038         break;
1039     case WINED3DSPR_CONST:
1040     {
1041         const char prefix = pshader? 'P':'V';
1042
1043         /* Relative addressing */
1044         if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
1045
1046            /* Relative addressing on shaders 2.0+ have a relative address token, 
1047             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
1048            if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 2)
1049            {
1050                glsl_src_param_t rel_param;
1051                shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
1052                if(reg) {
1053                    sprintf(tmpStr, "%cC[%s + %u]", prefix, rel_param.param_str, reg);
1054                } else {
1055                    sprintf(tmpStr, "%cC[%s]", prefix, rel_param.param_str);
1056                }
1057            } else {
1058                if(reg) {
1059                    sprintf(tmpStr, "%cC[A0.x + %u]", prefix, reg);
1060                } else {
1061                    sprintf(tmpStr, "%cC[A0.x]", prefix);
1062                }
1063            }
1064
1065         } else {
1066             if(shader_constant_is_local(This, reg)) {
1067                 sprintf(tmpStr, "%cLC%u", prefix, reg);
1068             } else {
1069                 sprintf(tmpStr, "%cC[%u]", prefix, reg);
1070             }
1071         }
1072
1073         break;
1074     }
1075     case WINED3DSPR_CONSTINT:
1076         if (pshader)
1077             sprintf(tmpStr, "PI[%u]", reg);
1078         else
1079             sprintf(tmpStr, "VI[%u]", reg);
1080         break;
1081     case WINED3DSPR_CONSTBOOL:
1082         if (pshader)
1083             sprintf(tmpStr, "PB[%u]", reg);
1084         else
1085             sprintf(tmpStr, "VB[%u]", reg);
1086         break;
1087     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1088         if (pshader) {
1089             sprintf(tmpStr, "T%u", reg);
1090         } else {
1091             sprintf(tmpStr, "A%u", reg);
1092         }
1093     break;
1094     case WINED3DSPR_LOOP:
1095         sprintf(tmpStr, "aL%u", This->baseShader.cur_loop_regno - 1);
1096     break;
1097     case WINED3DSPR_SAMPLER:
1098         if (pshader)
1099             sprintf(tmpStr, "Psampler%u", reg);
1100         else
1101             sprintf(tmpStr, "Vsampler%u", reg);
1102     break;
1103     case WINED3DSPR_COLOROUT:
1104         if (reg >= GL_LIMITS(buffers)) {
1105             WARN("Write to render target %u, only %d supported\n", reg, 4);
1106         }
1107         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
1108             sprintf(tmpStr, "gl_FragData[%u]", reg);
1109         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
1110             sprintf(tmpStr, "gl_FragColor");
1111         }
1112     break;
1113     case WINED3DSPR_RASTOUT:
1114         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
1115     break;
1116     case WINED3DSPR_DEPTHOUT:
1117         sprintf(tmpStr, "gl_FragDepth");
1118     break;
1119     case WINED3DSPR_ATTROUT:
1120         if (reg == 0) {
1121             sprintf(tmpStr, "gl_FrontColor");
1122         } else {
1123             sprintf(tmpStr, "gl_FrontSecondaryColor");
1124         }
1125     break;
1126     case WINED3DSPR_TEXCRDOUT:
1127         /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1128         if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3) sprintf(tmpStr, "OUT[%u]", reg);
1129         else sprintf(tmpStr, "gl_TexCoord[%u]", reg);
1130     break;
1131     case WINED3DSPR_MISCTYPE:
1132         if (reg == 0) {
1133             /* vPos */
1134             sprintf(tmpStr, "vpos");
1135         } else if (reg == 1){
1136             /* Note that gl_FrontFacing is a bool, while vFace is
1137              * a float for which the sign determines front/back
1138              */
1139             sprintf(tmpStr, "(gl_FrontFacing ? 1.0 : -1.0)");
1140         } else {
1141             FIXME("Unhandled misctype register %d\n", reg);
1142             sprintf(tmpStr, "unrecognized_register");
1143         }
1144         break;
1145     default:
1146         FIXME("Unhandled register name Type(%d)\n", regtype);
1147         sprintf(tmpStr, "unrecognized_register");
1148     break;
1149     }
1150
1151     strcat(regstr, tmpStr);
1152 }
1153
1154 /* Get the GLSL write mask for the destination register */
1155 static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
1156     char *ptr = write_mask;
1157     DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
1158
1159     if (shader_is_scalar(param)) {
1160         mask = WINED3DSP_WRITEMASK_0;
1161     } else {
1162         *ptr++ = '.';
1163         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
1164         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
1165         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
1166         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
1167     }
1168
1169     *ptr = '\0';
1170
1171     return mask;
1172 }
1173
1174 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1175     unsigned int size = 0;
1176
1177     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1178     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1179     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1180     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1181
1182     return size;
1183 }
1184
1185 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
1186     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1187      * but addressed as "rgba". To fix this we need to swap the register's x
1188      * and z components. */
1189     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
1190     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1191     char *ptr = swizzle_str;
1192
1193     if (!shader_is_scalar(param)) {
1194         *ptr++ = '.';
1195         /* swizzle bits fields: wwzzyyxx */
1196         if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
1197         if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
1198         if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
1199         if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
1200     }
1201
1202     *ptr = '\0';
1203 }
1204
1205 /* From a given parameter token, generate the corresponding GLSL string.
1206  * Also, return the actual register name and swizzle in case the
1207  * caller needs this information as well. */
1208 static void shader_glsl_add_src_param(const SHADER_OPCODE_ARG *arg, const DWORD param,
1209         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param)
1210 {
1211     BOOL is_color = FALSE;
1212     char swizzle_str[6];
1213
1214     src_param->reg_name[0] = '\0';
1215     src_param->param_str[0] = '\0';
1216     swizzle_str[0] = '\0';
1217
1218     shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
1219
1220     shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
1221     shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
1222 }
1223
1224 /* From a given parameter token, generate the corresponding GLSL string.
1225  * Also, return the actual register name and swizzle in case the
1226  * caller needs this information as well. */
1227 static DWORD shader_glsl_add_dst_param(const SHADER_OPCODE_ARG* arg, const DWORD param,
1228         const DWORD addr_token, glsl_dst_param_t *dst_param)
1229 {
1230     BOOL is_color = FALSE;
1231
1232     dst_param->mask_str[0] = '\0';
1233     dst_param->reg_name[0] = '\0';
1234
1235     shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
1236     return shader_glsl_get_write_mask(param, dst_param->mask_str);
1237 }
1238
1239 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1240 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, const SHADER_OPCODE_ARG *arg, const DWORD param)
1241 {
1242     glsl_dst_param_t dst_param;
1243     DWORD mask;
1244     int shift;
1245
1246     mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);
1247
1248     if(mask) {
1249         shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1250         shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
1251     }
1252
1253     return mask;
1254 }
1255
1256 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1257 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, const SHADER_OPCODE_ARG *arg)
1258 {
1259     return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
1260 }
1261
1262 /** Process GLSL instruction modifiers */
1263 void shader_glsl_add_instruction_modifiers(const SHADER_OPCODE_ARG* arg)
1264 {
1265     DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
1266  
1267     if (arg->opcode->dst_token && mask != 0) {
1268         glsl_dst_param_t dst_param;
1269
1270         shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1271
1272         if (mask & WINED3DSPDM_SATURATE) {
1273             /* _SAT means to clamp the value of the register to between 0 and 1 */
1274             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1275                     dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1276         }
1277         if (mask & WINED3DSPDM_MSAMPCENTROID) {
1278             FIXME("_centroid modifier not handled\n");
1279         }
1280         if (mask & WINED3DSPDM_PARTIALPRECISION) {
1281             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1282         }
1283     }
1284 }
1285
1286 static inline const char* shader_get_comp_op(
1287     const DWORD opcode) {
1288
1289     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
1290     switch (op) {
1291         case COMPARISON_GT: return ">";
1292         case COMPARISON_EQ: return "==";
1293         case COMPARISON_GE: return ">=";
1294         case COMPARISON_LT: return "<";
1295         case COMPARISON_NE: return "!=";
1296         case COMPARISON_LE: return "<=";
1297         default:
1298             FIXME("Unrecognized comparison value: %u\n", op);
1299             return "(\?\?)";
1300     }
1301 }
1302
1303 static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, BOOL texrect, BOOL lod, glsl_sample_function_t *sample_function) {
1304     /* Note that there's no such thing as a projected cube texture. */
1305     switch(sampler_type) {
1306         case WINED3DSTT_1D:
1307             if(lod) {
1308                 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1309             } else {
1310                 sample_function->name = projected ? "texture1DProj" : "texture1D";
1311             }
1312             sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1313             break;
1314         case WINED3DSTT_2D:
1315             if(texrect) {
1316                 if(lod) {
1317                     sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1318                 } else {
1319                     sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1320                 }
1321             } else {
1322                 if(lod) {
1323                     sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1324                 } else {
1325                     sample_function->name = projected ? "texture2DProj" : "texture2D";
1326                 }
1327             }
1328             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1329             break;
1330         case WINED3DSTT_CUBE:
1331             if(lod) {
1332                 sample_function->name = "textureCubeLod";
1333             } else {
1334                 sample_function->name = "textureCube";
1335             }
1336             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1337             break;
1338         case WINED3DSTT_VOLUME:
1339             if(lod) {
1340                 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1341             } else {
1342                 sample_function->name = projected ? "texture3DProj" : "texture3D";
1343             }
1344             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1345             break;
1346         default:
1347             sample_function->name = "";
1348             sample_function->coord_mask = 0;
1349             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1350             break;
1351     }
1352 }
1353
1354 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1355         BOOL sign_fixup, enum fixup_channel_source channel_source)
1356 {
1357     switch(channel_source)
1358     {
1359         case CHANNEL_SOURCE_ZERO:
1360             strcat(arguments, "0.0");
1361             break;
1362
1363         case CHANNEL_SOURCE_ONE:
1364             strcat(arguments, "1.0");
1365             break;
1366
1367         case CHANNEL_SOURCE_X:
1368             strcat(arguments, reg_name);
1369             strcat(arguments, ".x");
1370             break;
1371
1372         case CHANNEL_SOURCE_Y:
1373             strcat(arguments, reg_name);
1374             strcat(arguments, ".y");
1375             break;
1376
1377         case CHANNEL_SOURCE_Z:
1378             strcat(arguments, reg_name);
1379             strcat(arguments, ".z");
1380             break;
1381
1382         case CHANNEL_SOURCE_W:
1383             strcat(arguments, reg_name);
1384             strcat(arguments, ".w");
1385             break;
1386
1387         default:
1388             FIXME("Unhandled channel source %#x\n", channel_source);
1389             strcat(arguments, "undefined");
1390             break;
1391     }
1392
1393     if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1394 }
1395
1396 static void shader_glsl_color_correction(const struct SHADER_OPCODE_ARG *arg, struct color_fixup_desc fixup)
1397 {
1398     unsigned int mask_size, remaining;
1399     glsl_dst_param_t dst_param;
1400     char arguments[256];
1401     DWORD mask;
1402     BOOL dummy;
1403
1404     mask = 0;
1405     if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1406     if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1407     if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1408     if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1409     mask &= arg->dst;
1410
1411     if (!mask) return; /* Nothing to do */
1412
1413     if (is_yuv_fixup(fixup))
1414     {
1415         enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1416         FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1417         return;
1418     }
1419
1420     mask_size = shader_glsl_get_write_mask_size(mask);
1421
1422     dst_param.mask_str[0] = '\0';
1423     shader_glsl_get_write_mask(mask, dst_param.mask_str);
1424
1425     dst_param.reg_name[0] = '\0';
1426     shader_glsl_get_register_name(arg->dst, arg->dst_addr, dst_param.reg_name, &dummy, arg);
1427
1428     arguments[0] = '\0';
1429     remaining = mask_size;
1430     if (mask & WINED3DSP_WRITEMASK_0)
1431     {
1432         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1433         if (--remaining) strcat(arguments, ", ");
1434     }
1435     if (mask & WINED3DSP_WRITEMASK_1)
1436     {
1437         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1438         if (--remaining) strcat(arguments, ", ");
1439     }
1440     if (mask & WINED3DSP_WRITEMASK_2)
1441     {
1442         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1443         if (--remaining) strcat(arguments, ", ");
1444     }
1445     if (mask & WINED3DSP_WRITEMASK_3)
1446     {
1447         shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1448         if (--remaining) strcat(arguments, ", ");
1449     }
1450
1451     if (mask_size > 1)
1452     {
1453         shader_addline(arg->buffer, "%s%s = vec%u(%s);\n",
1454                 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1455     }
1456     else
1457     {
1458         shader_addline(arg->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1459     }
1460 }
1461
1462 static void shader_glsl_gen_sample_code(const SHADER_OPCODE_ARG *arg, DWORD sampler, const char *coord_reg,
1463                                         const glsl_sample_function_t *sample_function, DWORD swizzle,
1464                                         const char *bias) {
1465     const char *sampler_base;
1466     char dst_swizzle[6];
1467     struct color_fixup_desc fixup;
1468
1469     shader_glsl_get_swizzle(swizzle, FALSE, arg->dst, dst_swizzle);
1470
1471     if(shader_is_pshader_version(arg->reg_maps->shader_version)) {
1472         IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) arg->shader;
1473         fixup = This->cur_args->color_fixup[sampler];
1474         sampler_base = "Psampler";
1475     } else {
1476         sampler_base = "Vsampler";
1477         fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1478     }
1479
1480     shader_glsl_append_dst(arg->buffer, arg);
1481
1482     if(bias) {
1483         shader_addline(arg->buffer, "%s(%s%u, %s, %s)%s);\n",
1484                        sample_function->name, sampler_base, sampler, coord_reg, bias, dst_swizzle);
1485     } else {
1486         shader_addline(arg->buffer, "%s(%s%u, %s)%s);\n",
1487                        sample_function->name, sampler_base, sampler, coord_reg, dst_swizzle);
1488     }
1489
1490     if(!is_identity_fixup(fixup)) {
1491         shader_glsl_color_correction(arg, fixup);
1492     }
1493 }
1494
1495 /*****************************************************************************
1496  * 
1497  * Begin processing individual instruction opcodes
1498  * 
1499  ****************************************************************************/
1500
1501 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1502 static void shader_glsl_arith(const SHADER_OPCODE_ARG *arg)
1503 {
1504     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1505     SHADER_BUFFER* buffer = arg->buffer;
1506     glsl_src_param_t src0_param;
1507     glsl_src_param_t src1_param;
1508     DWORD write_mask;
1509     char op;
1510
1511     /* Determine the GLSL operator to use based on the opcode */
1512     switch (curOpcode->opcode) {
1513         case WINED3DSIO_MUL: op = '*'; break;
1514         case WINED3DSIO_ADD: op = '+'; break;
1515         case WINED3DSIO_SUB: op = '-'; break;
1516         default:
1517             op = ' ';
1518             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1519             break;
1520     }
1521
1522     write_mask = shader_glsl_append_dst(buffer, arg);
1523     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1524     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1525     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1526 }
1527
1528 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1529 static void shader_glsl_mov(const SHADER_OPCODE_ARG *arg)
1530 {
1531     SHADER_BUFFER* buffer = arg->buffer;
1532     glsl_src_param_t src0_param;
1533     DWORD write_mask;
1534
1535     write_mask = shader_glsl_append_dst(buffer, arg);
1536     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1537
1538     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1539      * shader versions WINED3DSIO_MOVA is used for this. */
1540     if ((WINED3DSHADER_VERSION_MAJOR(arg->reg_maps->shader_version) == 1
1541             && !shader_is_pshader_version(arg->reg_maps->shader_version)
1542             && shader_get_regtype(arg->dst) == WINED3DSPR_ADDR))
1543     {
1544         /* This is a simple floor() */
1545         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1546         if (mask_size > 1) {
1547             shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1548         } else {
1549             shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1550         }
1551     } else if(arg->opcode->opcode == WINED3DSIO_MOVA) {
1552         /* We need to *round* to the nearest int here. */
1553         unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1554         if (mask_size > 1) {
1555             shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n", mask_size, src0_param.param_str, mask_size, src0_param.param_str);
1556         } else {
1557             shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1558         }
1559     } else {
1560         shader_addline(buffer, "%s);\n", src0_param.param_str);
1561     }
1562 }
1563
1564 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1565 static void shader_glsl_dot(const SHADER_OPCODE_ARG *arg)
1566 {
1567     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1568     SHADER_BUFFER* buffer = arg->buffer;
1569     glsl_src_param_t src0_param;
1570     glsl_src_param_t src1_param;
1571     DWORD dst_write_mask, src_write_mask;
1572     unsigned int dst_size = 0;
1573
1574     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1575     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1576
1577     /* dp3 works on vec3, dp4 on vec4 */
1578     if (curOpcode->opcode == WINED3DSIO_DP4) {
1579         src_write_mask = WINED3DSP_WRITEMASK_ALL;
1580     } else {
1581         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1582     }
1583
1584     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
1585     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1586
1587     if (dst_size > 1) {
1588         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1589     } else {
1590         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1591     }
1592 }
1593
1594 /* Note that this instruction has some restrictions. The destination write mask
1595  * can't contain the w component, and the source swizzles have to be .xyzw */
1596 static void shader_glsl_cross(const SHADER_OPCODE_ARG *arg)
1597 {
1598     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1599     glsl_src_param_t src0_param;
1600     glsl_src_param_t src1_param;
1601     char dst_mask[6];
1602
1603     shader_glsl_get_write_mask(arg->dst, dst_mask);
1604     shader_glsl_append_dst(arg->buffer, arg);
1605     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1606     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1607     shader_addline(arg->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1608 }
1609
1610 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1611  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1612  * GLSL uses the value as-is. */
1613 static void shader_glsl_pow(const SHADER_OPCODE_ARG *arg)
1614 {
1615     SHADER_BUFFER *buffer = arg->buffer;
1616     glsl_src_param_t src0_param;
1617     glsl_src_param_t src1_param;
1618     DWORD dst_write_mask;
1619     unsigned int dst_size;
1620
1621     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1622     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1623
1624     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1625     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1626
1627     if (dst_size > 1) {
1628         shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1629     } else {
1630         shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1631     }
1632 }
1633
1634 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1635  * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1636  * GLSL uses the value as-is. */
1637 static void shader_glsl_log(const SHADER_OPCODE_ARG *arg)
1638 {
1639     SHADER_BUFFER *buffer = arg->buffer;
1640     glsl_src_param_t src0_param;
1641     DWORD dst_write_mask;
1642     unsigned int dst_size;
1643
1644     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1645     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1646
1647     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1648
1649     if (dst_size > 1) {
1650         shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1651     } else {
1652         shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1653     }
1654 }
1655
1656 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1657 static void shader_glsl_map2gl(const SHADER_OPCODE_ARG *arg)
1658 {
1659     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1660     SHADER_BUFFER* buffer = arg->buffer;
1661     glsl_src_param_t src_param;
1662     const char *instruction;
1663     char arguments[256];
1664     DWORD write_mask;
1665     unsigned i;
1666
1667     /* Determine the GLSL function to use based on the opcode */
1668     /* TODO: Possibly make this a table for faster lookups */
1669     switch (curOpcode->opcode) {
1670         case WINED3DSIO_MIN: instruction = "min"; break;
1671         case WINED3DSIO_MAX: instruction = "max"; break;
1672         case WINED3DSIO_ABS: instruction = "abs"; break;
1673         case WINED3DSIO_FRC: instruction = "fract"; break;
1674         case WINED3DSIO_NRM: instruction = "normalize"; break;
1675         case WINED3DSIO_EXP: instruction = "exp2"; break;
1676         case WINED3DSIO_SGN: instruction = "sign"; break;
1677         case WINED3DSIO_DSX: instruction = "dFdx"; break;
1678         case WINED3DSIO_DSY: instruction = "ycorrection.y * dFdy"; break;
1679         default: instruction = "";
1680             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1681             break;
1682     }
1683
1684     write_mask = shader_glsl_append_dst(buffer, arg);
1685
1686     arguments[0] = '\0';
1687     if (curOpcode->num_params > 0) {
1688         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
1689         strcat(arguments, src_param.param_str);
1690         for (i = 2; i < curOpcode->num_params; ++i) {
1691             strcat(arguments, ", ");
1692             shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
1693             strcat(arguments, src_param.param_str);
1694         }
1695     }
1696
1697     shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1698 }
1699
1700 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1701  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1702  *   dst.x = 2^(floor(src))
1703  *   dst.y = src - floor(src)
1704  *   dst.z = 2^src   (partial precision is allowed, but optional)
1705  *   dst.w = 1.0;
1706  * For 2.0 shaders, just do this (honoring writemask and swizzle):
1707  *   dst = 2^src;    (partial precision is allowed, but optional)
1708  */
1709 static void shader_glsl_expp(const SHADER_OPCODE_ARG *arg)
1710 {
1711     glsl_src_param_t src_param;
1712
1713     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1714
1715     if (arg->reg_maps->shader_version < WINED3DPS_VERSION(2,0))
1716     {
1717         char dst_mask[6];
1718
1719         shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1720         shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1721         shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1722         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1723
1724         shader_glsl_append_dst(arg->buffer, arg);
1725         shader_glsl_get_write_mask(arg->dst, dst_mask);
1726         shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1727     } else {
1728         DWORD write_mask;
1729         unsigned int mask_size;
1730
1731         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1732         mask_size = shader_glsl_get_write_mask_size(write_mask);
1733
1734         if (mask_size > 1) {
1735             shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1736         } else {
1737             shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1738         }
1739     }
1740 }
1741
1742 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1743 static void shader_glsl_rcp(const SHADER_OPCODE_ARG *arg)
1744 {
1745     glsl_src_param_t src_param;
1746     DWORD write_mask;
1747     unsigned int mask_size;
1748
1749     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1750     mask_size = shader_glsl_get_write_mask_size(write_mask);
1751     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1752
1753     if (mask_size > 1) {
1754         shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1755     } else {
1756         shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1757     }
1758 }
1759
1760 static void shader_glsl_rsq(const SHADER_OPCODE_ARG *arg)
1761 {
1762     SHADER_BUFFER* buffer = arg->buffer;
1763     glsl_src_param_t src_param;
1764     DWORD write_mask;
1765     unsigned int mask_size;
1766
1767     write_mask = shader_glsl_append_dst(buffer, arg);
1768     mask_size = shader_glsl_get_write_mask_size(write_mask);
1769
1770     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1771
1772     if (mask_size > 1) {
1773         shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1774     } else {
1775         shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1776     }
1777 }
1778
1779 /** Process signed comparison opcodes in GLSL. */
1780 static void shader_glsl_compare(const SHADER_OPCODE_ARG *arg)
1781 {
1782     glsl_src_param_t src0_param;
1783     glsl_src_param_t src1_param;
1784     DWORD write_mask;
1785     unsigned int mask_size;
1786
1787     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1788     mask_size = shader_glsl_get_write_mask_size(write_mask);
1789     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1790     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1791
1792     if (mask_size > 1) {
1793         const char *compare;
1794
1795         switch(arg->opcode->opcode) {
1796             case WINED3DSIO_SLT: compare = "lessThan"; break;
1797             case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
1798             default: compare = "";
1799                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1800         }
1801
1802         shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1803                 src0_param.param_str, src1_param.param_str);
1804     } else {
1805         switch(arg->opcode->opcode) {
1806             case WINED3DSIO_SLT:
1807                 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
1808                  * to return 0.0 but step returns 1.0 because step is not < x
1809                  * An alternative is a bvec compare padded with an unused second component.
1810                  * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
1811                  * issue. Playing with not() is not possible either because not() does not accept
1812                  * a scalar.
1813                  */
1814                 shader_addline(arg->buffer, "(%s < %s) ? 1.0 : 0.0);\n", src0_param.param_str, src1_param.param_str);
1815                 break;
1816             case WINED3DSIO_SGE:
1817                 /* Here we can use the step() function and safe a conditional */
1818                 shader_addline(arg->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
1819                 break;
1820             default:
1821                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1822         }
1823
1824     }
1825 }
1826
1827 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1828 static void shader_glsl_cmp(const SHADER_OPCODE_ARG *arg)
1829 {
1830     glsl_src_param_t src0_param;
1831     glsl_src_param_t src1_param;
1832     glsl_src_param_t src2_param;
1833     DWORD write_mask, cmp_channel = 0;
1834     unsigned int i, j;
1835     char mask_char[6];
1836     BOOL temp_destination = FALSE;
1837
1838     if(shader_is_scalar(arg->src[0])) {
1839         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1840
1841         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
1842         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1843         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1844
1845         shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1846                        src0_param.param_str, src1_param.param_str, src2_param.param_str);
1847     } else {
1848         DWORD src0reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
1849         DWORD src1reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
1850         DWORD src2reg = arg->src[2] & WINED3DSP_REGNUM_MASK;
1851         DWORD src0regtype = shader_get_regtype(arg->src[0]);
1852         DWORD src1regtype = shader_get_regtype(arg->src[1]);
1853         DWORD src2regtype = shader_get_regtype(arg->src[2]);
1854         DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1855         DWORD dstregtype = shader_get_regtype(arg->dst);
1856
1857         /* Cycle through all source0 channels */
1858         for (i=0; i<4; i++) {
1859             write_mask = 0;
1860             /* Find the destination channels which use the current source0 channel */
1861             for (j=0; j<4; j++) {
1862                 if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1863                     write_mask |= WINED3DSP_WRITEMASK_0 << j;
1864                     cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1865                 }
1866             }
1867
1868             /* Splitting the cmp instruction up in multiple lines imposes a problem:
1869             * The first lines may overwrite source parameters of the following lines.
1870             * Deal with that by using a temporary destination register if needed
1871             */
1872             if((src0reg == dstreg && src0regtype == dstregtype) ||
1873             (src1reg == dstreg && src1regtype == dstregtype) ||
1874             (src2reg == dstreg && src2regtype == dstregtype)) {
1875
1876                 write_mask = shader_glsl_get_write_mask(arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask), mask_char);
1877                 if (!write_mask) continue;
1878                 shader_addline(arg->buffer, "tmp0%s = (", mask_char);
1879                 temp_destination = TRUE;
1880             } else {
1881                 write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1882                 if (!write_mask) continue;
1883             }
1884
1885             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1886             shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1887             shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1888
1889             shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1890                         src0_param.param_str, src1_param.param_str, src2_param.param_str);
1891         }
1892
1893         if(temp_destination) {
1894             shader_glsl_get_write_mask(arg->dst, mask_char);
1895             shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst);
1896             shader_addline(arg->buffer, "tmp0%s);\n", mask_char);
1897         }
1898     }
1899
1900 }
1901
1902 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1903 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
1904  * the compare is done per component of src0. */
1905 static void shader_glsl_cnd(const SHADER_OPCODE_ARG *arg)
1906 {
1907     glsl_src_param_t src0_param;
1908     glsl_src_param_t src1_param;
1909     glsl_src_param_t src2_param;
1910     DWORD write_mask, cmp_channel = 0;
1911     unsigned int i, j;
1912
1913     if (arg->reg_maps->shader_version < WINED3DPS_VERSION(1, 4))
1914     {
1915         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1916         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1917         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1918         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1919
1920         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
1921         if(arg->opcode_token & WINED3DSI_COISSUE) {
1922             shader_addline(arg->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
1923         } else {
1924             shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1925                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
1926         }
1927         return;
1928     }
1929     /* Cycle through all source0 channels */
1930     for (i=0; i<4; i++) {
1931         write_mask = 0;
1932         /* Find the destination channels which use the current source0 channel */
1933         for (j=0; j<4; j++) {
1934             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1935                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1936                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1937             }
1938         }
1939         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1940         if (!write_mask) continue;
1941
1942         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1943         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1944         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1945
1946         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1947                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1948     }
1949 }
1950
1951 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1952 static void shader_glsl_mad(const SHADER_OPCODE_ARG *arg)
1953 {
1954     glsl_src_param_t src0_param;
1955     glsl_src_param_t src1_param;
1956     glsl_src_param_t src2_param;
1957     DWORD write_mask;
1958
1959     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1960     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1961     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1962     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1963     shader_addline(arg->buffer, "(%s * %s) + %s);\n",
1964             src0_param.param_str, src1_param.param_str, src2_param.param_str);
1965 }
1966
1967 /** Handles transforming all WINED3DSIO_M?x? opcodes for 
1968     Vertex shaders to GLSL codes */
1969 static void shader_glsl_mnxn(const SHADER_OPCODE_ARG *arg)
1970 {
1971     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1972     const SHADER_OPCODE *opcode_table = shader->baseShader.shader_ins;
1973     DWORD shader_version = arg->reg_maps->shader_version;
1974     int i;
1975     int nComponents = 0;
1976     SHADER_OPCODE_ARG tmpArg;
1977    
1978     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1979
1980     /* Set constants for the temporary argument */
1981     tmpArg.shader      = arg->shader;
1982     tmpArg.buffer      = arg->buffer;
1983     tmpArg.src[0]      = arg->src[0];
1984     tmpArg.src_addr[0] = arg->src_addr[0];
1985     tmpArg.src_addr[1] = arg->src_addr[1];
1986     tmpArg.reg_maps = arg->reg_maps; 
1987     
1988     switch(arg->opcode->opcode) {
1989         case WINED3DSIO_M4x4:
1990             nComponents = 4;
1991             tmpArg.opcode = shader_get_opcode(opcode_table, shader_version, WINED3DSIO_DP4);
1992             break;
1993         case WINED3DSIO_M4x3:
1994             nComponents = 3;
1995             tmpArg.opcode = shader_get_opcode(opcode_table, shader_version, WINED3DSIO_DP4);
1996             break;
1997         case WINED3DSIO_M3x4:
1998             nComponents = 4;
1999             tmpArg.opcode = shader_get_opcode(opcode_table, shader_version, WINED3DSIO_DP3);
2000             break;
2001         case WINED3DSIO_M3x3:
2002             nComponents = 3;
2003             tmpArg.opcode = shader_get_opcode(opcode_table, shader_version, WINED3DSIO_DP3);
2004             break;
2005         case WINED3DSIO_M3x2:
2006             nComponents = 2;
2007             tmpArg.opcode = shader_get_opcode(opcode_table, shader_version, WINED3DSIO_DP3);
2008             break;
2009         default:
2010             break;
2011     }
2012
2013     for (i = 0; i < nComponents; i++) {
2014         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
2015         tmpArg.src[1]      = arg->src[1]+i;
2016         shader_glsl_dot(&tmpArg);
2017     }
2018 }
2019
2020 /**
2021     The LRP instruction performs a component-wise linear interpolation 
2022     between the second and third operands using the first operand as the
2023     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
2024     This is equivalent to mix(src2, src1, src0);
2025 */
2026 static void shader_glsl_lrp(const SHADER_OPCODE_ARG *arg)
2027 {
2028     glsl_src_param_t src0_param;
2029     glsl_src_param_t src1_param;
2030     glsl_src_param_t src2_param;
2031     DWORD write_mask;
2032
2033     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2034
2035     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
2036     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
2037     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
2038
2039     shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
2040             src2_param.param_str, src1_param.param_str, src0_param.param_str);
2041 }
2042
2043 /** Process the WINED3DSIO_LIT instruction in GLSL:
2044  * dst.x = dst.w = 1.0
2045  * dst.y = (src0.x > 0) ? src0.x
2046  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2047  *                                        where src.w is clamped at +- 128
2048  */
2049 static void shader_glsl_lit(const SHADER_OPCODE_ARG *arg)
2050 {
2051     glsl_src_param_t src0_param;
2052     glsl_src_param_t src1_param;
2053     glsl_src_param_t src3_param;
2054     char dst_mask[6];
2055
2056     shader_glsl_append_dst(arg->buffer, arg);
2057     shader_glsl_get_write_mask(arg->dst, dst_mask);
2058
2059     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2060     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
2061     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
2062
2063     /* The sdk specifies the instruction like this
2064      * dst.x = 1.0;
2065      * if(src.x > 0.0) dst.y = src.x
2066      * else dst.y = 0.0.
2067      * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2068      * else dst.z = 0.0;
2069      * dst.w = 1.0;
2070      *
2071      * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2072      * dst.x = 1.0                                  ... No further explanation needed
2073      * dst.y = max(src.y, 0.0);                     ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2074      * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0;   ... 0 ^ power is 0, and otherwise we use y anyway
2075      * dst.w = 1.0.                                 ... Nothing fancy.
2076      *
2077      * So we still have one conditional in there. So do this:
2078      * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2079      *
2080      * step(0.0, x) will return 1 if src.x > 0.0, and 0 otherwise. So if y is 0 we get pow(0.0 * 1.0, power),
2081      * which sets dst.z to 0. If y > 0, but x = 0.0, we get pow(y * 0.0, power), which results in 0 too.
2082      * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2083      */
2084     shader_addline(arg->buffer, "vec4(1.0, max(%s, 0.0), pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2085                    src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2086 }
2087
2088 /** Process the WINED3DSIO_DST instruction in GLSL:
2089  * dst.x = 1.0
2090  * dst.y = src0.x * src0.y
2091  * dst.z = src0.z
2092  * dst.w = src1.w
2093  */
2094 static void shader_glsl_dst(const SHADER_OPCODE_ARG *arg)
2095 {
2096     glsl_src_param_t src0y_param;
2097     glsl_src_param_t src0z_param;
2098     glsl_src_param_t src1y_param;
2099     glsl_src_param_t src1w_param;
2100     char dst_mask[6];
2101
2102     shader_glsl_append_dst(arg->buffer, arg);
2103     shader_glsl_get_write_mask(arg->dst, dst_mask);
2104
2105     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2106     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2107     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2108     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2109
2110     shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2111             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2112 }
2113
2114 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2115  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2116  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2117  * 
2118  * dst.x = cos(src0.?)
2119  * dst.y = sin(src0.?)
2120  * dst.z = dst.z
2121  * dst.w = dst.w
2122  */
2123 static void shader_glsl_sincos(const SHADER_OPCODE_ARG *arg)
2124 {
2125     glsl_src_param_t src0_param;
2126     DWORD write_mask;
2127
2128     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2129     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2130
2131     switch (write_mask) {
2132         case WINED3DSP_WRITEMASK_0:
2133             shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
2134             break;
2135
2136         case WINED3DSP_WRITEMASK_1:
2137             shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
2138             break;
2139
2140         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2141             shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2142             break;
2143
2144         default:
2145             ERR("Write mask should be .x, .y or .xy\n");
2146             break;
2147     }
2148 }
2149
2150 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2151  * Start a for() loop where src1.y is the initial value of aL,
2152  *  increment aL by src1.z for a total of src1.x iterations.
2153  *  Need to use a temporary variable for this operation.
2154  */
2155 /* FIXME: I don't think nested loops will work correctly this way. */
2156 static void shader_glsl_loop(const SHADER_OPCODE_ARG *arg)
2157 {
2158     glsl_src_param_t src1_param;
2159     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
2160     DWORD regtype = shader_get_regtype(arg->src[1]);
2161     DWORD reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
2162     const DWORD *control_values = NULL;
2163     const local_constant *constant;
2164
2165     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2166
2167     /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2168      * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2169      * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2170      * addressing.
2171      */
2172     if(regtype == WINED3DSPR_CONSTINT) {
2173         LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2174             if(constant->idx == reg) {
2175                 control_values = constant->value;
2176                 break;
2177             }
2178         }
2179     }
2180
2181     if(control_values) {
2182         if(control_values[2] > 0) {
2183             shader_addline(arg->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
2184                            shader->baseShader.cur_loop_depth, control_values[1],
2185                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2186                            shader->baseShader.cur_loop_depth, control_values[2]);
2187         } else if(control_values[2] == 0) {
2188             shader_addline(arg->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
2189                            shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
2190                            shader->baseShader.cur_loop_depth, control_values[0],
2191                            shader->baseShader.cur_loop_depth);
2192         } else {
2193             shader_addline(arg->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
2194                            shader->baseShader.cur_loop_depth, control_values[1],
2195                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2196                            shader->baseShader.cur_loop_depth, control_values[2]);
2197         }
2198     } else {
2199         shader_addline(arg->buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2200                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2201                        src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2202                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2203     }
2204
2205     shader->baseShader.cur_loop_depth++;
2206     shader->baseShader.cur_loop_regno++;
2207 }
2208
2209 static void shader_glsl_end(const SHADER_OPCODE_ARG *arg)
2210 {
2211     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
2212
2213     shader_addline(arg->buffer, "}\n");
2214
2215     if(arg->opcode->opcode == WINED3DSIO_ENDLOOP) {
2216         shader->baseShader.cur_loop_depth--;
2217         shader->baseShader.cur_loop_regno--;
2218     }
2219     if(arg->opcode->opcode == WINED3DSIO_ENDREP) {
2220         shader->baseShader.cur_loop_depth--;
2221     }
2222 }
2223
2224 static void shader_glsl_rep(const SHADER_OPCODE_ARG *arg)
2225 {
2226     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
2227     glsl_src_param_t src0_param;
2228
2229     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2230     shader_addline(arg->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2231                    shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2232                    src0_param.param_str, shader->baseShader.cur_loop_depth);
2233     shader->baseShader.cur_loop_depth++;
2234 }
2235
2236 static void shader_glsl_if(const SHADER_OPCODE_ARG *arg)
2237 {
2238     glsl_src_param_t src0_param;
2239
2240     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2241     shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
2242 }
2243
2244 static void shader_glsl_ifc(const SHADER_OPCODE_ARG *arg)
2245 {
2246     glsl_src_param_t src0_param;
2247     glsl_src_param_t src1_param;
2248
2249     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2250     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2251
2252     shader_addline(arg->buffer, "if (%s %s %s) {\n",
2253             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2254 }
2255
2256 static void shader_glsl_else(const SHADER_OPCODE_ARG *arg)
2257 {
2258     shader_addline(arg->buffer, "} else {\n");
2259 }
2260
2261 static void shader_glsl_break(const SHADER_OPCODE_ARG *arg)
2262 {
2263     shader_addline(arg->buffer, "break;\n");
2264 }
2265
2266 /* FIXME: According to MSDN the compare is done per component. */
2267 static void shader_glsl_breakc(const SHADER_OPCODE_ARG *arg)
2268 {
2269     glsl_src_param_t src0_param;
2270     glsl_src_param_t src1_param;
2271
2272     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
2273     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2274
2275     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
2276             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2277 }
2278
2279 static void shader_glsl_label(const SHADER_OPCODE_ARG *arg)
2280 {
2281
2282     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2283     shader_addline(arg->buffer, "}\n");
2284     shader_addline(arg->buffer, "void subroutine%u () {\n",  snum);
2285 }
2286
2287 static void shader_glsl_call(const SHADER_OPCODE_ARG *arg)
2288 {
2289     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2290     shader_addline(arg->buffer, "subroutine%u();\n", snum);
2291 }
2292
2293 static void shader_glsl_callnz(const SHADER_OPCODE_ARG *arg)
2294 {
2295     glsl_src_param_t src1_param;
2296
2297     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2298     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2299     shader_addline(arg->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, snum);
2300 }
2301
2302 /*********************************************
2303  * Pixel Shader Specific Code begins here
2304  ********************************************/
2305 static void pshader_glsl_tex(const SHADER_OPCODE_ARG *arg)
2306 {
2307     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2308     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2309     DWORD shader_version = arg->reg_maps->shader_version;
2310     glsl_sample_function_t sample_function;
2311     DWORD sampler_type;
2312     DWORD sampler_idx;
2313     BOOL projected, texrect = FALSE;
2314     DWORD mask = 0, swizzle;
2315
2316     /* 1.0-1.4: Use destination register as sampler source.
2317      * 2.0+: Use provided sampler source. */
2318     if (shader_version < WINED3DPS_VERSION(2,0)) sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2319     else sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2320     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2321
2322     if (shader_version < WINED3DPS_VERSION(1,4))
2323     {
2324         DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2325
2326         /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2327         if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2328             projected = TRUE;
2329             switch (flags & ~WINED3DTTFF_PROJECTED) {
2330                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2331                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2332                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2333                 case WINED3DTTFF_COUNT4:
2334                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2335             }
2336         } else {
2337             projected = FALSE;
2338         }
2339     }
2340     else if (shader_version < WINED3DPS_VERSION(2,0))
2341     {
2342         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2343
2344         if (src_mod == WINED3DSPSM_DZ) {
2345             projected = TRUE;
2346             mask = WINED3DSP_WRITEMASK_2;
2347         } else if (src_mod == WINED3DSPSM_DW) {
2348             projected = TRUE;
2349             mask = WINED3DSP_WRITEMASK_3;
2350         } else {
2351             projected = FALSE;
2352         }
2353     } else {
2354         if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
2355                 /* ps 2.0 texldp instruction always divides by the fourth component. */
2356                 projected = TRUE;
2357                 mask = WINED3DSP_WRITEMASK_3;
2358         } else {
2359             projected = FALSE;
2360         }
2361     }
2362
2363     if(deviceImpl->stateBlock->textures[sampler_idx] &&
2364        IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2365         texrect = TRUE;
2366     }
2367
2368     shader_glsl_get_sample_function(sampler_type, projected, texrect, FALSE, &sample_function);
2369     mask |= sample_function.coord_mask;
2370
2371     if (shader_version < WINED3DPS_VERSION(2,0)) swizzle = WINED3DVS_NOSWIZZLE;
2372     else swizzle = arg->src[1] & WINED3DSP_SWIZZLE_MASK;
2373
2374     /* 1.0-1.3: Use destination register as coordinate source.
2375        1.4+: Use provided coordinate source register. */
2376     if (shader_version < WINED3DPS_VERSION(1,4))
2377     {
2378         char coord_mask[6], srcreg[12];
2379         shader_glsl_get_write_mask(mask, coord_mask);
2380         sprintf(srcreg, "T%u%s", sampler_idx, coord_mask);
2381         shader_glsl_gen_sample_code(arg, sampler_idx, srcreg, &sample_function, swizzle, NULL);
2382     } else {
2383         glsl_src_param_t coord_param;
2384         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
2385         if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
2386             glsl_src_param_t bias;
2387             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);
2388             shader_glsl_gen_sample_code(arg, sampler_idx, coord_param.param_str, &sample_function,
2389                                         swizzle, bias.param_str);
2390         } else {
2391             shader_glsl_gen_sample_code(arg, sampler_idx, coord_param.param_str, &sample_function,
2392                                         swizzle, NULL);
2393         }
2394     }
2395 }
2396
2397 static void shader_glsl_texldl(const SHADER_OPCODE_ARG *arg)
2398 {
2399     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
2400     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2401     glsl_sample_function_t sample_function;
2402     glsl_src_param_t coord_param, lod_param;
2403     DWORD sampler_type;
2404     DWORD sampler_idx;
2405     BOOL texrect = FALSE;
2406     DWORD swizzle = arg->src[1] & WINED3DSP_SWIZZLE_MASK;
2407
2408     shader_glsl_append_dst(arg->buffer, arg);
2409
2410     sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2411     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2412     if(deviceImpl->stateBlock->textures[sampler_idx] &&
2413        IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2414         texrect = TRUE;
2415     }
2416     shader_glsl_get_sample_function(sampler_type, FALSE, texrect, TRUE, &sample_function);
2417     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
2418
2419     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);
2420
2421     if (shader_is_pshader_version(arg->reg_maps->shader_version))
2422     {
2423         /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2424          * However, they seem to work just fine in fragment shaders as well. */
2425         WARN("Using %s in fragment shader.\n", sample_function.name);
2426     }
2427     shader_glsl_gen_sample_code(arg, sampler_idx, coord_param.param_str,
2428                                 &sample_function, swizzle,
2429                                 lod_param.param_str);
2430 }
2431
2432 static void pshader_glsl_texcoord(const SHADER_OPCODE_ARG *arg)
2433 {
2434     /* FIXME: Make this work for more than just 2D textures */
2435     SHADER_BUFFER* buffer = arg->buffer;
2436     DWORD write_mask;
2437     char dst_mask[6];
2438
2439     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2440     shader_glsl_get_write_mask(write_mask, dst_mask);
2441
2442     if (arg->reg_maps->shader_version != WINED3DPS_VERSION(1,4))
2443     {
2444         DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2445         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
2446     } else {
2447         DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
2448         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2449         char dst_swizzle[6];
2450
2451         shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);
2452
2453         if (src_mod == WINED3DSPSM_DZ) {
2454             glsl_src_param_t div_param;
2455             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2456             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
2457
2458             if (mask_size > 1) {
2459                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2460             } else {
2461                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2462             }
2463         } else if (src_mod == WINED3DSPSM_DW) {
2464             glsl_src_param_t div_param;
2465             unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2466             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
2467
2468             if (mask_size > 1) {
2469                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2470             } else {
2471                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2472             }
2473         } else {
2474             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2475         }
2476     }
2477 }
2478
2479 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2480  * Take a 3-component dot product of the TexCoord[dstreg] and src,
2481  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2482 static void pshader_glsl_texdp3tex(const SHADER_OPCODE_ARG *arg)
2483 {
2484     glsl_src_param_t src0_param;
2485     char coord_param[64];
2486     glsl_sample_function_t sample_function;
2487     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2488     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2489     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2490
2491     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2492
2493     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2494      * scalar, and projected sampling would require 4.
2495      *
2496      * It is a dependent read - not valid with conditional NP2 textures
2497      */
2498     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2499
2500     switch(count_bits(sample_function.coord_mask)) {
2501         case 1:
2502             sprintf(coord_param, "dot(gl_TexCoord[%u].xyz, %s)",
2503                     sampler_idx, src0_param.param_str);
2504             break;
2505
2506         case 2:
2507             sprintf(coord_param, "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)",
2508                     sampler_idx, src0_param.param_str);
2509             break;
2510
2511         case 3:
2512             sprintf(coord_param, "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)",
2513                     sampler_idx, src0_param.param_str);
2514             break;
2515         default:
2516             FIXME("Unexpected mask bitcount %d\n", count_bits(sample_function.coord_mask));
2517     }
2518     shader_glsl_gen_sample_code(arg, sampler_idx, coord_param,
2519                                 &sample_function, WINED3DVS_NOSWIZZLE,
2520                                 NULL);
2521 }
2522
2523 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2524  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2525 static void pshader_glsl_texdp3(const SHADER_OPCODE_ARG *arg)
2526 {
2527     glsl_src_param_t src0_param;
2528     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2529     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2530     DWORD dst_mask;
2531     unsigned int mask_size;
2532
2533     dst_mask = shader_glsl_append_dst(arg->buffer, arg);
2534     mask_size = shader_glsl_get_write_mask_size(dst_mask);
2535     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2536
2537     if (mask_size > 1) {
2538         shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2539     } else {
2540         shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2541     }
2542 }
2543
2544 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2545  * Calculate the depth as dst.x / dst.y   */
2546 static void pshader_glsl_texdepth(const SHADER_OPCODE_ARG *arg)
2547 {
2548     glsl_dst_param_t dst_param;
2549
2550     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2551
2552     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2553      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2554      * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2555      * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2556      * >= 1.0 or < 0.0
2557      */
2558     shader_addline(arg->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name);
2559 }
2560
2561 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2562  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2563  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
2564  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2565  */
2566 static void pshader_glsl_texm3x2depth(const SHADER_OPCODE_ARG *arg)
2567 {
2568     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2569     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2570     glsl_src_param_t src0_param;
2571
2572     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2573
2574     shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2575     shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2576 }
2577
2578 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2579  * Calculate the 1st of a 2-row matrix multiplication. */
2580 static void pshader_glsl_texm3x2pad(const SHADER_OPCODE_ARG *arg)
2581 {
2582     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2583     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2584     SHADER_BUFFER* buffer = arg->buffer;
2585     glsl_src_param_t src0_param;
2586
2587     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2588     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2589 }
2590
2591 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2592  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2593 static void pshader_glsl_texm3x3pad(const SHADER_OPCODE_ARG* arg)
2594 {
2595     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2596     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2597     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2598     SHADER_BUFFER* buffer = arg->buffer;
2599     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2600     glsl_src_param_t src0_param;
2601
2602     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2603     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2604     current_state->texcoord_w[current_state->current_row++] = reg;
2605 }
2606
2607 static void pshader_glsl_texm3x2tex(const SHADER_OPCODE_ARG *arg)
2608 {
2609     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2610     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2611     SHADER_BUFFER* buffer = arg->buffer;
2612     glsl_src_param_t src0_param;
2613     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2614     glsl_sample_function_t sample_function;
2615
2616     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2617     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2618
2619     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2620
2621     /* Sample the texture using the calculated coordinates */
2622     shader_glsl_gen_sample_code(arg, reg, "tmp0.xy",
2623                                 &sample_function, WINED3DVS_NOSWIZZLE,
2624                                 NULL);
2625 }
2626
2627 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2628  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2629 static void pshader_glsl_texm3x3tex(const SHADER_OPCODE_ARG *arg)
2630 {
2631     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2632     glsl_src_param_t src0_param;
2633     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2634     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2635     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2636     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2637     glsl_sample_function_t sample_function;
2638
2639     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2640     shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2641
2642     /* Dependent read, not valid with conditional NP2 */
2643     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2644
2645     /* Sample the texture using the calculated coordinates */
2646     shader_glsl_gen_sample_code(arg, reg, "tmp0.xyz",
2647                                 &sample_function, WINED3DVS_NOSWIZZLE,
2648                                 NULL);
2649
2650     current_state->current_row = 0;
2651 }
2652
2653 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2654  * Perform the 3rd row of a 3x3 matrix multiply */
2655 static void pshader_glsl_texm3x3(const SHADER_OPCODE_ARG *arg)
2656 {
2657     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2658     glsl_src_param_t src0_param;
2659     char dst_mask[6];
2660     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2661     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2662     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2663
2664     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2665
2666     shader_glsl_append_dst(arg->buffer, arg);
2667     shader_glsl_get_write_mask(arg->dst, dst_mask);
2668     shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2669
2670     current_state->current_row = 0;
2671 }
2672
2673 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
2674  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2675 static void pshader_glsl_texm3x3spec(const SHADER_OPCODE_ARG *arg)
2676 {
2677     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2678     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2679     glsl_src_param_t src0_param;
2680     glsl_src_param_t src1_param;
2681     SHADER_BUFFER* buffer = arg->buffer;
2682     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2683     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2684     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2685     glsl_sample_function_t sample_function;
2686
2687     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2688     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
2689
2690     /* Perform the last matrix multiply operation */
2691     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2692     /* Reflection calculation */
2693     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2694
2695     /* Dependent read, not valid with conditional NP2 */
2696     shader_glsl_get_sample_function(stype, FALSE, FALSE, FALSE, &sample_function);
2697
2698     /* Sample the texture */
2699     shader_glsl_gen_sample_code(arg, reg, "tmp0.xyz",
2700                                 &sample_function, WINED3DVS_NOSWIZZLE,
2701                                 NULL);
2702
2703     current_state->current_row = 0;
2704 }
2705
2706 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
2707  * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2708 static void pshader_glsl_texm3x3vspec(const SHADER_OPCODE_ARG *arg)
2709 {
2710     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2711     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2712     SHADER_BUFFER* buffer = arg->buffer;
2713     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2714     glsl_src_param_t src0_param;
2715     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2716     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2717     glsl_sample_function_t sample_function;
2718
2719     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2720
2721     /* Perform the last matrix multiply operation */
2722     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2723
2724     /* Construct the eye-ray vector from w coordinates */
2725     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2726             current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2727     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2728
2729     /* Dependent read, not valid with conditional NP2 */
2730     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2731
2732     /* Sample the texture using the calculated coordinates */
2733     shader_glsl_gen_sample_code(arg, reg, "tmp0.xyz",
2734                                 &sample_function, WINED3DVS_NOSWIZZLE,
2735                                 NULL);
2736
2737     current_state->current_row = 0;
2738 }
2739
2740 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2741  * Apply a fake bump map transform.
2742  * texbem is pshader <= 1.3 only, this saves a few version checks
2743  */
2744 static void pshader_glsl_texbem(const SHADER_OPCODE_ARG *arg)
2745 {
2746     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2747     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2748     char coord[128];
2749     glsl_sample_function_t sample_function;
2750     glsl_src_param_t coord_param;
2751     DWORD sampler_type;
2752     DWORD sampler_idx;
2753     DWORD mask;
2754     DWORD flags;
2755     char coord_mask[6];
2756
2757     sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2758     flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2759
2760     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2761     /* Dependent read, not valid with conditional NP2 */
2762     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2763     mask = sample_function.coord_mask;
2764
2765     shader_glsl_get_write_mask(mask, coord_mask);
2766
2767     /* with projective textures, texbem only divides the static texture coord, not the displacement,
2768          * so we can't let the GL handle this.
2769          */
2770     if (flags & WINED3DTTFF_PROJECTED) {
2771         DWORD div_mask=0;
2772         char coord_div_mask[3];
2773         switch (flags & ~WINED3DTTFF_PROJECTED) {
2774             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2775             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2776             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2777             case WINED3DTTFF_COUNT4:
2778             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2779         }
2780         shader_glsl_get_write_mask(div_mask, coord_div_mask);
2781         shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2782     }
2783
2784     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2785
2786     sprintf(coord, "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s",
2787             sampler_idx, coord_mask, sampler_idx, coord_param.param_str, coord_mask);
2788     shader_glsl_gen_sample_code(arg, sampler_idx, coord,
2789                                 &sample_function, WINED3DVS_NOSWIZZLE,
2790                                 NULL);
2791
2792     if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
2793         glsl_src_param_t luminance_param;
2794         glsl_dst_param_t dst_param;
2795
2796         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2797         shader_glsl_add_dst_param(arg, arg->dst, arg->dst_addr, &dst_param);
2798
2799         shader_addline(arg->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
2800                        dst_param.reg_name, dst_param.mask_str,
2801                        luminance_param.param_str, sampler_idx, sampler_idx);
2802     }
2803 }
2804
2805 static void pshader_glsl_bem(const SHADER_OPCODE_ARG *arg)
2806 {
2807     glsl_src_param_t src0_param, src1_param;
2808     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2809
2810     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
2811     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);
2812
2813     shader_glsl_append_dst(arg->buffer, arg);
2814     shader_addline(arg->buffer, "%s + bumpenvmat%d * %s);\n",
2815                    src0_param.param_str, sampler_idx, src1_param.param_str);
2816 }
2817
2818 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2819  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2820 static void pshader_glsl_texreg2ar(const SHADER_OPCODE_ARG *arg)
2821 {
2822     glsl_src_param_t src0_param;
2823     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2824     char src[16];
2825     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2826     glsl_sample_function_t sample_function;
2827
2828     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2829
2830     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2831     sprintf(src, "%s.wx", src0_param.reg_name);
2832     shader_glsl_gen_sample_code(arg, sampler_idx, src,
2833                                 &sample_function, WINED3DVS_NOSWIZZLE,
2834                                 NULL);
2835 }
2836
2837 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2838  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2839 static void pshader_glsl_texreg2gb(const SHADER_OPCODE_ARG *arg)
2840 {
2841     glsl_src_param_t src0_param;
2842     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2843     char src[16];
2844     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2845     glsl_sample_function_t sample_function;
2846
2847     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2848
2849     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2850     sprintf(src, "%s.yz", src0_param.reg_name);
2851     shader_glsl_gen_sample_code(arg, sampler_idx, src,
2852                                 &sample_function, WINED3DVS_NOSWIZZLE,
2853                                 NULL);
2854 }
2855
2856 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2857  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2858 static void pshader_glsl_texreg2rgb(const SHADER_OPCODE_ARG *arg)
2859 {
2860     glsl_src_param_t src0_param;
2861     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2862     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2863     glsl_sample_function_t sample_function;
2864
2865     /* Dependent read, not valid with conditional NP2 */
2866     shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, FALSE, &sample_function);
2867     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2868
2869     shader_glsl_gen_sample_code(arg, sampler_idx, src0_param.param_str,
2870                                 &sample_function, WINED3DVS_NOSWIZZLE,
2871                                 NULL);
2872 }
2873
2874 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2875  * If any of the first 3 components are < 0, discard this pixel */
2876 static void pshader_glsl_texkill(const SHADER_OPCODE_ARG *arg)
2877 {
2878     glsl_dst_param_t dst_param;
2879
2880     /* The argument is a destination parameter, and no writemasks are allowed */
2881     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2882     if ((arg->reg_maps->shader_version >= WINED3DPS_VERSION(2,0)))
2883     {
2884         /* 2.0 shaders compare all 4 components in texkill */
2885         shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2886     } else {
2887         /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
2888          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2889          * 4 components are defined, only the first 3 are used
2890          */
2891         shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2892     }
2893 }
2894
2895 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2896  * dst = dot2(src0, src1) + src2 */
2897 static void pshader_glsl_dp2add(const SHADER_OPCODE_ARG *arg)
2898 {
2899     glsl_src_param_t src0_param;
2900     glsl_src_param_t src1_param;
2901     glsl_src_param_t src2_param;
2902     DWORD write_mask;
2903     unsigned int mask_size;
2904
2905     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2906     mask_size = shader_glsl_get_write_mask_size(write_mask);
2907
2908     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2909     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2910     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2911
2912     if (mask_size > 1) {
2913         shader_addline(arg->buffer, "vec%d(dot(%s, %s) + %s));\n", mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
2914     } else {
2915         shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2916     }
2917 }
2918
2919 static void pshader_glsl_input_pack(SHADER_BUFFER* buffer, const struct semantic* semantics_in,
2920         IWineD3DPixelShader *iface, enum vertexprocessing_mode vertexprocessing)
2921 {
2922    unsigned int i;
2923    IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
2924
2925    for (i = 0; i < MAX_REG_INPUT; i++) {
2926
2927        DWORD usage_token = semantics_in[i].usage;
2928        DWORD register_token = semantics_in[i].reg;
2929        DWORD usage, usage_idx;
2930        char reg_mask[6];
2931
2932        /* Uninitialized */
2933        if (!usage_token) continue;
2934        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2935        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2936        shader_glsl_get_write_mask(register_token, reg_mask);
2937
2938        switch(usage) {
2939
2940            case WINED3DDECLUSAGE_TEXCOORD:
2941                if(usage_idx < 8 && vertexprocessing == pretransformed) {
2942                    shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2943                                   This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
2944                } else {
2945                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2946                                   This->input_reg_map[i], reg_mask, reg_mask);
2947                }
2948                break;
2949
2950            case WINED3DDECLUSAGE_COLOR:
2951                if (usage_idx == 0)
2952                    shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
2953                        This->input_reg_map[i], reg_mask, reg_mask);
2954                else if (usage_idx == 1)
2955                    shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
2956                        This->input_reg_map[i], reg_mask, reg_mask);
2957                else
2958                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2959                        This->input_reg_map[i], reg_mask, reg_mask);
2960                break;
2961
2962            default:
2963                shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2964                    This->input_reg_map[i], reg_mask, reg_mask);
2965         }
2966     }
2967 }
2968
2969 /*********************************************
2970  * Vertex Shader Specific Code begins here
2971  ********************************************/
2972
2973 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
2974     glsl_program_key_t *key;
2975
2976     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2977     key->vshader = entry->vshader;
2978     key->pshader = entry->pshader;
2979     key->vs_args = entry->vs_args;
2980     key->ps_args = entry->ps_args;
2981
2982     hash_table_put(priv->glsl_program_lookup, key, entry);
2983 }
2984
2985 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
2986         IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
2987         struct ps_compile_args *ps_args) {
2988     glsl_program_key_t key;
2989
2990     key.vshader = vshader;
2991     key.pshader = pshader;
2992     key.vs_args = *vs_args;
2993     key.ps_args = *ps_args;
2994
2995     return hash_table_get(priv->glsl_program_lookup, &key);
2996 }
2997
2998 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
2999         struct glsl_shader_prog_link *entry)
3000 {
3001     glsl_program_key_t *key;
3002
3003     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3004     key->vshader = entry->vshader;
3005     key->pshader = entry->pshader;
3006     key->vs_args = entry->vs_args;
3007     key->ps_args = entry->ps_args;
3008     hash_table_remove(priv->glsl_program_lookup, key);
3009
3010     GL_EXTCALL(glDeleteObjectARB(entry->programId));
3011     if (entry->vshader) list_remove(&entry->vshader_entry);
3012     if (entry->pshader) list_remove(&entry->pshader_entry);
3013     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3014     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3015     HeapFree(GetProcessHeap(), 0, entry);
3016 }
3017
3018 static void handle_ps3_input(SHADER_BUFFER *buffer, const struct semantic *semantics_in,
3019         const struct semantic *semantics_out, const WineD3D_GL_Info *gl_info, const DWORD *map)
3020 {
3021     unsigned int i, j;
3022     DWORD usage_token, usage_token_out;
3023     DWORD register_token, register_token_out;
3024     DWORD usage, usage_idx, usage_out, usage_idx_out;
3025     DWORD *set;
3026     DWORD in_idx;
3027     DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
3028     char reg_mask[6], reg_mask_out[6];
3029     char destination[50];
3030
3031     set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3032
3033     if (!semantics_out) {
3034         /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3035         shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3036         shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3037     }
3038
3039     for(i = 0; i < MAX_REG_INPUT; i++) {
3040         usage_token = semantics_in[i].usage;
3041         if (!usage_token) continue;
3042
3043         in_idx = map[i];
3044         if (in_idx >= (in_count + 2)) {
3045             FIXME("More input varyings declared than supported, expect issues\n");
3046             continue;
3047         } else if(map[i] == -1) {
3048             /* Declared, but not read register */
3049             continue;
3050         }
3051
3052         if (in_idx == in_count) {
3053             sprintf(destination, "gl_FrontColor");
3054         } else if (in_idx == in_count + 1) {
3055             sprintf(destination, "gl_FrontSecondaryColor");
3056         } else {
3057             sprintf(destination, "IN[%u]", in_idx);
3058         }
3059
3060         register_token = semantics_in[i].reg;
3061
3062         usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
3063         usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
3064         set[map[i]] = shader_glsl_get_write_mask(register_token, reg_mask);
3065
3066         if(!semantics_out) {
3067             switch(usage) {
3068                 case WINED3DDECLUSAGE_COLOR:
3069                     if (usage_idx == 0)
3070                         shader_addline(buffer, "%s%s = front_color%s;\n",
3071                                        destination, reg_mask, reg_mask);
3072                     else if (usage_idx == 1)
3073                         shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3074                                        destination, reg_mask, reg_mask);
3075                     else
3076                         shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3077                                        destination, reg_mask, reg_mask);
3078                     break;
3079
3080                 case WINED3DDECLUSAGE_TEXCOORD:
3081                     if (usage_idx < 8) {
3082                         shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3083                                        destination, reg_mask, usage_idx, reg_mask);
3084                     } else {
3085                         shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3086                                        destination, reg_mask, reg_mask);
3087                     }
3088                     break;
3089
3090                 case WINED3DDECLUSAGE_FOG:
3091                     shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3092                                    destination, reg_mask, reg_mask);
3093                     break;
3094
3095                 default:
3096                     shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3097                                    destination, reg_mask, reg_mask);
3098             }
3099         } else {
3100             BOOL found = FALSE;
3101             for(j = 0; j < MAX_REG_OUTPUT; j++) {
3102                 usage_token_out = semantics_out[j].usage;
3103                 if (!usage_token_out) continue;
3104                 register_token_out = semantics_out[j].reg;
3105
3106                 usage_out = (usage_token_out & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
3107                 usage_idx_out = (usage_token_out & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
3108                 shader_glsl_get_write_mask(register_token_out, reg_mask_out);
3109
3110                 if(usage == usage_out &&
3111                    usage_idx == usage_idx_out) {
3112                     shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3113                                    destination, reg_mask, j, reg_mask);
3114                     found = TRUE;
3115                 }
3116             }
3117             if(!found) {
3118                 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3119                                destination, reg_mask, reg_mask);
3120             }
3121         }
3122     }
3123
3124     /* This is solely to make the compiler / linker happy and avoid warning about undefined
3125      * varyings. It shouldn't result in any real code executed on the GPU, since all read
3126      * input varyings are assigned above, if the optimizer works properly.
3127      */
3128     for(i = 0; i < in_count + 2; i++) {
3129         if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3130             unsigned int size = 0;
3131             memset(reg_mask, 0, sizeof(reg_mask));
3132             if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3133                 reg_mask[size] = 'x';
3134                 size++;
3135             }
3136             if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3137                 reg_mask[size] = 'y';
3138                 size++;
3139             }
3140             if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3141                 reg_mask[size] = 'z';
3142                 size++;
3143             }
3144             if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3145                 reg_mask[size] = 'w';
3146                 size++;
3147             }
3148
3149             if (i == in_count) {
3150                 sprintf(destination, "gl_FrontColor");
3151             } else if (i == in_count + 1) {
3152                 sprintf(destination, "gl_FrontSecondaryColor");
3153             } else {
3154                 sprintf(destination, "IN[%u]", i);
3155             }
3156
3157             if (size == 1) {
3158                 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3159             } else {
3160                 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3161             }
3162         }
3163     }
3164
3165     HeapFree(GetProcessHeap(), 0, set);
3166 }
3167
3168 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3169         IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3170 {
3171     GLhandleARB ret = 0;
3172     IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3173     IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3174     IWineD3DDeviceImpl *device;
3175     DWORD vs_major = WINED3DSHADER_VERSION_MAJOR(vs->baseShader.reg_maps.shader_version);
3176     DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.reg_maps.shader_version) : 0;
3177     unsigned int i;
3178     SHADER_BUFFER buffer;
3179     DWORD usage_token;
3180     DWORD register_token;
3181     DWORD usage, usage_idx, writemask;
3182     char reg_mask[6];
3183     const struct semantic *semantics_out, *semantics_in;
3184
3185     shader_buffer_init(&buffer);
3186
3187     shader_addline(&buffer, "#version 120\n");
3188
3189     if(vs_major < 3 && ps_major < 3) {
3190         /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3191          * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3192          */
3193         device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3194         if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3195             !device->frag_pipe->ffp_proj_control) {
3196             shader_addline(&buffer, "void order_ps_input() {\n");
3197             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3198                 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3199                    vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3200                     shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3201                 }
3202             }
3203             shader_addline(&buffer, "}\n");
3204         } else {
3205             shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3206         }
3207     } else if(ps_major < 3 && vs_major >= 3) {
3208         /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3209         semantics_out = vs->semantics_out;
3210
3211         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3212         for(i = 0; i < MAX_REG_OUTPUT; i++) {
3213             usage_token = semantics_out[i].usage;
3214             if (!usage_token) continue;
3215             register_token = semantics_out[i].reg;
3216
3217             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
3218             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
3219             writemask = shader_glsl_get_write_mask(register_token, reg_mask);
3220
3221             switch(usage) {
3222                 case WINED3DDECLUSAGE_COLOR:
3223                     if (usage_idx == 0)
3224                         shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3225                     else if (usage_idx == 1)
3226                         shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3227                     break;
3228
3229                 case WINED3DDECLUSAGE_POSITION:
3230                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3231                     break;
3232
3233                 case WINED3DDECLUSAGE_TEXCOORD:
3234                     if (usage_idx < 8) {
3235                         if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;
3236
3237                         shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3238                                         usage_idx, reg_mask, i, reg_mask);
3239                         if(!(writemask & WINED3DSP_WRITEMASK_3)) {
3240                             shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
3241                         }
3242                     }
3243                     break;
3244
3245                 case WINED3DDECLUSAGE_PSIZE:
3246                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3247                     break;
3248
3249                 case WINED3DDECLUSAGE_FOG:
3250                     shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3251                     break;
3252
3253                 default:
3254                     break;
3255             }
3256         }
3257         shader_addline(&buffer, "}\n");
3258
3259     } else if(ps_major >= 3 && vs_major >= 3) {
3260         semantics_out = vs->semantics_out;
3261         semantics_in = ps->semantics_in;
3262
3263         /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3264         shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3265         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3266
3267         /* First, sort out position and point size. Those are not passed to the pixel shader */
3268         for(i = 0; i < MAX_REG_OUTPUT; i++) {
3269             usage_token = semantics_out[i].usage;
3270             if (!usage_token) continue;
3271             register_token = semantics_out[i].reg;
3272
3273             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
3274             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
3275             shader_glsl_get_write_mask(register_token, reg_mask);
3276
3277             switch(usage) {
3278                 case WINED3DDECLUSAGE_POSITION:
3279                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3280                     break;
3281
3282                 case WINED3DDECLUSAGE_PSIZE:
3283                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3284                     break;
3285
3286                 default:
3287                     break;
3288             }
3289         }
3290
3291         /* Then, fix the pixel shader input */
3292         handle_ps3_input(&buffer, semantics_in, semantics_out, gl_info, ps->input_reg_map);
3293
3294         shader_addline(&buffer, "}\n");
3295     } else if(ps_major >= 3 && vs_major < 3) {
3296         semantics_in = ps->semantics_in;
3297
3298         shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3299         shader_addline(&buffer, "void order_ps_input() {\n");
3300         /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3301          * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3302          * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3303          */
3304         handle_ps3_input(&buffer, semantics_in, NULL, gl_info, ps->input_reg_map);
3305         shader_addline(&buffer, "}\n");
3306     } else {
3307         ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3308     }
3309
3310     ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3311     checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3312     GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3313     checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3314     GL_EXTCALL(glCompileShaderARB(ret));
3315     checkGLcall("glCompileShaderARB(ret)");
3316
3317     shader_buffer_free(&buffer);
3318     return ret;
3319 }
3320
3321 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3322         GLhandleARB programId, char prefix)
3323 {
3324     const local_constant *lconst;
3325     GLuint tmp_loc;
3326     const float *value;
3327     char glsl_name[8];
3328
3329     LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3330         value = (const float *)lconst->value;
3331         snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3332         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3333         GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3334     }
3335     checkGLcall("Hardcoding local constants\n");
3336 }
3337
3338 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3339  * It sets the programId on the current StateBlock (because it should be called
3340  * inside of the DrawPrimitive() part of the render loop).
3341  *
3342  * If a program for the given combination does not exist, create one, and store
3343  * the program in the hash table.  If it creates a program, it will link the
3344  * given objects, too.
3345  */
3346 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3347     IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
3348     struct shader_glsl_priv *priv          = This->shader_priv;
3349     const WineD3D_GL_Info *gl_info         = &This->adapter->gl_info;
3350     IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
3351     IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
3352     struct glsl_shader_prog_link *entry    = NULL;
3353     GLhandleARB programId                  = 0;
3354     GLhandleARB reorder_shader_id          = 0;
3355     int i;
3356     char glsl_name[8];
3357     GLhandleARB vshader_id, pshader_id;
3358     struct ps_compile_args ps_compile_args;
3359     struct vs_compile_args vs_compile_args;
3360
3361     if(use_vs) {
3362         find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3363     } else {
3364         /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3365         memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3366     }
3367     if(use_ps) {
3368         find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3369     } else {
3370         /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3371         memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3372     }
3373     entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3374     if (entry) {
3375         priv->glsl_program = entry;
3376         return;
3377     }
3378
3379     /* If we get to this point, then no matching program exists, so we create one */
3380     programId = GL_EXTCALL(glCreateProgramObjectARB());
3381     TRACE("Created new GLSL shader program %u\n", programId);
3382
3383     /* Create the entry */
3384     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3385     entry->programId = programId;
3386     entry->vshader = vshader;
3387     entry->pshader = pshader;
3388     entry->vs_args = vs_compile_args;
3389     entry->ps_args = ps_compile_args;
3390     entry->constant_version = 0;
3391     /* Add the hash table entry */
3392     add_glsl_program_entry(priv, entry);
3393
3394     /* Set the current program */
3395     priv->glsl_program = entry;
3396
3397     if(use_vs) {
3398         vshader_id = find_gl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
3399     } else {
3400         vshader_id = 0;
3401     }
3402
3403     /* Attach GLSL vshader */
3404     if (vshader_id) {
3405         int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
3406         char tmp_name[10];
3407
3408         reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
3409         TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
3410         GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
3411         checkGLcall("glAttachObjectARB");
3412         /* Flag the reorder function for deletion, then it will be freed automatically when the program
3413          * is destroyed
3414          */
3415         GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
3416
3417         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
3418         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
3419         checkGLcall("glAttachObjectARB");
3420
3421         /* Bind vertex attributes to a corresponding index number to match
3422          * the same index numbers as ARB_vertex_programs (makes loading
3423          * vertex attributes simpler).  With this method, we can use the
3424          * exact same code to load the attributes later for both ARB and
3425          * GLSL shaders.
3426          *
3427          * We have to do this here because we need to know the Program ID
3428          * in order to make the bindings work, and it has to be done prior
3429          * to linking the GLSL program. */
3430         for (i = 0; i < max_attribs; ++i) {
3431             if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
3432                 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
3433                 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
3434             }
3435         }
3436         checkGLcall("glBindAttribLocationARB");
3437
3438         list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3439     }
3440
3441     if(use_ps) {
3442         pshader_id = find_gl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
3443     } else {
3444         pshader_id = 0;
3445     }
3446
3447     /* Attach GLSL pshader */
3448     if (pshader_id) {
3449         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3450         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3451         checkGLcall("glAttachObjectARB");
3452
3453         list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3454     }
3455
3456     /* Link the program */
3457     TRACE("Linking GLSL shader program %u\n", programId);
3458     GL_EXTCALL(glLinkProgramARB(programId));
3459     print_glsl_info_log(&GLINFO_LOCATION, programId);
3460
3461     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3462     for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3463         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3464         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3465     }
3466     for (i = 0; i < MAX_CONST_I; ++i) {
3467         snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
3468         entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3469     }
3470     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3471     for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3472         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3473         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3474     }
3475     for (i = 0; i < MAX_CONST_I; ++i) {
3476         snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
3477         entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3478     }
3479
3480     if(pshader) {
3481         for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
3482             char name[32];
3483             sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
3484             entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3485             sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3486             entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3487             sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3488             entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3489         }
3490     }
3491
3492
3493     entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
3494     entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3495     checkGLcall("Find glsl program uniform locations");
3496
3497     if (pshader
3498             && WINED3DSHADER_VERSION_MAJOR(((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version) >= 3
3499             && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > GL_LIMITS(glsl_varyings) / 4)
3500     {
3501         TRACE("Shader %d needs vertex color clamping disabled\n", programId);
3502         entry->vertex_color_clamp = GL_FALSE;
3503     } else {
3504         entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
3505     }
3506
3507     /* Set the shader to allow uniform loading on it */
3508     GL_EXTCALL(glUseProgramObjectARB(programId));
3509     checkGLcall("glUseProgramObjectARB(programId)");
3510
3511     /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
3512      * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
3513      * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
3514      * vertex shader with fixed function pixel processing is used we make sure that the card
3515      * supports enough samplers to allow the max number of vertex samplers with all possible
3516      * fixed function fragment processing setups. So once the program is linked these samplers
3517      * won't change.
3518      */
3519     if(vshader_id) {
3520         /* Load vertex shader samplers */
3521         shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
3522     }
3523     if(pshader_id) {
3524         /* Load pixel shader samplers */
3525         shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
3526     }
3527
3528     /* If the local constants do not have to be loaded with the environment constants,
3529      * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
3530      * later
3531      */
3532     if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
3533         hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
3534     }
3535     if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
3536         hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
3537     }
3538 }
3539
3540 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
3541 {
3542     GLhandleARB program_id;
3543     GLhandleARB vshader_id, pshader_id;
3544     static const char *blt_vshader[] =
3545     {
3546         "#version 120\n"
3547         "void main(void)\n"
3548         "{\n"
3549         "    gl_Position = gl_Vertex;\n"
3550         "    gl_FrontColor = vec4(1.0);\n"
3551         "    gl_TexCoord[0] = gl_MultiTexCoord0;\n"
3552         "}\n"
3553     };
3554
3555     static const char *blt_pshaders[tex_type_count] =
3556     {
3557         /* tex_1d */
3558         NULL,
3559         /* tex_2d */
3560         "#version 120\n"
3561         "uniform sampler2D sampler;\n"
3562         "void main(void)\n"
3563         "{\n"
3564         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3565         "}\n",
3566         /* tex_3d */
3567         NULL,
3568         /* tex_cube */
3569         "#version 120\n"
3570         "uniform samplerCube sampler;\n"
3571         "void main(void)\n"
3572         "{\n"
3573         "    gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
3574         "}\n",
3575         /* tex_rect */
3576         "#version 120\n"
3577         "#extension GL_ARB_texture_rectangle : enable\n"
3578         "uniform sampler2DRect sampler;\n"
3579         "void main(void)\n"
3580         "{\n"
3581         "    gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
3582         "}\n",
3583     };
3584
3585     if (!blt_pshaders[tex_type])
3586     {
3587         FIXME("tex_type %#x not supported\n", tex_type);
3588         tex_type = tex_2d;
3589     }
3590
3591     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3592     GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3593     GL_EXTCALL(glCompileShaderARB(vshader_id));
3594
3595     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3596     GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
3597     GL_EXTCALL(glCompileShaderARB(pshader_id));
3598
3599     program_id = GL_EXTCALL(glCreateProgramObjectARB());
3600     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3601     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3602     GL_EXTCALL(glLinkProgramARB(program_id));
3603
3604     print_glsl_info_log(&GLINFO_LOCATION, program_id);
3605
3606     /* Once linked we can mark the shaders for deletion. They will be deleted once the program
3607      * is destroyed
3608      */
3609     GL_EXTCALL(glDeleteObjectARB(vshader_id));
3610     GL_EXTCALL(glDeleteObjectARB(pshader_id));
3611     return program_id;
3612 }
3613
3614 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3615     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3616     struct shader_glsl_priv *priv = This->shader_priv;
3617     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3618     GLhandleARB program_id = 0;
3619     GLenum old_vertex_color_clamp, current_vertex_color_clamp;
3620
3621     old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3622
3623     if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3624     else priv->glsl_program = NULL;
3625
3626     current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3627
3628     if (old_vertex_color_clamp != current_vertex_color_clamp) {
3629         if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
3630             GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
3631             checkGLcall("glClampColorARB");
3632         } else {
3633             FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
3634         }
3635     }
3636
3637     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3638     if (program_id) TRACE("Using GLSL program %u\n", program_id);
3639     GL_EXTCALL(glUseProgramObjectARB(program_id));
3640     checkGLcall("glUseProgramObjectARB");
3641 }
3642
3643 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
3644     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3645     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3646     struct shader_glsl_priv *priv = This->shader_priv;
3647     GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
3648
3649     if (!*blt_program) {
3650         GLhandleARB loc;
3651         *blt_program = create_glsl_blt_shader(gl_info, tex_type);
3652         loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
3653         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3654         GL_EXTCALL(glUniform1iARB(loc, 0));
3655     } else {
3656         GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3657     }
3658 }
3659
3660 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
3661     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3662     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3663     struct shader_glsl_priv *priv = This->shader_priv;
3664     GLhandleARB program_id;
3665
3666     program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3667     if (program_id) TRACE("Using GLSL program %u\n", program_id);
3668
3669     GL_EXTCALL(glUseProgramObjectARB(program_id));
3670     checkGLcall("glUseProgramObjectARB");
3671 }
3672
3673 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
3674     const struct list *linked_programs;
3675     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
3676     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3677     struct shader_glsl_priv *priv = device->shader_priv;
3678     const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
3679     IWineD3DPixelShaderImpl *ps = NULL;
3680     IWineD3DVertexShaderImpl *vs = NULL;
3681
3682     /* Note: Do not use QueryInterface here to find out which shader type this is because this code
3683      * can be called from IWineD3DBaseShader::Release
3684      */
3685     char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
3686
3687     if(pshader) {
3688         ps = (IWineD3DPixelShaderImpl *) This;
3689         if(ps->num_gl_shaders == 0) return;
3690     } else {
3691         vs = (IWineD3DVertexShaderImpl *) This;
3692         if(vs->num_gl_shaders == 0) return;
3693     }
3694
3695     linked_programs = &This->baseShader.linked_programs;
3696
3697     TRACE("Deleting linked programs\n");
3698     if (linked_programs->next) {
3699         struct glsl_shader_prog_link *entry, *entry2;
3700
3701         if(pshader) {
3702             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
3703                 delete_glsl_program_entry(priv, gl_info, entry);
3704             }
3705         } else {
3706             LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
3707                 delete_glsl_program_entry(priv, gl_info, entry);
3708             }
3709         }
3710     }
3711
3712     if(pshader) {
3713         UINT i;
3714
3715         ENTER_GL();
3716         for(i = 0; i < ps->num_gl_shaders; i++) {
3717             TRACE("deleting pshader %u\n", ps->gl_shaders[i].prgId);
3718             GL_EXTCALL(glDeleteObjectARB(ps->gl_shaders[i].prgId));
3719             checkGLcall("glDeleteObjectARB");
3720         }
3721         LEAVE_GL();
3722         HeapFree(GetProcessHeap(), 0, ps->gl_shaders);
3723         ps->gl_shaders = NULL;
3724         ps->num_gl_shaders = 0;
3725         ps->shader_array_size = 0;
3726     } else {
3727         UINT i;
3728
3729         ENTER_GL();
3730         for(i = 0; i < vs->num_gl_shaders; i++) {
3731             TRACE("deleting vshader %u\n", vs->gl_shaders[i].prgId);
3732             GL_EXTCALL(glDeleteObjectARB(vs->gl_shaders[i].prgId));
3733             checkGLcall("glDeleteObjectARB");
3734         }
3735         LEAVE_GL();
3736         HeapFree(GetProcessHeap(), 0, vs->gl_shaders);
3737         vs->gl_shaders = NULL;
3738         vs->num_gl_shaders = 0;
3739         vs->shader_array_size = 0;
3740     }
3741 }
3742
3743 static unsigned int glsl_program_key_hash(const void *key)
3744 {
3745     const glsl_program_key_t *k = key;
3746
3747     unsigned int hash = ((DWORD_PTR) k->vshader) | ((DWORD_PTR) k->pshader) << 16;
3748     hash += ~(hash << 15);
3749     hash ^=  (hash >> 10);
3750     hash +=  (hash << 3);
3751     hash ^=  (hash >> 6);
3752     hash += ~(hash << 11);
3753     hash ^=  (hash >> 16);
3754
3755     return hash;
3756 }
3757
3758 static BOOL glsl_program_key_compare(const void *keya, const void *keyb)
3759 {
3760     const glsl_program_key_t *ka = keya;
3761     const glsl_program_key_t *kb = keyb;
3762
3763     return ka->vshader == kb->vshader && ka->pshader == kb->pshader &&
3764            (memcmp(&ka->ps_args, &kb->ps_args, sizeof(kb->ps_args)) == 0) &&
3765            (memcmp(&ka->vs_args, &kb->vs_args, sizeof(kb->vs_args)) == 0);
3766 }
3767
3768 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
3769 {
3770     SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
3771     void *mem = HeapAlloc(GetProcessHeap(), 0, size);
3772
3773     if (!mem)
3774     {
3775         ERR("Failed to allocate memory\n");
3776         return FALSE;
3777     }
3778
3779     heap->entries = mem;
3780     heap->entries[1].version = 0;
3781     heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
3782     heap->size = 1;
3783
3784     return TRUE;
3785 }
3786
3787 static void constant_heap_free(struct constant_heap *heap)
3788 {
3789     HeapFree(GetProcessHeap(), 0, heap->entries);
3790 }
3791
3792 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
3793     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3794     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3795     struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
3796     SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
3797
3798     priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
3799     if (!priv->stack)
3800     {
3801         ERR("Failed to allocate memory.\n");
3802         HeapFree(GetProcessHeap(), 0, priv);
3803         return E_OUTOFMEMORY;
3804     }
3805
3806     if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
3807     {
3808         ERR("Failed to initialize vertex shader constant heap\n");
3809         HeapFree(GetProcessHeap(), 0, priv->stack);
3810         HeapFree(GetProcessHeap(), 0, priv);
3811         return E_OUTOFMEMORY;
3812     }
3813
3814     if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
3815     {
3816         ERR("Failed to initialize pixel shader constant heap\n");
3817         constant_heap_free(&priv->vconst_heap);
3818         HeapFree(GetProcessHeap(), 0, priv->stack);
3819         HeapFree(GetProcessHeap(), 0, priv);
3820         return E_OUTOFMEMORY;
3821     }
3822
3823     priv->glsl_program_lookup = hash_table_create(glsl_program_key_hash, glsl_program_key_compare);
3824     priv->next_constant_version = 1;
3825
3826     This->shader_priv = priv;
3827     return WINED3D_OK;
3828 }
3829
3830 static void shader_glsl_free(IWineD3DDevice *iface) {
3831     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3832     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3833     struct shader_glsl_priv *priv = This->shader_priv;
3834     int i;
3835
3836     for (i = 0; i < tex_type_count; ++i)
3837     {
3838         if (priv->depth_blt_program[i])
3839         {
3840             GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
3841         }
3842     }
3843
3844     hash_table_destroy(priv->glsl_program_lookup, NULL, NULL);
3845     constant_heap_free(&priv->pconst_heap);
3846     constant_heap_free(&priv->vconst_heap);
3847
3848     HeapFree(GetProcessHeap(), 0, This->shader_priv);
3849     This->shader_priv = NULL;
3850 }
3851
3852 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
3853     /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
3854     return FALSE;
3855 }
3856
3857 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer, const struct ps_compile_args *args) {
3858     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3859     const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3860     CONST DWORD *function = This->baseShader.function;
3861     const char *fragcolor;
3862     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3863
3864     /* Create the hw GLSL shader object and assign it as the shader->prgId */
3865     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3866
3867     shader_addline(buffer, "#version 120\n");
3868
3869     if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3870         shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
3871     }
3872     if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3873         /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3874          * drivers write a warning if we don't do so
3875          */
3876         shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3877     }
3878
3879     /* Base Declarations */
3880     shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
3881
3882     /* Pack 3.0 inputs */
3883     if (reg_maps->shader_version >= WINED3DPS_VERSION(3,0) && args->vp_mode != vertexshader) {
3884         pshader_glsl_input_pack(buffer, This->semantics_in, iface, args->vp_mode);
3885     }
3886
3887     /* Base Shader Body */
3888     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
3889
3890     /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3891     if (reg_maps->shader_version < WINED3DPS_VERSION(2,0))
3892     {
3893         /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3894         if(GL_SUPPORT(ARB_DRAW_BUFFERS))
3895             shader_addline(buffer, "gl_FragData[0] = R0;\n");
3896         else
3897             shader_addline(buffer, "gl_FragColor = R0;\n");
3898     }
3899
3900     if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3901         fragcolor = "gl_FragData[0]";
3902     } else {
3903         fragcolor = "gl_FragColor";
3904     }
3905     if(args->srgb_correction) {
3906         shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
3907                         fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
3908                         srgb_sub_high, srgb_sub_high, srgb_sub_high);
3909         shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
3910         shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
3911         shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
3912         shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
3913         shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
3914     }
3915     /* Pixel shader < 3.0 do not replace the fog stage.
3916      * This implements linear fog computation and blending.
3917      * TODO: non linear fog
3918      * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3919      * -1/(e-s) and e/(e-s) respectively.
3920      */
3921     if(reg_maps->shader_version < WINED3DPS_VERSION(3,0)) {
3922         switch(args->fog) {
3923             case FOG_OFF: break;
3924             case FOG_LINEAR:
3925                 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3926                 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3927                 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3928                 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3929                 break;
3930             case FOG_EXP:
3931                 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3932                 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3933                 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3934                 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3935                 break;
3936             case FOG_EXP2:
3937                 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3938                 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3939                 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3940                 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3941                 break;
3942         }
3943     }
3944
3945     shader_addline(buffer, "}\n");
3946
3947     TRACE("Compiling shader object %u\n", shader_obj);
3948     GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3949     GL_EXTCALL(glCompileShaderARB(shader_obj));
3950     print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
3951
3952     /* Store the shader object */
3953     return shader_obj;
3954 }
3955
3956 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer, const struct vs_compile_args *args) {
3957     IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
3958     const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3959     CONST DWORD *function = This->baseShader.function;
3960     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3961
3962     /* Create the hw GLSL shader program and assign it as the shader->prgId */
3963     GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3964
3965     shader_addline(buffer, "#version 120\n");
3966
3967     /* Base Declarations */
3968     shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
3969
3970     /* Base Shader Body */
3971     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
3972
3973     /* Unpack 3.0 outputs */
3974     if (reg_maps->shader_version >= WINED3DVS_VERSION(3,0)) shader_addline(buffer, "order_ps_input(OUT);\n");
3975     else shader_addline(buffer, "order_ps_input();\n");
3976
3977     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
3978      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
3979      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
3980      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
3981      */
3982     if(args->fog_src == VS_FOG_Z) {
3983         shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
3984     } else if (!reg_maps->fog) {
3985         shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
3986     }
3987
3988     /* Write the final position.
3989      *
3990      * OpenGL coordinates specify the center of the pixel while d3d coords specify
3991      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
3992      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3993      * contains 1.0 to allow a mad.
3994      */
3995     shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
3996     shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
3997
3998     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3999      *
4000      * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4001      * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4002      * which is the same as z = z * 2 - w.
4003      */
4004     shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4005
4006     shader_addline(buffer, "}\n");
4007
4008     TRACE("Compiling shader object %u\n", shader_obj);
4009     GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4010     GL_EXTCALL(glCompileShaderARB(shader_obj));
4011     print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4012
4013     return shader_obj;
4014 }
4015
4016 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4017 {
4018     /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4019      * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4020      * vs_nv_version which is based on NV_vertex_program.
4021      * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4022      * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4023      * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4024      * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4025      */
4026     if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4027         pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4028     else
4029         pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4030     TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4031     pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4032
4033     /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4034      * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4035      * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4036      * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4037      * in max native instructions. Intel and others also offer the info in this extension but they
4038      * don't support GLSL (at least on Windows).
4039      *
4040      * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4041      * of instructions is 512 or less we have to do with ps2.0 hardware.
4042      * NOTE: ps3.0 hardware requires 512 or more instructions but ati and nvidia offer 'enough' (1024 vs 4096) on their most basic ps3.0 hardware.
4043      */
4044     if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4045         pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4046     else
4047         pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4048
4049     /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4050      * Direct3D minimum requirement.
4051      *
4052      * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4053      * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4054      *
4055      * The problem is that the refrast clamps temporary results in the shader to
4056      * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4057      * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4058      * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4059      * offer a way to query this.
4060      */
4061     pCaps->PixelShader1xMaxValue = 8.0;
4062     TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4063 }
4064
4065 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4066 {
4067     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4068     {
4069         TRACE("Checking support for fixup:\n");
4070         dump_color_fixup_desc(fixup);
4071     }
4072
4073     /* We support everything except YUV conversions. */
4074     if (!is_yuv_fixup(fixup))
4075     {
4076         TRACE("[OK]\n");
4077         return TRUE;
4078     }
4079
4080     TRACE("[FAILED]\n");
4081     return FALSE;
4082 }
4083
4084 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4085 {
4086     /* WINED3DSIH_ABS           */ shader_glsl_map2gl,
4087     /* WINED3DSIH_ADD           */ shader_glsl_arith,
4088     /* WINED3DSIH_BEM           */ pshader_glsl_bem,
4089     /* WINED3DSIH_BREAK         */ shader_glsl_break,
4090     /* WINED3DSIH_BREAKC        */ shader_glsl_breakc,
4091     /* WINED3DSIH_BREAKP        */ NULL,
4092     /* WINED3DSIH_CALL          */ shader_glsl_call,
4093     /* WINED3DSIH_CALLNZ        */ shader_glsl_callnz,
4094     /* WINED3DSIH_CMP           */ shader_glsl_cmp,
4095     /* WINED3DSIH_CND           */ shader_glsl_cnd,
4096     /* WINED3DSIH_CRS           */ shader_glsl_cross,
4097     /* WINED3DSIH_DCL           */ NULL,
4098     /* WINED3DSIH_DEF           */ NULL,
4099     /* WINED3DSIH_DEFB          */ NULL,
4100     /* WINED3DSIH_DEFI          */ NULL,
4101     /* WINED3DSIH_DP2ADD        */ pshader_glsl_dp2add,
4102     /* WINED3DSIH_DP3           */ shader_glsl_dot,
4103     /* WINED3DSIH_DP4           */ shader_glsl_dot,
4104     /* WINED3DSIH_DST           */ shader_glsl_dst,
4105     /* WINED3DSIH_DSX           */ shader_glsl_map2gl,
4106     /* WINED3DSIH_DSY           */ shader_glsl_map2gl,
4107     /* WINED3DSIH_ELSE          */ shader_glsl_else,
4108     /* WINED3DSIH_ENDIF         */ shader_glsl_end,
4109     /* WINED3DSIH_ENDLOOP       */ shader_glsl_end,
4110     /* WINED3DSIH_ENDREP        */ shader_glsl_end,
4111     /* WINED3DSIH_EXP           */ shader_glsl_map2gl,
4112     /* WINED3DSIH_EXPP          */ shader_glsl_expp,
4113     /* WINED3DSIH_FRC           */ shader_glsl_map2gl,
4114     /* WINED3DSIH_IF            */ shader_glsl_if,
4115     /* WINED3DSIH_IFC           */ shader_glsl_ifc,
4116     /* WINED3DSIH_LABEL         */ shader_glsl_label,
4117     /* WINED3DSIH_LIT           */ shader_glsl_lit,
4118     /* WINED3DSIH_LOG           */ shader_glsl_log,
4119     /* WINED3DSIH_LOGP          */ shader_glsl_log,
4120     /* WINED3DSIH_LOOP          */ shader_glsl_loop,
4121     /* WINED3DSIH_LRP           */ shader_glsl_lrp,
4122     /* WINED3DSIH_M3x2          */ shader_glsl_mnxn,
4123     /* WINED3DSIH_M3x3          */ shader_glsl_mnxn,
4124     /* WINED3DSIH_M3x4          */ shader_glsl_mnxn,
4125     /* WINED3DSIH_M4x3          */ shader_glsl_mnxn,
4126     /* WINED3DSIH_M4x4          */ shader_glsl_mnxn,
4127     /* WINED3DSIH_MAD           */ shader_glsl_mad,
4128     /* WINED3DSIH_MAX           */ shader_glsl_map2gl,
4129     /* WINED3DSIH_MIN           */ shader_glsl_map2gl,
4130     /* WINED3DSIH_MOV           */ shader_glsl_mov,
4131     /* WINED3DSIH_MOVA          */ shader_glsl_mov,
4132     /* WINED3DSIH_MUL           */ shader_glsl_arith,
4133     /* WINED3DSIH_NOP           */ NULL,
4134     /* WINED3DSIH_NRM           */ shader_glsl_map2gl,
4135     /* WINED3DSIH_PHASE         */ NULL,
4136     /* WINED3DSIH_POW           */ shader_glsl_pow,
4137     /* WINED3DSIH_RCP           */ shader_glsl_rcp,
4138     /* WINED3DSIH_REP           */ shader_glsl_rep,
4139     /* WINED3DSIH_RET           */ NULL,
4140     /* WINED3DSIH_RSQ           */ shader_glsl_rsq,
4141     /* WINED3DSIH_SETP          */ NULL,
4142     /* WINED3DSIH_SGE           */ shader_glsl_compare,
4143     /* WINED3DSIH_SGN           */ shader_glsl_map2gl,
4144     /* WINED3DSIH_SINCOS        */ shader_glsl_sincos,
4145     /* WINED3DSIH_SLT           */ shader_glsl_compare,
4146     /* WINED3DSIH_SUB           */ shader_glsl_arith,
4147     /* WINED3DSIH_TEX           */ pshader_glsl_tex,
4148     /* WINED3DSIH_TEXBEM        */ pshader_glsl_texbem,
4149     /* WINED3DSIH_TEXBEML       */ pshader_glsl_texbem,
4150     /* WINED3DSIH_TEXCOORD      */ pshader_glsl_texcoord,
4151     /* WINED3DSIH_TEXDEPTH      */ pshader_glsl_texdepth,
4152     /* WINED3DSIH_TEXDP3        */ pshader_glsl_texdp3,
4153     /* WINED3DSIH_TEXDP3TEX     */ pshader_glsl_texdp3tex,
4154     /* WINED3DSIH_TEXKILL       */ pshader_glsl_texkill,
4155     /* WINED3DSIH_TEXLDD        */ NULL,
4156     /* WINED3DSIH_TEXLDL        */ shader_glsl_texldl,
4157     /* WINED3DSIH_TEXM3x2DEPTH  */ pshader_glsl_texm3x2depth,
4158     /* WINED3DSIH_TEXM3x2PAD    */ pshader_glsl_texm3x2pad,
4159     /* WINED3DSIH_TEXM3x2TEX    */ pshader_glsl_texm3x2tex,
4160     /* WINED3DSIH_TEXM3x3       */ pshader_glsl_texm3x3,
4161     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
4162     /* WINED3DSIH_TEXM3x3PAD    */ pshader_glsl_texm3x3pad,
4163     /* WINED3DSIH_TEXM3x3SPEC   */ pshader_glsl_texm3x3spec,
4164     /* WINED3DSIH_TEXM3x3TEX    */ pshader_glsl_texm3x3tex,
4165     /* WINED3DSIH_TEXM3x3VSPEC  */ pshader_glsl_texm3x3vspec,
4166     /* WINED3DSIH_TEXREG2AR     */ pshader_glsl_texreg2ar,
4167     /* WINED3DSIH_TEXREG2GB     */ pshader_glsl_texreg2gb,
4168     /* WINED3DSIH_TEXREG2RGB    */ pshader_glsl_texreg2rgb,
4169 };
4170
4171 const shader_backend_t glsl_shader_backend = {
4172     shader_glsl_instruction_handler_table,
4173     shader_glsl_select,
4174     shader_glsl_select_depth_blt,
4175     shader_glsl_deselect_depth_blt,
4176     shader_glsl_update_float_vertex_constants,
4177     shader_glsl_update_float_pixel_constants,
4178     shader_glsl_load_constants,
4179     shader_glsl_destroy,
4180     shader_glsl_alloc,
4181     shader_glsl_free,
4182     shader_glsl_dirty_const,
4183     shader_glsl_generate_pshader,
4184     shader_glsl_generate_vshader,
4185     shader_glsl_get_caps,
4186     shader_glsl_color_fixup_supported,
4187 };