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