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