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