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