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