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