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