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