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