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