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