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