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