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