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