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