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