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