wined3d: Implement the varying map.
[wine] / dlls / wined3d / glsl_shader.c
1 /*
2  * GLSL pixel and vertex shader implementation
3  *
4  * Copyright 2006 Jason Green 
5  * Copyright 2006-2007 Henri Verbeet
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 /*
23  * D3D shader asm has swizzles on source parameters, and write masks for
24  * destination parameters. GLSL uses swizzles for both. The result of this is
25  * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
26  * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
27  * mask for the destination parameter into account.
28  */
29
30 #include "config.h"
31 #include <stdio.h>
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
36
37 #define GLINFO_LOCATION      (*gl_info)
38
39 typedef struct {
40     char reg_name[50];
41     char mask_str[6];
42 } glsl_dst_param_t;
43
44 typedef struct {
45     char reg_name[50];
46     char param_str[100];
47 } glsl_src_param_t;
48
49 typedef struct {
50     const char *name;
51     DWORD coord_mask;
52 } glsl_sample_function_t;
53
54 /** Prints the GLSL info log which will contain error messages if they exist */
55 void print_glsl_info_log(WineD3D_GL_Info *gl_info, GLhandleARB obj) {
56     
57     int infologLength = 0;
58     char *infoLog;
59
60     GL_EXTCALL(glGetObjectParameterivARB(obj,
61                GL_OBJECT_INFO_LOG_LENGTH_ARB,
62                &infologLength));
63
64     /* A size of 1 is just a null-terminated string, so the log should be bigger than
65      * that if there are errors. */
66     if (infologLength > 1)
67     {
68         infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
69         GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
70         FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
71         HeapFree(GetProcessHeap(), 0, infoLog);
72     }
73 }
74
75 /**
76  * Loads (pixel shader) samplers
77  */
78 static void shader_glsl_load_psamplers(
79     WineD3D_GL_Info *gl_info,
80     IWineD3DStateBlock* iface) {
81
82     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
83     GLhandleARB programId = stateBlock->glsl_program->programId;
84     GLhandleARB name_loc;
85     int i;
86     char sampler_name[20];
87
88     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
89         snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
90         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
91         if (name_loc != -1) {
92             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
93             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
94                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
95                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
96                 checkGLcall("glUniform1iARB");
97             } else {
98                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
99             }
100         }
101     }
102 }
103
104 static void shader_glsl_load_vsamplers(WineD3D_GL_Info *gl_info, IWineD3DStateBlock* iface) {
105     IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
106     GLhandleARB programId = stateBlock->glsl_program->programId;
107     GLhandleARB name_loc;
108     char sampler_name[20];
109     int i;
110
111     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
112         snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
113         name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
114         if (name_loc != -1) {
115             int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
116             if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
117                 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
118                 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
119                 checkGLcall("glUniform1iARB");
120             } else {
121                 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
122             }
123         }
124     }
125 }
126
127 /** 
128  * Loads floating point constants (aka uniforms) into the currently set GLSL program.
129  * When constant_list == NULL, it will load all the constants.
130  */
131 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
132         unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
133         struct list *constant_list) {
134     constants_entry *constant;
135     local_constant* lconst;
136     GLhandleARB tmp_loc;
137     DWORD i, j, k;
138     DWORD *idx;
139
140     if (TRACE_ON(d3d_shader)) {
141         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
142             idx = constant->idx;
143             j = constant->count;
144             while (j--) {
145                 i = *idx++;
146                 tmp_loc = constant_locations[i];
147                 if (tmp_loc != -1) {
148                     TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
149                             constants[i * 4 + 0], constants[i * 4 + 1],
150                             constants[i * 4 + 2], constants[i * 4 + 3]);
151                 }
152             }
153         }
154     }
155
156     /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
157     if(WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1 &&
158        shader_is_pshader_version(This->baseShader.hex_version)) {
159         float lcl_const[4];
160
161         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
162             idx = constant->idx;
163             j = constant->count;
164             while (j--) {
165                 i = *idx++;
166                 tmp_loc = constant_locations[i];
167                 if (tmp_loc != -1) {
168                     /* We found this uniform name in the program - go ahead and send the data */
169                     k = i * 4;
170                     if(constants[k + 0] < -1.0) lcl_const[0] = -1.0;
171                     else if(constants[k + 0] > 1.0) lcl_const[0] = 1.0;
172                     else lcl_const[0] = constants[k + 0];
173                     if(constants[k + 1] < -1.0) lcl_const[1] = -1.0;
174                     else if(constants[k + 1] > 1.0) lcl_const[1] = 1.0;
175                     else lcl_const[1] = constants[k + 1];
176                     if(constants[k + 2] < -1.0) lcl_const[2] = -1.0;
177                     else if(constants[k + 2] > 1.0) lcl_const[2] = 1.0;
178                     else lcl_const[2] = constants[k + 2];
179                     if(constants[k + 3] < -1.0) lcl_const[3] = -1.0;
180                     else if(constants[k + 3] > 1.0) lcl_const[3] = 1.0;
181                     else lcl_const[3] = constants[k + 3];
182
183                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, lcl_const));
184                 }
185             }
186         }
187     } else {
188         LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
189             idx = constant->idx;
190             j = constant->count;
191             while (j--) {
192                 i = *idx++;
193                 tmp_loc = constant_locations[i];
194                 if (tmp_loc != -1) {
195                     /* We found this uniform name in the program - go ahead and send the data */
196                     GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
197                 }
198             }
199         }
200     }
201     checkGLcall("glUniform4fvARB()");
202
203     /* Load immediate constants */
204     if (TRACE_ON(d3d_shader)) {
205         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
206             tmp_loc = constant_locations[lconst->idx];
207             if (tmp_loc != -1) {
208                 GLfloat* values = (GLfloat*)lconst->value;
209                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
210                         values[0], values[1], values[2], values[3]);
211             }
212         }
213     }
214     /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
215     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
216         tmp_loc = constant_locations[lconst->idx];
217         if (tmp_loc != -1) {
218             /* We found this uniform name in the program - go ahead and send the data */
219             GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
220         }
221     }
222     checkGLcall("glUniform4fvARB()");
223 }
224
225 /** 
226  * Loads integer constants (aka uniforms) into the currently set GLSL program.
227  * When @constants_set == NULL, it will load all the constants.
228  */
229 static void shader_glsl_load_constantsI(
230     IWineD3DBaseShaderImpl* This,
231     WineD3D_GL_Info *gl_info,
232     GLhandleARB programId,
233     unsigned max_constants,
234     int* constants,
235     BOOL* constants_set) {
236     
237     GLhandleARB tmp_loc;
238     int i;
239     char tmp_name[8];
240     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
241     const char* prefix = is_pshader? "PI":"VI";
242     struct list* ptr;
243
244     for (i=0; i<max_constants; ++i) {
245         if (NULL == constants_set || constants_set[i]) {
246
247             TRACE_(d3d_constants)("Loading constants %i: %i, %i, %i, %i\n",
248                   i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
249
250             /* TODO: Benchmark and see if it would be beneficial to store the 
251              * locations of the constants to avoid looking up each time */
252             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
253             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
254             if (tmp_loc != -1) {
255                 /* We found this uniform name in the program - go ahead and send the data */
256                 GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, &constants[i*4]));
257                 checkGLcall("glUniform4ivARB");
258             }
259         }
260     }
261
262     /* Load immediate constants */
263     ptr = list_head(&This->baseShader.constantsI);
264     while (ptr) {
265         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
266         unsigned int idx = lconst->idx;
267         GLint* values = (GLint*) lconst->value;
268
269         TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
270             values[0], values[1], values[2], values[3]);
271
272         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
273         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
274         if (tmp_loc != -1) {
275             /* We found this uniform name in the program - go ahead and send the data */
276             GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, values));
277             checkGLcall("glUniform4ivARB");
278         }
279         ptr = list_next(&This->baseShader.constantsI, ptr);
280     }
281 }
282
283 /** 
284  * Loads boolean constants (aka uniforms) into the currently set GLSL program.
285  * When @constants_set == NULL, it will load all the constants.
286  */
287 static void shader_glsl_load_constantsB(
288     IWineD3DBaseShaderImpl* This,
289     WineD3D_GL_Info *gl_info,
290     GLhandleARB programId,
291     unsigned max_constants,
292     BOOL* constants,
293     BOOL* constants_set) {
294     
295     GLhandleARB tmp_loc;
296     int i;
297     char tmp_name[8];
298     char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
299     const char* prefix = is_pshader? "PB":"VB";
300     struct list* ptr;
301
302     for (i=0; i<max_constants; ++i) {
303         if (NULL == constants_set || constants_set[i]) {
304
305             TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i*4]);
306
307             /* TODO: Benchmark and see if it would be beneficial to store the 
308              * locations of the constants to avoid looking up each time */
309             snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
310             tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
311             if (tmp_loc != -1) {
312                 /* We found this uniform name in the program - go ahead and send the data */
313                 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i*4]));
314                 checkGLcall("glUniform1ivARB");
315             }
316         }
317     }
318
319     /* Load immediate constants */
320     ptr = list_head(&This->baseShader.constantsB);
321     while (ptr) {
322         local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
323         unsigned int idx = lconst->idx;
324         GLint* values = (GLint*) lconst->value;
325
326         TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
327
328         snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
329         tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
330         if (tmp_loc != -1) {
331             /* We found this uniform name in the program - go ahead and send the data */
332             GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
333             checkGLcall("glUniform1ivARB");
334         }
335         ptr = list_next(&This->baseShader.constantsB, ptr);
336     }
337 }
338
339
340
341 /**
342  * Loads the app-supplied constants into the currently set GLSL program.
343  */
344 void shader_glsl_load_constants(
345     IWineD3DDevice* device,
346     char usePixelShader,
347     char useVertexShader) {
348    
349     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
350     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
351     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
352
353     GLhandleARB *constant_locations;
354     struct list *constant_list;
355     GLhandleARB programId;
356     GLint pos;
357
358     if (!stateBlock->glsl_program) {
359         /* No GLSL program set - nothing to do. */
360         return;
361     }
362     programId = stateBlock->glsl_program->programId;
363
364     if (useVertexShader) {
365         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
366         GLint pos;
367
368         constant_locations = stateBlock->glsl_program->vuniformF_locations;
369         constant_list = &stateBlock->set_vconstantsF;
370
371         /* Load vertex shader samplers */
372         shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)stateBlock);
373
374         /* Load DirectX 9 float constants/uniforms for vertex shader */
375         shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
376                 stateBlock->vertexShaderConstantF, constant_locations, constant_list);
377
378         /* Load DirectX 9 integer constants/uniforms for vertex shader */
379         shader_glsl_load_constantsI(vshader, gl_info, programId, MAX_CONST_I,
380                                     stateBlock->vertexShaderConstantI,
381                                     stateBlock->changed.vertexShaderConstantsI);
382
383         /* Load DirectX 9 boolean constants/uniforms for vertex shader */
384         shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
385                                     stateBlock->vertexShaderConstantB,
386                                     stateBlock->changed.vertexShaderConstantsB);
387
388         /* Upload the position fixup params */
389         pos = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
390         checkGLcall("glGetUniformLocationARB");
391         GL_EXTCALL(glUniform4fvARB(pos, 1, &deviceImpl->posFixup[0]));
392         checkGLcall("glUniform4fvARB");
393     }
394
395     if (usePixelShader) {
396
397         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
398
399         constant_locations = stateBlock->glsl_program->puniformF_locations;
400         constant_list = &stateBlock->set_pconstantsF;
401
402         /* Load pixel shader samplers */
403         shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*) stateBlock);
404
405         /* Load DirectX 9 float constants/uniforms for pixel shader */
406         shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
407                 stateBlock->pixelShaderConstantF, constant_locations, constant_list);
408
409         /* Load DirectX 9 integer constants/uniforms for pixel shader */
410         shader_glsl_load_constantsI(pshader, gl_info, programId, MAX_CONST_I,
411                                     stateBlock->pixelShaderConstantI, 
412                                     stateBlock->changed.pixelShaderConstantsI);
413
414         /* Load DirectX 9 boolean constants/uniforms for pixel shader */
415         shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
416                                     stateBlock->pixelShaderConstantB, 
417                                     stateBlock->changed.pixelShaderConstantsB);
418
419         /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
420          * It can't be 0 for a valid texbem instruction.
421          */
422         if(((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat != -1) {
423             float *data = (float *) &stateBlock->textureState[(int) ((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat][WINED3DTSS_BUMPENVMAT00];
424             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "bumpenvmat"));
425             checkGLcall("glGetUniformLocationARB");
426             GL_EXTCALL(glUniformMatrix2fvARB(pos, 1, 0, data));
427             checkGLcall("glUniformMatrix2fvARB");
428
429             /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
430              * is set too, so we can check that in the needsbumpmat check
431              */
432             if(((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams != -1) {
433                 int stage = ((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams;
434                 GLfloat *scale = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
435                 GLfloat *offset = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
436
437                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminancescale"));
438                 checkGLcall("glGetUniformLocationARB");
439                 GL_EXTCALL(glUniform1fvARB(pos, 1, scale));
440                 checkGLcall("glUniform1fvARB");
441                 pos = GL_EXTCALL(glGetUniformLocationARB(programId, "luminanceoffset"));
442                 checkGLcall("glGetUniformLocationARB");
443                 GL_EXTCALL(glUniform1fvARB(pos, 1, offset));
444                 checkGLcall("glUniform1fvARB");
445             }
446         } else if(((IWineD3DPixelShaderImpl *) pshader)->srgb_enabled &&
447                   !((IWineD3DPixelShaderImpl *) pshader)->srgb_mode_hardcoded) {
448             float comparison[4];
449             float mul_low[4];
450
451             if(stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
452                 comparison[0] = srgb_cmp; comparison[1] = srgb_cmp;
453                 comparison[2] = srgb_cmp; comparison[3] = srgb_cmp;
454
455                 mul_low[0] = srgb_mul_low; mul_low[1] = srgb_mul_low;
456                 mul_low[2] = srgb_mul_low; mul_low[3] = srgb_mul_low;
457             } else {
458                 comparison[0] = 1.0 / 0.0; comparison[1] = 1.0 / 0.0;
459                 comparison[2] = 1.0 / 0.0; comparison[3] = 1.0 / 0.0;
460
461                 mul_low[0] = 1.0; mul_low[1] = 1.0;
462                 mul_low[2] = 1.0; mul_low[3] = 1.0;
463             }
464
465             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_comparison"));
466             checkGLcall("glGetUniformLocationARB");
467             GL_EXTCALL(glUniform4fvARB(pos, 1, comparison));
468             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_mul_low"));
469             checkGLcall("glGetUniformLocationARB");
470             GL_EXTCALL(glUniform4fvARB(pos, 1, mul_low));
471         }
472         if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
473             float correction_params[4];
474             pos = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
475             checkGLcall("glGetUniformLocationARB");
476             if(deviceImpl->render_offscreen) {
477                 correction_params[0] = 0.0;
478                 correction_params[1] = 1.0;
479             } else {
480                 /* position is window relative, not viewport relative */
481                 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
482                 correction_params[1] = -1.0;
483             }
484             GL_EXTCALL(glUniform4fvARB(pos, 1, correction_params));
485         }
486     }
487 }
488
489 /** Generate the variable & register declarations for the GLSL output target */
490 void shader_generate_glsl_declarations(
491     IWineD3DBaseShader *iface,
492     shader_reg_maps* reg_maps,
493     SHADER_BUFFER* buffer,
494     WineD3D_GL_Info* gl_info) {
495
496     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
497     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
498     int i;
499     unsigned int extra_constants_needed = 0;
500
501     /* There are some minor differences between pixel and vertex shaders */
502     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
503     char prefix = pshader ? 'P' : 'V';
504
505     /* Prototype the subroutines */
506     for (i = 0; i < This->baseShader.limits.label; i++) {
507         if (reg_maps->labels[i])
508             shader_addline(buffer, "void subroutine%lu();\n", i);
509     }
510
511     /* Declare the constants (aka uniforms) */
512     if (This->baseShader.limits.constant_float > 0) {
513         unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
514                 (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
515         shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
516     }
517
518     if (This->baseShader.limits.constant_int > 0)
519         shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
520
521     if (This->baseShader.limits.constant_bool > 0)
522         shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
523
524     if(!pshader) {
525         shader_addline(buffer, "uniform vec4 posFixup;\n");
526         /* Predeclaration; This function is added at link time based on the pixel shader.
527          * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
528          * that. We know the input to the reorder function at vertex shader compile time, so
529          * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
530          * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
531          * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
532          * it will write to the varying array. Here we depend on the shader optimizer on sorting that
533          * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
534          * inout.
535          */
536         if(This->baseShader.hex_version >= WINED3DVS_VERSION(3, 0)) {
537             shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
538         } else {
539             shader_addline(buffer, "void order_ps_input();\n");
540         }
541     } else {
542         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
543
544         if(reg_maps->bumpmat != -1) {
545             shader_addline(buffer, "uniform mat2 bumpenvmat;\n");
546             if(reg_maps->luminanceparams) {
547                 shader_addline(buffer, "uniform float luminancescale;\n");
548                 shader_addline(buffer, "uniform float luminanceoffset;\n");
549                 extra_constants_needed++;
550             }
551             extra_constants_needed++;
552         }
553
554         if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
555             ps_impl->srgb_enabled = 1;
556             if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
557                 shader_addline(buffer, "uniform vec4 srgb_mul_low;\n");
558                 shader_addline(buffer, "uniform vec4 srgb_comparison;\n");
559                 ps_impl->srgb_mode_hardcoded = 0;
560                 extra_constants_needed++;
561             } else {
562                 ps_impl->srgb_mode_hardcoded = 1;
563                 shader_addline(buffer, "const vec4 srgb_mul_low = {%f, %f, %f, %f};\n",
564                                srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
565                 shader_addline(buffer, "const vec4 srgb_comparison = {%f, %f, %f, %f};\n",
566                                srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
567             }
568         } else {
569             IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
570
571             /* Do not write any srgb fixup into the shader to save shader size and processing time.
572              * As a consequence, we can't toggle srgb write on without recompilation
573              */
574             ps_impl->srgb_enabled = 0;
575             ps_impl->srgb_mode_hardcoded = 1;
576         }
577         if(reg_maps->vpos || reg_maps->usesdsy) {
578             if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
579                 shader_addline(buffer, "uniform vec4 ycorrection;\n");
580                 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
581                 extra_constants_needed++;
582             } else {
583                 /* This happens because we do not have proper tracking of the constant registers that are
584                  * actually used, only the max limit of the shader version
585                  */
586                 FIXME("Cannot find a free uniform for vpos correction params\n");
587                 shader_addline(buffer, "const vec4 ycorrection = {%f, %f, 0.0, 0.0};\n",
588                                device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
589                                device->render_offscreen ? 1.0 : -1.0);
590             }
591             shader_addline(buffer, "vec4 vpos;\n");
592         }
593     }
594
595     /* Declare texture samplers */ 
596     for (i = 0; i < This->baseShader.limits.sampler; i++) {
597         if (reg_maps->samplers[i]) {
598
599             DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
600             switch (stype) {
601
602                 case WINED3DSTT_1D:
603                     shader_addline(buffer, "uniform sampler1D %csampler%lu;\n", prefix, i);
604                     break;
605                 case WINED3DSTT_2D:
606                     shader_addline(buffer, "uniform sampler2D %csampler%lu;\n", prefix, i);
607                     break;
608                 case WINED3DSTT_CUBE:
609                     shader_addline(buffer, "uniform samplerCube %csampler%lu;\n", prefix, i);
610                     break;
611                 case WINED3DSTT_VOLUME:
612                     shader_addline(buffer, "uniform sampler3D %csampler%lu;\n", prefix, i);
613                     break;
614                 default:
615                     shader_addline(buffer, "uniform unsupported_sampler %csampler%lu;\n", prefix, i);
616                     FIXME("Unrecognized sampler type: %#x\n", stype);
617                     break;
618             }
619         }
620     }
621     
622     /* Declare address variables */
623     for (i = 0; i < This->baseShader.limits.address; i++) {
624         if (reg_maps->address[i])
625             shader_addline(buffer, "ivec4 A%d;\n", i);
626     }
627
628     /* Declare texture coordinate temporaries and initialize them */
629     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
630         if (reg_maps->texcoord[i]) 
631             shader_addline(buffer, "vec4 T%lu = gl_TexCoord[%lu];\n", i, i);
632     }
633
634     /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
635      * helper function shader that is linked in at link time
636      */
637     if(pshader && This->baseShader.hex_version >= WINED3DVS_VERSION(3, 0)) {
638         if(use_vs(device)) {
639             shader_addline(buffer, "varying vec4 IN[%lu];\n", GL_LIMITS(glsl_varyings) / 4);
640         } else {
641             /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
642              * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
643              * pixel shader that reads the fixed function color into the packed input registers.
644              */
645             shader_addline(buffer, "vec4 IN[%lu];\n", GL_LIMITS(glsl_varyings) / 4);
646         }
647     }
648
649     /* Declare output register temporaries */
650     if(This->baseShader.limits.packed_output) {
651         shader_addline(buffer, "vec4 OUT[%lu];\n", This->baseShader.limits.packed_output);
652     }
653
654     /* Declare temporary variables */
655     for(i = 0; i < This->baseShader.limits.temporary; i++) {
656         if (reg_maps->temporary[i])
657             shader_addline(buffer, "vec4 R%lu;\n", i);
658     }
659
660     /* Declare attributes */
661     for (i = 0; i < This->baseShader.limits.attributes; i++) {
662         if (reg_maps->attributes[i])
663             shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
664     }
665
666     /* Declare loop registers aLx */
667     for (i = 0; i < reg_maps->loop_depth; i++) {
668         shader_addline(buffer, "int aL%u;\n", i);
669         shader_addline(buffer, "int tmpInt%u;\n", i);
670     }
671
672     /* Temporary variables for matrix operations */
673     shader_addline(buffer, "vec4 tmp0;\n");
674     shader_addline(buffer, "vec4 tmp1;\n");
675
676     /* Start the main program */
677     shader_addline(buffer, "void main() {\n");
678     if(pshader && reg_maps->vpos) {
679         shader_addline(buffer, "vpos = vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1) - 0.5;\n");
680     }
681 }
682
683 /*****************************************************************************
684  * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
685  *
686  * For more information, see http://wiki.winehq.org/DirectX-Shaders
687  ****************************************************************************/
688
689 /* Prototypes */
690 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
691         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
692
693 /** Used for opcode modifiers - They multiply the result by the specified amount */
694 static const char * const shift_glsl_tab[] = {
695     "",           /*  0 (none) */ 
696     "2.0 * ",     /*  1 (x2)   */ 
697     "4.0 * ",     /*  2 (x4)   */ 
698     "8.0 * ",     /*  3 (x8)   */ 
699     "16.0 * ",    /*  4 (x16)  */ 
700     "32.0 * ",    /*  5 (x32)  */ 
701     "",           /*  6 (x64)  */ 
702     "",           /*  7 (x128) */ 
703     "",           /*  8 (d256) */ 
704     "",           /*  9 (d128) */ 
705     "",           /* 10 (d64)  */ 
706     "",           /* 11 (d32)  */ 
707     "0.0625 * ",  /* 12 (d16)  */ 
708     "0.125 * ",   /* 13 (d8)   */ 
709     "0.25 * ",    /* 14 (d4)   */ 
710     "0.5 * "      /* 15 (d2)   */ 
711 };
712
713 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
714 static void shader_glsl_gen_modifier (
715     const DWORD instr,
716     const char *in_reg,
717     const char *in_regswizzle,
718     char *out_str) {
719
720     out_str[0] = 0;
721     
722     if (instr == WINED3DSIO_TEXKILL)
723         return;
724
725     switch (instr & WINED3DSP_SRCMOD_MASK) {
726     case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
727     case WINED3DSPSM_DW:
728     case WINED3DSPSM_NONE:
729         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
730         break;
731     case WINED3DSPSM_NEG:
732         sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
733         break;
734     case WINED3DSPSM_NOT:
735         sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
736         break;
737     case WINED3DSPSM_BIAS:
738         sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
739         break;
740     case WINED3DSPSM_BIASNEG:
741         sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
742         break;
743     case WINED3DSPSM_SIGN:
744         sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
745         break;
746     case WINED3DSPSM_SIGNNEG:
747         sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
748         break;
749     case WINED3DSPSM_COMP:
750         sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
751         break;
752     case WINED3DSPSM_X2:
753         sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
754         break;
755     case WINED3DSPSM_X2NEG:
756         sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
757         break;
758     case WINED3DSPSM_ABS:
759         sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
760         break;
761     case WINED3DSPSM_ABSNEG:
762         sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
763         break;
764     default:
765         FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
766         sprintf(out_str, "%s%s", in_reg, in_regswizzle);
767     }
768 }
769
770 /** Writes the GLSL variable name that corresponds to the register that the
771  * DX opcode parameter is trying to access */
772 static void shader_glsl_get_register_name(
773     const DWORD param,
774     const DWORD addr_token,
775     char* regstr,
776     BOOL* is_color,
777     SHADER_OPCODE_ARG* arg) {
778
779     /* oPos, oFog and oPts in D3D */
780     static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
781
782     DWORD reg = param & WINED3DSP_REGNUM_MASK;
783     DWORD regtype = shader_get_regtype(param);
784     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
785     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
786     WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
787
788     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
789     char tmpStr[50];
790
791     *is_color = FALSE;   
792  
793     switch (regtype) {
794     case WINED3DSPR_TEMP:
795         sprintf(tmpStr, "R%u", reg);
796     break;
797     case WINED3DSPR_INPUT:
798         if (pshader) {
799             /* Pixel shaders >= 3.0 */
800             if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3) {
801                 if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
802                     glsl_src_param_t rel_param;
803                     shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
804
805                     sprintf(tmpStr, "IN[%s + %u]", rel_param.param_str,
806                             ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
807                 } else {
808                     sprintf(tmpStr, "IN[%u]",
809                             ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
810                 }
811             } else {
812                 if (reg==0)
813                     strcpy(tmpStr, "gl_Color");
814                 else
815                     strcpy(tmpStr, "gl_SecondaryColor");
816             }
817         } else {
818             if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
819                *is_color = TRUE;
820             sprintf(tmpStr, "attrib%u", reg);
821         } 
822         break;
823     case WINED3DSPR_CONST:
824     {
825         const char* prefix = pshader? "PC":"VC";
826
827         /* Relative addressing */
828         if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
829
830            /* Relative addressing on shaders 2.0+ have a relative address token, 
831             * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
832            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
833                glsl_src_param_t rel_param;
834                shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
835                sprintf(tmpStr, "%s[%s + %u]", prefix, rel_param.param_str, reg);
836            } else
837                sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
838
839         } else
840              sprintf(tmpStr, "%s[%u]", prefix, reg);
841
842         break;
843     }
844     case WINED3DSPR_CONSTINT:
845         if (pshader)
846             sprintf(tmpStr, "PI[%u]", reg);
847         else
848             sprintf(tmpStr, "VI[%u]", reg);
849         break;
850     case WINED3DSPR_CONSTBOOL:
851         if (pshader)
852             sprintf(tmpStr, "PB[%u]", reg);
853         else
854             sprintf(tmpStr, "VB[%u]", reg);
855         break;
856     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
857         if (pshader) {
858             sprintf(tmpStr, "T%u", reg);
859         } else {
860             sprintf(tmpStr, "A%u", reg);
861         }
862     break;
863     case WINED3DSPR_LOOP:
864         sprintf(tmpStr, "aL%u", This->baseShader.cur_loop_regno - 1);
865     break;
866     case WINED3DSPR_SAMPLER:
867         if (pshader)
868             sprintf(tmpStr, "Psampler%u", reg);
869         else
870             sprintf(tmpStr, "Vsampler%u", reg);
871     break;
872     case WINED3DSPR_COLOROUT:
873         if (reg >= GL_LIMITS(buffers)) {
874             WARN("Write to render target %u, only %d supported\n", reg, 4);
875         }
876         if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
877             sprintf(tmpStr, "gl_FragData[%u]", reg);
878         } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
879             sprintf(tmpStr, "gl_FragColor");
880         }
881     break;
882     case WINED3DSPR_RASTOUT:
883         sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
884     break;
885     case WINED3DSPR_DEPTHOUT:
886         sprintf(tmpStr, "gl_FragDepth");
887     break;
888     case WINED3DSPR_ATTROUT:
889         if (reg == 0) {
890             sprintf(tmpStr, "gl_FrontColor");
891         } else {
892             sprintf(tmpStr, "gl_FrontSecondaryColor");
893         }
894     break;
895     case WINED3DSPR_TEXCRDOUT:
896         /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
897         if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
898             sprintf(tmpStr, "OUT[%u]", reg);
899         else
900             sprintf(tmpStr, "gl_TexCoord[%u]", reg);
901     break;
902     case WINED3DSPR_MISCTYPE:
903         if (reg == 0) {
904             /* vPos */
905             sprintf(tmpStr, "vpos");
906         } else if (reg == 1){
907             /* Note that gl_FrontFacing is a bool, while vFace is
908              * a float for which the sign determines front/back
909              */
910             sprintf(tmpStr, "(gl_FrontFacing ? 1.0 : -1.0)");
911         } else {
912             FIXME("Unhandled misctype register %d\n", reg);
913             sprintf(tmpStr, "unrecognized_register");
914         }
915         break;
916     default:
917         FIXME("Unhandled register name Type(%d)\n", regtype);
918         sprintf(tmpStr, "unrecognized_register");
919     break;
920     }
921
922     strcat(regstr, tmpStr);
923 }
924
925 /* Get the GLSL write mask for the destination register */
926 static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
927     char *ptr = write_mask;
928     DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
929
930     if (shader_is_scalar(param)) {
931         mask = WINED3DSP_WRITEMASK_0;
932     } else {
933         *ptr++ = '.';
934         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
935         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
936         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
937         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
938     }
939
940     *ptr = '\0';
941
942     return mask;
943 }
944
945 static size_t shader_glsl_get_write_mask_size(DWORD write_mask) {
946     size_t size = 0;
947
948     if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
949     if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
950     if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
951     if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
952
953     return size;
954 }
955
956 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
957     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
958      * but addressed as "rgba". To fix this we need to swap the register's x
959      * and z components. */
960     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
961     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
962     char *ptr = swizzle_str;
963
964     if (!shader_is_scalar(param)) {
965         *ptr++ = '.';
966         /* swizzle bits fields: wwzzyyxx */
967         if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
968         if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
969         if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
970         if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
971     }
972
973     *ptr = '\0';
974 }
975
976 /* From a given parameter token, generate the corresponding GLSL string.
977  * Also, return the actual register name and swizzle in case the
978  * caller needs this information as well. */
979 static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
980         const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param) {
981     BOOL is_color = FALSE;
982     char swizzle_str[6];
983
984     src_param->reg_name[0] = '\0';
985     src_param->param_str[0] = '\0';
986     swizzle_str[0] = '\0';
987
988     shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
989
990     shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
991     shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
992 }
993
994 /* From a given parameter token, generate the corresponding GLSL string.
995  * Also, return the actual register name and swizzle in case the
996  * caller needs this information as well. */
997 static DWORD shader_glsl_add_dst_param(SHADER_OPCODE_ARG* arg, const DWORD param,
998         const DWORD addr_token, glsl_dst_param_t *dst_param) {
999     BOOL is_color = FALSE;
1000
1001     dst_param->mask_str[0] = '\0';
1002     dst_param->reg_name[0] = '\0';
1003
1004     shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
1005     return shader_glsl_get_write_mask(param, dst_param->mask_str);
1006 }
1007
1008 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1009 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg, const DWORD param) {
1010     glsl_dst_param_t dst_param;
1011     DWORD mask;
1012     int shift;
1013
1014     mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);
1015
1016     if(mask) {
1017         shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1018         shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
1019     }
1020
1021     return mask;
1022 }
1023
1024 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1025 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg) {
1026     return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
1027 }
1028
1029 /** Process GLSL instruction modifiers */
1030 void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
1031     
1032     DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
1033  
1034     if (arg->opcode->dst_token && mask != 0) {
1035         glsl_dst_param_t dst_param;
1036
1037         shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1038
1039         if (mask & WINED3DSPDM_SATURATE) {
1040             /* _SAT means to clamp the value of the register to between 0 and 1 */
1041             shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1042                     dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1043         }
1044         if (mask & WINED3DSPDM_MSAMPCENTROID) {
1045             FIXME("_centroid modifier not handled\n");
1046         }
1047         if (mask & WINED3DSPDM_PARTIALPRECISION) {
1048             /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1049         }
1050     }
1051 }
1052
1053 static inline const char* shader_get_comp_op(
1054     const DWORD opcode) {
1055
1056     DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
1057     switch (op) {
1058         case COMPARISON_GT: return ">";
1059         case COMPARISON_EQ: return "==";
1060         case COMPARISON_GE: return ">=";
1061         case COMPARISON_LT: return "<";
1062         case COMPARISON_NE: return "!=";
1063         case COMPARISON_LE: return "<=";
1064         default:
1065             FIXME("Unrecognized comparison value: %u\n", op);
1066             return "(\?\?)";
1067     }
1068 }
1069
1070 static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, glsl_sample_function_t *sample_function) {
1071     /* Note that there's no such thing as a projected cube texture. */
1072     switch(sampler_type) {
1073         case WINED3DSTT_1D:
1074             sample_function->name = projected ? "texture1DProj" : "texture1D";
1075             sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1076             break;
1077         case WINED3DSTT_2D:
1078             sample_function->name = projected ? "texture2DProj" : "texture2D";
1079             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1080             break;
1081         case WINED3DSTT_CUBE:
1082             sample_function->name = "textureCube";
1083             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1084             break;
1085         case WINED3DSTT_VOLUME:
1086             sample_function->name = projected ? "texture3DProj" : "texture3D";
1087             sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1088             break;
1089         default:
1090             sample_function->name = "";
1091             FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1092             break;
1093     }
1094 }
1095
1096 static void shader_glsl_color_correction(SHADER_OPCODE_ARG* arg) {
1097     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1098     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) shader->baseShader.device;
1099     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
1100     glsl_dst_param_t dst_param;
1101     glsl_dst_param_t dst_param2;
1102     WINED3DFORMAT fmt;
1103     WINED3DFORMAT conversion_group;
1104     IWineD3DBaseTextureImpl *texture;
1105     DWORD mask, mask_size;
1106     UINT i;
1107     BOOL recorded = FALSE;
1108     DWORD sampler_idx;
1109     DWORD hex_version = shader->baseShader.hex_version;
1110
1111     switch(arg->opcode->opcode) {
1112         case WINED3DSIO_TEX:
1113             if (hex_version < WINED3DPS_VERSION(2,0)) {
1114                 sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1115             } else {
1116                 sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
1117             }
1118             break;
1119
1120         case WINED3DSIO_TEXLDL:
1121             FIXME("Add color fixup for vertex texture WINED3DSIO_TEXLDL\n");
1122             return;
1123
1124         case WINED3DSIO_TEXDP3TEX:
1125         case WINED3DSIO_TEXM3x3TEX:
1126         case WINED3DSIO_TEXM3x3SPEC:
1127         case WINED3DSIO_TEXM3x3VSPEC:
1128         case WINED3DSIO_TEXBEM:
1129         case WINED3DSIO_TEXREG2AR:
1130         case WINED3DSIO_TEXREG2GB:
1131         case WINED3DSIO_TEXREG2RGB:
1132             sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1133             break;
1134
1135         default:
1136             /* Not a texture sampling instruction, nothing to do */
1137             return;
1138     };
1139
1140     texture = (IWineD3DBaseTextureImpl *) deviceImpl->stateBlock->textures[sampler_idx];
1141     if(texture) {
1142         fmt = texture->resource.format;
1143         conversion_group = texture->baseTexture.shader_conversion_group;
1144     } else {
1145         fmt = WINED3DFMT_UNKNOWN;
1146         conversion_group = WINED3DFMT_UNKNOWN;
1147     }
1148
1149     /* before doing anything, record the sampler with the format in the format conversion list,
1150      * but check if it's not there already
1151      */
1152     for(i = 0; i < shader->baseShader.num_sampled_samplers; i++) {
1153         if(shader->baseShader.sampled_samplers[i] == sampler_idx) {
1154             recorded = TRUE;
1155             break;
1156         }
1157     }
1158     if(!recorded) {
1159         shader->baseShader.sampled_samplers[shader->baseShader.num_sampled_samplers] = sampler_idx;
1160         shader->baseShader.num_sampled_samplers++;
1161         shader->baseShader.sampled_format[sampler_idx] = conversion_group;
1162     }
1163
1164     switch(fmt) {
1165         case WINED3DFMT_V8U8:
1166         case WINED3DFMT_V16U16:
1167             if(GL_SUPPORT(NV_TEXTURE_SHADER) ||
1168               (GL_SUPPORT(ATI_ENVMAP_BUMPMAP) && fmt == WINED3DFMT_V8U8)) {
1169                 /* The 3rd channel returns 1.0 in d3d, but 0.0 in gl. Fix this while we're at it :-) */
1170                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_2, &dst_param);
1171                 mask_size = shader_glsl_get_write_mask_size(mask);
1172                 if(mask_size >= 3) {
1173                     shader_addline(arg->buffer, "%s.%c = 1.0;\n", dst_param.reg_name, dst_param.mask_str[3]);
1174                 }
1175             } else {
1176                 /* Correct the sign, but leave the blue as it is - it was loaded correctly already */
1177                 mask = shader_glsl_add_dst_param(arg, arg->dst,
1178                                           WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1,
1179                                           &dst_param);
1180                 mask_size = shader_glsl_get_write_mask_size(mask);
1181                 if(mask_size >= 2) {
1182                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1183                     dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
1184                     dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
1185                 } else if(mask_size == 1) {
1186                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str[1],
1187                     dst_param.reg_name, dst_param.mask_str[1]);
1188                 }
1189             }
1190             break;
1191
1192         case WINED3DFMT_X8L8V8U8:
1193             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1194                 /* Red and blue are the signed channels, fix them up; Blue(=L) is correct already,
1195                  * and a(X) is always 1.0
1196                  */
1197                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
1198                 mask_size = shader_glsl_get_write_mask_size(mask);
1199                 if(mask_size >= 2) {
1200                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1201                                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
1202                                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
1203                 } else if(mask_size == 1) {
1204                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
1205                                    dst_param.reg_name, dst_param.mask_str[1],
1206                                    dst_param.reg_name, dst_param.mask_str[1]);
1207                 }
1208             }
1209             break;
1210
1211         case WINED3DFMT_L6V5U5:
1212             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1213                 mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
1214                 mask_size = shader_glsl_get_write_mask_size(mask);
1215                 shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_2, &dst_param2);
1216                 if(mask_size >= 3) {
1217                     /* Swap y and z (U and L), and do a sign conversion on x and the new y(V and U) */
1218                     shader_addline(arg->buffer, "tmp0.g = %s.%c;\n",
1219                                    dst_param.reg_name, dst_param.mask_str[2]);
1220                     shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
1221                                    dst_param.reg_name, dst_param.mask_str[2], dst_param.mask_str[1],
1222                                    dst_param2.reg_name, dst_param.mask_str[1], dst_param.mask_str[3]);
1223                     shader_addline(arg->buffer, "%s.%c = tmp0.g;\n", dst_param.reg_name,
1224                                    dst_param.mask_str[3]);
1225                 } else if(mask_size == 2) {
1226                     /* This is bad: We have VL, but we need VU */
1227                     FIXME("2 components sampled from a converted L6V5U5 texture\n");
1228                 } else {
1229                     shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
1230                                    dst_param.reg_name, dst_param.mask_str[1],
1231                                    dst_param2.reg_name, dst_param.mask_str[1]);
1232                 }
1233             }
1234             break;
1235
1236         case WINED3DFMT_Q8W8V8U8:
1237             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
1238                 /* Correct the sign in all channels. The writemask just applies as-is, no
1239                  * need for checking the mask size
1240                  */
1241                 shader_glsl_add_dst_param(arg, arg->dst,
1242                                           WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 |
1243                                           WINED3DSP_WRITEMASK_2 | WINED3DSP_WRITEMASK_3,
1244                                           &dst_param);
1245                 shader_addline(arg->buffer, "%s%s = %s%s * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str,
1246                                dst_param.reg_name, dst_param.mask_str);
1247             }
1248             break;
1249
1250             /* stupid compiler */
1251         default:
1252             break;
1253     }
1254 }
1255
1256 /*****************************************************************************
1257  * 
1258  * Begin processing individual instruction opcodes
1259  * 
1260  ****************************************************************************/
1261
1262 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1263 void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
1264     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1265     SHADER_BUFFER* buffer = arg->buffer;
1266     glsl_src_param_t src0_param;
1267     glsl_src_param_t src1_param;
1268     DWORD write_mask;
1269     char op;
1270
1271     /* Determine the GLSL operator to use based on the opcode */
1272     switch (curOpcode->opcode) {
1273         case WINED3DSIO_MUL: op = '*'; break;
1274         case WINED3DSIO_ADD: op = '+'; break;
1275         case WINED3DSIO_SUB: op = '-'; break;
1276         default:
1277             op = ' ';
1278             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1279             break;
1280     }
1281
1282     write_mask = shader_glsl_append_dst(buffer, arg);
1283     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1284     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1285     shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1286 }
1287
1288 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1289 void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
1290     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1291     SHADER_BUFFER* buffer = arg->buffer;
1292     glsl_src_param_t src0_param;
1293     DWORD write_mask;
1294
1295     write_mask = shader_glsl_append_dst(buffer, arg);
1296     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1297
1298     /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1299      * shader versions WINED3DSIO_MOVA is used for this. */
1300     if ((WINED3DSHADER_VERSION_MAJOR(shader->baseShader.hex_version) == 1 &&
1301             !shader_is_pshader_version(shader->baseShader.hex_version) &&
1302             shader_get_regtype(arg->dst) == WINED3DSPR_ADDR) ||
1303             arg->opcode->opcode == WINED3DSIO_MOVA) {
1304         /* We need to *round* to the nearest int here. */
1305         size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
1306         if (mask_size > 1) {
1307             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);
1308         } else {
1309             shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1310         }
1311     } else {
1312         shader_addline(buffer, "%s);\n", src0_param.param_str);
1313     }
1314 }
1315
1316 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1317 void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
1318     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1319     SHADER_BUFFER* buffer = arg->buffer;
1320     glsl_src_param_t src0_param;
1321     glsl_src_param_t src1_param;
1322     DWORD dst_write_mask, src_write_mask;
1323     size_t dst_size = 0;
1324
1325     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1326     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1327
1328     /* dp3 works on vec3, dp4 on vec4 */
1329     if (curOpcode->opcode == WINED3DSIO_DP4) {
1330         src_write_mask = WINED3DSP_WRITEMASK_ALL;
1331     } else {
1332         src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1333     }
1334
1335     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
1336     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1337
1338     if (dst_size > 1) {
1339         shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1340     } else {
1341         shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1342     }
1343 }
1344
1345 /* Note that this instruction has some restrictions. The destination write mask
1346  * can't contain the w component, and the source swizzles have to be .xyzw */
1347 void shader_glsl_cross(SHADER_OPCODE_ARG *arg) {
1348     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1349     glsl_src_param_t src0_param;
1350     glsl_src_param_t src1_param;
1351     char dst_mask[6];
1352
1353     shader_glsl_get_write_mask(arg->dst, dst_mask);
1354     shader_glsl_append_dst(arg->buffer, arg);
1355     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
1356     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1357     shader_addline(arg->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1358 }
1359
1360 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1361  * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1362  * GLSL uses the value as-is. */
1363 void shader_glsl_pow(SHADER_OPCODE_ARG *arg) {
1364     SHADER_BUFFER *buffer = arg->buffer;
1365     glsl_src_param_t src0_param;
1366     glsl_src_param_t src1_param;
1367     DWORD dst_write_mask;
1368     size_t dst_size;
1369
1370     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1371     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1372
1373     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1374     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1375
1376     if (dst_size > 1) {
1377         shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1378     } else {
1379         shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1380     }
1381 }
1382
1383 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1384  * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1385  * GLSL uses the value as-is. */
1386 void shader_glsl_log(SHADER_OPCODE_ARG *arg) {
1387     SHADER_BUFFER *buffer = arg->buffer;
1388     glsl_src_param_t src0_param;
1389     DWORD dst_write_mask;
1390     size_t dst_size;
1391
1392     dst_write_mask = shader_glsl_append_dst(buffer, arg);
1393     dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1394
1395     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1396
1397     if (dst_size > 1) {
1398         shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1399     } else {
1400         shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1401     }
1402 }
1403
1404 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1405 void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
1406     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1407     SHADER_BUFFER* buffer = arg->buffer;
1408     glsl_src_param_t src_param;
1409     const char *instruction;
1410     char arguments[256];
1411     DWORD write_mask;
1412     unsigned i;
1413
1414     /* Determine the GLSL function to use based on the opcode */
1415     /* TODO: Possibly make this a table for faster lookups */
1416     switch (curOpcode->opcode) {
1417         case WINED3DSIO_MIN: instruction = "min"; break;
1418         case WINED3DSIO_MAX: instruction = "max"; break;
1419         case WINED3DSIO_ABS: instruction = "abs"; break;
1420         case WINED3DSIO_FRC: instruction = "fract"; break;
1421         case WINED3DSIO_NRM: instruction = "normalize"; break;
1422         case WINED3DSIO_LOGP:
1423         case WINED3DSIO_LOG: instruction = "log2"; break;
1424         case WINED3DSIO_EXP: instruction = "exp2"; break;
1425         case WINED3DSIO_SGN: instruction = "sign"; break;
1426         case WINED3DSIO_DSX: instruction = "dFdx"; break;
1427         case WINED3DSIO_DSY: instruction = "ycorrection.y * dFdy"; break;
1428         default: instruction = "";
1429             FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
1430             break;
1431     }
1432
1433     write_mask = shader_glsl_append_dst(buffer, arg);
1434
1435     arguments[0] = '\0';
1436     if (curOpcode->num_params > 0) {
1437         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
1438         strcat(arguments, src_param.param_str);
1439         for (i = 2; i < curOpcode->num_params; ++i) {
1440             strcat(arguments, ", ");
1441             shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
1442             strcat(arguments, src_param.param_str);
1443         }
1444     }
1445
1446     shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1447 }
1448
1449 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1450  * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1451  *   dst.x = 2^(floor(src))
1452  *   dst.y = src - floor(src)
1453  *   dst.z = 2^src   (partial precision is allowed, but optional)
1454  *   dst.w = 1.0;
1455  * For 2.0 shaders, just do this (honoring writemask and swizzle):
1456  *   dst = 2^src;    (partial precision is allowed, but optional)
1457  */
1458 void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
1459     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1460     glsl_src_param_t src_param;
1461
1462     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1463
1464     if (shader->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
1465         char dst_mask[6];
1466
1467         shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1468         shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1469         shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1470         shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1471
1472         shader_glsl_append_dst(arg->buffer, arg);
1473         shader_glsl_get_write_mask(arg->dst, dst_mask);
1474         shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1475     } else {
1476         DWORD write_mask;
1477         size_t mask_size;
1478
1479         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1480         mask_size = shader_glsl_get_write_mask_size(write_mask);
1481
1482         if (mask_size > 1) {
1483             shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1484         } else {
1485             shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1486         }
1487     }
1488 }
1489
1490 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1491 void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1492     glsl_src_param_t src_param;
1493     DWORD write_mask;
1494     size_t mask_size;
1495
1496     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1497     mask_size = shader_glsl_get_write_mask_size(write_mask);
1498     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1499
1500     if (mask_size > 1) {
1501         shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1502     } else {
1503         shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1504     }
1505 }
1506
1507 void shader_glsl_rsq(SHADER_OPCODE_ARG* arg) {
1508     SHADER_BUFFER* buffer = arg->buffer;
1509     glsl_src_param_t src_param;
1510     DWORD write_mask;
1511     size_t mask_size;
1512
1513     write_mask = shader_glsl_append_dst(buffer, arg);
1514     mask_size = shader_glsl_get_write_mask_size(write_mask);
1515
1516     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1517
1518     if (mask_size > 1) {
1519         shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1520     } else {
1521         shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1522     }
1523 }
1524
1525 /** Process signed comparison opcodes in GLSL. */
1526 void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1527     glsl_src_param_t src0_param;
1528     glsl_src_param_t src1_param;
1529     DWORD write_mask;
1530     size_t mask_size;
1531
1532     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1533     mask_size = shader_glsl_get_write_mask_size(write_mask);
1534     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1535     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1536
1537     if (mask_size > 1) {
1538         const char *compare;
1539
1540         switch(arg->opcode->opcode) {
1541             case WINED3DSIO_SLT: compare = "lessThan"; break;
1542             case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
1543             default: compare = "";
1544                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1545         }
1546
1547         shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1548                 src0_param.param_str, src1_param.param_str);
1549     } else {
1550         const char *compare;
1551
1552         switch(arg->opcode->opcode) {
1553             case WINED3DSIO_SLT: compare = "<"; break;
1554             case WINED3DSIO_SGE: compare = ">="; break;
1555             default: compare = "";
1556                 FIXME("Can't handle opcode %s\n", arg->opcode->name);
1557         }
1558
1559         shader_addline(arg->buffer, "(%s %s %s) ? 1.0 : 0.0);\n",
1560                 src0_param.param_str, compare, src1_param.param_str);
1561     }
1562 }
1563
1564 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1565 void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1566     glsl_src_param_t src0_param;
1567     glsl_src_param_t src1_param;
1568     glsl_src_param_t src2_param;
1569     DWORD write_mask, cmp_channel = 0;
1570     unsigned int i, j;
1571     char mask_char[6];
1572     BOOL temp_destination = FALSE;
1573
1574     DWORD src0reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
1575     DWORD src1reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
1576     DWORD src2reg = arg->src[2] & WINED3DSP_REGNUM_MASK;
1577     DWORD src0regtype = shader_get_regtype(arg->src[0]);
1578     DWORD src1regtype = shader_get_regtype(arg->src[1]);
1579     DWORD src2regtype = shader_get_regtype(arg->src[2]);
1580     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1581     DWORD dstregtype = shader_get_regtype(arg->dst);
1582
1583     /* Cycle through all source0 channels */
1584     for (i=0; i<4; i++) {
1585         write_mask = 0;
1586         /* Find the destination channels which use the current source0 channel */
1587         for (j=0; j<4; j++) {
1588             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1589                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1590                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1591             }
1592         }
1593
1594         /* Splitting the cmp instruction up in multiple lines imposes a problem:
1595          * The first lines may overwrite source parameters of the following lines.
1596          * Deal with that by using a temporary destination register if needed
1597          */
1598         if((src0reg == dstreg && src0regtype == dstregtype) ||
1599            (src1reg == dstreg && src1regtype == dstregtype) ||
1600            (src2reg == dstreg && src2regtype == dstregtype)) {
1601
1602             write_mask = shader_glsl_get_write_mask(arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask), mask_char);
1603             if (!write_mask) continue;
1604             shader_addline(arg->buffer, "tmp0%s = (", mask_char);
1605             temp_destination = TRUE;
1606         } else {
1607             write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1608             if (!write_mask) continue;
1609         }
1610
1611         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1612         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1613         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1614
1615             shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
1616                            src0_param.param_str, src1_param.param_str, src2_param.param_str);
1617     }
1618
1619     if(temp_destination) {
1620         shader_glsl_get_write_mask(arg->dst, mask_char);
1621         shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst);
1622         shader_addline(arg->buffer, "tmp0%s);\n", mask_char);
1623     }
1624
1625 }
1626
1627 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1628 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
1629  * the compare is done per component of src0. */
1630 void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1631     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1632     glsl_src_param_t src0_param;
1633     glsl_src_param_t src1_param;
1634     glsl_src_param_t src2_param;
1635     DWORD write_mask, cmp_channel = 0;
1636     unsigned int i, j;
1637
1638     if (shader->baseShader.hex_version < WINED3DPS_VERSION(1, 4)) {
1639         write_mask = shader_glsl_append_dst(arg->buffer, arg);
1640         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1641         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1642         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1643
1644         /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
1645         if(arg->opcode_token & WINED3DSI_COISSUE) {
1646             shader_addline(arg->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
1647         } else {
1648             shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1649                     src0_param.param_str, src1_param.param_str, src2_param.param_str);
1650         }
1651         return;
1652     }
1653     /* Cycle through all source0 channels */
1654     for (i=0; i<4; i++) {
1655         write_mask = 0;
1656         /* Find the destination channels which use the current source0 channel */
1657         for (j=0; j<4; j++) {
1658             if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
1659                 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1660                 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1661             }
1662         }
1663         write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
1664         if (!write_mask) continue;
1665
1666         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
1667         shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1668         shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1669
1670         shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1671                 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1672     }
1673 }
1674
1675 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1676 void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1677     glsl_src_param_t src0_param;
1678     glsl_src_param_t src1_param;
1679     glsl_src_param_t src2_param;
1680     DWORD write_mask;
1681
1682     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1683     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1684     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1685     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1686     shader_addline(arg->buffer, "(%s * %s) + %s);\n",
1687             src0_param.param_str, src1_param.param_str, src2_param.param_str);
1688 }
1689
1690 /** Handles transforming all WINED3DSIO_M?x? opcodes for 
1691     Vertex shaders to GLSL codes */
1692 void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
1693     int i;
1694     int nComponents = 0;
1695     SHADER_OPCODE_ARG tmpArg;
1696    
1697     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1698
1699     /* Set constants for the temporary argument */
1700     tmpArg.shader      = arg->shader;
1701     tmpArg.buffer      = arg->buffer;
1702     tmpArg.src[0]      = arg->src[0];
1703     tmpArg.src_addr[0] = arg->src_addr[0];
1704     tmpArg.src_addr[1] = arg->src_addr[1];
1705     tmpArg.reg_maps = arg->reg_maps; 
1706     
1707     switch(arg->opcode->opcode) {
1708         case WINED3DSIO_M4x4:
1709             nComponents = 4;
1710             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1711             break;
1712         case WINED3DSIO_M4x3:
1713             nComponents = 3;
1714             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1715             break;
1716         case WINED3DSIO_M3x4:
1717             nComponents = 4;
1718             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1719             break;
1720         case WINED3DSIO_M3x3:
1721             nComponents = 3;
1722             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1723             break;
1724         case WINED3DSIO_M3x2:
1725             nComponents = 2;
1726             tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1727             break;
1728         default:
1729             break;
1730     }
1731
1732     for (i = 0; i < nComponents; i++) {
1733         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1734         tmpArg.src[1]      = arg->src[1]+i;
1735         shader_glsl_dot(&tmpArg);
1736     }
1737 }
1738
1739 /**
1740     The LRP instruction performs a component-wise linear interpolation 
1741     between the second and third operands using the first operand as the
1742     blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
1743     This is equivalent to mix(src2, src1, src0);
1744 */
1745 void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1746     glsl_src_param_t src0_param;
1747     glsl_src_param_t src1_param;
1748     glsl_src_param_t src2_param;
1749     DWORD write_mask;
1750
1751     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1752
1753     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1754     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1755     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1756
1757     shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
1758             src2_param.param_str, src1_param.param_str, src0_param.param_str);
1759 }
1760
1761 /** Process the WINED3DSIO_LIT instruction in GLSL:
1762  * dst.x = dst.w = 1.0
1763  * dst.y = (src0.x > 0) ? src0.x
1764  * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
1765  *                                        where src.w is clamped at +- 128
1766  */
1767 void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1768     glsl_src_param_t src0_param;
1769     glsl_src_param_t src1_param;
1770     glsl_src_param_t src3_param;
1771     char dst_mask[6];
1772
1773     shader_glsl_append_dst(arg->buffer, arg);
1774     shader_glsl_get_write_mask(arg->dst, dst_mask);
1775
1776     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1777     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
1778     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
1779
1780     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",
1781         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);
1782 }
1783
1784 /** Process the WINED3DSIO_DST instruction in GLSL:
1785  * dst.x = 1.0
1786  * dst.y = src0.x * src0.y
1787  * dst.z = src0.z
1788  * dst.w = src1.w
1789  */
1790 void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1791     glsl_src_param_t src0y_param;
1792     glsl_src_param_t src0z_param;
1793     glsl_src_param_t src1y_param;
1794     glsl_src_param_t src1w_param;
1795     char dst_mask[6];
1796
1797     shader_glsl_append_dst(arg->buffer, arg);
1798     shader_glsl_get_write_mask(arg->dst, dst_mask);
1799
1800     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
1801     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
1802     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
1803     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
1804
1805     shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
1806             src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
1807 }
1808
1809 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
1810  * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
1811  * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
1812  * 
1813  * dst.x = cos(src0.?)
1814  * dst.y = sin(src0.?)
1815  * dst.z = dst.z
1816  * dst.w = dst.w
1817  */
1818 void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1819     glsl_src_param_t src0_param;
1820     DWORD write_mask;
1821
1822     write_mask = shader_glsl_append_dst(arg->buffer, arg);
1823     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1824
1825     switch (write_mask) {
1826         case WINED3DSP_WRITEMASK_0:
1827             shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
1828             break;
1829
1830         case WINED3DSP_WRITEMASK_1:
1831             shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
1832             break;
1833
1834         case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
1835             shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
1836             break;
1837
1838         default:
1839             ERR("Write mask should be .x, .y or .xy\n");
1840             break;
1841     }
1842 }
1843
1844 /** Process the WINED3DSIO_LOOP instruction in GLSL:
1845  * Start a for() loop where src1.y is the initial value of aL,
1846  *  increment aL by src1.z for a total of src1.x iterations.
1847  *  Need to use a temporary variable for this operation.
1848  */
1849 /* FIXME: I don't think nested loops will work correctly this way. */
1850 void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1851     glsl_src_param_t src1_param;
1852     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1853     DWORD regtype = shader_get_regtype(arg->src[1]);
1854     DWORD reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
1855     const DWORD *control_values = NULL;
1856     local_constant *constant;
1857
1858     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
1859
1860     /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
1861      * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
1862      * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
1863      * addressing.
1864      */
1865     if(regtype == WINED3DSPR_CONSTINT) {
1866         LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
1867             if(constant->idx == reg) {
1868                 control_values = constant->value;
1869                 break;
1870             }
1871         }
1872     }
1873
1874     if(control_values) {
1875         if(control_values[2] > 0) {
1876             shader_addline(arg->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
1877                            shader->baseShader.cur_loop_depth, control_values[1],
1878                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
1879                            shader->baseShader.cur_loop_depth, control_values[2]);
1880         } else if(control_values[2] == 0) {
1881             shader_addline(arg->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
1882                            shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
1883                            shader->baseShader.cur_loop_depth, control_values[0],
1884                            shader->baseShader.cur_loop_depth);
1885         } else {
1886             shader_addline(arg->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
1887                            shader->baseShader.cur_loop_depth, control_values[1],
1888                            shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
1889                            shader->baseShader.cur_loop_depth, control_values[2]);
1890         }
1891     } else {
1892         shader_addline(arg->buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
1893                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
1894                        src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
1895                        shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
1896     }
1897
1898     shader->baseShader.cur_loop_depth++;
1899     shader->baseShader.cur_loop_regno++;
1900 }
1901
1902 void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1903     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1904
1905     shader_addline(arg->buffer, "}\n");
1906
1907     if(arg->opcode->opcode == WINED3DSIO_ENDLOOP) {
1908         shader->baseShader.cur_loop_depth--;
1909         shader->baseShader.cur_loop_regno--;
1910     }
1911     if(arg->opcode->opcode == WINED3DSIO_ENDREP) {
1912         shader->baseShader.cur_loop_depth--;
1913     }
1914 }
1915
1916 void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
1917     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1918     glsl_src_param_t src0_param;
1919
1920     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1921     shader_addline(arg->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
1922                    shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
1923                    src0_param.param_str, shader->baseShader.cur_loop_depth);
1924     shader->baseShader.cur_loop_depth++;
1925 }
1926
1927 void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1928     glsl_src_param_t src0_param;
1929
1930     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1931     shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
1932 }
1933
1934 void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
1935     glsl_src_param_t src0_param;
1936     glsl_src_param_t src1_param;
1937
1938     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1939     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1940
1941     shader_addline(arg->buffer, "if (%s %s %s) {\n",
1942             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1943 }
1944
1945 void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
1946     shader_addline(arg->buffer, "} else {\n");
1947 }
1948
1949 void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
1950     shader_addline(arg->buffer, "break;\n");
1951 }
1952
1953 /* FIXME: According to MSDN the compare is done per component. */
1954 void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
1955     glsl_src_param_t src0_param;
1956     glsl_src_param_t src1_param;
1957
1958     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1959     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1960
1961     shader_addline(arg->buffer, "if (%s %s %s) break;\n",
1962             src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
1963 }
1964
1965 void shader_glsl_label(SHADER_OPCODE_ARG* arg) {
1966
1967     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1968     shader_addline(arg->buffer, "}\n");
1969     shader_addline(arg->buffer, "void subroutine%lu () {\n",  snum);
1970 }
1971
1972 void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
1973     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1974     shader_addline(arg->buffer, "subroutine%lu();\n", snum);
1975 }
1976
1977 void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
1978     glsl_src_param_t src1_param;
1979
1980     DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1981     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1982     shader_addline(arg->buffer, "if (%s) subroutine%lu();\n", src1_param.param_str, snum);
1983 }
1984
1985 /*********************************************
1986  * Pixel Shader Specific Code begins here
1987  ********************************************/
1988 void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
1989     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1990     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1991     DWORD hex_version = This->baseShader.hex_version;
1992     char dst_swizzle[6];
1993     glsl_sample_function_t sample_function;
1994     DWORD sampler_type;
1995     DWORD sampler_idx;
1996     BOOL projected;
1997     DWORD mask = 0;
1998
1999     /* All versions have a destination register */
2000     shader_glsl_append_dst(arg->buffer, arg);
2001
2002     /* 1.0-1.4: Use destination register as sampler source.
2003      * 2.0+: Use provided sampler source. */
2004     if (hex_version < WINED3DPS_VERSION(1,4)) {
2005         DWORD flags;
2006
2007         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2008         flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2009
2010         if (flags & WINED3DTTFF_PROJECTED) {
2011             projected = TRUE;
2012             switch (flags & ~WINED3DTTFF_PROJECTED) {
2013                 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2014                 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2015                 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2016                 case WINED3DTTFF_COUNT4:
2017                 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2018             }
2019         } else {
2020             projected = FALSE;
2021         }
2022     } else if (hex_version < WINED3DPS_VERSION(2,0)) {
2023         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2024         sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2025
2026         if (src_mod == WINED3DSPSM_DZ) {
2027             projected = TRUE;
2028             mask = WINED3DSP_WRITEMASK_2;
2029         } else if (src_mod == WINED3DSPSM_DW) {
2030             projected = TRUE;
2031             mask = WINED3DSP_WRITEMASK_3;
2032         } else {
2033             projected = FALSE;
2034         }
2035     } else {
2036         sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2037         if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
2038                 /* ps 2.0 texldp instruction always divides by the fourth component. */
2039                 projected = TRUE;
2040                 mask = WINED3DSP_WRITEMASK_3;
2041         } else {
2042             projected = FALSE;
2043         }
2044     }
2045
2046     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2047     shader_glsl_get_sample_function(sampler_type, projected, &sample_function);
2048     mask |= sample_function.coord_mask;
2049
2050     if (hex_version < WINED3DPS_VERSION(2,0)) {
2051         shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2052     } else {
2053         shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
2054     }
2055
2056     /* 1.0-1.3: Use destination register as coordinate source.
2057        1.4+: Use provided coordinate source register. */
2058     if (hex_version < WINED3DPS_VERSION(1,4)) {
2059         char coord_mask[6];
2060         shader_glsl_get_write_mask(mask, coord_mask);
2061         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s)%s);\n",
2062                 sample_function.name, sampler_idx, sampler_idx, coord_mask, dst_swizzle);
2063     } else {
2064         glsl_src_param_t coord_param;
2065         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
2066         if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
2067             glsl_src_param_t bias;
2068             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);
2069
2070             shader_addline(arg->buffer, "%s(Psampler%u, %s, %s)%s);\n",
2071                     sample_function.name, sampler_idx, coord_param.param_str,
2072                     bias.param_str, dst_swizzle);
2073         } else {
2074             shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n",
2075                     sample_function.name, sampler_idx, coord_param.param_str, dst_swizzle);
2076         }
2077     }
2078 }
2079
2080 void shader_glsl_texldl(SHADER_OPCODE_ARG* arg) {
2081     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
2082     glsl_sample_function_t sample_function;
2083     glsl_src_param_t coord_param, lod_param;
2084     char dst_swizzle[6];
2085     DWORD sampler_type;
2086     DWORD sampler_idx;
2087
2088     shader_glsl_append_dst(arg->buffer, arg);
2089     shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
2090
2091     sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2092     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2093     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2094     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
2095
2096     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);
2097
2098     if (shader_is_pshader_version(This->baseShader.hex_version)) {
2099         /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2100          * However, they seem to work just fine in fragment shaders as well. */
2101         WARN("Using %sLod in fragment shader.\n", sample_function.name);
2102         shader_addline(arg->buffer, "%sLod(Psampler%u, %s, %s)%s);\n",
2103                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
2104     } else {
2105         shader_addline(arg->buffer, "%sLod(Vsampler%u, %s, %s)%s);\n",
2106                 sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
2107     }
2108 }
2109
2110 void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {
2111
2112     /* FIXME: Make this work for more than just 2D textures */
2113     
2114     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2115     SHADER_BUFFER* buffer = arg->buffer;
2116     DWORD hex_version = This->baseShader.hex_version;
2117     DWORD write_mask;
2118     char dst_mask[6];
2119
2120     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2121     shader_glsl_get_write_mask(write_mask, dst_mask);
2122
2123     if (hex_version != WINED3DPS_VERSION(1,4)) {
2124         DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2125         shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
2126     } else {
2127         DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
2128         DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
2129         char dst_swizzle[6];
2130
2131         shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);
2132
2133         if (src_mod == WINED3DSPSM_DZ) {
2134             glsl_src_param_t div_param;
2135             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
2136             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
2137
2138             if (mask_size > 1) {
2139                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2140             } else {
2141                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2142             }
2143         } else if (src_mod == WINED3DSPSM_DW) {
2144             glsl_src_param_t div_param;
2145             size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
2146             shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
2147
2148             if (mask_size > 1) {
2149                 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2150             } else {
2151                 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2152             }
2153         } else {
2154             shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2155         }
2156     }
2157 }
2158
2159 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2160  * Take a 3-component dot product of the TexCoord[dstreg] and src,
2161  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2162 void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
2163     glsl_src_param_t src0_param;
2164     char dst_mask[6];
2165     glsl_sample_function_t sample_function;
2166     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2167     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2168     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2169
2170     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2171
2172     shader_glsl_append_dst(arg->buffer, arg);
2173     shader_glsl_get_write_mask(arg->dst, dst_mask);
2174
2175     /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2176      * scalar, and projected sampling would require 4
2177      */
2178     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2179
2180     switch(count_bits(sample_function.coord_mask)) {
2181         case 1:
2182             shader_addline(arg->buffer, "%s(Psampler%u, dot(gl_TexCoord[%u].xyz, %s))%s);\n",
2183                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2184             break;
2185
2186         case 2:
2187             shader_addline(arg->buffer, "%s(Psampler%u, vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0))%s);\n",
2188                           sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2189             break;
2190
2191         case 3:
2192             shader_addline(arg->buffer, "%s(Psampler%u, vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0))%s);\n",
2193                            sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
2194             break;
2195         default:
2196             FIXME("Unexpected mask bitcount %d\n", count_bits(sample_function.coord_mask));
2197     }
2198 }
2199
2200 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2201  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2202 void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
2203     glsl_src_param_t src0_param;
2204     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2205     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2206     DWORD dst_mask;
2207     size_t mask_size;
2208
2209     dst_mask = shader_glsl_append_dst(arg->buffer, arg);
2210     mask_size = shader_glsl_get_write_mask_size(dst_mask);
2211     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2212
2213     if (mask_size > 1) {
2214         shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2215     } else {
2216         shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2217     }
2218 }
2219
2220 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2221  * Calculate the depth as dst.x / dst.y   */
2222 void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
2223     glsl_dst_param_t dst_param;
2224
2225     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2226
2227     /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2228      * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2229      * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2230      * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2231      * >= 1.0 or < 0.0
2232      */
2233     shader_addline(arg->buffer, "gl_FragDepth = (%s.y == 0.0) ? 1.0 : clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name, dst_param.reg_name);
2234 }
2235
2236 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2237  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2238  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
2239  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2240  */
2241 void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
2242     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2243     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2244     glsl_src_param_t src0_param;
2245
2246     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2247
2248     shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2249     shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2250 }
2251
2252 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2253  * Calculate the 1st of a 2-row matrix multiplication. */
2254 void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
2255     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2256     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2257     SHADER_BUFFER* buffer = arg->buffer;
2258     glsl_src_param_t src0_param;
2259
2260     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2261     shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2262 }
2263
2264 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2265  * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2266 void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {
2267
2268     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2269     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2270     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2271     SHADER_BUFFER* buffer = arg->buffer;
2272     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2273     glsl_src_param_t src0_param;
2274
2275     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2276     shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2277     current_state->texcoord_w[current_state->current_row++] = reg;
2278 }
2279
2280 void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
2281     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2282     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2283     SHADER_BUFFER* buffer = arg->buffer;
2284     glsl_src_param_t src0_param;
2285     char dst_mask[6];
2286
2287     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2288     shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2289
2290     shader_glsl_append_dst(buffer, arg);
2291     shader_glsl_get_write_mask(arg->dst, dst_mask);
2292
2293     /* Sample the texture using the calculated coordinates */
2294     shader_addline(buffer, "texture2D(Psampler%u, tmp0.xy)%s);\n", reg, dst_mask);
2295 }
2296
2297 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2298  * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2299 void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
2300     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2301     glsl_src_param_t src0_param;
2302     char dst_mask[6];
2303     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2304     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2305     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2306     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2307     glsl_sample_function_t sample_function;
2308
2309     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2310     shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2311
2312     shader_glsl_append_dst(arg->buffer, arg);
2313     shader_glsl_get_write_mask(arg->dst, dst_mask);
2314     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2315
2316     /* Sample the texture using the calculated coordinates */
2317     shader_addline(arg->buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2318
2319     current_state->current_row = 0;
2320 }
2321
2322 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2323  * Perform the 3rd row of a 3x3 matrix multiply */
2324 void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
2325     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2326     glsl_src_param_t src0_param;
2327     char dst_mask[6];
2328     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2329     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2330     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2331
2332     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2333
2334     shader_glsl_append_dst(arg->buffer, arg);
2335     shader_glsl_get_write_mask(arg->dst, dst_mask);
2336     shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2337
2338     current_state->current_row = 0;
2339 }
2340
2341 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
2342  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2343 void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {
2344
2345     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2346     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2347     glsl_src_param_t src0_param;
2348     glsl_src_param_t src1_param;
2349     char dst_mask[6];
2350     SHADER_BUFFER* buffer = arg->buffer;
2351     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2352     DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2353     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2354     glsl_sample_function_t sample_function;
2355
2356     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2357     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
2358
2359     /* Perform the last matrix multiply operation */
2360     shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2361     /* Reflection calculation */
2362     shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2363
2364     shader_glsl_append_dst(buffer, arg);
2365     shader_glsl_get_write_mask(arg->dst, dst_mask);
2366     shader_glsl_get_sample_function(stype, FALSE, &sample_function);
2367
2368     /* Sample the texture */
2369     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2370
2371     current_state->current_row = 0;
2372 }
2373
2374 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
2375  * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2376 void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
2377
2378     IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2379     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2380     SHADER_BUFFER* buffer = arg->buffer;
2381     SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2382     glsl_src_param_t src0_param;
2383     char dst_mask[6];
2384     DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2385     DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2386     glsl_sample_function_t sample_function;
2387
2388     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2389
2390     /* Perform the last matrix multiply operation */
2391     shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2392
2393     /* Construct the eye-ray vector from w coordinates */
2394     shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2395             current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2396     shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2397
2398     shader_glsl_append_dst(buffer, arg);
2399     shader_glsl_get_write_mask(arg->dst, dst_mask);
2400     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2401
2402     /* Sample the texture using the calculated coordinates */
2403     shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);
2404
2405     current_state->current_row = 0;
2406 }
2407
2408 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2409  * Apply a fake bump map transform.
2410  * texbem is pshader <= 1.3 only, this saves a few version checks
2411  */
2412 void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
2413     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2414     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2415     char dst_swizzle[6];
2416     glsl_sample_function_t sample_function;
2417     glsl_src_param_t coord_param;
2418     DWORD sampler_type;
2419     DWORD sampler_idx;
2420     DWORD mask;
2421     DWORD flags;
2422     char coord_mask[6];
2423
2424     sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2425     flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2426
2427     sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2428     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2429     mask = sample_function.coord_mask;
2430
2431     shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2432
2433     shader_glsl_get_write_mask(mask, coord_mask);
2434
2435     /* with projective textures, texbem only divides the static texture coord, not the displacement,
2436          * so we can't let the GL handle this.
2437          */
2438     if (flags & WINED3DTTFF_PROJECTED) {
2439         DWORD div_mask=0;
2440         char coord_div_mask[3];
2441         switch (flags & ~WINED3DTTFF_PROJECTED) {
2442             case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2443             case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2444             case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2445             case WINED3DTTFF_COUNT4:
2446             case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2447         }
2448         shader_glsl_get_write_mask(div_mask, coord_div_mask);
2449         shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2450     }
2451
2452     shader_glsl_append_dst(arg->buffer, arg);
2453     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2454     if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
2455         glsl_src_param_t luminance_param;
2456         shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2457         shader_addline(arg->buffer, "(%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )*(%s * luminancescale + luminanceoffset))%s);\n",
2458                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask,
2459                        luminance_param.param_str, dst_swizzle);
2460     } else {
2461         shader_addline(arg->buffer, "%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )%s);\n",
2462                        sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask, dst_swizzle);
2463     }
2464 }
2465
2466 void pshader_glsl_bem(SHADER_OPCODE_ARG* arg) {
2467     glsl_src_param_t src0_param, src1_param;
2468
2469     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
2470     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);
2471
2472     shader_glsl_append_dst(arg->buffer, arg);
2473     shader_addline(arg->buffer, "%s + bumpenvmat * %s);\n",
2474                    src0_param.param_str, src1_param.param_str);
2475 }
2476
2477 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2478  * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2479 void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
2480
2481     glsl_src_param_t src0_param;
2482     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2483     char dst_mask[6];
2484
2485     shader_glsl_append_dst(arg->buffer, arg);
2486     shader_glsl_get_write_mask(arg->dst, dst_mask);
2487     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2488
2489     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.wx)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2490 }
2491
2492 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2493  * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2494 void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
2495     glsl_src_param_t src0_param;
2496     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2497     char dst_mask[6];
2498
2499     shader_glsl_append_dst(arg->buffer, arg);
2500     shader_glsl_get_write_mask(arg->dst, dst_mask);
2501     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2502
2503     shader_addline(arg->buffer, "texture2D(Psampler%u, %s.yz)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2504 }
2505
2506 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2507  * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2508 void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
2509     glsl_src_param_t src0_param;
2510     char dst_mask[6];
2511     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
2512     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2513     glsl_sample_function_t sample_function;
2514
2515     shader_glsl_append_dst(arg->buffer, arg);
2516     shader_glsl_get_write_mask(arg->dst, dst_mask);
2517     shader_glsl_get_sample_function(sampler_type, FALSE, &sample_function);
2518     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2519
2520     shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n", sample_function.name, sampler_idx, src0_param.param_str, dst_mask);
2521 }
2522
2523 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2524  * If any of the first 3 components are < 0, discard this pixel */
2525 void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
2526     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2527     DWORD hex_version = This->baseShader.hex_version;
2528     glsl_dst_param_t dst_param;
2529
2530     /* The argument is a destination parameter, and no writemasks are allowed */
2531     shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2532     if((hex_version >= WINED3DPS_VERSION(2,0))) {
2533         /* 2.0 shaders compare all 4 components in texkill */
2534         shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2535     } else {
2536         /* 1.X shaders only compare the first 3 components, propably due to the nature of the texkill
2537          * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2538          * 4 components are defined, only the first 3 are used
2539          */
2540         shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2541     }
2542 }
2543
2544 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2545  * dst = dot2(src0, src1) + src2 */
2546 void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
2547     glsl_src_param_t src0_param;
2548     glsl_src_param_t src1_param;
2549     glsl_src_param_t src2_param;
2550     DWORD write_mask;
2551     size_t mask_size;
2552
2553     write_mask = shader_glsl_append_dst(arg->buffer, arg);
2554     mask_size = shader_glsl_get_write_mask_size(write_mask);
2555
2556     shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2557     shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2558     shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2559
2560     shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2561 }
2562
2563 void pshader_glsl_input_pack(
2564    SHADER_BUFFER* buffer,
2565    semantic* semantics_in,
2566    IWineD3DPixelShader *iface) {
2567
2568    unsigned int i;
2569    IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
2570
2571    for (i = 0; i < MAX_REG_INPUT; i++) {
2572
2573        DWORD usage_token = semantics_in[i].usage;
2574        DWORD register_token = semantics_in[i].reg;
2575        DWORD usage, usage_idx;
2576        char reg_mask[6];
2577
2578        /* Uninitialized */
2579        if (!usage_token) continue;
2580        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2581        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2582        shader_glsl_get_write_mask(register_token, reg_mask);
2583
2584        switch(usage) {
2585
2586            case WINED3DDECLUSAGE_TEXCOORD:
2587                if(usage_idx < 8 && This->vertexprocessing == pretransformed) {
2588                    shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2589                                   This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
2590                } else {
2591                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2592                                   This->input_reg_map[i], reg_mask, reg_mask);
2593                }
2594                break;
2595
2596            case WINED3DDECLUSAGE_COLOR:
2597                if (usage_idx == 0)
2598                    shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
2599                        This->input_reg_map[i], reg_mask, reg_mask);
2600                else if (usage_idx == 1)
2601                    shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
2602                        This->input_reg_map[i], reg_mask, reg_mask);
2603                else
2604                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2605                        This->input_reg_map[i], reg_mask, reg_mask);
2606                break;
2607
2608            default:
2609                shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2610                    This->input_reg_map[i], reg_mask, reg_mask);
2611         }
2612     }
2613 }
2614
2615 /*********************************************
2616  * Vertex Shader Specific Code begins here
2617  ********************************************/
2618
2619 static void add_glsl_program_entry(IWineD3DDeviceImpl *device, struct glsl_shader_prog_link *entry) {
2620     glsl_program_key_t *key;
2621
2622     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2623     key->vshader = entry->vshader;
2624     key->pshader = entry->pshader;
2625
2626     hash_table_put(device->glsl_program_lookup, key, entry);
2627 }
2628
2629 static struct glsl_shader_prog_link *get_glsl_program_entry(IWineD3DDeviceImpl *device,
2630         GLhandleARB vshader, GLhandleARB pshader) {
2631     glsl_program_key_t key;
2632
2633     key.vshader = vshader;
2634     key.pshader = pshader;
2635
2636     return (struct glsl_shader_prog_link *)hash_table_get(device->glsl_program_lookup, &key);
2637 }
2638
2639 void delete_glsl_program_entry(IWineD3DDevice *iface, struct glsl_shader_prog_link *entry) {
2640     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2641     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2642     glsl_program_key_t *key;
2643
2644     key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
2645     key->vshader = entry->vshader;
2646     key->pshader = entry->pshader;
2647     hash_table_remove(This->glsl_program_lookup, key);
2648
2649     GL_EXTCALL(glDeleteObjectARB(entry->programId));
2650     if (entry->vshader) list_remove(&entry->vshader_entry);
2651     if (entry->pshader) list_remove(&entry->pshader_entry);
2652     HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
2653     HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
2654     HeapFree(GetProcessHeap(), 0, entry);
2655 }
2656
2657 static void handle_ps3_input(SHADER_BUFFER *buffer, semantic *semantics_in, semantic *semantics_out, WineD3D_GL_Info *gl_info, DWORD *map) {
2658     unsigned int i, j;
2659     DWORD usage_token, usage_token_out;
2660     DWORD register_token, register_token_out;
2661     DWORD usage, usage_idx, usage_out, usage_idx_out;
2662     DWORD *set;
2663     char reg_mask[6], reg_mask_out[6];
2664
2665     set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (GL_LIMITS(glsl_varyings) / 4));
2666
2667     for(i = 0; i < MAX_REG_INPUT; i++) {
2668         usage_token = semantics_in[i].usage;
2669         if (!usage_token) continue;
2670         if(map[i] >= (GL_LIMITS(glsl_varyings) / 4)) {
2671             FIXME("More input varyings declared than supported, expect issues\n");
2672             continue;
2673         } else if(map[i] == -1) {
2674             /* Declared, but not read register */
2675             continue;
2676         }
2677         register_token = semantics_in[i].reg;
2678
2679         usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2680         usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2681         set[map[i]] = shader_glsl_get_write_mask(register_token, reg_mask);
2682
2683         if(!semantics_out) {
2684             switch(usage) {
2685                 case WINED3DDECLUSAGE_COLOR:
2686                     if (usage_idx == 0)
2687                         shader_addline(buffer, "IN[%u]%s = gl_FrontColor%s;\n",
2688                                        map[i], reg_mask, reg_mask);
2689                     else if (usage_idx == 1)
2690                         shader_addline(buffer, "IN[%u]%s = gl_FrontSecondaryColor%s;\n",
2691                                        map[i], reg_mask, reg_mask);
2692                     else
2693                         shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2694                                        map[i], reg_mask, reg_mask);
2695                     break;
2696
2697                 case WINED3DDECLUSAGE_TEXCOORD:
2698                     if (usage_idx < 8) {
2699                         shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2700                                        map[i], reg_mask, usage_idx, reg_mask);
2701                     } else {
2702                         shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2703                                        map[i], reg_mask, reg_mask);
2704                     }
2705                     break;
2706
2707                 case WINED3DDECLUSAGE_FOG:
2708                     shader_addline(buffer, "IN[%u]%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
2709                                    map[i], reg_mask, reg_mask);
2710                     break;
2711
2712                 default:
2713                     shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2714                                    map[i], reg_mask, reg_mask);
2715             }
2716         } else {
2717             BOOL found = FALSE;
2718             for(j = 0; j < MAX_REG_OUTPUT; j++) {
2719                 usage_token_out = semantics_out[j].usage;
2720                 if (!usage_token_out) continue;
2721                 register_token_out = semantics_out[j].reg;
2722
2723                 usage_out = (usage_token_out & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2724                 usage_idx_out = (usage_token_out & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2725                 shader_glsl_get_write_mask(register_token_out, reg_mask_out);
2726
2727                 if(usage == usage_out &&
2728                    usage_idx == usage_idx_out) {
2729                     shader_addline(buffer, "IN[%u]%s = OUT[%u]%s;\n",
2730                                    map[i], reg_mask, j, reg_mask);
2731                     found = TRUE;
2732                 }
2733             }
2734             if(!found) {
2735                 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2736                                map[i], reg_mask, reg_mask);
2737             }
2738         }
2739     }
2740
2741     /* This is solely to make the compiler / linker happy and avoid warning about undefined
2742      * varyings. It shouldn't result in any real code executed on the GPU, since all read
2743      * input varyings are assigned above, if the optimizer works properly.
2744      */
2745     for(i = 0; i < GL_LIMITS(glsl_varyings) / 4; i++) {
2746         if(set[i] != WINED3DSP_WRITEMASK_ALL) {
2747             unsigned int size = 0;
2748             memset(reg_mask, 0, sizeof(reg_mask));
2749             if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
2750                 reg_mask[size] = 'x';
2751                 size++;
2752             }
2753             if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
2754                 reg_mask[size] = 'y';
2755                 size++;
2756             }
2757             if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
2758                 reg_mask[size] = 'z';
2759                 size++;
2760             }
2761             if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
2762                 reg_mask[size] = 'w';
2763                 size++;
2764             }
2765             switch(size) {
2766                 case 1:
2767                     shader_addline(buffer, "IN[%u].%s = 0.0;\n", i, reg_mask);
2768                     break;
2769                 case 2:
2770                     shader_addline(buffer, "IN[%u].%s = vec2(0.0, 0.0);\n", i, reg_mask);
2771                     break;
2772                 case 3:
2773                     shader_addline(buffer, "IN[%u].%s = vec3(0.0, 0.0, 0.0);\n", i, reg_mask);
2774                     break;
2775                 case 4:
2776                     shader_addline(buffer, "IN[%u].%s = vec4(0.0, 0.0, 0.0, 0.0);\n", i, reg_mask);
2777                     break;
2778             }
2779         }
2780     }
2781
2782     HeapFree(GetProcessHeap(), 0, set);
2783 }
2784
2785 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
2786         IWineD3DPixelShader *pixelshader,
2787         WineD3D_GL_Info *gl_info) {
2788     GLhandleARB ret = 0;
2789     IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
2790     IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
2791     DWORD vs_major = vs ? WINED3DSHADER_VERSION_MAJOR(vs->baseShader.hex_version) : 0;
2792     DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.hex_version) : 0;
2793     unsigned int i;
2794     SHADER_BUFFER buffer;
2795     DWORD usage_token;
2796     DWORD register_token;
2797     DWORD usage, usage_idx;
2798     char reg_mask[6];
2799     semantic *semantics_out, *semantics_in;
2800
2801     buffer.buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SHADER_PGMSIZE);
2802     buffer.bsize = 0;
2803     buffer.lineNo = 0;
2804     buffer.newline = TRUE;
2805
2806     if(vs_major < 3 && ps_major < 3) {
2807         /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them */
2808         shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
2809     } else if(ps_major < 3 && vs_major >= 3) {
2810         /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
2811         semantics_out = vs->semantics_out;
2812
2813         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
2814         for(i = 0; i < MAX_REG_OUTPUT; i++) {
2815             usage_token = semantics_out[i].usage;
2816             if (!usage_token) continue;
2817             register_token = semantics_out[i].reg;
2818
2819             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2820             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2821             shader_glsl_get_write_mask(register_token, reg_mask);
2822
2823             switch(usage) {
2824                 case WINED3DDECLUSAGE_COLOR:
2825                     if (usage_idx == 0)
2826                         shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2827                     else if (usage_idx == 1)
2828                         shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2829                     break;
2830
2831                 case WINED3DDECLUSAGE_POSITION:
2832                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2833                     break;
2834
2835                 case WINED3DDECLUSAGE_TEXCOORD:
2836                     if (usage_idx < 8) {
2837                         shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
2838                                        usage_idx, reg_mask, i, reg_mask);
2839                     }
2840                     break;
2841
2842                 case WINED3DDECLUSAGE_PSIZE:
2843                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
2844                     break;
2845
2846                 case WINED3DDECLUSAGE_FOG:
2847                     shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
2848                     break;
2849
2850                 default:
2851                     break;
2852             }
2853         }
2854         shader_addline(&buffer, "}\n");
2855
2856     } else if(ps_major >= 3 && vs_major >= 3) {
2857         semantics_out = vs->semantics_out;
2858         semantics_in = ps->semantics_in;
2859
2860         /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
2861         shader_addline(&buffer, "varying vec4 IN[%lu];\n", GL_LIMITS(glsl_varyings) / 4);
2862         shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
2863
2864         /* First, sort out position and point size. Those are not passed to the pixel shader */
2865         for(i = 0; i < MAX_REG_OUTPUT; i++) {
2866             usage_token = semantics_out[i].usage;
2867             if (!usage_token) continue;
2868             register_token = semantics_out[i].reg;
2869
2870             usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
2871             usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2872             shader_glsl_get_write_mask(register_token, reg_mask);
2873
2874             switch(usage) {
2875                 case WINED3DDECLUSAGE_POSITION:
2876                     shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
2877                     break;
2878
2879                 case WINED3DDECLUSAGE_PSIZE:
2880                     shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
2881                     break;
2882
2883                 default:
2884                     break;
2885             }
2886         }
2887
2888         /* Then, fix the pixel shader input */
2889         handle_ps3_input(&buffer, semantics_in, semantics_out, gl_info, ps->input_reg_map);
2890
2891         shader_addline(&buffer, "}\n");
2892     } else if(ps_major >= 3 && vs_major < 3) {
2893         semantics_in = ps->semantics_in;
2894
2895         shader_addline(&buffer, "varying vec4 IN[%lu];\n", GL_LIMITS(glsl_varyings) / 4);
2896         shader_addline(&buffer, "void order_ps_input() {\n");
2897         /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
2898          * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
2899          * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
2900          */
2901         handle_ps3_input(&buffer, semantics_in, NULL, gl_info, ps->input_reg_map);
2902         shader_addline(&buffer, "}\n");
2903     } else {
2904         ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
2905     }
2906
2907     ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
2908     checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
2909     GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
2910     checkGLcall("glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL)");
2911     GL_EXTCALL(glCompileShaderARB(ret));
2912     checkGLcall("glCompileShaderARB(ret)");
2913
2914     HeapFree(GetProcessHeap(), 0, buffer.buffer);
2915     return ret;
2916 }
2917
2918 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
2919  * It sets the programId on the current StateBlock (because it should be called
2920  * inside of the DrawPrimitive() part of the render loop).
2921  *
2922  * If a program for the given combination does not exist, create one, and store
2923  * the program in the hash table.  If it creates a program, it will link the
2924  * given objects, too.
2925  */
2926 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
2927     IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
2928     WineD3D_GL_Info *gl_info               = &This->adapter->gl_info;
2929     IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
2930     IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
2931     struct glsl_shader_prog_link *entry    = NULL;
2932     GLhandleARB programId                  = 0;
2933     GLhandleARB reorder_shader_id          = 0;
2934     int i;
2935     char glsl_name[8];
2936
2937     GLhandleARB vshader_id = use_vs ? ((IWineD3DBaseShaderImpl*)vshader)->baseShader.prgId : 0;
2938     GLhandleARB pshader_id = use_ps ? ((IWineD3DBaseShaderImpl*)pshader)->baseShader.prgId : 0;
2939     entry = get_glsl_program_entry(This, vshader_id, pshader_id);
2940     if (entry) {
2941         This->stateBlock->glsl_program = entry;
2942         return;
2943     }
2944
2945     /* If we get to this point, then no matching program exists, so we create one */
2946     programId = GL_EXTCALL(glCreateProgramObjectARB());
2947     TRACE("Created new GLSL shader program %u\n", programId);
2948
2949     /* Create the entry */
2950     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
2951     entry->programId = programId;
2952     entry->vshader = vshader_id;
2953     entry->pshader = pshader_id;
2954     /* Add the hash table entry */
2955     add_glsl_program_entry(This, entry);
2956
2957     /* Set the current program */
2958     This->stateBlock->glsl_program = entry;
2959
2960     /* Attach GLSL vshader */
2961     if (vshader_id) {
2962         int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
2963         char tmp_name[10];
2964
2965         TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
2966         GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
2967         checkGLcall("glAttachObjectARB");
2968
2969         /* Bind vertex attributes to a corresponding index number to match
2970          * the same index numbers as ARB_vertex_programs (makes loading
2971          * vertex attributes simpler).  With this method, we can use the
2972          * exact same code to load the attributes later for both ARB and
2973          * GLSL shaders.
2974          *
2975          * We have to do this here because we need to know the Program ID
2976          * in order to make the bindings work, and it has to be done prior
2977          * to linking the GLSL program. */
2978         for (i = 0; i < max_attribs; ++i) {
2979             if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
2980                 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
2981                 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
2982             }
2983         }
2984         checkGLcall("glBindAttribLocationARB");
2985
2986         list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
2987
2988         reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
2989         TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
2990         GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
2991         checkGLcall("glAttachObjectARB");
2992         /* Flag the reorder function for deletion, then it will be freed automatically when the program
2993          * is destroyed
2994          */
2995         GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
2996     }
2997
2998     /* Attach GLSL pshader */
2999     if (pshader_id) {
3000         TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3001         GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3002         checkGLcall("glAttachObjectARB");
3003
3004         list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3005     }
3006
3007     /* Link the program */
3008     TRACE("Linking GLSL shader program %u\n", programId);
3009     GL_EXTCALL(glLinkProgramARB(programId));
3010     print_glsl_info_log(&GLINFO_LOCATION, programId);
3011
3012     entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3013     for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3014         snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3015         entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3016     }
3017     entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3018     for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3019         snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3020         entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3021     }
3022 }
3023
3024 static GLhandleARB create_glsl_blt_shader(WineD3D_GL_Info *gl_info) {
3025     GLhandleARB program_id;
3026     GLhandleARB vshader_id, pshader_id;
3027     const char *blt_vshader[] = {
3028         "void main(void)\n"
3029         "{\n"
3030         "    gl_Position = gl_Vertex;\n"
3031         "    gl_FrontColor = vec4(1.0);\n"
3032         "    gl_TexCoord[0].x = (gl_Vertex.x * 0.5) + 0.5;\n"
3033         "    gl_TexCoord[0].y = (-gl_Vertex.y * 0.5) + 0.5;\n"
3034         "}\n"
3035     };
3036
3037     const char *blt_pshader[] = {
3038         "uniform sampler2D sampler;\n"
3039         "void main(void)\n"
3040         "{\n"
3041         "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3042         "}\n"
3043     };
3044
3045     vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3046     GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3047     GL_EXTCALL(glCompileShaderARB(vshader_id));
3048
3049     pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3050     GL_EXTCALL(glShaderSourceARB(pshader_id, 1, blt_pshader, NULL));
3051     GL_EXTCALL(glCompileShaderARB(pshader_id));
3052
3053     program_id = GL_EXTCALL(glCreateProgramObjectARB());
3054     GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3055     GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3056     GL_EXTCALL(glLinkProgramARB(program_id));
3057
3058     print_glsl_info_log(&GLINFO_LOCATION, program_id);
3059
3060     return program_id;
3061 }
3062
3063 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3064     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3065     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3066     GLhandleARB program_id = 0;
3067
3068     if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3069     else This->stateBlock->glsl_program = NULL;
3070
3071     program_id = This->stateBlock->glsl_program ? This->stateBlock->glsl_program->programId : 0;
3072     if (program_id) TRACE("Using GLSL program %u\n", program_id);
3073     GL_EXTCALL(glUseProgramObjectARB(program_id));
3074     checkGLcall("glUseProgramObjectARB");
3075 }
3076
3077 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface) {
3078     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3079     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3080     static GLhandleARB program_id = 0;
3081     static GLhandleARB loc = -1;
3082
3083     if (!program_id) {
3084         program_id = create_glsl_blt_shader(gl_info);
3085         loc = GL_EXTCALL(glGetUniformLocationARB(program_id, "sampler"));
3086     }
3087
3088     GL_EXTCALL(glUseProgramObjectARB(program_id));
3089     GL_EXTCALL(glUniform1iARB(loc, 0));
3090 }
3091
3092 static void shader_glsl_cleanup(IWineD3DDevice *iface) {
3093     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3094     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3095     GL_EXTCALL(glUseProgramObjectARB(0));
3096 }
3097
3098 const shader_backend_t glsl_shader_backend = {
3099     &shader_glsl_select,
3100     &shader_glsl_select_depth_blt,
3101     &shader_glsl_load_constants,
3102     &shader_glsl_cleanup,
3103     &shader_glsl_color_correction
3104 };