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