wintrust: Implement SoftpubCleanup.
[wine] / dlls / wined3d / glsl_shader.c
1 /*
2  * GLSL pixel and vertex shader implementation
3  *
4  * Copyright 2006 Jason Green 
5  * Copyright 2006-2007 Henri Verbeet
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 /*
23  * D3D shader asm has swizzles on source parameters, and write masks for
24  * destination parameters. GLSL uses swizzles for both. The result of this is
25  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
26  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
27  * mask for the destination parameter into account.
28  */
29
30 #include "config.h"
31 #include <stdio.h>
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
36
37 #define GLINFO_LOCATION      (*gl_info)
38
39 typedef struct {
40     char reg_name[50];
41     char mask_str[6];
42 } glsl_dst_param_t;
43
44 typedef struct {
45     char reg_name[50];
46     char param_str[100];
47 } glsl_src_param_t;
48
49 typedef struct {
50     const char *name;
51     DWORD coord_mask;
52 } glsl_sample_function_t;
53
54 /** Prints the GLSL info log which will contain error messages if they exist */
55 void print_glsl_info_log(WineD3D_GL_Info *gl_info, GLhandleARB obj) {
56     
57     int infologLength = 0;
58     char *infoLog;
59
60     GL_EXTCALL(glGetObjectParameterivARB(obj,
61                GL_OBJECT_INFO_LOG_LENGTH_ARB,
62                &infologLength));
63
64     /* A size of 1 is just a null-terminated string, so the log should be bigger than
65      * that if there are errors. */
66     if (infologLength > 1)
67     {
68         infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
69         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
70         FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
71         HeapFree(GetProcessHeap(), 0, infoLog);
72     }
73 }
74
75 /**
76  * Loads (pixel shader) samplers
77  */
78 static void shader_glsl_load_psamplers(
79     WineD3D_GL_Info *gl_info,
80     IWineD3DStateBlock* iface) {
81
82     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
83     GLhandleARB programId = stateBlock->glsl_program->programId;
84     GLhandleARB name_loc;
85     int i;
86     char sampler_name[20];
87
88     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
89         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
90         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
91         if (name_loc != -1) {
92             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
93             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
94                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
95                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
96                 checkGLcall("glUniform1iARB");
97             } else {
98                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
99             }
100         }
101     }
102 }
103
104 static void shader_glsl_load_vsamplers(WineD3D_GL_Info *gl_info, IWineD3DStateBlock* iface) {
105     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
106     GLhandleARB programId = stateBlock->glsl_program->programId;
107     GLhandleARB name_loc;
108     char sampler_name[20];
109     int i;
110
111     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
112         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
113         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
114         if (name_loc != -1) {
115             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
116             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
117                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
118                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
119                 checkGLcall("glUniform1iARB");
120             } else {
121                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
122             }
123         }
124     }
125 }
126
127 /** 
128  * Loads floating point constants (aka uniforms) into the currently set GLSL program.
129  * When constant_list == NULL, it will load all the constants.
130  */
131 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
132         unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
133         struct list *constant_list) {
134     constants_entry *constant;
135     local_constant* lconst;
136     GLhandleARB tmp_loc;
137     DWORD i, j;
138     DWORD *idx;
139
140     if (TRACE_ON(d3d_shader)) {
141         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
142             idx = constant->idx;
143             j = constant->count;
144             while (j--) {
145                 i = *idx++;
146                 tmp_loc = constant_locations[i];
147                 if (tmp_loc != -1) {
148                     TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
149                             constants[i * 4 + 0], constants[i * 4 + 1],
150                             constants[i * 4 + 2], constants[i * 4 + 3]);
151                 }
152             }
153         }
154     }
155     LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
156         idx = constant->idx;
157         j = constant->count;
158         while (j--) {
159             i = *idx++;
160             tmp_loc = constant_locations[i];
161             if (tmp_loc != -1) {
162                 /* We found this uniform name in the program - go ahead and send the data */
163                 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
164             }
165         }
166     }
167     checkGLcall("glUniform4fvARB()");
168
169     /* Load immediate constants */
170     if (TRACE_ON(d3d_shader)) {
171         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
172             tmp_loc = constant_locations[lconst->idx];
173             if (tmp_loc != -1) {
174                 GLfloat* values = (GLfloat*)lconst->value;
175                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
176                         values[0], values[1], values[2], values[3]);
177             }
178         }
179     }
180     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
181         tmp_loc = constant_locations[lconst->idx];
182         if (tmp_loc != -1) {
183             /* We found this uniform name in the program - go ahead and send the data */
184             GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
185         }
186     }
187     checkGLcall("glUniform4fvARB()");
188 }
189
190 /** 
191  * Loads integer constants (aka uniforms) into the currently set GLSL program.
192  * When @constants_set == NULL, it will load all the constants.
193  */
194 static void shader_glsl_load_constantsI(
195     IWineD3DBaseShaderImpl* This,
196     WineD3D_GL_Info *gl_info,
197     GLhandleARB programId,
198     unsigned max_constants,
199     int* constants,
200     BOOL* constants_set) {
201     
202     GLhandleARB tmp_loc;
203     int i;
204     char tmp_name[8];
205     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
206     const char* prefix = is_pshader? "PI":"VI";
207     struct list* ptr;
208
209     for (i=0; i<max_constants; ++i) {
210         if (NULL == constants_set || constants_set[i]) {
211
212             TRACE_(d3d_constants)("Loading constants %i: %i, %i, %i, %i\n",
213                   i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
214
215             /* TODO: Benchmark and see if it would be beneficial to store the 
216              * locations of the constants to avoid looking up each time */
217             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
218             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
219             if (tmp_loc != -1) {
220                 /* We found this uniform name in the program - go ahead and send the data */
221                 GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, &constants[i*4]));
222                 checkGLcall("glUniform4ivARB");
223             }
224         }
225     }
226
227     /* Load immediate constants */
228     ptr = list_head(&This->baseShader.constantsI);
229     while (ptr) {
230         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
231         unsigned int idx = lconst->idx;
232         GLint* values = (GLint*) lconst->value;
233
234         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
235             values[0], values[1], values[2], values[3]);
236
237         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
238         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
239         if (tmp_loc != -1) {
240             /* We found this uniform name in the program - go ahead and send the data */
241             GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, values));
242             checkGLcall("glUniform4ivARB");
243         }
244         ptr = list_next(&This->baseShader.constantsI, ptr);
245     }
246 }
247
248 /** 
249  * Loads boolean constants (aka uniforms) into the currently set GLSL program.
250  * When @constants_set == NULL, it will load all the constants.
251  */
252 static void shader_glsl_load_constantsB(
253     IWineD3DBaseShaderImpl* This,
254     WineD3D_GL_Info *gl_info,
255     GLhandleARB programId,
256     unsigned max_constants,
257     BOOL* constants,
258     BOOL* constants_set) {
259     
260     GLhandleARB tmp_loc;
261     int i;
262     char tmp_name[8];
263     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
264     const char* prefix = is_pshader? "PB":"VB";
265     struct list* ptr;
266
267     for (i=0; i<max_constants; ++i) {
268         if (NULL == constants_set || constants_set[i]) {
269
270             TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i*4]);
271
272             /* TODO: Benchmark and see if it would be beneficial to store the 
273              * locations of the constants to avoid looking up each time */
274             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
275             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
276             if (tmp_loc != -1) {
277                 /* We found this uniform name in the program - go ahead and send the data */
278                 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i*4]));
279                 checkGLcall("glUniform1ivARB");
280             }
281         }
282     }
283
284     /* Load immediate constants */
285     ptr = list_head(&This->baseShader.constantsB);
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\n", idx, values[0]);
292
293         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
294         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
295         if (tmp_loc != -1) {
296             /* We found this uniform name in the program - go ahead and send the data */
297             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
298             checkGLcall("glUniform1ivARB");
299         }
300         ptr = list_next(&This->baseShader.constantsB, ptr);
301     }
302 }
303
304
305
306 /**
307  * Loads the app-supplied constants into the currently set GLSL program.
308  */
309 void shader_glsl_load_constants(
310     IWineD3DDevice* device,
311     char usePixelShader,
312     char useVertexShader) {
313    
314     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
315     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
316     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
317
318     GLhandleARB *constant_locations;
319     struct list *constant_list;
320     GLhandleARB programId;
321     GLint pos;
322
323     if (!stateBlock->glsl_program) {
324         /* No GLSL program set - nothing to do. */
325         return;
326     }
327     programId = stateBlock->glsl_program->programId;
328
329     if (useVertexShader) {
330         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
331         GLint pos;
332
333         constant_locations = stateBlock->glsl_program->vuniformF_locations;
334         constant_list = &stateBlock->set_vconstantsF;
335
336         /* Load vertex shader samplers */
337         shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)stateBlock);
338
339         /* Load DirectX 9 float constants/uniforms for vertex shader */
340         shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
341                 stateBlock->vertexShaderConstantF, constant_locations, constant_list);
342
343         /* Load DirectX 9 integer constants/uniforms for vertex shader */
344         shader_glsl_load_constantsI(vshader, gl_info, programId, MAX_CONST_I,
345                                     stateBlock->vertexShaderConstantI,
346                                     stateBlock->changed.vertexShaderConstantsI);
347
348         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
349         shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
350                                     stateBlock->vertexShaderConstantB,
351                                     stateBlock->changed.vertexShaderConstantsB);
352
353         /* Upload the position fixup params */
354         pos = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
355         checkGLcall("glGetUniformLocationARB");
356         GL_EXTCALL(glUniform4fvARB(pos, 1, &deviceImpl->posFixup[0]));
357         checkGLcall("glUniform4fvARB");
358     }
359
360     if (usePixelShader) {
361
362         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
363
364         constant_locations = stateBlock->glsl_program->puniformF_locations;
365         constant_list = &stateBlock->set_pconstantsF;
366
367         /* Load pixel shader samplers */
368         shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*) stateBlock);
369
370         /* Load DirectX 9 float constants/uniforms for pixel shader */
371         shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
372                 stateBlock->pixelShaderConstantF, constant_locations, constant_list);
373
374         /* Load DirectX 9 integer constants/uniforms for pixel shader */
375         shader_glsl_load_constantsI(pshader, gl_info, programId, MAX_CONST_I,
376                                     stateBlock->pixelShaderConstantI, 
377                                     stateBlock->changed.pixelShaderConstantsI);
378
379         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
380         shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
381                                     stateBlock->pixelShaderConstantB, 
382                                     stateBlock->changed.pixelShaderConstantsB);
383
384         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
385          * It can't be 0 for a valid texbem instruction.
386          */
387         if(((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat != -1) {
388             float *data = (float *) &stateBlock->textureState[(int) ((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat][WINED3DTSS_BUMPENVMAT00];
389             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "bumpenvmat"));
390             checkGLcall("glGetUniformLocationARB");
391             GL_EXTCALL(glUniformMatrix2fvARB(pos, 1, 0, data));
392             checkGLcall("glUniformMatrix2fvARB");
393
394             /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
395              * is set too, so we can check that in the needsbumpmat check
396              */
397             if(((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams != -1) {
398                 int stage = ((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams;
399                 GLfloat *scale = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
400                 GLfloat *offset = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
401
402                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminancescale"));
403                 checkGLcall("glGetUniformLocationARB");
404                 GL_EXTCALL(glUniform1fvARB(pos, 1, scale));
405                 checkGLcall("glUniform1fvARB");
406                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminanceoffset"));
407                 checkGLcall("glGetUniformLocationARB");
408                 GL_EXTCALL(glUniform1fvARB(pos, 1, offset));
409                 checkGLcall("glUniform1fvARB");
410             }
411         }
412     }
413 }
414
415 /** Generate the variable & register declarations for the GLSL output target */
416 void shader_generate_glsl_declarations(
417     IWineD3DBaseShader *iface,
418     shader_reg_maps* reg_maps,
419     SHADER_BUFFER* buffer,
420     WineD3D_GL_Info* gl_info) {
421
422     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
423     int i;
424
425     /* There are some minor differences between pixel and vertex shaders */
426     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
427     char prefix = pshader ? 'P' : 'V';
428
429     /* Prototype the subroutines */
430     for (i = 0; i < This->baseShader.limits.label; i++) {
431         if (reg_maps->labels[i])
432             shader_addline(buffer, "void subroutine%lu();\n", i);
433     }
434
435     /* Declare the constants (aka uniforms) */
436     if (This->baseShader.limits.constant_float > 0) {
437         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
438                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
439         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
440     }
441
442     if (This->baseShader.limits.constant_int > 0)
443         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
444
445     if (This->baseShader.limits.constant_bool > 0)
446         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
447
448     if(!pshader)
449         shader_addline(buffer, "uniform vec4 posFixup;\n");
450     else if(reg_maps->bumpmat != -1) {
451         shader_addline(buffer, "uniform mat2 bumpenvmat;\n");
452         if(reg_maps->luminanceparams) {
453             shader_addline(buffer, "uniform float luminancescale;\n");
454             shader_addline(buffer, "uniform float luminanceoffset;\n");
455         }
456     }
457
458     /* Declare texture samplers */ 
459     for (i = 0; i < This->baseShader.limits.sampler; i++) {
460         if (reg_maps->samplers[i]) {
461
462             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
463             switch (stype) {
464
465                 case WINED3DSTT_1D:
466                     shader_addline(buffer, "uniform sampler1D %csampler%lu;\n", prefix, i);
467                     break;
468                 case WINED3DSTT_2D:
469                     shader_addline(buffer, "uniform sampler2D %csampler%lu;\n", prefix, i);
470                     break;
471                 case WINED3DSTT_CUBE:
472                     shader_addline(buffer, "uniform samplerCube %csampler%lu;\n", prefix, i);
473                     break;
474                 case WINED3DSTT_VOLUME:
475                     shader_addline(buffer, "uniform sampler3D %csampler%lu;\n", prefix, i);
476                     break;
477                 default:
478                     shader_addline(buffer, "uniform unsupported_sampler %csampler%lu;\n", prefix, i);
479                     FIXME("Unrecognized sampler type: %#x\n", stype);
480                     break;
481             }
482         }
483     }
484     
485     /* Declare address variables */
486     for (i = 0; i < This->baseShader.limits.address; i++) {
487         if (reg_maps->address[i])
488             shader_addline(buffer, "ivec4 A%d;\n", i);
489     }
490
491     /* Declare texture coordinate temporaries and initialize them */
492     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
493         if (reg_maps->texcoord[i]) 
494             shader_addline(buffer, "vec4 T%lu = gl_TexCoord[%lu];\n", i, i);
495     }
496
497     /* Declare input register temporaries */
498     for (i=0; i < This->baseShader.limits.packed_input; i++) {
499         if (reg_maps->packed_input[i])
500             shader_addline(buffer, "vec4 IN%lu;\n", i);
501     }
502
503     /* Declare output register temporaries */
504     for (i = 0; i < This->baseShader.limits.packed_output; i++) {
505         if (reg_maps->packed_output[i])
506             shader_addline(buffer, "vec4 OUT%lu;\n", i);
507     }
508
509     /* Declare temporary variables */
510     for(i = 0; i < This->baseShader.limits.temporary; i++) {
511         if (reg_maps->temporary[i])
512             shader_addline(buffer, "vec4 R%lu;\n", i);
513     }
514
515     /* Declare attributes */
516     for (i = 0; i < This->baseShader.limits.attributes; i++) {
517         if (reg_maps->attributes[i])
518             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
519     }
520
521     /* Declare loop register aL */
522     if (reg_maps->loop) {
523         shader_addline(buffer, "int aL;\n");
524         shader_addline(buffer, "int tmpInt;\n");
525     }
526     
527     /* Temporary variables for matrix operations */
528     shader_addline(buffer, "vec4 tmp0;\n");
529     shader_addline(buffer, "vec4 tmp1;\n");
530
531     /* Start the main program */
532     shader_addline(buffer, "void main() {\n");
533 }
534
535 /*****************************************************************************
536  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
537  *
538  * For more information, see http://wiki.winehq.org/DirectX-Shaders
539  ****************************************************************************/
540
541 /* Prototypes */
542 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
543         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
544
545 /** Used for opcode modifiers - They multiply the result by the specified amount */
546 static const char * const shift_glsl_tab[] = {
547     "",           /*  0 (none) */ 
548     "2.0 * ",     /*  1 (x2)   */ 
549     "4.0 * ",     /*  2 (x4)   */ 
550     "8.0 * ",     /*  3 (x8)   */ 
551     "16.0 * ",    /*  4 (x16)  */ 
552     "32.0 * ",    /*  5 (x32)  */ 
553     "",           /*  6 (x64)  */ 
554     "",           /*  7 (x128) */ 
555     "",           /*  8 (d256) */ 
556     "",           /*  9 (d128) */ 
557     "",           /* 10 (d64)  */ 
558     "",           /* 11 (d32)  */ 
559     "0.0625 * ",  /* 12 (d16)  */ 
560     "0.125 * ",   /* 13 (d8)   */ 
561     "0.25 * ",    /* 14 (d4)   */ 
562     "0.5 * "      /* 15 (d2)   */ 
563 };
564
565 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
566 static void shader_glsl_gen_modifier (
567     const DWORD instr,
568     const char *in_reg,
569     const char *in_regswizzle,
570     char *out_str) {
571
572     out_str[0] = 0;
573     
574     if (instr == WINED3DSIO_TEXKILL)
575         return;
576
577     switch (instr & WINED3DSP_SRCMOD_MASK) {
578     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
579     case WINED3DSPSM_DW:
580     case WINED3DSPSM_NONE:
581         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
582         break;
583     case WINED3DSPSM_NEG:
584         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
585         break;
586     case WINED3DSPSM_NOT:
587         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
588         break;
589     case WINED3DSPSM_BIAS:
590         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
591         break;
592     case WINED3DSPSM_BIASNEG:
593         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
594         break;
595     case WINED3DSPSM_SIGN:
596         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
597         break;
598     case WINED3DSPSM_SIGNNEG:
599         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
600         break;
601     case WINED3DSPSM_COMP:
602         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
603         break;
604     case WINED3DSPSM_X2:
605         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
606         break;
607     case WINED3DSPSM_X2NEG:
608         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
609         break;
610     case WINED3DSPSM_ABS:
611         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
612         break;
613     case WINED3DSPSM_ABSNEG:
614         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
615         break;
616     default:
617         FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
618         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
619     }
620 }
621
622 /** Writes the GLSL variable name that corresponds to the register that the
623  * DX opcode parameter is trying to access */
624 static void shader_glsl_get_register_name(
625     const DWORD param,
626     const DWORD addr_token,
627     char* regstr,
628     BOOL* is_color,
629     SHADER_OPCODE_ARG* arg) {
630
631     /* oPos, oFog and oPts in D3D */
632     static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
633
634     DWORD reg = param & WINED3DSP_REGNUM_MASK;
635     DWORD regtype = shader_get_regtype(param);
636     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
637     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
638     WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
639
640     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
641     char tmpStr[50];
642
643     *is_color = FALSE;   
644  
645     switch (regtype) {
646     case WINED3DSPR_TEMP:
647         sprintf(tmpStr, "R%u", reg);
648     break;
649     case WINED3DSPR_INPUT:
650         if (pshader) {
651             /* Pixel shaders >= 3.0 */
652             if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
653                 sprintf(tmpStr, "IN%u", reg);
654              else {
655                 if (reg==0)
656                     strcpy(tmpStr, "gl_Color");
657                 else
658                     strcpy(tmpStr, "gl_SecondaryColor");
659             }
660         } else {
661             if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
662                *is_color = TRUE;
663             sprintf(tmpStr, "attrib%u", reg);
664         } 
665         break;
666     case WINED3DSPR_CONST:
667     {
668         const char* prefix = pshader? "PC":"VC";
669
670         /* Relative addressing */
671         if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
672
673            /* Relative addressing on shaders 2.0+ have a relative address token, 
674             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
675            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
676                glsl_src_param_t rel_param;
677                shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
678                sprintf(tmpStr, "%s[%s + %u]", prefix, rel_param.param_str, reg);
679            } else
680                sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
681
682         } else
683              sprintf(tmpStr, "%s[%u]", prefix, reg);
684
685         break;
686     }
687     case WINED3DSPR_CONSTINT:
688         if (pshader)
689             sprintf(tmpStr, "PI[%u]", reg);
690         else
691             sprintf(tmpStr, "VI[%u]", reg);
692         break;
693     case WINED3DSPR_CONSTBOOL:
694         if (pshader)
695             sprintf(tmpStr, "PB[%u]", reg);
696         else
697             sprintf(tmpStr, "VB[%u]", reg);
698         break;
699     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
700         if (pshader) {
701             sprintf(tmpStr, "T%u", reg);
702         } else {
703             sprintf(tmpStr, "A%u", reg);
704         }
705     break;
706     case WINED3DSPR_LOOP:
707         sprintf(tmpStr, "aL");
708     break;
709     case WINED3DSPR_SAMPLER:
710         if (pshader)
711             sprintf(tmpStr, "Psampler%u", reg);
712         else
713             sprintf(tmpStr, "Vsampler%u", reg);
714     break;
715     case WINED3DSPR_COLOROUT:
716         if (reg >= GL_LIMITS(buffers)) {
717             WARN("Write to render target %u, only %d supported\n", reg, 4);
718         }
719         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
720             sprintf(tmpStr, "gl_FragData[%u]", reg);
721         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
722             sprintf(tmpStr, "gl_FragColor");
723         }
724     break;
725     case WINED3DSPR_RASTOUT:
726         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
727     break;
728     case WINED3DSPR_DEPTHOUT:
729         sprintf(tmpStr, "gl_FragDepth");
730     break;
731     case WINED3DSPR_ATTROUT:
732         if (reg == 0) {
733             sprintf(tmpStr, "gl_FrontColor");
734         } else {
735             sprintf(tmpStr, "gl_FrontSecondaryColor");
736         }
737     break;
738     case WINED3DSPR_TEXCRDOUT:
739         /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
740         if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
741             sprintf(tmpStr, "OUT%u", reg);
742         else
743             sprintf(tmpStr, "gl_TexCoord[%u]", reg);
744     break;
745     case WINED3DSPR_MISCTYPE:
746         if (reg == 0) {
747             /* vPos */
748             sprintf(tmpStr, "gl_FragCoord");
749         } else {
750             /* gl_FrontFacing could be used for vFace, but note that
751              * gl_FrontFacing is a bool, while vFace is a float for
752              * which the sign determines front/back */
753             FIXME("Unhandled misctype register %d\n", reg);
754             sprintf(tmpStr, "unrecognized_register");
755         }
756         break;
757     default:
758         FIXME("Unhandled register name Type(%d)\n", regtype);
759         sprintf(tmpStr, "unrecognized_register");
760     break;
761     }
762
763     strcat(regstr, tmpStr);
764 }
765
766 /* Get the GLSL write mask for the destination register */
767 static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
768     char *ptr = write_mask;
769     DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
770
771     if (shader_is_scalar(param)) {
772         mask = WINED3DSP_WRITEMASK_0;
773     } else {
774         *ptr++ = '.';
775         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
776         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
777         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
778         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
779     }
780
781     *ptr = '\0';
782
783     return mask;
784 }
785
786 static size_t shader_glsl_get_write_mask_size(DWORD write_mask) {
787     size_t size = 0;
788
789     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
790     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
791     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
792     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
793
794     return size;
795 }
796
797 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
798     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
799      * but addressed as "rgba". To fix this we need to swap the register's x
800      * and z components. */
801     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
802     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
803     char *ptr = swizzle_str;
804
805     if (!shader_is_scalar(param)) {
806         *ptr++ = '.';
807         /* swizzle bits fields: wwzzyyxx */
808         if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
809         if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
810         if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
811         if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
812     }
813
814     *ptr = '\0';
815 }
816
817 /* From a given parameter token, generate the corresponding GLSL string.
818  * Also, return the actual register name and swizzle in case the
819  * caller needs this information as well. */
820 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
821         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param) {
822     BOOL is_color = FALSE;
823     char swizzle_str[6];
824
825     src_param->reg_name[0] = '\0';
826     src_param->param_str[0] = '\0';
827     swizzle_str[0] = '\0';
828
829     shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
830
831     shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
832     shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
833 }
834
835 /* From a given parameter token, generate the corresponding GLSL string.
836  * Also, return the actual register name and swizzle in case the
837  * caller needs this information as well. */
838 static DWORD shader_glsl_add_dst_param(SHADER_OPCODE_ARG* arg, const DWORD param,
839         const DWORD addr_token, glsl_dst_param_t *dst_param) {
840     BOOL is_color = FALSE;
841
842     dst_param->mask_str[0] = '\0';
843     dst_param->reg_name[0] = '\0';
844
845     shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
846     return shader_glsl_get_write_mask(param, dst_param->mask_str);
847 }
848
849 /* Append the destination part of the instruction to the buffer, return the effective write mask */
850 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg, const DWORD param) {
851     glsl_dst_param_t dst_param;
852     DWORD mask;
853     int shift;
854
855     mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);
856
857     if(mask) {
858         shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
859         shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
860     }
861
862     return mask;
863 }
864
865 /* Append the destination part of the instruction to the buffer, return the effective write mask */
866 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg) {
867     return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
868 }
869
870 /** Process GLSL instruction modifiers */
871 void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
872     
873     DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
874  
875     if (arg->opcode->dst_token && mask != 0) {
876         glsl_dst_param_t dst_param;
877
878         shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
879
880         if (mask & WINED3DSPDM_SATURATE) {
881             /* _SAT means to clamp the value of the register to between 0 and 1 */
882             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
883                     dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
884         }
885         if (mask & WINED3DSPDM_MSAMPCENTROID) {
886             FIXME("_centroid modifier not handled\n");
887         }
888         if (mask & WINED3DSPDM_PARTIALPRECISION) {
889             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
890         }
891     }
892 }
893
894 static inline const char* shader_get_comp_op(
895     const DWORD opcode) {
896
897     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
898     switch (op) {
899         case COMPARISON_GT: return ">";
900         case COMPARISON_EQ: return "==";
901         case COMPARISON_GE: return ">=";
902         case COMPARISON_LT: return "<";
903         case COMPARISON_NE: return "!=";
904         case COMPARISON_LE: return "<=";
905         default:
906             FIXME("Unrecognized comparison value: %u\n", op);
907             return "(\?\?)";
908     }
909 }
910
911 static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, glsl_sample_function_t *sample_function) {
912     /* Note that there's no such thing as a projected cube texture. */
913     switch(sampler_type) {
914         case WINED3DSTT_1D:
915             sample_function->name = projected ? "texture1DProj" : "texture1D";
916             sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
917             break;
918         case WINED3DSTT_2D:
919             sample_function->name = projected ? "texture2DProj" : "texture2D";
920             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
921             break;
922         case WINED3DSTT_CUBE:
923             sample_function->name = "textureCube";
924             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
925             break;
926         case WINED3DSTT_VOLUME:
927             sample_function->name = projected ? "texture3DProj" : "texture3D";
928             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
929             break;
930         default:
931             sample_function->name = "";
932             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
933             break;
934     }
935 }
936
937
938 /*****************************************************************************
939  * 
940  * Begin processing individual instruction opcodes
941  * 
942  ****************************************************************************/
943
944 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
945 void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
946     CONST SHADER_OPCODE* curOpcode = arg->opcode;
947     SHADER_BUFFER* buffer = arg->buffer;
948     glsl_src_param_t src0_param;
949     glsl_src_param_t src1_param;
950     DWORD write_mask;
951     char op;
952
953     /* Determine the GLSL operator to use based on the opcode */
954     switch (curOpcode->opcode) {
955         case WINED3DSIO_MUL: op = '*'; break;
956         case WINED3DSIO_ADD: op = '+'; break;
957         case WINED3DSIO_SUB: op = '-'; break;
958         default:
959             op = ' ';
960             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
961             break;
962     }
963
964     write_mask = shader_glsl_append_dst(buffer, arg);
965     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
966     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
967     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
968 }
969
970 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
971 void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
972     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
973     SHADER_BUFFER* buffer = arg->buffer;
974     glsl_src_param_t src0_param;
975     DWORD write_mask;
976
977     write_mask = shader_glsl_append_dst(buffer, arg);
978     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
979
980     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
981      * shader versions WINED3DSIO_MOVA is used for this. */
982     if ((WINED3DSHADER_VERSION_MAJOR(shader->baseShader.hex_version) == 1 &&
983             !shader_is_pshader_version(shader->baseShader.hex_version) &&
984             shader_get_regtype(arg->dst) == WINED3DSPR_ADDR) ||
985             arg->opcode->opcode == WINED3DSIO_MOVA) {
986         /* We need to *round* to the nearest int here. */
987         size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
988         if (mask_size > 1) {
989             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);
990         } else {
991             shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
992         }
993     } else {
994         shader_addline(buffer, "%s);\n", src0_param.param_str);
995     }
996 }
997
998 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
999 void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
1000     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1001     SHADER_BUFFER* buffer = arg->buffer;
1002     glsl_src_param_t src0_param;
1003     glsl_src_param_t src1_param;
1004     DWORD dst_write_mask, src_write_mask;
1005     size_t dst_size = 0;
1006
1007     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1008     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1009
1010     /* dp3 works on vec3, dp4 on vec4 */
1011     if (curOpcode->opcode == WINED3DSIO_DP4) {
1012         src_write_mask = WINED3DSP_WRITEMASK_ALL;
1013     } else {
1014         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1015     }
1016
1017     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
1018     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1019
1020     if (dst_size > 1) {
1021         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1022     } else {
1023         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1024     }
1025 }
1026
1027 /* Note that this instruction has some restrictions. The destination write mask
1028  * can't contain the w component, and the source swizzles have to be .xyzw */
1029 void shader_glsl_cross(SHADER_OPCODE_ARG *arg) {
1030     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1031     glsl_src_param_t src0_param;
1032     glsl_src_param_t src1_param;
1033     char dst_mask[6];
1034
1035     shader_glsl_get_write_mask(arg->dst, dst_mask);
1036     shader_glsl_append_dst(arg->buffer, arg);
1037     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1038     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1039     shader_addline(arg->buffer, "cross(%s, %s).%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1040 }
1041
1042 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1043  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1044  * GLSL uses the value as-is. */
1045 void shader_glsl_pow(SHADER_OPCODE_ARG *arg) {
1046     SHADER_BUFFER *buffer = arg->buffer;
1047     glsl_src_param_t src0_param;
1048     glsl_src_param_t src1_param;
1049     DWORD dst_write_mask;
1050     size_t dst_size;
1051
1052     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1053     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1054
1055     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1056     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1057
1058     if (dst_size > 1) {
1059         shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1060     } else {
1061         shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1062     }
1063 }
1064
1065 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1066 void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
1067     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1068     SHADER_BUFFER* buffer = arg->buffer;
1069     glsl_src_param_t src_param;
1070     const char *instruction;
1071     char arguments[256];
1072     DWORD write_mask;
1073     unsigned i;
1074
1075     /* Determine the GLSL function to use based on the opcode */
1076     /* TODO: Possibly make this a table for faster lookups */
1077     switch (curOpcode->opcode) {
1078         case WINED3DSIO_MIN: instruction = "min"; break;
1079         case WINED3DSIO_MAX: instruction = "max"; break;
1080         case WINED3DSIO_ABS: instruction = "abs"; break;
1081         case WINED3DSIO_FRC: instruction = "fract"; break;
1082         case WINED3DSIO_NRM: instruction = "normalize"; break;
1083         case WINED3DSIO_LOGP:
1084         case WINED3DSIO_LOG: instruction = "log2"; break;
1085         case WINED3DSIO_EXP: instruction = "exp2"; break;
1086         case WINED3DSIO_SGN: instruction = "sign"; break;
1087         case WINED3DSIO_DSX: instruction = "dFdx"; break;
1088         case WINED3DSIO_DSY: instruction = "dFdy"; break;
1089         default: instruction = "";
1090             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1091             break;
1092     }
1093
1094     write_mask = shader_glsl_append_dst(buffer, arg);
1095
1096     arguments[0] = '\0';
1097     if (curOpcode->num_params > 0) {
1098         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
1099         strcat(arguments, src_param.param_str);
1100         for (i = 2; i < curOpcode->num_params; ++i) {
1101             strcat(arguments, ", ");
1102             shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
1103             strcat(arguments, src_param.param_str);
1104         }
1105     }
1106
1107     shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1108 }
1109
1110 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1111  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1112  *   dst.x = 2^(floor(src))
1113  *   dst.y = src - floor(src)
1114  *   dst.z = 2^src   (partial precision is allowed, but optional)
1115  *   dst.w = 1.0;
1116  * For 2.0 shaders, just do this (honoring writemask and swizzle):
1117  *   dst = 2^src;    (partial precision is allowed, but optional)
1118  */
1119 void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
1120     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1121     glsl_src_param_t src_param;
1122
1123     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1124
1125     if (shader->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
1126         char dst_mask[6];
1127
1128         shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1129         shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1130         shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1131         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1132
1133         shader_glsl_append_dst(arg->buffer, arg);
1134         shader_glsl_get_write_mask(arg->dst, dst_mask);
1135         shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1136     } else {
1137         DWORD write_mask;
1138         size_t mask_size;
1139
1140         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1141         mask_size = shader_glsl_get_write_mask_size(write_mask);
1142
1143         if (mask_size > 1) {
1144             shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1145         } else {
1146             shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1147         }
1148     }
1149 }
1150
1151 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1152 void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1153     glsl_src_param_t src_param;
1154     DWORD write_mask;
1155     size_t mask_size;
1156
1157     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1158     mask_size = shader_glsl_get_write_mask_size(write_mask);
1159     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1160
1161     if (mask_size > 1) {
1162         shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1163     } else {
1164         shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1165     }
1166 }
1167
1168 void shader_glsl_rsq(SHADER_OPCODE_ARG* arg) {
1169     SHADER_BUFFER* buffer = arg->buffer;
1170     glsl_src_param_t src_param;
1171     DWORD write_mask;
1172     size_t mask_size;
1173
1174     write_mask = shader_glsl_append_dst(buffer, arg);
1175     mask_size = shader_glsl_get_write_mask_size(write_mask);
1176
1177     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1178
1179     if (mask_size > 1) {
1180         shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1181     } else {
1182         shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1183     }
1184 }
1185
1186 /** Process signed comparison opcodes in GLSL. */
1187 void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1188     glsl_src_param_t src0_param;
1189     glsl_src_param_t src1_param;
1190     DWORD write_mask;
1191     size_t mask_size;
1192
1193     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1194     mask_size = shader_glsl_get_write_mask_size(write_mask);
1195     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1196     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1197
1198     if (mask_size > 1) {
1199         const char *compare;
1200
1201         switch(arg->opcode->opcode) {
1202             case WINED3DSIO_SLT: compare = "lessThan"; break;
1203             case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
1204             default: compare = "";
1205                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1206         }
1207
1208         shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1209                 src0_param.param_str, src1_param.param_str);
1210     } else {
1211         const char *compare;
1212
1213         switch(arg->opcode->opcode) {
1214             case WINED3DSIO_SLT: compare = "<"; break;
1215             case WINED3DSIO_SGE: compare = ">="; break;
1216             default: compare = "";
1217                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1218         }
1219
1220         shader_addline(arg->buffer, "(%s %s %s) ? 1.0 : 0.0);\n",
1221                 src0_param.param_str, compare, src1_param.param_str);
1222     }
1223 }
1224
1225 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1226 void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1227     glsl_src_param_t src0_param;
1228     glsl_src_param_t src1_param;
1229     glsl_src_param_t src2_param;
1230     DWORD write_mask, cmp_channel = 0;
1231     unsigned int i, j;
1232
1233     /* Cycle through all source0 channels */
1234     for (i=0; i<4; i++) {
1235         write_mask = 0;
1236         /* Find the destination channels which use the current source0 channel */
1237         for (j=0; j<4; j++) {
1238             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1239                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1240                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1241             }
1242         }
1243         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1244         if (!write_mask) continue;
1245
1246         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1247         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1248         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1249
1250         shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1251                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1252     }
1253 }
1254
1255 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1256 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
1257  * the compare is done per component of src0. */
1258 void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1259     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1260     glsl_src_param_t src0_param;
1261     glsl_src_param_t src1_param;
1262     glsl_src_param_t src2_param;
1263     DWORD write_mask, cmp_channel = 0;
1264     unsigned int i, j;
1265
1266     if (shader->baseShader.hex_version < WINED3DPS_VERSION(1, 4)) {
1267         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1268         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1269         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1270         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1271         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1272                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1273         return;
1274     }
1275     /* Cycle through all source0 channels */
1276     for (i=0; i<4; i++) {
1277         write_mask = 0;
1278         /* Find the destination channels which use the current source0 channel */
1279         for (j=0; j<4; j++) {
1280             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1281                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1282                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1283             }
1284         }
1285         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1286         if (!write_mask) continue;
1287
1288         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1289         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1290         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1291
1292         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1293                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1294     }
1295 }
1296
1297 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1298 void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1299     glsl_src_param_t src0_param;
1300     glsl_src_param_t src1_param;
1301     glsl_src_param_t src2_param;
1302     DWORD write_mask;
1303
1304     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1305     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1306     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1307     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1308     shader_addline(arg->buffer, "(%s * %s) + %s);\n",
1309             src0_param.param_str, src1_param.param_str, src2_param.param_str);
1310 }
1311
1312 /** Handles transforming all WINED3DSIO_M?x? opcodes for 
1313     Vertex shaders to GLSL codes */
1314 void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
1315     int i;
1316     int nComponents = 0;
1317     SHADER_OPCODE_ARG tmpArg;
1318    
1319     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1320
1321     /* Set constants for the temporary argument */
1322     tmpArg.shader      = arg->shader;
1323     tmpArg.buffer      = arg->buffer;
1324     tmpArg.src[0]      = arg->src[0];
1325     tmpArg.src_addr[0] = arg->src_addr[0];
1326     tmpArg.src_addr[1] = arg->src_addr[1];
1327     tmpArg.reg_maps = arg->reg_maps; 
1328     
1329     switch(arg->opcode->opcode) {
1330         case WINED3DSIO_M4x4:
1331             nComponents = 4;
1332             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1333             break;
1334         case WINED3DSIO_M4x3:
1335             nComponents = 3;
1336             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1337             break;
1338         case WINED3DSIO_M3x4:
1339             nComponents = 4;
1340             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1341             break;
1342         case WINED3DSIO_M3x3:
1343             nComponents = 3;
1344             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1345             break;
1346         case WINED3DSIO_M3x2:
1347             nComponents = 2;
1348             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1349             break;
1350         default:
1351             break;
1352     }
1353
1354     for (i = 0; i < nComponents; i++) {
1355         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1356         tmpArg.src[1]      = arg->src[1]+i;
1357         shader_glsl_dot(&tmpArg);
1358     }
1359 }
1360
1361 /**
1362     The LRP instruction performs a component-wise linear interpolation 
1363     between the second and third operands using the first operand as the
1364     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
1365     This is equivalent to mix(src2, src1, src0);
1366 */
1367 void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1368     glsl_src_param_t src0_param;
1369     glsl_src_param_t src1_param;
1370     glsl_src_param_t src2_param;
1371     DWORD write_mask;
1372
1373     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1374
1375     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1376     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1377     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1378
1379     shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
1380             src2_param.param_str, src1_param.param_str, src0_param.param_str);
1381 }
1382
1383 /** Process the WINED3DSIO_LIT instruction in GLSL:
1384  * dst.x = dst.w = 1.0
1385  * dst.y = (src0.x > 0) ? src0.x
1386  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
1387  *                                        where src.w is clamped at +- 128
1388  */
1389 void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1390     glsl_src_param_t src0_param;
1391     glsl_src_param_t src1_param;
1392     glsl_src_param_t src3_param;
1393     char dst_mask[6];
1394
1395     shader_glsl_append_dst(arg->buffer, arg);
1396     shader_glsl_get_write_mask(arg->dst, dst_mask);
1397
1398     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1399     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
1400     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
1401
1402     shader_addline(arg->buffer, "vec4(1.0, (%s > 0.0 ? %s : 0.0), (%s > 0.0 ? ((%s > 0.0) ? pow(%s, clamp(%s, -128.0, 128.0)) : 0.0) : 0.0), 1.0)%s);\n",
1403         src0_param.param_str, src0_param.param_str, src0_param.param_str, src1_param.param_str, src1_param.param_str, src3_param.param_str, dst_mask);
1404 }
1405
1406 /** Process the WINED3DSIO_DST instruction in GLSL:
1407  * dst.x = 1.0
1408  * dst.y = src0.x * src0.y
1409  * dst.z = src0.z
1410  * dst.w = src1.w
1411  */
1412 void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1413     glsl_src_param_t src0y_param;
1414     glsl_src_param_t src0z_param;
1415     glsl_src_param_t src1y_param;
1416     glsl_src_param_t src1w_param;
1417     char dst_mask[6];
1418
1419     shader_glsl_append_dst(arg->buffer, arg);
1420     shader_glsl_get_write_mask(arg->dst, dst_mask);
1421
1422     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
1423     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
1424     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
1425     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
1426
1427     shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
1428             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
1429 }
1430
1431 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
1432  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
1433  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
1434  * 
1435  * dst.x = cos(src0.?)
1436  * dst.y = sin(src0.?)
1437  * dst.z = dst.z
1438  * dst.w = dst.w
1439  */
1440 void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1441     glsl_src_param_t src0_param;
1442     DWORD write_mask;
1443
1444     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1445     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1446
1447     switch (write_mask) {
1448         case WINED3DSP_WRITEMASK_0:
1449             shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
1450             break;
1451
1452         case WINED3DSP_WRITEMASK_1:
1453             shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
1454             break;
1455
1456         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
1457             shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
1458             break;
1459
1460         default:
1461             ERR("Write mask should be .x, .y or .xy\n");
1462             break;
1463     }
1464 }
1465
1466 /** Process the WINED3DSIO_LOOP instruction in GLSL:
1467  * Start a for() loop where src1.y is the initial value of aL,
1468  *  increment aL by src1.z for a total of src1.x iterations.
1469  *  Need to use a temporary variable for this operation.
1470  */
1471 /* FIXME: I don't think nested loops will work correctly this way. */
1472 void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1473     glsl_src_param_t src1_param;
1474
1475     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
1476   
1477     shader_addline(arg->buffer, "for (tmpInt = 0, aL = %s.y; tmpInt < %s.x; tmpInt++, aL += %s.z) {\n",
1478             src1_param.reg_name, src1_param.reg_name, src1_param.reg_name);
1479 }
1480
1481 void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1482     shader_addline(arg->buffer, "}\n");
1483 }
1484
1485 void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
1486     glsl_src_param_t src0_param;
1487
1488     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1489     shader_addline(arg->buffer, "for (tmpInt = 0; tmpInt < %s; tmpInt++) {\n", src0_param.param_str);
1490 }
1491
1492 void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1493     glsl_src_param_t src0_param;
1494
1495     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1496     shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
1497 }
1498
1499 void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
1500     glsl_src_param_t src0_param;
1501     glsl_src_param_t src1_param;
1502
1503     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1504     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1505
1506     shader_addline(arg->buffer, "if (%s %s %s) {\n",
1507             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1508 }
1509
1510 void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
1511     shader_addline(arg->buffer, "} else {\n");
1512 }
1513
1514 void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
1515     shader_addline(arg->buffer, "break;\n");
1516 }
1517
1518 /* FIXME: According to MSDN the compare is done per component. */
1519 void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
1520     glsl_src_param_t src0_param;
1521     glsl_src_param_t src1_param;
1522
1523     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1524     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1525
1526     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
1527             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1528 }
1529
1530 void shader_glsl_label(SHADER_OPCODE_ARG* arg) {
1531
1532     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1533     shader_addline(arg->buffer, "}\n");
1534     shader_addline(arg->buffer, "void subroutine%lu () {\n",  snum);
1535 }
1536
1537 void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
1538     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1539     shader_addline(arg->buffer, "subroutine%lu();\n", snum);
1540 }
1541
1542 void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
1543     glsl_src_param_t src1_param;
1544
1545     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1546     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1547     shader_addline(arg->buffer, "if (%s) subroutine%lu();\n", src1_param.param_str, snum);
1548 }
1549
1550 /*********************************************
1551  * Pixel Shader Specific Code begins here
1552  ********************************************/
1553 void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
1554     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1555     DWORD hex_version = This->baseShader.hex_version;
1556     char dst_swizzle[6];
1557     glsl_sample_function_t sample_function;
1558     DWORD sampler_type;
1559     DWORD sampler_idx;
1560     BOOL projected;
1561     DWORD mask = 0;
1562
1563     /* All versions have a destination register */
1564     shader_glsl_append_dst(arg->buffer, arg);
1565
1566     /* 1.0-1.4: Use destination register as sampler source.
1567      * 2.0+: Use provided sampler source. */
1568     if (hex_version < WINED3DPS_VERSION(1,4)) {
1569         IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1570         DWORD flags;
1571
1572         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1573         flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1574
1575         if (flags & WINED3DTTFF_PROJECTED) {
1576             projected = TRUE;
1577             switch (flags & ~WINED3DTTFF_PROJECTED) {
1578                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
1579                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
1580                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
1581                 case WINED3DTTFF_COUNT4:
1582                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
1583             }
1584         } else {
1585             projected = FALSE;
1586         }
1587     } else if (hex_version < WINED3DPS_VERSION(2,0)) {
1588         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1589         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1590
1591         if (src_mod == WINED3DSPSM_DZ) {
1592             projected = TRUE;
1593             mask = WINED3DSP_WRITEMASK_2;
1594         } else if (src_mod == WINED3DSPSM_DW) {
1595             projected = TRUE;
1596             mask = WINED3DSP_WRITEMASK_3;
1597         } else {
1598             projected = FALSE;
1599         }
1600     } else {
1601         sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1602         if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
1603                 /* ps 2.0 texldp instruction always divides by the fourth component. */
1604                 projected = TRUE;
1605                 mask = WINED3DSP_WRITEMASK_3;
1606         } else {
1607             projected = FALSE;
1608         }
1609     }
1610
1611     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1612     shader_glsl_get_sample_function(sampler_type, projected, &sample_function);
1613     mask |= sample_function.coord_mask;
1614
1615     if (hex_version < WINED3DPS_VERSION(2,0)) {
1616         shader_glsl_get_write_mask(arg->dst, dst_swizzle);
1617     } else {
1618         shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
1619     }
1620
1621     /* 1.0-1.3: Use destination register as coordinate source.
1622        1.4+: Use provided coordinate source register. */
1623     if (hex_version < WINED3DPS_VERSION(1,4)) {
1624         char coord_mask[6];
1625         shader_glsl_get_write_mask(mask, coord_mask);
1626         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s)%s);\n",
1627                 sample_function.name, sampler_idx, sampler_idx, coord_mask, dst_swizzle);
1628     } else {
1629         glsl_src_param_t coord_param;
1630         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
1631         if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
1632             glsl_src_param_t bias;
1633             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);
1634
1635             shader_addline(arg->buffer, "%s(Psampler%u, %s, %s)%s);\n",
1636                     sample_function.name, sampler_idx, coord_param.param_str,
1637                     bias.param_str, dst_swizzle);
1638         } else {
1639             shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n",
1640                     sample_function.name, sampler_idx, coord_param.param_str, dst_swizzle);
1641         }
1642     }
1643 }
1644
1645 void shader_glsl_texldl(SHADER_OPCODE_ARG* arg) {
1646     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
1647     glsl_sample_function_t sample_function;
1648     glsl_src_param_t coord_param, lod_param;
1649     char dst_swizzle[6];
1650     DWORD sampler_type;
1651     DWORD sampler_idx;
1652
1653     shader_glsl_append_dst(arg->buffer, arg);
1654     shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
1655
1656     sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1657     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1658     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1659     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
1660
1661     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);
1662
1663     if (shader_is_pshader_version(This->baseShader.hex_version)) {
1664         /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
1665          * However, they seem to work just fine in fragment shaders as well. */
1666         WARN("Using %sLod in fragment shader.\n", sample_function.name);
1667         shader_addline(arg->buffer, "%sLod(Psampler%u, %s, %s)%s);\n",
1668                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
1669     } else {
1670         shader_addline(arg->buffer, "%sLod(Vsampler%u, %s, %s)%s);\n",
1671                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
1672     }
1673 }
1674
1675 void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {
1676
1677     /* FIXME: Make this work for more than just 2D textures */
1678     
1679     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1680     SHADER_BUFFER* buffer = arg->buffer;
1681     DWORD hex_version = This->baseShader.hex_version;
1682     DWORD write_mask;
1683     char dst_mask[6];
1684
1685     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1686     shader_glsl_get_write_mask(write_mask, dst_mask);
1687
1688     if (hex_version != WINED3DPS_VERSION(1,4)) {
1689         DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1690         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
1691     } else {
1692         DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
1693         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1694         char dst_swizzle[6];
1695
1696         shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);
1697
1698         if (src_mod == WINED3DSPSM_DZ) {
1699             glsl_src_param_t div_param;
1700             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1701             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
1702
1703             if (mask_size > 1) {
1704                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
1705             } else {
1706                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
1707             }
1708         } else if (src_mod == WINED3DSPSM_DW) {
1709             glsl_src_param_t div_param;
1710             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1711             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
1712
1713             if (mask_size > 1) {
1714                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
1715             } else {
1716                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
1717             }
1718         } else {
1719             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
1720         }
1721     }
1722 }
1723
1724 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
1725  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1726  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1727 void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
1728     glsl_src_param_t src0_param;
1729     char dst_mask[6];
1730     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1731     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1732
1733     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1734
1735     shader_glsl_append_dst(arg->buffer, arg);
1736     shader_glsl_get_write_mask(arg->dst, dst_mask);
1737     shader_addline(arg->buffer, "texture2D(Psampler%u, vec2(dot(gl_TexCoord[%u].xyz, %s), 0.5))%s);\n",
1738             sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
1739 }
1740
1741 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
1742  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1743 void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
1744     glsl_src_param_t src0_param;
1745     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1746     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1747     DWORD dst_mask;
1748     size_t mask_size;
1749
1750     dst_mask = shader_glsl_append_dst(arg->buffer, arg);
1751     mask_size = shader_glsl_get_write_mask_size(dst_mask);
1752     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1753
1754     if (mask_size > 1) {
1755         shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
1756     } else {
1757         shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
1758     }
1759 }
1760
1761 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
1762  * Calculate the depth as dst.x / dst.y   */
1763 void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
1764     glsl_dst_param_t dst_param;
1765
1766     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1767
1768     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
1769      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
1770      * this doesn't always work, so clamp the results manually. Wether or not the x value is clamped at 1
1771      * too is irrelevant, since if x = 0, any y value < 1.0(and > 1.0 is not allowed) results in a result
1772      * >= 1.0 or < 0.0
1773      */
1774     shader_addline(arg->buffer, "gl_FragDepth = (%s.y == 0.0) ? 1.0 : clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name, dst_param.reg_name);
1775 }
1776
1777 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
1778  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1779  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1780  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1781  */
1782 void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
1783     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1784     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1785     glsl_src_param_t src0_param;
1786
1787     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1788
1789     shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
1790     shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
1791 }
1792
1793 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
1794  * Calculate the 1st of a 2-row matrix multiplication. */
1795 void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
1796     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1797     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1798     SHADER_BUFFER* buffer = arg->buffer;
1799     glsl_src_param_t src0_param;
1800
1801     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1802     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1803 }
1804
1805 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
1806  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
1807 void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {
1808
1809     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1810     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1811     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1812     SHADER_BUFFER* buffer = arg->buffer;
1813     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1814     glsl_src_param_t src0_param;
1815
1816     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1817     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
1818     current_state->texcoord_w[current_state->current_row++] = reg;
1819 }
1820
1821 void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1822     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1823     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1824     SHADER_BUFFER* buffer = arg->buffer;
1825     glsl_src_param_t src0_param;
1826     char dst_mask[6];
1827
1828     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1829     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1830
1831     shader_glsl_append_dst(buffer, arg);
1832     shader_glsl_get_write_mask(arg->dst, dst_mask);
1833
1834     /* Sample the texture using the calculated coordinates */
1835     shader_addline(buffer, "texture2D(Psampler%u, tmp0.xy)%s);\n", reg, dst_mask);
1836 }
1837
1838 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
1839  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
1840 void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1841     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1842     glsl_src_param_t src0_param;
1843     char dst_mask[6];
1844     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1845     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1846     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1847     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1848     glsl_sample_function_t sample_function;
1849
1850     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1851     shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1852
1853     shader_glsl_append_dst(arg->buffer, arg);
1854     shader_glsl_get_write_mask(arg->dst, dst_mask);
1855     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1856
1857     /* Sample the texture using the calculated coordinates */
1858     shader_addline(arg->buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
1859
1860     current_state->current_row = 0;
1861 }
1862
1863 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
1864  * Perform the 3rd row of a 3x3 matrix multiply */
1865 void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
1866     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1867     glsl_src_param_t src0_param;
1868     char dst_mask[6];
1869     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1870     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1871     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1872
1873     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1874
1875     shader_glsl_append_dst(arg->buffer, arg);
1876     shader_glsl_get_write_mask(arg->dst, dst_mask);
1877     shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
1878
1879     current_state->current_row = 0;
1880 }
1881
1882 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
1883  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1884 void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {
1885
1886     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1887     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1888     glsl_src_param_t src0_param;
1889     glsl_src_param_t src1_param;
1890     char dst_mask[6];
1891     SHADER_BUFFER* buffer = arg->buffer;
1892     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1893     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1894     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1895     glsl_sample_function_t sample_function;
1896
1897     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1898     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1899
1900     /* Perform the last matrix multiply operation */
1901     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
1902
1903     /* Calculate reflection vector, 2*(tmp0.src1)*tmp0-src1
1904      * This is equivalent to reflect(-src1, tmp0); */
1905     shader_addline(buffer, "tmp0.xyz = reflect(-(%s), tmp0.xyz);\n", src1_param.param_str);
1906
1907     shader_glsl_append_dst(buffer, arg);
1908     shader_glsl_get_write_mask(arg->dst, dst_mask);
1909     shader_glsl_get_sample_function(stype, FALSE, &sample_function);
1910
1911     /* Sample the texture */
1912     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
1913
1914     current_state->current_row = 0;
1915 }
1916
1917 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
1918  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1919 void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
1920
1921     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1922     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1923     SHADER_BUFFER* buffer = arg->buffer;
1924     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1925     glsl_src_param_t src0_param;
1926     char dst_mask[6];
1927     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1928     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1929     glsl_sample_function_t sample_function;
1930
1931     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1932
1933     /* Perform the last matrix multiply operation */
1934     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
1935
1936     /* Construct the eye-ray vector from w coordinates */
1937     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
1938             current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
1939
1940     /* Calculate reflection vector (Assume normal is normalized): RF = 2*(tmp0.tmp1)*tmp0-tmp1
1941      * This is equivalent to reflect(-tmp1, tmp0); */
1942     shader_addline(buffer, "tmp0.xyz = reflect(-tmp1.xyz, tmp0.xyz);\n");
1943
1944     shader_glsl_append_dst(buffer, arg);
1945     shader_glsl_get_write_mask(arg->dst, dst_mask);
1946     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1947
1948     /* Sample the texture using the calculated coordinates */
1949     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
1950
1951     current_state->current_row = 0;
1952 }
1953
1954 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
1955  * Apply a fake bump map transform.
1956  * texbem is pshader <= 1.3 only, this saves a few version checks
1957  */
1958 void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
1959     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1960     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1961     char dst_swizzle[6];
1962     glsl_sample_function_t sample_function;
1963     glsl_src_param_t coord_param;
1964     DWORD sampler_type;
1965     DWORD sampler_idx;
1966     DWORD mask;
1967     DWORD flags;
1968     char coord_mask[6];
1969
1970     sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1971     flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1972
1973     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
1974     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
1975     mask = sample_function.coord_mask;
1976
1977     shader_glsl_get_write_mask(arg->dst, dst_swizzle);
1978
1979     shader_glsl_get_write_mask(mask, coord_mask);
1980
1981     /* with projective textures, texbem only divides the static texture coord, not the displacement,
1982          * so we can't let the GL handle this.
1983          */
1984     if (flags & WINED3DTTFF_PROJECTED) {
1985         DWORD div_mask=0;
1986         char coord_div_mask[3];
1987         switch (flags & ~WINED3DTTFF_PROJECTED) {
1988             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
1989             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
1990             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
1991             case WINED3DTTFF_COUNT4:
1992             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
1993         }
1994         shader_glsl_get_write_mask(div_mask, coord_div_mask);
1995         shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
1996     }
1997
1998     shader_glsl_append_dst(arg->buffer, arg);
1999     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2000     if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
2001         glsl_src_param_t luminance_param;
2002         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2003         shader_addline(arg->buffer, "(%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )*(%s * luminancescale + luminanceoffset))%s);\n",
2004                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask,
2005                        luminance_param.param_str, dst_swizzle);
2006     } else {
2007         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )%s);\n",
2008                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask, dst_swizzle);
2009     }
2010 }
2011
2012 void pshader_glsl_bem(SHADER_OPCODE_ARG* arg) {
2013     glsl_src_param_t src0_param, src1_param;
2014
2015     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
2016     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);
2017
2018     shader_glsl_append_dst(arg->buffer, arg);
2019     shader_addline(arg->buffer, "%s + bumpenvmat * %s);\n",
2020                    src0_param.param_str, src1_param.param_str);
2021 }
2022
2023 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2024  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2025 void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
2026     glsl_src_param_t src0_param;
2027     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2028     char dst_mask[6];
2029
2030     shader_glsl_append_dst(arg->buffer, arg);
2031     shader_glsl_get_write_mask(arg->dst, dst_mask);
2032     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2033
2034     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.wx)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2035 }
2036
2037 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2038  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2039 void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
2040     glsl_src_param_t src0_param;
2041     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2042     char dst_mask[6];
2043
2044     shader_glsl_append_dst(arg->buffer, arg);
2045     shader_glsl_get_write_mask(arg->dst, dst_mask);
2046     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2047
2048     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.yz)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2049 }
2050
2051 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2052  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2053 void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
2054     glsl_src_param_t src0_param;
2055     char dst_mask[6];
2056     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2057     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2058     glsl_sample_function_t sample_function;
2059
2060     shader_glsl_append_dst(arg->buffer, arg);
2061     shader_glsl_get_write_mask(arg->dst, dst_mask);
2062     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2063     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2064
2065     shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n", sample_function.name, sampler_idx, src0_param.param_str, dst_mask);
2066 }
2067
2068 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2069  * If any of the first 3 components are < 0, discard this pixel */
2070 void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
2071     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2072     DWORD hex_version = This->baseShader.hex_version;
2073     glsl_dst_param_t dst_param;
2074
2075     /* The argument is a destination parameter, and no writemasks are allowed */
2076     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2077     if((hex_version >= WINED3DPS_VERSION(2,0))) {
2078         /* 2.0 shaders compare all 4 components in texkill */
2079         shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2080     } else {
2081         /* 1.X shaders only compare the first 3 components, propably due to the nature of the texkill
2082          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2083          * 4 components are defined, only the first 3 are used
2084          */
2085         shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2086     }
2087 }
2088
2089 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2090  * dst = dot2(src0, src1) + src2 */
2091 void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
2092     glsl_src_param_t src0_param;
2093     glsl_src_param_t src1_param;
2094     glsl_src_param_t src2_param;
2095     DWORD write_mask;
2096     size_t mask_size;
2097
2098     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2099     mask_size = shader_glsl_get_write_mask_size(write_mask);
2100
2101     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2102     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2103     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2104
2105     shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2106 }
2107
2108 void pshader_glsl_input_pack(
2109    SHADER_BUFFER* buffer,
2110    semantic* semantics_in) {
2111
2112    unsigned int i;
2113
2114    for (i = 0; i < MAX_REG_INPUT; i++) {
2115
2116        DWORD usage_token = semantics_in[i].usage;
2117        DWORD register_token = semantics_in[i].reg;
2118        DWORD usage, usage_idx;
2119        char reg_mask[6];
2120
2121        /* Uninitialized */
2122        if (!usage_token) continue;
2123        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2124        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2125        shader_glsl_get_write_mask(register_token, reg_mask);
2126
2127        switch(usage) {
2128
2129            case WINED3DDECLUSAGE_COLOR:
2130                if (usage_idx == 0)
2131                    shader_addline(buffer, "IN%u%s = vec4(gl_Color)%s;\n",
2132                        i, reg_mask, reg_mask);
2133                else if (usage_idx == 1)
2134                    shader_addline(buffer, "IN%u%s = vec4(gl_SecondaryColor)%s;\n",
2135                        i, reg_mask, reg_mask);
2136                else
2137                    shader_addline(buffer, "IN%u%s = vec4(unsupported_color_input)%s;\n",
2138                        i, reg_mask, reg_mask);
2139                break;
2140
2141            case WINED3DDECLUSAGE_TEXCOORD:
2142                shader_addline(buffer, "IN%u%s = vec4(gl_TexCoord[%u])%s;\n",
2143                    i, reg_mask, usage_idx, reg_mask );
2144                break;
2145
2146            case WINED3DDECLUSAGE_FOG:
2147                shader_addline(buffer, "IN%u%s = vec4(gl_FogFragCoord)%s;\n",
2148                    i, reg_mask, reg_mask);
2149                break;
2150
2151            default:
2152                shader_addline(buffer, "IN%u%s = vec4(unsupported_input)%s;\n",
2153                    i, reg_mask, reg_mask);
2154         }
2155     }
2156 }
2157
2158 /*********************************************
2159  * Vertex Shader Specific Code begins here
2160  ********************************************/
2161
2162 void vshader_glsl_output_unpack(
2163    SHADER_BUFFER* buffer,
2164    semantic* semantics_out) {
2165
2166    unsigned int i;
2167
2168    for (i = 0; i < MAX_REG_OUTPUT; i++) {
2169
2170        DWORD usage_token = semantics_out[i].usage;
2171        DWORD register_token = semantics_out[i].reg;
2172        DWORD usage, usage_idx;
2173        char reg_mask[6];
2174
2175        /* Uninitialized */
2176        if (!usage_token) continue;
2177
2178        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2179        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2180        shader_glsl_get_write_mask(register_token, reg_mask);
2181
2182        switch(usage) {
2183
2184            case WINED3DDECLUSAGE_COLOR:
2185                if (usage_idx == 0)
2186                    shader_addline(buffer, "gl_FrontColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2187                else if (usage_idx == 1)
2188                    shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2189                else
2190                    shader_addline(buffer, "unsupported_color_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2191                break;
2192
2193            case WINED3DDECLUSAGE_POSITION:
2194                shader_addline(buffer, "gl_Position%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2195                break;
2196
2197            case WINED3DDECLUSAGE_TEXCOORD:
2198                shader_addline(buffer, "gl_TexCoord[%u]%s = OUT%u%s;\n",
2199                    usage_idx, reg_mask, i, reg_mask);
2200                break;
2201
2202            case WINED3DDECLUSAGE_PSIZE:
2203                shader_addline(buffer, "gl_PointSize = OUT%u.x;\n", i);
2204                break;
2205
2206            case WINED3DDECLUSAGE_FOG:
2207                shader_addline(buffer, "gl_FogFragCoord = OUT%u%s;\n", i, reg_mask);
2208                break;
2209
2210            default:
2211                shader_addline(buffer, "unsupported_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
2212        }
2213     }
2214 }
2215
2216 static void add_glsl_program_entry(IWineD3DDeviceImpl *device, struct glsl_shader_prog_link *entry) {
2217     glsl_program_key_t *key;
2218
2219     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2220     key->vshader = entry->vshader;
2221     key->pshader = entry->pshader;
2222
2223     hash_table_put(device->glsl_program_lookup, key, entry);
2224 }
2225
2226 static struct glsl_shader_prog_link *get_glsl_program_entry(IWineD3DDeviceImpl *device,
2227         GLhandleARB vshader, GLhandleARB pshader) {
2228     glsl_program_key_t key;
2229
2230     key.vshader = vshader;
2231     key.pshader = pshader;
2232
2233     return (struct glsl_shader_prog_link *)hash_table_get(device->glsl_program_lookup, &key);
2234 }
2235
2236 void delete_glsl_program_entry(IWineD3DDevice *iface, struct glsl_shader_prog_link *entry) {
2237     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2238     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2239     glsl_program_key_t *key;
2240
2241     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2242     key->vshader = entry->vshader;
2243     key->pshader = entry->pshader;
2244     hash_table_remove(This->glsl_program_lookup, key);
2245
2246     GL_EXTCALL(glDeleteObjectARB(entry->programId));
2247     if (entry->vshader) list_remove(&entry->vshader_entry);
2248     if (entry->pshader) list_remove(&entry->pshader_entry);
2249     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
2250     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
2251     HeapFree(GetProcessHeap(), 0, entry);
2252 }
2253
2254 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
2255  * It sets the programId on the current StateBlock (because it should be called
2256  * inside of the DrawPrimitive() part of the render loop).
2257  *
2258  * If a program for the given combination does not exist, create one, and store
2259  * the program in the hash table.  If it creates a program, it will link the
2260  * given objects, too.
2261  */
2262 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
2263     IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
2264     WineD3D_GL_Info *gl_info               = &This->adapter->gl_info;
2265     IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
2266     IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
2267     struct glsl_shader_prog_link *entry    = NULL;
2268     GLhandleARB programId                  = 0;
2269     int i;
2270     char glsl_name[8];
2271
2272     GLhandleARB vshader_id = use_vs ? ((IWineD3DBaseShaderImpl*)vshader)->baseShader.prgId : 0;
2273     GLhandleARB pshader_id = use_ps ? ((IWineD3DBaseShaderImpl*)pshader)->baseShader.prgId : 0;
2274     entry = get_glsl_program_entry(This, vshader_id, pshader_id);
2275     if (entry) {
2276         This->stateBlock->glsl_program = entry;
2277         return;
2278     }
2279
2280     /* If we get to this point, then no matching program exists, so we create one */
2281     programId = GL_EXTCALL(glCreateProgramObjectARB());
2282     TRACE("Created new GLSL shader program %u\n", programId);
2283
2284     /* Create the entry */
2285     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
2286     entry->programId = programId;
2287     entry->vshader = vshader_id;
2288     entry->pshader = pshader_id;
2289     /* Add the hash table entry */
2290     add_glsl_program_entry(This, entry);
2291
2292     /* Set the current program */
2293     This->stateBlock->glsl_program = entry;
2294
2295     /* Attach GLSL vshader */
2296     if (vshader_id) {
2297         int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
2298         char tmp_name[10];
2299
2300         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
2301         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
2302         checkGLcall("glAttachObjectARB");
2303
2304         /* Bind vertex attributes to a corresponding index number to match
2305          * the same index numbers as ARB_vertex_programs (makes loading
2306          * vertex attributes simpler).  With this method, we can use the
2307          * exact same code to load the attributes later for both ARB and
2308          * GLSL shaders.
2309          *
2310          * We have to do this here because we need to know the Program ID
2311          * in order to make the bindings work, and it has to be done prior
2312          * to linking the GLSL program. */
2313         for (i = 0; i < max_attribs; ++i) {
2314              snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
2315              GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
2316         }
2317         checkGLcall("glBindAttribLocationARB");
2318
2319         list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
2320     }
2321
2322     /* Attach GLSL pshader */
2323     if (pshader_id) {
2324         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
2325         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
2326         checkGLcall("glAttachObjectARB");
2327
2328         list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
2329     }
2330
2331     /* Link the program */
2332     TRACE("Linking GLSL shader program %u\n", programId);
2333     GL_EXTCALL(glLinkProgramARB(programId));
2334     print_glsl_info_log(&GLINFO_LOCATION, programId);
2335
2336     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
2337     for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
2338         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
2339         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
2340     }
2341     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
2342     for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
2343         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
2344         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
2345     }
2346 }
2347
2348 static GLhandleARB create_glsl_blt_shader(WineD3D_GL_Info *gl_info) {
2349     GLhandleARB program_id;
2350     GLhandleARB vshader_id, pshader_id;
2351     const char *blt_vshader[] = {
2352         "void main(void)\n"
2353         "{\n"
2354         "    gl_Position = gl_Vertex;\n"
2355         "    gl_FrontColor = vec4(1.0);\n"
2356         "    gl_TexCoord[0].x = (gl_Vertex.x * 0.5) + 0.5;\n"
2357         "    gl_TexCoord[0].y = (-gl_Vertex.y * 0.5) + 0.5;\n"
2358         "}\n"
2359     };
2360
2361     const char *blt_pshader[] = {
2362         "uniform sampler2D sampler;\n"
2363         "void main(void)\n"
2364         "{\n"
2365         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
2366         "}\n"
2367     };
2368
2369     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
2370     GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
2371     GL_EXTCALL(glCompileShaderARB(vshader_id));
2372
2373     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
2374     GL_EXTCALL(glShaderSourceARB(pshader_id, 1, blt_pshader, NULL));
2375     GL_EXTCALL(glCompileShaderARB(pshader_id));
2376
2377     program_id = GL_EXTCALL(glCreateProgramObjectARB());
2378     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
2379     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
2380     GL_EXTCALL(glLinkProgramARB(program_id));
2381
2382     print_glsl_info_log(&GLINFO_LOCATION, program_id);
2383
2384     return program_id;
2385 }
2386
2387 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
2388     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2389     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2390     GLhandleARB program_id = 0;
2391
2392     if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
2393     else This->stateBlock->glsl_program = NULL;
2394
2395     program_id = This->stateBlock->glsl_program ? This->stateBlock->glsl_program->programId : 0;
2396     if (program_id) TRACE("Using GLSL program %u\n", program_id);
2397     GL_EXTCALL(glUseProgramObjectARB(program_id));
2398     checkGLcall("glUseProgramObjectARB");
2399 }
2400
2401 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface) {
2402     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2403     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2404     static GLhandleARB program_id = 0;
2405     static GLhandleARB loc = -1;
2406
2407     if (!program_id) {
2408         program_id = create_glsl_blt_shader(gl_info);
2409         loc = GL_EXTCALL(glGetUniformLocationARB(program_id, "sampler"));
2410     }
2411
2412     GL_EXTCALL(glUseProgramObjectARB(program_id));
2413     GL_EXTCALL(glUniform1iARB(loc, 0));
2414 }
2415
2416 static void shader_glsl_cleanup(IWineD3DDevice *iface) {
2417     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2418     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2419     GL_EXTCALL(glUseProgramObjectARB(0));
2420 }
2421
2422 const shader_backend_t glsl_shader_backend = {
2423     &shader_glsl_select,
2424     &shader_glsl_select_depth_blt,
2425     &shader_glsl_load_constants,
2426     &shader_glsl_cleanup
2427 };