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