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