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