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