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