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