dnsapi: Cast-qual warnings fix.
[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_(d3d_shader)("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     IWineD3DStateBlock* iface,
273     char usePixelShader,
274     char useVertexShader) {
275     
276     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
277     WineD3D_GL_Info *gl_info = &((IWineD3DImpl*)stateBlock->wineD3DDevice->wineD3D)->gl_info;
278     GLhandleARB *constant_locations;
279     struct list *constant_list;
280     GLhandleARB programId;
281     
282     if (!stateBlock->glsl_program) {
283         /* No GLSL program set - nothing to do. */
284         return;
285     }
286     programId = stateBlock->glsl_program->programId;
287
288     if (useVertexShader) {
289         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
290         IWineD3DVertexShaderImpl* vshader_impl = (IWineD3DVertexShaderImpl*) vshader;
291
292         IWineD3DVertexDeclarationImpl* vertexDeclaration =
293             (IWineD3DVertexDeclarationImpl*) vshader_impl->vertexDeclaration;
294
295         constant_locations = stateBlock->glsl_program->vuniformF_locations;
296         constant_list = &stateBlock->set_vconstantsF;
297
298         if (NULL != vertexDeclaration && NULL != vertexDeclaration->constants) {
299             /* Load DirectX 8 float constants/uniforms for vertex shader */
300             shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
301                     vertexDeclaration->constants, constant_locations, NULL);
302         }
303
304         /* Load DirectX 9 float constants/uniforms for vertex shader */
305         shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
306                 stateBlock->vertexShaderConstantF, constant_locations, constant_list);
307
308         /* Load DirectX 9 integer constants/uniforms for vertex shader */
309         shader_glsl_load_constantsI(vshader, gl_info, programId, MAX_CONST_I,
310                                     stateBlock->vertexShaderConstantI,
311                                     stateBlock->set.vertexShaderConstantsI);
312
313         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
314         shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
315                                     stateBlock->vertexShaderConstantB,
316                                     stateBlock->set.vertexShaderConstantsB);
317     }
318
319     if (usePixelShader) {
320
321         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
322
323         constant_locations = stateBlock->glsl_program->puniformF_locations;
324         constant_list = &stateBlock->set_pconstantsF;
325
326         /* Load pixel shader samplers */
327         shader_glsl_load_psamplers(gl_info, iface);
328
329         /* Load DirectX 9 float constants/uniforms for pixel shader */
330         shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
331                 stateBlock->pixelShaderConstantF, constant_locations, constant_list);
332
333         /* Load DirectX 9 integer constants/uniforms for pixel shader */
334         shader_glsl_load_constantsI(pshader, gl_info, programId, MAX_CONST_I,
335                                     stateBlock->pixelShaderConstantI, 
336                                     stateBlock->set.pixelShaderConstantsI);
337         
338         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
339         shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
340                                     stateBlock->pixelShaderConstantB, 
341                                     stateBlock->set.pixelShaderConstantsB);
342     }
343 }
344
345 /** Generate the variable & register declarations for the GLSL output target */
346 void shader_generate_glsl_declarations(
347     IWineD3DBaseShader *iface,
348     shader_reg_maps* reg_maps,
349     SHADER_BUFFER* buffer,
350     WineD3D_GL_Info* gl_info) {
351
352     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
353     int i;
354
355     /* There are some minor differences between pixel and vertex shaders */
356     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
357     char prefix = pshader ? 'P' : 'V';
358
359     /* Prototype the subroutines */
360     for (i = 0; i < This->baseShader.limits.label; i++) {
361         if (reg_maps->labels[i])
362             shader_addline(buffer, "void subroutine%lu();\n", i);
363     }
364
365     /* Declare the constants (aka uniforms) */
366     if (This->baseShader.limits.constant_float > 0) {
367         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
368                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
369         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
370     }
371
372     if (This->baseShader.limits.constant_int > 0)
373         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
374
375     if (This->baseShader.limits.constant_bool > 0)
376         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
377
378     /* Declare texture samplers */ 
379     for (i = 0; i < This->baseShader.limits.sampler; i++) {
380         if (reg_maps->samplers[i]) {
381
382             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
383             switch (stype) {
384
385                 case WINED3DSTT_1D:
386                     shader_addline(buffer, "uniform sampler1D %csampler%lu;\n", prefix, i);
387                     break;
388                 case WINED3DSTT_2D:
389                     shader_addline(buffer, "uniform sampler2D %csampler%lu;\n", prefix, i);
390                     break;
391                 case WINED3DSTT_CUBE:
392                     shader_addline(buffer, "uniform samplerCube %csampler%lu;\n", prefix, i);
393                     break;
394                 case WINED3DSTT_VOLUME:
395                     shader_addline(buffer, "uniform sampler3D %csampler%lu;\n", prefix, i);
396                     break;
397                 default:
398                     shader_addline(buffer, "uniform unsupported_sampler %csampler%lu;\n", prefix, i);
399                     FIXME("Unrecognized sampler type: %#lx\n", stype);
400                     break;
401             }
402         }
403     }
404     
405     /* Declare address variables */
406     for (i = 0; i < This->baseShader.limits.address; i++) {
407         if (reg_maps->address[i])
408             shader_addline(buffer, "ivec4 A%ld;\n", i);
409     }
410
411     /* Declare texture coordinate temporaries and initialize them */
412     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
413         if (reg_maps->texcoord[i]) 
414             shader_addline(buffer, "vec4 T%lu = gl_TexCoord[%lu];\n", i, i);
415     }
416
417     /* Declare input register temporaries */
418     for (i=0; i < This->baseShader.limits.packed_input; i++) {
419         if (reg_maps->packed_input[i])
420             shader_addline(buffer, "vec4 IN%lu;\n", i);
421     }
422
423     /* Declare output register temporaries */
424     for (i = 0; i < This->baseShader.limits.packed_output; i++) {
425         if (reg_maps->packed_output[i])
426             shader_addline(buffer, "vec4 OUT%lu;\n", i);
427     }
428
429     /* Declare temporary variables */
430     for(i = 0; i < This->baseShader.limits.temporary; i++) {
431         if (reg_maps->temporary[i])
432             shader_addline(buffer, "vec4 R%lu;\n", i);
433     }
434
435     /* Declare attributes */
436     for (i = 0; i < This->baseShader.limits.attributes; i++) {
437         if (reg_maps->attributes[i])
438             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
439     }
440
441     /* Declare loop register aL */
442     if (reg_maps->loop) {
443         shader_addline(buffer, "int aL;\n");
444         shader_addline(buffer, "int tmpInt;\n");
445     }
446     
447     /* Temporary variables for matrix operations */
448     shader_addline(buffer, "vec4 tmp0;\n");
449     shader_addline(buffer, "vec4 tmp1;\n");
450
451     /* Start the main program */
452     shader_addline(buffer, "void main() {\n");
453 }
454
455 /*****************************************************************************
456  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
457  *
458  * For more information, see http://wiki.winehq.org/DirectX-Shaders
459  ****************************************************************************/
460
461 /* Prototypes */
462 static void shader_glsl_add_param(
463     SHADER_OPCODE_ARG* arg,
464     const DWORD param,
465     const DWORD addr_token,
466     BOOL is_input,
467     char *reg_name,
468     char *reg_mask,
469     char *out_str);
470
471 /** Used for opcode modifiers - They multiply the result by the specified amount */
472 static const char* shift_glsl_tab[] = {
473     "",           /*  0 (none) */ 
474     "2.0 * ",     /*  1 (x2)   */ 
475     "4.0 * ",     /*  2 (x4)   */ 
476     "8.0 * ",     /*  3 (x8)   */ 
477     "16.0 * ",    /*  4 (x16)  */ 
478     "32.0 * ",    /*  5 (x32)  */ 
479     "",           /*  6 (x64)  */ 
480     "",           /*  7 (x128) */ 
481     "",           /*  8 (d256) */ 
482     "",           /*  9 (d128) */ 
483     "",           /* 10 (d64)  */ 
484     "",           /* 11 (d32)  */ 
485     "0.0625 * ",  /* 12 (d16)  */ 
486     "0.125 * ",   /* 13 (d8)   */ 
487     "0.25 * ",    /* 14 (d4)   */ 
488     "0.5 * "      /* 15 (d2)   */ 
489 };
490
491 /** Print the beginning of the generated GLSL string. example: "reg_name.xyzw = vec4("
492  * Will also change the reg_mask if necessary (not all register types are equal in DX vs GL)  */
493 static void shader_glsl_add_dst(DWORD param, const char* reg_name, char* reg_mask, char* outStr) {
494
495     int shift = (param & D3DSP_DSTSHIFT_MASK) >> D3DSP_DSTSHIFT_SHIFT;
496     char cast[6];
497     
498     if ((shader_get_regtype(param) == D3DSPR_RASTOUT)
499          && ((param & D3DSP_REGNUM_MASK) != 0)) {
500         /* gl_FogFragCoord or glPointSize - both floats */
501         strcpy(cast, "float");
502         strcpy(reg_mask, "");
503
504     } else if (reg_name[0] == 'A') {
505         /* Address register for vertex shaders (ivec4) */
506         strcpy(cast, "ivec4");
507         
508     } else {
509         /* Everything else should be a 4 component float vector */
510         strcpy(cast, "vec4");
511     }
512     
513     sprintf(outStr, "%s%s = %s%s(", reg_name, reg_mask, shift_glsl_tab[shift], cast); 
514 }
515
516 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
517 static void shader_glsl_gen_modifier (
518     const DWORD instr,
519     const char *in_reg,
520     const char *in_regswizzle,
521     char *out_str) {
522
523     out_str[0] = 0;
524     
525     if (instr == D3DSIO_TEXKILL)
526         return;
527
528     switch (instr & D3DSP_SRCMOD_MASK) {
529     case D3DSPSM_NONE:
530         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
531         break;
532     case D3DSPSM_NEG:
533         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
534         break;
535     case D3DSPSM_NOT:
536         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
537         break;
538     case D3DSPSM_BIAS:
539         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
540         break;
541     case D3DSPSM_BIASNEG:
542         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
543         break;
544     case D3DSPSM_SIGN:
545         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
546         break;
547     case D3DSPSM_SIGNNEG:
548         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
549         break;
550     case D3DSPSM_COMP:
551         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
552         break;
553     case D3DSPSM_X2:
554         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
555         break;
556     case D3DSPSM_X2NEG:
557         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
558         break;
559     case D3DSPSM_DZ:    /* reg1_db = { reg1.r/b, reg1.g/b, ...}  The g & a components are undefined, so we'll leave them alone */
560         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);
561         break;
562     case D3DSPSM_DW:
563         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);
564         break;
565     case D3DSPSM_ABS:
566         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
567         break;
568     case D3DSPSM_ABSNEG:
569         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
570         break;
571     default:
572         FIXME("Unhandled modifier %lu\n", (instr & D3DSP_SRCMOD_MASK));
573         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
574     }
575 }
576
577 /** Writes the GLSL variable name that corresponds to the register that the
578  * DX opcode parameter is trying to access */
579 static void shader_glsl_get_register_name(
580     const DWORD param,
581     const DWORD addr_token,
582     char* regstr,
583     BOOL* is_color,
584     SHADER_OPCODE_ARG* arg) {
585
586     /* oPos, oFog and oPts in D3D */
587     const char* hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
588
589     WineD3D_GL_Info *gl_info = &((IWineD3DImpl*)((IWineD3DPixelShaderImpl*)arg->shader)->wineD3DDevice->wineD3D)->gl_info;
590     DWORD reg = param & D3DSP_REGNUM_MASK;
591     DWORD regtype = shader_get_regtype(param);
592     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
593     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
594     char tmpStr[50];
595
596     *is_color = FALSE;   
597  
598     switch (regtype) {
599     case D3DSPR_TEMP:
600         sprintf(tmpStr, "R%lu", reg);
601     break;
602     case D3DSPR_INPUT:
603         if (pshader) {
604             /* Pixel shaders >= 3.0 */
605             if (D3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
606                 sprintf(tmpStr, "IN%lu", reg);
607              else {
608                 if (reg==0)
609                     strcpy(tmpStr, "gl_Color");
610                 else
611                     strcpy(tmpStr, "gl_SecondaryColor");
612             }
613         } else {
614             if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
615                *is_color = TRUE;
616             sprintf(tmpStr, "attrib%lu", reg);
617         } 
618         break;
619     case D3DSPR_CONST:
620     {
621         const char* prefix = pshader? "PC":"VC";
622
623         /* Relative addressing */
624         if (param & D3DVS_ADDRMODE_RELATIVE) {
625
626            /* Relative addressing on shaders 2.0+ have a relative address token, 
627             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
628            if (D3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
629                char relStr[100], relReg[50], relMask[6];
630                shader_glsl_add_param(arg, addr_token, 0, TRUE, relReg, relMask, relStr);
631                sprintf(tmpStr, "%s[%s + %lu]", prefix, relStr, reg);
632            } else
633                sprintf(tmpStr, "%s[A0.x + %lu]", prefix, reg);
634
635         } else
636              sprintf(tmpStr, "%s[%lu]", prefix, reg);
637
638         break;
639     }
640     case D3DSPR_CONSTINT:
641         if (pshader)
642             sprintf(tmpStr, "PI[%lu]", reg);
643         else
644             sprintf(tmpStr, "VI[%lu]", reg);
645         break;
646     case D3DSPR_CONSTBOOL:
647         if (pshader)
648             sprintf(tmpStr, "PB[%lu]", reg);
649         else
650             sprintf(tmpStr, "VB[%lu]", reg);
651         break;
652     case D3DSPR_TEXTURE: /* case D3DSPR_ADDR: */
653         if (pshader) {
654             sprintf(tmpStr, "T%lu", reg);
655         } else {
656             sprintf(tmpStr, "A%lu", reg);
657         }
658     break;
659     case D3DSPR_LOOP:
660         sprintf(tmpStr, "aL");
661     break;
662     case D3DSPR_SAMPLER:
663         if (pshader)
664             sprintf(tmpStr, "Psampler%lu", reg);
665         else
666             sprintf(tmpStr, "Vsampler%lu", reg);
667     break;
668     case D3DSPR_COLOROUT:
669         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
670             sprintf(tmpStr, "gl_FragData[%lu]", reg);
671             if (reg > 0) {
672                 /* TODO: See GL_ARB_draw_buffers */
673                 FIXME("Unsupported write to render target %lu\n", reg);
674             }
675         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
676             if (reg > 0)
677                 WARN("This OpenGL implementation doesn't support writing to multiple render targets!\n");
678             else
679                 sprintf(tmpStr, "gl_FragColor");
680         }
681     break;
682     case D3DSPR_RASTOUT:
683         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
684     break;
685     case D3DSPR_DEPTHOUT:
686         sprintf(tmpStr, "gl_FragDepth");
687     break;
688     case D3DSPR_ATTROUT:
689         if (reg == 0) {
690             sprintf(tmpStr, "gl_FrontColor");
691         } else {
692             sprintf(tmpStr, "gl_FrontSecondaryColor");
693         }
694     break;
695     case D3DSPR_TEXCRDOUT:
696         /* Vertex shaders >= 3.0: D3DSPR_OUTPUT */
697         if (D3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
698             sprintf(tmpStr, "OUT%lu", reg);
699         else
700             sprintf(tmpStr, "gl_TexCoord[%lu]", reg);
701     break;
702     default:
703         FIXME("Unhandled register name Type(%ld)\n", regtype);
704         sprintf(tmpStr, "unrecognized_register");
705     break;
706     }
707
708     strcat(regstr, tmpStr);
709 }
710
711 /* Writes the GLSL writemask for the destination register */
712 static void shader_glsl_get_output_register_swizzle(
713     const DWORD param,
714     char *write_mask) {
715    
716     *write_mask = 0;
717     if ((param & D3DSP_WRITEMASK_ALL) != D3DSP_WRITEMASK_ALL) {
718         strcat(write_mask, ".");
719         if (param & D3DSP_WRITEMASK_0) strcat(write_mask, "x");
720         if (param & D3DSP_WRITEMASK_1) strcat(write_mask, "y");
721         if (param & D3DSP_WRITEMASK_2) strcat(write_mask, "z");
722         if (param & D3DSP_WRITEMASK_3) strcat(write_mask, "w");
723     }
724 }
725
726 static void shader_glsl_get_input_register_swizzle(
727     const DWORD param,
728     BOOL is_color,
729     char *reg_mask) {
730     
731     const char swizzle_reg_chars_color_fix[] = "zyxw";
732     const char swizzle_reg_chars[] = "xyzw";
733     const char* swizzle_regs = NULL;
734    
735     /** operand input */
736     DWORD swizzle = (param & D3DVS_SWIZZLE_MASK) >> D3DVS_SWIZZLE_SHIFT;
737     DWORD swizzle_x = swizzle & 0x03;
738     DWORD swizzle_y = (swizzle >> 2) & 0x03;
739     DWORD swizzle_z = (swizzle >> 4) & 0x03;
740     DWORD swizzle_w = (swizzle >> 6) & 0x03;
741
742     if (is_color) {
743       swizzle_regs = swizzle_reg_chars_color_fix;
744     } else {
745       swizzle_regs = swizzle_reg_chars;
746     }
747
748     /**
749      * swizzle bits fields:
750      *  WWZZYYXX
751      */
752     if ((D3DVS_NOSWIZZLE >> D3DVS_SWIZZLE_SHIFT) == swizzle) { /* D3DVS_NOSWIZZLE == 0xE4 << D3DVS_SWIZZLE_SHIFT */
753       if (is_color) {
754             sprintf(reg_mask, ".%c%c%c%c",
755                 swizzle_regs[swizzle_x],
756                 swizzle_regs[swizzle_y],
757                 swizzle_regs[swizzle_z],
758                 swizzle_regs[swizzle_w]);
759       }
760       return ;
761     }
762     if (swizzle_x == swizzle_y &&
763         swizzle_x == swizzle_z &&
764         swizzle_x == swizzle_w)
765     {
766       sprintf(reg_mask, ".%c", swizzle_regs[swizzle_x]);
767     } else {
768       sprintf(reg_mask, ".%c%c%c%c",
769               swizzle_regs[swizzle_x],
770               swizzle_regs[swizzle_y],
771               swizzle_regs[swizzle_z],
772               swizzle_regs[swizzle_w]);
773     }
774 }
775
776 /** From a given parameter token, generate the corresponding GLSL string.
777  * Also, return the actual register name and swizzle in case the 
778  * caller needs this information as well. */
779 static void shader_glsl_add_param(
780     SHADER_OPCODE_ARG* arg,
781     const DWORD param,
782     const DWORD addr_token,
783     BOOL is_input,
784     char *reg_name,
785     char *reg_mask,
786     char *out_str) {
787
788     BOOL is_color = FALSE;
789     reg_mask[0] = reg_name[0] = out_str[0] = 0;
790
791     shader_glsl_get_register_name(param, addr_token, reg_name, &is_color, arg);
792     
793     if (is_input) {
794         shader_glsl_get_input_register_swizzle(param, is_color, reg_mask);
795         shader_glsl_gen_modifier(param, reg_name, reg_mask, out_str);
796     } else {
797         shader_glsl_get_output_register_swizzle(param, reg_mask);
798         sprintf(out_str, "%s%s", reg_name, reg_mask);
799     }
800 }
801
802 /** Process GLSL instruction modifiers */
803 void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
804     
805     DWORD mask = arg->dst & D3DSP_DSTMOD_MASK;
806  
807     if (arg->opcode->dst_token && mask != 0) {
808         char dst_reg[50];
809         char dst_mask[6];
810         char dst_str[100];
811        
812         shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
813
814         if (mask & D3DSPDM_SATURATE) {
815             /* _SAT means to clamp the value of the register to between 0 and 1 */
816             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_reg, dst_mask, dst_reg, dst_mask);
817         }
818         if (mask & D3DSPDM_MSAMPCENTROID) {
819             FIXME("_centroid modifier not handled\n");
820         }
821         if (mask & D3DSPDM_PARTIALPRECISION) {
822             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
823         }
824     }
825 }
826
827 static inline const char* shader_get_comp_op(
828     const DWORD opcode) {
829
830     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
831     switch (op) {
832         case COMPARISON_GT: return ">";
833         case COMPARISON_EQ: return "==";
834         case COMPARISON_GE: return ">=";
835         case COMPARISON_LT: return "<";
836         case COMPARISON_NE: return "!=";
837         case COMPARISON_LE: return "<=";
838         default:
839             FIXME("Unrecognized comparison value: %lu\n", op);
840             return "(\?\?)";
841     }
842 }
843
844 /*****************************************************************************
845  * 
846  * Begin processing individual instruction opcodes
847  * 
848  ****************************************************************************/
849
850 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
851 void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
852
853     CONST SHADER_OPCODE* curOpcode = arg->opcode;
854     SHADER_BUFFER* buffer = arg->buffer;
855     char tmpLine[256];
856     char dst_reg[50], src0_reg[50], src1_reg[50];
857     char dst_mask[6], src0_mask[6], src1_mask[6];
858     char dst_str[100], src0_str[100], src1_str[100];
859
860     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
861     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
862     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
863     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
864     strcat(tmpLine, "vec4(");
865     strcat(tmpLine, src0_str);
866     strcat(tmpLine, ")");
867
868     /* Determine the GLSL operator to use based on the opcode */
869     switch (curOpcode->opcode) {
870         case D3DSIO_MUL:    strcat(tmpLine, " * "); break;
871         case D3DSIO_ADD:    strcat(tmpLine, " + "); break;
872         case D3DSIO_SUB:    strcat(tmpLine, " - "); break;
873         default:
874             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
875             break;
876     }
877     shader_addline(buffer, "%svec4(%s))%s;\n", tmpLine, src1_str, dst_mask);
878 }
879
880 /* Process the D3DSIO_MOV opcode using GLSL (dst = src) */
881 void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
882
883     SHADER_BUFFER* buffer = arg->buffer;
884     char tmpLine[256];
885     char dst_str[100], src0_str[100];
886     char dst_reg[50], src0_reg[50];
887     char dst_mask[6], src0_mask[6];
888
889     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
890     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
891     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
892     shader_addline(buffer, "%s%s)%s;\n", tmpLine, src0_str, dst_mask);
893 }
894
895 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
896 void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
897
898     CONST SHADER_OPCODE* curOpcode = arg->opcode;
899     SHADER_BUFFER* buffer = arg->buffer;
900     char tmpDest[100];
901     char dst_str[100], src0_str[100], src1_str[100];
902     char dst_reg[50], src0_reg[50], src1_reg[50];
903     char dst_mask[6], src0_mask[6], src1_mask[6];
904     char cast[6];
905
906     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
907     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
908     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
909
910     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpDest);
911  
912     /* Need to cast the src vectors to vec3 for dp3, and vec4 for dp4 */
913     if (curOpcode->opcode == D3DSIO_DP4)
914         strcpy(cast, "vec4(");
915     else
916         strcpy(cast, "vec3(");
917     
918     shader_addline(buffer, "%sdot(%s%s), %s%s)))%s;\n",
919                    tmpDest, cast, src0_str, cast, src1_str, dst_mask);
920 }
921
922 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
923 void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
924
925     CONST SHADER_OPCODE* curOpcode = arg->opcode;
926     SHADER_BUFFER* buffer = arg->buffer;
927     char tmpLine[256];
928     char dst_str[100], src_str[100];
929     char dst_reg[50], src_reg[50];
930     char dst_mask[6], src_mask[6];
931     unsigned i;
932     
933     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
934
935     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
936  
937     /* Determine the GLSL function to use based on the opcode */
938     /* TODO: Possibly make this a table for faster lookups */
939     switch (curOpcode->opcode) {
940             case D3DSIO_MIN:    strcat(tmpLine, "min"); break;
941             case D3DSIO_MAX:    strcat(tmpLine, "max"); break;
942             case D3DSIO_RSQ:    strcat(tmpLine, "inversesqrt"); break;
943             case D3DSIO_ABS:    strcat(tmpLine, "abs"); break;
944             case D3DSIO_FRC:    strcat(tmpLine, "fract"); break;
945             case D3DSIO_POW:    strcat(tmpLine, "pow"); break;
946             case D3DSIO_CRS:    strcat(tmpLine, "cross"); break;
947             case D3DSIO_NRM:    strcat(tmpLine, "normalize"); break;
948             case D3DSIO_LOGP:
949             case D3DSIO_LOG:    strcat(tmpLine, "log2"); break;
950             case D3DSIO_EXP:    strcat(tmpLine, "exp2"); break;
951             case D3DSIO_SGE:    strcat(tmpLine, "greaterThanEqual"); break;
952             case D3DSIO_SLT:    strcat(tmpLine, "lessThan"); break;
953             case D3DSIO_SGN:    strcat(tmpLine, "sign"); break;
954         default:
955             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
956             break;
957     }
958
959     strcat(tmpLine, "(");
960
961     if (curOpcode->num_params > 0) {
962         strcat(tmpLine, "vec4(");
963         shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
964         strcat(tmpLine, src_str);
965         strcat(tmpLine, ")");
966         for (i = 2; i < curOpcode->num_params; ++i) {
967             strcat(tmpLine, ", vec4(");
968             shader_glsl_add_param(arg, arg->src[i-1], arg->src_addr[i-1], TRUE, src_reg, src_mask, src_str);
969             strcat(tmpLine, src_str);
970             strcat(tmpLine, ")");
971         }
972     }
973     shader_addline(buffer, "%s))%s;\n", tmpLine, dst_mask);
974
975 }
976
977 /** Process the D3DSIO_EXPP instruction in GLSL:
978  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
979  *   dst.x = 2^(floor(src))
980  *   dst.y = src - floor(src)
981  *   dst.z = 2^src   (partial precision is allowed, but optional)
982  *   dst.w = 1.0;
983  * For 2.0 shaders, just do this (honoring writemask and swizzle):
984  *   dst = 2^src;    (partial precision is allowed, but optional)
985  */
986 void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
987
988     char tmpLine[256];
989     char dst_str[100], src_str[100];
990     char dst_reg[50], src_reg[50];
991     char dst_mask[6], src_mask[6];
992     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
993     DWORD hex_version = This->baseShader.hex_version;
994     
995     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
996     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
997     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
998
999     if (hex_version < D3DPS_VERSION(2,0)) {
1000         shader_addline(arg->buffer, "tmp0.x = vec4(exp2(floor(%s))).x;\n", src_str);
1001         shader_addline(arg->buffer, "tmp0.y = vec4(%s - floor(%s)).y;\n", src_str, src_str);
1002         shader_addline(arg->buffer, "tmp0.z = vec4(exp2(%s)).x;\n", src_str);
1003         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1004         shader_addline(arg->buffer, "%svec4(tmp0))%s;\n", tmpLine, dst_mask);
1005     } else {
1006         shader_addline(arg->buffer, "%svec4(exp2(%s)))%s;\n", tmpLine, src_str, dst_mask);
1007     }
1008 }
1009
1010 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1011 void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1012
1013     char tmpLine[256];
1014     char dst_str[100], src_str[100];
1015     char dst_reg[50], src_reg[50];
1016     char dst_mask[6], src_mask[6];
1017     
1018     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1019     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
1020     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1021     strcat(tmpLine, "1.0 / ");
1022     shader_addline(arg->buffer, "%s%s)%s;\n", tmpLine, src_str, dst_mask);
1023 }
1024
1025 /** Process signed comparison opcodes in GLSL. */
1026 void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1027
1028     char tmpLine[256];
1029     char dst_str[100], src0_str[100], src1_str[100];
1030     char dst_reg[50], src0_reg[50], src1_reg[50];
1031     char dst_mask[6], src0_mask[6], src1_mask[6];
1032     
1033     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1034     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1035     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1036
1037     /* If we are comparing vectors and not scalars, we should process this through map2gl using the GLSL functions. */
1038     if (strlen(src0_mask) != 2) {
1039         shader_glsl_map2gl(arg);
1040     } else {
1041         char compareStr[3];
1042         compareStr[0] = 0;
1043         shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1044
1045         switch (arg->opcode->opcode) {
1046             case D3DSIO_SLT:    strcpy(compareStr, "<"); break;
1047             case D3DSIO_SGE:    strcpy(compareStr, ">="); break;
1048             default:
1049                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1050         }
1051         shader_addline(arg->buffer, "%s(float(%s) %s float(%s)) ? 1.0 : 0.0)%s;\n",
1052                        tmpLine, src0_str, compareStr, src1_str, dst_mask);
1053     }
1054 }
1055
1056 /** Process CMP instruction in GLSL (dst = src0.x > 0.0 ? src1.x : src2.x), per channel */
1057 void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1058
1059     char tmpLine[256];
1060     char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
1061     char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
1062     char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1063    
1064     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1065     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1066     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1067     shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);
1068
1069     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1070     shader_addline(arg->buffer, "%smix(vec4(%s), vec4(%s), vec4(lessThan(vec4(%s), vec4(0.0)))))%s;\n",
1071         tmpLine, src1_str, src2_str, src0_str, dst_mask);
1072 }
1073
1074 /** Process the CND opcode in GLSL (dst = (src0 < 0.5) ? src1 : src2) */
1075 void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1076
1077     char tmpLine[256];
1078     char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
1079     char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
1080     char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1081  
1082     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1083     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1084     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1085     shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);   
1086     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1087     shader_addline(arg->buffer, "%s(%s < 0.5) ? %s : %s)%s;\n", 
1088                    tmpLine, src0_str, src1_str, src2_str, dst_mask);
1089 }
1090
1091 /** GLSL code generation for D3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1092 void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1093
1094     char tmpLine[256];
1095     char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
1096     char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
1097     char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1098     
1099     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1100     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1101     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1102     shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);     
1103     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1104
1105     shader_addline(arg->buffer, "%s(vec4(%s) * vec4(%s)) + vec4(%s))%s;\n",
1106                    tmpLine, src0_str, src1_str, src2_str, dst_mask);
1107 }
1108
1109 /** Handles transforming all D3DSIO_M?x? opcodes for 
1110     Vertex shaders to GLSL codes */
1111 void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
1112     int i;
1113     int nComponents = 0;
1114     SHADER_OPCODE_ARG tmpArg;
1115    
1116     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1117
1118     /* Set constants for the temporary argument */
1119     tmpArg.shader      = arg->shader;
1120     tmpArg.buffer      = arg->buffer;
1121     tmpArg.src[0]      = arg->src[0];
1122     tmpArg.src_addr[0] = arg->src_addr[0];
1123     tmpArg.src_addr[1] = arg->src_addr[1];
1124     tmpArg.reg_maps = arg->reg_maps; 
1125     
1126     switch(arg->opcode->opcode) {
1127         case D3DSIO_M4x4:
1128             nComponents = 4;
1129             tmpArg.opcode = &IWineD3DVertexShaderImpl_shader_ins[D3DSIO_DP4];
1130             break;
1131         case D3DSIO_M4x3:
1132             nComponents = 3;
1133             tmpArg.opcode = &IWineD3DVertexShaderImpl_shader_ins[D3DSIO_DP4];
1134             break;
1135         case D3DSIO_M3x4:
1136             nComponents = 4;
1137             tmpArg.opcode = &IWineD3DVertexShaderImpl_shader_ins[D3DSIO_DP3];
1138             break;
1139         case D3DSIO_M3x3:
1140             nComponents = 3;
1141             tmpArg.opcode = &IWineD3DVertexShaderImpl_shader_ins[D3DSIO_DP3];
1142             break;
1143         case D3DSIO_M3x2:
1144             nComponents = 2;
1145             tmpArg.opcode = &IWineD3DVertexShaderImpl_shader_ins[D3DSIO_DP3];
1146             break;
1147         default:
1148             break;
1149     }
1150
1151     for (i = 0; i < nComponents; i++) {
1152         tmpArg.dst = ((arg->dst) & ~D3DSP_WRITEMASK_ALL)|(D3DSP_WRITEMASK_0<<i);
1153         tmpArg.src[1]      = arg->src[1]+i;
1154         shader_glsl_dot(&tmpArg);
1155     }
1156 }
1157
1158 /**
1159     The LRP instruction performs a component-wise linear interpolation 
1160     between the second and third operands using the first operand as the
1161     blend factor.  Equation:  (dst = src2 * (src1 - src0) + src0)
1162 */
1163 void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1164
1165     char tmpLine[256];
1166     char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
1167     char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
1168     char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1169    
1170     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1171     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1172     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1173     shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);     
1174
1175     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1176     
1177     shader_addline(arg->buffer, "%s%s + %s * (%s - %s))%s;\n",
1178                    tmpLine, src2_str, src0_str, src1_str, src2_str, dst_mask);
1179 }
1180
1181 /** Process the D3DSIO_LIT instruction in GLSL:
1182  * dst.x = dst.w = 1.0
1183  * dst.y = (src0.x > 0) ? src0.x
1184  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
1185  *                                        where src.w is clamped at +- 128
1186  */
1187 void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1188
1189     char dst_str[100], src0_str[100];
1190     char dst_reg[50], src0_reg[50];
1191     char dst_mask[6], src0_mask[6];
1192    
1193     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1194     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1195
1196     shader_addline(arg->buffer,
1197         "%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",
1198         dst_str, src0_reg, src0_reg, src0_reg, src0_reg, src0_reg, src0_reg, dst_mask);
1199 }
1200
1201 /** Process the D3DSIO_DST instruction in GLSL:
1202  * dst.x = 1.0
1203  * dst.y = src0.x * src0.y
1204  * dst.z = src0.z
1205  * dst.w = src1.w
1206  */
1207 void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1208
1209     char dst_str[100], src0_str[100], src1_str[100];
1210     char dst_reg[50], src0_reg[50], src1_reg[50];
1211     char dst_mask[6], src0_mask[6], src1_mask[6];
1212    
1213     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1214     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1215     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1216
1217     shader_addline(arg->buffer, "%s = vec4(1.0, %s.x * %s.y, %s.z, %s.w)%s;\n",
1218                    dst_str, src0_reg, src1_reg, src0_reg, src1_reg, dst_mask);
1219 }
1220
1221 /** Process the D3DSIO_SINCOS instruction in GLSL:
1222  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
1223  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
1224  * 
1225  * dst.x = cos(src0.?)
1226  * dst.y = sin(src0.?)
1227  * dst.z = dst.z
1228  * dst.w = dst.w
1229  */
1230 void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1231     
1232     char dst_str[100], src0_str[100];
1233     char dst_reg[50], src0_reg[50];
1234     char dst_mask[6], src0_mask[6];
1235    
1236     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1237     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1238
1239     shader_addline(arg->buffer, "%s = vec4(cos(%s), sin(%s), %s.z, %s.w)%s;\n",
1240                    dst_str, src0_str, src0_str, dst_reg, dst_reg, dst_mask);
1241 }
1242
1243 /** Process the D3DSIO_LOOP instruction in GLSL:
1244  * Start a for() loop where src0.y is the initial value of aL,
1245  *  increment aL by src0.z for a total of src0.x iterations.
1246  *  Need to use a temporary variable for this operation.
1247  */
1248 void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1249     
1250     char src1_str[100];
1251     char src1_reg[50];
1252     char src1_mask[6];
1253     
1254     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1255   
1256     shader_addline(arg->buffer, "for (tmpInt = 0, aL = %s.y; tmpInt < %s.x; tmpInt++, aL += %s.z) {\n",
1257                    src1_reg, src1_reg, src1_reg);
1258 }
1259
1260 void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1261     shader_addline(arg->buffer, "}\n");
1262 }
1263
1264 void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
1265
1266     char src0_str[100];
1267     char src0_reg[50];
1268     char src0_mask[6];
1269
1270     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1271     shader_addline(arg->buffer, "for (tmpInt = 0; tmpInt < %s.x; tmpInt++) {\n", src0_reg);
1272 }
1273
1274 void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1275
1276     char src0_str[100];
1277     char src0_reg[50];
1278     char src0_mask[6];
1279
1280     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1281     shader_addline(arg->buffer, "if (%s) {\n", src0_str); 
1282 }
1283
1284 void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
1285
1286     char src0_str[100], src1_str[100];
1287     char src0_reg[50], src1_reg[50];
1288     char src0_mask[6], src1_mask[6];
1289
1290     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1291     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1292
1293     shader_addline(arg->buffer, "if (%s %s %s) {\n",
1294         src0_str, shader_get_comp_op(arg->opcode_token), src1_str);
1295 }
1296
1297 void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
1298     shader_addline(arg->buffer, "} else {\n");
1299 }
1300
1301 void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
1302     shader_addline(arg->buffer, "break;\n");
1303 }
1304
1305 void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
1306
1307     char src0_str[100], src1_str[100];
1308     char src0_reg[50], src1_reg[50];
1309     char src0_mask[6], src1_mask[6];
1310
1311     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1312     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1313
1314     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
1315         src0_str, shader_get_comp_op(arg->opcode_token), src1_str);
1316 }
1317
1318 void shader_glsl_label(SHADER_OPCODE_ARG* arg) {
1319
1320     DWORD snum = (arg->src[0]) & D3DSP_REGNUM_MASK;
1321     shader_addline(arg->buffer, "}\n");
1322     shader_addline(arg->buffer, "void subroutine%lu () {\n",  snum);
1323 }
1324
1325 void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
1326     DWORD snum = (arg->src[0]) & D3DSP_REGNUM_MASK;
1327     shader_addline(arg->buffer, "subroutine%lu();\n", snum);
1328 }
1329
1330 void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
1331
1332     char src1_str[100];
1333     char src1_reg[50];
1334     char src1_mask[6];
1335    
1336     DWORD snum = (arg->src[0]) & D3DSP_REGNUM_MASK;
1337     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1338     shader_addline(arg->buffer, "if (%s) subroutine%lu();\n", src1_str, snum);
1339 }
1340
1341 /*********************************************
1342  * Pixel Shader Specific Code begins here
1343  ********************************************/
1344 void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
1345
1346     /* FIXME: Make this work for more than just 2D textures */
1347     
1348     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1349     SHADER_BUFFER* buffer = arg->buffer;
1350     DWORD hex_version = This->baseShader.hex_version;
1351
1352     char dst_str[100],   dst_reg[50],  dst_mask[6];
1353     char coord_str[100], coord_reg[50], coord_mask[6];
1354     char sampler_str[100], sampler_reg[50], sampler_mask[6];
1355     DWORD reg_dest_code = arg->dst & D3DSP_REGNUM_MASK;
1356     DWORD sampler_code, sampler_type;
1357
1358     /* All versions have a destination register */
1359     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1360
1361     /* 1.0-1.3: Use destination register as coordinate source.
1362        1.4+: Use provided coordinate source register. */
1363     if (hex_version < D3DPS_VERSION(1,4))
1364        strcpy(coord_reg, dst_reg);
1365     else
1366        shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, coord_reg, coord_mask, coord_str);
1367
1368     /* 1.0-1.4: Use destination register as coordinate source.
1369      * 2.0+: Use provided coordinate source register. */
1370     if (hex_version < D3DPS_VERSION(2,0)) {
1371         sprintf(sampler_str, "Psampler%lu", reg_dest_code); 
1372         sampler_code = reg_dest_code;
1373     }       
1374     else {
1375         shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, sampler_reg, sampler_mask, sampler_str);
1376         sampler_code = arg->src[1] & D3DSP_REGNUM_MASK;
1377     }         
1378
1379     sampler_type = arg->reg_maps->samplers[sampler_code] & WINED3DSP_TEXTURETYPE_MASK;
1380     if(This->wineD3DDevice->stateBlock->textureState[sampler_code][D3DTSS_TEXTURETRANSFORMFLAGS] & D3DTTFF_PROJECTED) {
1381         switch(sampler_type) {
1382
1383             case WINED3DSTT_2D:
1384                 shader_addline(buffer, "%s = texture2DProj(%s, %s);\n", dst_str, sampler_str, coord_reg);
1385                 break;
1386             case WINED3DSTT_CUBE:
1387                 shader_addline(buffer, "%s = textureCubeProj(%s, %s);\n", dst_str, sampler_str, coord_reg);
1388                 break;
1389             case WINED3DSTT_VOLUME:
1390                 shader_addline(buffer, "%s = texture3DProj(%s, %s);\n", dst_str, sampler_str, coord_reg);
1391                 break;
1392             default:
1393                 shader_addline(buffer, "%s = unrecognized_stype(%s, %s.stp);\n", dst_str, sampler_str, coord_reg);
1394                 FIXME("Unrecognized sampler type: %#lx;\n", sampler_type);
1395                 break;
1396         }
1397     } else {
1398         switch(sampler_type) {
1399
1400             case WINED3DSTT_2D:
1401                 shader_addline(buffer, "%s = texture2D(%s, %s.st);\n", dst_str, sampler_str, coord_reg);
1402                 break;
1403             case WINED3DSTT_CUBE:
1404                 shader_addline(buffer, "%s = textureCube(%s, %s.stp);\n", dst_str, sampler_str, coord_reg);
1405                 break;
1406             case WINED3DSTT_VOLUME:
1407                 shader_addline(buffer, "%s = texture3D(%s, %s.stp);\n", dst_str, sampler_str, coord_reg);
1408                 break;
1409             default:
1410                 shader_addline(buffer, "%s = unrecognized_stype(%s, %s.stp);\n", dst_str, sampler_str, coord_reg);
1411                 FIXME("Unrecognized sampler type: %#lx;\n", sampler_type);
1412                 break;
1413         }
1414     }
1415 }
1416
1417 void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {
1418
1419     /* FIXME: Make this work for more than just 2D textures */
1420     
1421     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1422     SHADER_BUFFER* buffer = arg->buffer;
1423     DWORD hex_version = This->baseShader.hex_version;
1424
1425     char tmpStr[100];
1426     char tmpReg[50];
1427     char tmpMask[6];
1428     tmpReg[0] = 0;
1429
1430     shader_glsl_add_param(arg, arg->dst, 0, FALSE, tmpReg, tmpMask, tmpStr);
1431
1432     if (hex_version != D3DPS_VERSION(1,4)) {
1433         DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1434         shader_addline(buffer, "%s = clamp(gl_TexCoord[%lu], 0.0, 1.0);\n", tmpReg, reg);
1435     } else {
1436         DWORD reg2 = arg->src[0] & D3DSP_REGNUM_MASK;
1437         shader_addline(buffer, "%s = gl_TexCoord[%lu]%s;\n", tmpStr, reg2, tmpMask);
1438    }
1439 }
1440
1441 /** Process the D3DSIO_TEXDP3TEX instruction in GLSL:
1442  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1443  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1444 void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
1445
1446     DWORD dstreg = arg->dst & D3DSP_REGNUM_MASK;
1447     char src0_str[100], dst_str[100];
1448     char src0_name[50], dst_name[50];
1449     char src0_mask[6],  dst_mask[6];
1450
1451     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
1452     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1453
1454     shader_addline(arg->buffer, "tmp0.x = dot(vec3(gl_TexCoord[%lu]), vec3(%s));\n", dstreg, src0_str);
1455     shader_addline(arg->buffer, "%s = vec4(texture1D(Psampler%lu, tmp0.x))%s;\n", dst_str, dstreg, dst_mask);
1456 }
1457
1458 /** Process the D3DSIO_TEXDP3 instruction in GLSL:
1459  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1460 void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
1461
1462     DWORD dstreg = arg->dst & D3DSP_REGNUM_MASK;
1463     char src0_str[100], dst_str[100];
1464     char src0_name[50], dst_name[50];
1465     char src0_mask[6],  dst_mask[6];
1466
1467     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
1468     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1469
1470     shader_addline(arg->buffer, "%s = vec4(dot(vec3(T%lu), vec3(%s)))%s;\n",
1471             dst_str, dstreg, src0_str, dst_mask);
1472 }
1473
1474 /** Process the D3DSIO_TEXDEPTH instruction in GLSL:
1475  * Calculate the depth as dst.x / dst.y   */
1476 void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
1477     
1478     char dst_str[100];
1479     char dst_reg[50];
1480     char dst_mask[6];
1481    
1482     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1483
1484     shader_addline(arg->buffer, "gl_FragDepth = %s.x / %s.y;\n", dst_reg, dst_reg);
1485 }
1486
1487 /** Process the D3DSIO_TEXM3X2DEPTH instruction in GLSL:
1488  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1489  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1490  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1491  */
1492 void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
1493     
1494     DWORD dstreg = arg->dst & D3DSP_REGNUM_MASK;
1495     char src0_str[100], dst_str[100];
1496     char src0_name[50], dst_name[50];
1497     char src0_mask[6],  dst_mask[6];
1498
1499     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
1500     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1501
1502     shader_addline(arg->buffer, "tmp0.y = dot(vec3(T%lu), vec3(%s));\n", dstreg, src0_str);
1503     shader_addline(arg->buffer, "gl_FragDepth = vec4((tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y)%s;\n", dst_str, dst_name);
1504 }
1505
1506 /** Process the D3DSIO_TEXM3X2PAD instruction in GLSL
1507  * Calculate the 1st of a 2-row matrix multiplication. */
1508 void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
1509
1510     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1511     SHADER_BUFFER* buffer = arg->buffer;
1512     char src0_str[100];
1513     char src0_name[50];
1514     char src0_mask[6];
1515
1516     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1517     shader_addline(buffer, "tmp0.x = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1518 }
1519
1520 /** Process the D3DSIO_TEXM3X3PAD instruction in GLSL
1521  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
1522 void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {
1523
1524     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1525     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1526     SHADER_BUFFER* buffer = arg->buffer;
1527     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
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.%c = dot(vec3(T%lu), vec3(%s));\n", 'x' + current_state->current_row, reg, src0_str);
1534     current_state->texcoord_w[current_state->current_row++] = reg;
1535 }
1536
1537 void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1538
1539     /* FIXME: Make this work for more than just 2D textures */
1540     
1541     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1542     SHADER_BUFFER* buffer = arg->buffer;
1543     char src0_str[100];
1544     char src0_name[50];
1545     char src0_mask[6];
1546
1547     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1548     shader_addline(buffer, "tmp0.y = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1549     shader_addline(buffer, "T%lu = texture2D(Psampler%lu, tmp0.st);\n", reg, reg);
1550 }
1551
1552 /** Process the D3DSIO_TEXM3X3TEX instruction in GLSL
1553  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculate coordinates */
1554 void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1555
1556     char src0_str[100];
1557     char src0_name[50];
1558     char src0_mask[6];
1559     char dimensions[5];
1560     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1561     DWORD src0_regnum = arg->src[0] & D3DSP_REGNUM_MASK;
1562     DWORD stype = arg->reg_maps->samplers[src0_regnum] & WINED3DSP_TEXTURETYPE_MASK;
1563     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1564     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1565     
1566     switch (stype) {
1567         case WINED3DSTT_2D:     strcpy(dimensions, "2D");   break;
1568         case WINED3DSTT_CUBE:   strcpy(dimensions, "Cube"); break;
1569         case WINED3DSTT_VOLUME: strcpy(dimensions, "3D");   break;
1570         default:
1571             strcpy(dimensions, "");
1572             FIXME("Unrecognized sampler type: %#lx\n", stype);
1573             break;
1574     }
1575
1576     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1577     shader_addline(arg->buffer, "tmp0.z = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1578     shader_addline(arg->buffer, "T%lu = texture%s(Psampler%lu, tmp0.%s);\n", 
1579             reg, dimensions, reg, (stype == WINED3DSTT_2D) ? "xy" : "xyz");
1580     current_state->current_row = 0;
1581 }
1582
1583 /** Process the D3DSIO_TEXM3X3 instruction in GLSL
1584  * Perform the 3rd row of a 3x3 matrix multiply */
1585 void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
1586
1587     char src0_str[100];
1588     char src0_name[50];
1589     char src0_mask[6];
1590     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1591     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1592     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1593     
1594     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1595     
1596     shader_addline(arg->buffer, "tmp0.z = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1597     shader_addline(arg->buffer, "T%lu = vec4(tmp0.x, tmp0.y, tmp0.z, 1.0);\n", reg);
1598     current_state->current_row = 0;
1599 }
1600
1601 /** Process the D3DSIO_TEXM3X3SPEC instruction in GLSL 
1602  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1603 void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {
1604
1605     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1606     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1607     char dimensions[5];
1608     char src0_str[100], src0_name[50], src0_mask[6];
1609     char src1_str[100], src1_name[50], src1_mask[6];
1610     SHADER_BUFFER* buffer = arg->buffer;
1611     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1612     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1613
1614     switch (stype) {
1615         case WINED3DSTT_2D:     strcpy(dimensions, "2D");   break;
1616         case WINED3DSTT_CUBE:   strcpy(dimensions, "Cube"); break;
1617         case WINED3DSTT_VOLUME: strcpy(dimensions, "3D");   break;
1618         default:
1619             strcpy(dimensions, "");
1620             FIXME("Unrecognized sampler type: %#lx\n", stype);
1621             break;
1622     }
1623
1624     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1625     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_name, src1_mask, src1_str);
1626
1627     /* Perform the last matrix multiply operation */
1628     shader_addline(buffer, "tmp0.z = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1629
1630     /* Calculate reflection vector */
1631     shader_addline(buffer, "tmp0.xyz = reflect(-vec3(%s), vec3(tmp0));\n", src1_str);
1632
1633     /* Sample the texture */
1634     shader_addline(buffer, "T%lu = texture%s(Psampler%lu, tmp0.%s);\n", 
1635             reg, dimensions, reg, (stype == WINED3DSTT_2D) ? "xy" : "xyz");
1636     current_state->current_row = 0;
1637 }
1638
1639 /** Process the D3DSIO_TEXM3X3VSPEC instruction in GLSL 
1640  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
1641 void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
1642
1643     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
1644     DWORD reg = arg->dst & D3DSP_REGNUM_MASK;
1645     SHADER_BUFFER* buffer = arg->buffer;
1646     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1647     char src0_str[100], src0_name[50], src0_mask[6];
1648
1649     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1650
1651     /* Perform the last matrix multiply operation */
1652     shader_addline(buffer, "tmp0.z = dot(vec3(T%lu), vec3(%s));\n", reg, src0_str);
1653
1654     /* Construct the eye-ray vector from w coordinates */
1655     shader_addline(buffer, "tmp1.x = gl_TexCoord[%lu].w;\n", current_state->texcoord_w[0]);
1656     shader_addline(buffer, "tmp1.y = gl_TexCoord[%lu].w;\n", current_state->texcoord_w[1]);
1657     shader_addline(buffer, "tmp1.z = gl_TexCoord[%lu].w;\n", reg);
1658
1659     /* Calculate reflection vector (Assume normal is normalized): RF = 2*(N.E)*N -E */
1660     shader_addline(buffer, "tmp0.x = dot(vec3(tmp0), vec3(tmp1));\n");
1661     shader_addline(buffer, "tmp0 = tmp0.w * tmp0;\n");
1662     shader_addline(buffer, "tmp0 = (2.0 * tmp0) - tmp1;\n");
1663
1664     /* FIXME:
1665      * We don't really know if a Cube or a Volume texture is being sampled, but since Cube textures
1666      * are used more commonly, we'll default to that.
1667      * We probably need to push back the pixel shader generation code until drawPrimitive() for 
1668      * shader versions < 2.0, since that's the only time we can guarantee that we're sampling
1669      * the correct type of texture because we can lookup what textures are bound at that point.
1670      */
1671     shader_addline(buffer, "T%lu = textureCube(Psampler%lu, tmp0.xyz);\n", reg, reg);
1672     current_state->current_row = 0;
1673 }
1674
1675 /** Process the D3DSIO_TEXBEM instruction in GLSL.
1676  * Apply a fake bump map transform.
1677  * FIXME: Should apply the BUMPMAPENV matrix.  For now, just sample the texture */
1678 void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
1679
1680     DWORD reg1 = arg->dst & D3DSP_REGNUM_MASK;
1681     DWORD reg2 = arg->src[0] & D3DSP_REGNUM_MASK;
1682
1683     FIXME("Not applying the BUMPMAPENV matrix for pixel shader instruction texbem.\n");
1684     shader_addline(arg->buffer, "T%lu = texture2D(Psampler%lu, gl_TexCoord[%lu].xy + T%lu.xy);\n",
1685             reg1, reg1, reg1, reg2);
1686 }
1687
1688 /** Process the D3DSIO_TEXREG2AR instruction in GLSL
1689  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
1690 void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
1691     
1692     char tmpLine[255];
1693     char dst_str[100], src0_str[100];
1694     char dst_reg[50], src0_reg[50];
1695     char dst_mask[6], src0_mask[6];
1696     DWORD src0_regnum = arg->src[0] & D3DSP_REGNUM_MASK;
1697
1698     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1699     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1700
1701     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1702     shader_addline(arg->buffer, "%stexture2D(Psampler%lu, %s.yz))%s;\n",
1703             tmpLine, src0_regnum, dst_reg, dst_mask);
1704 }
1705
1706 /** Process the D3DSIO_TEXREG2GB instruction in GLSL
1707  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
1708 void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
1709
1710     char tmpLine[255];
1711     char dst_str[100], src0_str[100];
1712     char dst_reg[50], src0_reg[50];
1713     char dst_mask[6], src0_mask[6];
1714     DWORD src0_regnum = arg->src[0] & D3DSP_REGNUM_MASK;
1715
1716     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1717     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1718
1719     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1720     shader_addline(arg->buffer, "%stexture2D(Psampler%lu, %s.yz))%s;\n",
1721             tmpLine, src0_regnum, dst_reg, dst_mask);
1722 }
1723
1724 /** Process the D3DSIO_TEXREG2RGB instruction in GLSL
1725  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
1726 void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
1727
1728     char tmpLine[255];
1729     char dst_str[100], src0_str[100];
1730     char dst_reg[50], src0_reg[50];
1731     char dst_mask[6], src0_mask[6];
1732     char dimensions[5];
1733     DWORD src0_regnum = arg->src[0] & D3DSP_REGNUM_MASK;
1734     DWORD stype = arg->reg_maps->samplers[src0_regnum] & WINED3DSP_TEXTURETYPE_MASK;
1735     switch (stype) {
1736         case WINED3DSTT_2D:     strcpy(dimensions, "2D");   break;
1737         case WINED3DSTT_CUBE:   strcpy(dimensions, "Cube"); break;
1738         case WINED3DSTT_VOLUME: strcpy(dimensions, "3D");   break;
1739         default:
1740             strcpy(dimensions, "");
1741             FIXME("Unrecognized sampler type: %#lx\n", stype);
1742             break;
1743     }
1744
1745     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1746     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1747
1748     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1749     shader_addline(arg->buffer, "%stexture%s(Psampler%lu, %s.%s))%s;\n",
1750             tmpLine, dimensions, src0_regnum, dst_reg, (stype == WINED3DSTT_2D) ? "xy" : "xyz", dst_mask);
1751 }
1752
1753 /** Process the D3DSIO_TEXKILL instruction in GLSL.
1754  * If any of the first 3 components are < 0, discard this pixel */
1755 void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
1756
1757     char dst_str[100], dst_name[50], dst_mask[6];
1758
1759     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
1760     shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_name);
1761 }
1762
1763 /** Process the D3DSIO_DP2ADD instruction in GLSL.
1764  * dst = dot2(src0, src1) + src2 */
1765 void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
1766
1767     char tmpLine[256];
1768     char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
1769     char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
1770     char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1771  
1772     shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1773     shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1774     shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
1775     shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);   
1776     shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1777     shader_addline(arg->buffer, "%sdot(vec2(%s), vec2(%s)) + %s)%s;\n",
1778                    tmpLine, src0_str, src1_str, src2_str, dst_mask);
1779 }
1780
1781 void pshader_glsl_input_pack(
1782    SHADER_BUFFER* buffer,
1783    semantic* semantics_in) {
1784
1785    unsigned int i;
1786
1787    for (i = 0; i < MAX_REG_INPUT; i++) {
1788
1789        DWORD usage_token = semantics_in[i].usage;
1790        DWORD register_token = semantics_in[i].reg;
1791        DWORD usage, usage_idx;
1792        char reg_mask[6];
1793
1794        /* Uninitialized */
1795        if (!usage_token) continue;
1796        usage = (usage_token & D3DSP_DCL_USAGE_MASK) >> D3DSP_DCL_USAGE_SHIFT;
1797        usage_idx = (usage_token & D3DSP_DCL_USAGEINDEX_MASK) >> D3DSP_DCL_USAGEINDEX_SHIFT;
1798        shader_glsl_get_output_register_swizzle(register_token, reg_mask);
1799
1800        switch(usage) {
1801
1802            case D3DDECLUSAGE_COLOR:
1803                if (usage_idx == 0)
1804                    shader_addline(buffer, "IN%lu%s = vec4(gl_Color)%s;\n",
1805                        i, reg_mask, reg_mask);
1806                else if (usage_idx == 1)
1807                    shader_addline(buffer, "IN%lu%s = vec4(gl_SecondaryColor)%s;\n",
1808                        i, reg_mask, reg_mask);
1809                else
1810                    shader_addline(buffer, "IN%lu%s = vec4(unsupported_color_input)%s;\n",
1811                        i, reg_mask, reg_mask);
1812                break;
1813
1814            case D3DDECLUSAGE_TEXCOORD:
1815                shader_addline(buffer, "IN%lu%s = vec4(gl_TexCoord[%lu])%s;\n",
1816                    i, reg_mask, usage_idx, reg_mask );
1817                break;
1818
1819            case D3DDECLUSAGE_FOG:
1820                shader_addline(buffer, "IN%lu%s = vec4(gl_FogFragCoord)%s;\n",
1821                    i, reg_mask, reg_mask);
1822                break;
1823
1824            default:
1825                shader_addline(buffer, "IN%lu%s = vec4(unsupported_input)%s;\n",
1826                    i, reg_mask, reg_mask);
1827         }
1828     }
1829 }
1830
1831 /*********************************************
1832  * Vertex Shader Specific Code begins here
1833  ********************************************/
1834
1835 void vshader_glsl_output_unpack(
1836    SHADER_BUFFER* buffer,
1837    semantic* semantics_out) {
1838
1839    unsigned int i;
1840
1841    for (i = 0; i < MAX_REG_OUTPUT; i++) {
1842
1843        DWORD usage_token = semantics_out[i].usage;
1844        DWORD register_token = semantics_out[i].reg;
1845        DWORD usage, usage_idx;
1846        char reg_mask[6];
1847
1848        /* Uninitialized */
1849        if (!usage_token) continue;
1850
1851        usage = (usage_token & D3DSP_DCL_USAGE_MASK) >> D3DSP_DCL_USAGE_SHIFT;
1852        usage_idx = (usage_token & D3DSP_DCL_USAGEINDEX_MASK) >> D3DSP_DCL_USAGEINDEX_SHIFT;
1853        shader_glsl_get_output_register_swizzle(register_token, reg_mask);
1854
1855        switch(usage) {
1856
1857            case D3DDECLUSAGE_COLOR:
1858                if (usage_idx == 0)
1859                    shader_addline(buffer, "gl_FrontColor%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1860                else if (usage_idx == 1)
1861                    shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1862                else
1863                    shader_addline(buffer, "unsupported_color_output%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1864                break;
1865
1866            case D3DDECLUSAGE_POSITION:
1867                shader_addline(buffer, "gl_Position%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1868                break;
1869  
1870            case D3DDECLUSAGE_TEXCOORD:
1871                shader_addline(buffer, "gl_TexCoord[%lu]%s = OUT%lu%s;\n",
1872                    usage_idx, reg_mask, i, reg_mask);
1873                break;
1874
1875            case WINED3DSHADERDECLUSAGE_PSIZE:
1876                shader_addline(buffer, "gl_PointSize = OUT%lu.x;\n", i);
1877                break;
1878
1879            case WINED3DSHADERDECLUSAGE_FOG:
1880                shader_addline(buffer, "gl_FogFragCoord%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1881                break;
1882
1883            default:
1884                shader_addline(buffer, "unsupported_output%s = OUT%lu%s;\n", reg_mask, i, reg_mask);
1885        }
1886     }
1887 }