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