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