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