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