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