wined3d: Move a TRACE up a few lines.
[wine] / dlls / wined3d / arb_program_shader.c
1 /*
2  * Pixel and vertex shaders implementation using ARB_vertex_program
3  * and ARB_fragment_program GL extensions.
4  *
5  * Copyright 2002-2003 Jason Edmeades
6  * Copyright 2002-2003 Raphael Junqueira
7  * Copyright 2004 Christian Costa
8  * Copyright 2005 Oliver Stieber
9  * Copyright 2006 Ivan Gyurdiev
10  * Copyright 2006 Jason Green
11  * Copyright 2006 Henri Verbeet
12  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30
31 #include <math.h>
32 #include <stdio.h>
33
34 #include "wined3d_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
39
40 #define GLINFO_LOCATION      (*gl_info)
41
42 /********************************************************
43  * ARB_[vertex/fragment]_program helper functions follow
44  ********************************************************/
45
46 /** 
47  * Loads floating point constants into the currently set ARB_vertex/fragment_program.
48  * When constant_list == NULL, it will load all the constants.
49  *  
50  * @target_type should be either GL_VERTEX_PROGRAM_ARB (for vertex shaders)
51  *  or GL_FRAGMENT_PROGRAM_ARB (for pixel shaders)
52  */
53 static unsigned int shader_arb_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info, GLuint target_type,
54         unsigned int max_constants, float* constants, char *dirty_consts) {
55     local_constant* lconst;
56     DWORD i, j;
57     unsigned int ret;
58
59     if (TRACE_ON(d3d_shader)) {
60         for(i = 0; i < max_constants; i++) {
61             if(!dirty_consts[i]) continue;
62             TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
63                         constants[i * 4 + 0], constants[i * 4 + 1],
64                         constants[i * 4 + 2], constants[i * 4 + 3]);
65         }
66     }
67     /* In 1.X pixel shaders constants are implicitly clamped in the range [-1;1] */
68     if(target_type == GL_FRAGMENT_PROGRAM_ARB &&
69        WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1) {
70         float lcl_const[4];
71         for(i = 0; i < max_constants; i++) {
72             if(!dirty_consts[i]) continue;
73             dirty_consts[i] = 0;
74
75             j = 4 * i;
76             if(constants[j + 0] > 1.0) lcl_const[0] = 1.0;
77             else if(constants[j + 0] < -1.0) lcl_const[0] = -1.0;
78             else lcl_const[0] = constants[j + 0];
79
80             if(constants[j + 1] > 1.0) lcl_const[1] = 1.0;
81             else if(constants[j + 1] < -1.0) lcl_const[1] = -1.0;
82             else lcl_const[1] = constants[j + 1];
83
84             if(constants[j + 2] > 1.0) lcl_const[2] = 1.0;
85             else if(constants[j + 2] < -1.0) lcl_const[2] = -1.0;
86             else lcl_const[2] = constants[j + 2];
87
88             if(constants[j + 3] > 1.0) lcl_const[3] = 1.0;
89             else if(constants[j + 3] < -1.0) lcl_const[3] = -1.0;
90             else lcl_const[3] = constants[j + 3];
91
92             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
93         }
94     } else {
95         if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
96             /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
97              * or just reloading *all* constants at once
98              *
99             GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, 0, max_constants, constants));
100              */
101             for(i = 0; i < max_constants; i++) {
102                 if(!dirty_consts[i]) continue;
103
104                 /* Find the next block of dirty constants */
105                 dirty_consts[i] = 0;
106                 j = i;
107                 for(i++; (i < max_constants) && dirty_consts[i]; i++) {
108                     dirty_consts[i] = 0;
109                 }
110
111                 GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
112             }
113         } else {
114             for(i = 0; i < max_constants; i++) {
115                 if(dirty_consts[i]) {
116                     dirty_consts[i] = 0;
117                     GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
118                 }
119             }
120         }
121     }
122     checkGLcall("glProgramEnvParameter4fvARB()");
123
124     /* Load immediate constants */
125     if(This->baseShader.load_local_constsF) {
126         if (TRACE_ON(d3d_shader)) {
127             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
128                 GLfloat* values = (GLfloat*)lconst->value;
129                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
130                         values[0], values[1], values[2], values[3]);
131             }
132         }
133         /* Immediate constants are clamped for 1.X shaders at loading times */
134         ret = 0;
135         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
136             dirty_consts[lconst->idx] = 1; /* Dirtify so the non-immediate constant overwrites it next time */
137             ret = max(ret, lconst->idx + 1);
138             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, lconst->idx, (GLfloat*)lconst->value));
139         }
140         checkGLcall("glProgramEnvParameter4fvARB()");
141         return ret; /* The loaded immediate constants need reloading for the next shader */
142     } else {
143         return 0; /* No constants are dirty now */
144     }
145 }
146
147 /**
148  * Loads the app-supplied constants into the currently set ARB_[vertex/fragment]_programs.
149  * 
150  * We only support float constants in ARB at the moment, so don't 
151  * worry about the Integers or Booleans
152  */
153 void shader_arb_load_constants(
154     IWineD3DDevice* device,
155     char usePixelShader,
156     char useVertexShader) {
157    
158     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device; 
159     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
160     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
161     unsigned char i;
162
163     if (useVertexShader) {
164         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
165
166         /* Load DirectX 9 float constants for vertex shader */
167         deviceImpl->highest_dirty_vs_const = shader_arb_load_constantsF(
168                 vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
169                 deviceImpl->highest_dirty_vs_const,
170                 stateBlock->vertexShaderConstantF,
171                 deviceImpl->activeContext->vshader_const_dirty);
172
173         /* Upload the position fixup */
174         GL_EXTCALL(glProgramEnvParameter4fvARB(GL_VERTEX_PROGRAM_ARB, ARB_SHADER_PRIVCONST_POS, deviceImpl->posFixup));
175     }
176
177     if (usePixelShader) {
178
179         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
180         IWineD3DPixelShaderImpl *psi = (IWineD3DPixelShaderImpl *) pshader;
181
182         /* Load DirectX 9 float constants for pixel shader */
183         deviceImpl->highest_dirty_ps_const = shader_arb_load_constantsF(
184                 pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
185                 deviceImpl->highest_dirty_ps_const,
186                 stateBlock->pixelShaderConstantF,
187                 deviceImpl->activeContext->pshader_const_dirty);
188
189         for(i = 0; i < psi->numbumpenvmatconsts; i++) {
190             /* The state manager takes care that this function is always called if the bump env matrix changes
191              */
192             float *data = (float *) &stateBlock->textureState[(int) psi->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
193             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->bumpenvmatconst[i].const_num, data));
194             deviceImpl->activeContext->pshader_const_dirty[psi->bumpenvmatconst[i].const_num] = 1;
195
196             if(psi->luminanceconst[i].const_num != -1) {
197                 /* WINED3DTSS_BUMPENVLSCALE and WINED3DTSS_BUMPENVLOFFSET are next to each other.
198                  * point gl to the scale, and load 4 floats. x = scale, y = offset, z and w are junk, we
199                  * don't care about them. The pointers are valid for sure because the stateblock is bigger.
200                  * (they're WINED3DTSS_TEXTURETRANSFORMFLAGS and WINED3DTSS_ADDRESSW, so most likely 0 or NaN
201                  */
202                 float *scale = (float *) &stateBlock->textureState[(int) psi->luminanceconst[i].texunit][WINED3DTSS_BUMPENVLSCALE];
203                 GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->luminanceconst[i].const_num, scale));
204                 deviceImpl->activeContext->pshader_const_dirty[psi->luminanceconst[i].const_num] = 1;
205             }
206         }
207
208         if(((IWineD3DPixelShaderImpl *) pshader)->srgb_enabled &&
209            !((IWineD3DPixelShaderImpl *) pshader)->srgb_mode_hardcoded) {
210             float comparison[4];
211             float mul_low[4];
212
213             if(stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
214                 comparison[0] = srgb_cmp; comparison[1] = srgb_cmp;
215                 comparison[2] = srgb_cmp; comparison[3] = srgb_cmp;
216
217                 mul_low[0] = srgb_mul_low; mul_low[1] = srgb_mul_low;
218                 mul_low[2] = srgb_mul_low; mul_low[3] = srgb_mul_low;
219             } else {
220                 comparison[0] = 1.0 / 0.0; comparison[1] = 1.0 / 0.0;
221                 comparison[2] = 1.0 / 0.0; comparison[3] = 1.0 / 0.0;
222
223                 mul_low[0] = 1.0; mul_low[1] = 1.0;
224                 mul_low[2] = 1.0; mul_low[3] = 1.0;
225             }
226             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->srgb_cmp_const, comparison));
227             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->srgb_low_const, mul_low));
228             checkGLcall("Load sRGB correction constants\n");
229             deviceImpl->activeContext->pshader_const_dirty[psi->srgb_low_const] = 1;
230             deviceImpl->activeContext->pshader_const_dirty[psi->srgb_cmp_const] = 1;
231
232         }
233     }
234 }
235
236 /* Generate the variable & register declarations for the ARB_vertex_program output target */
237 void shader_generate_arb_declarations(
238     IWineD3DBaseShader *iface,
239     shader_reg_maps* reg_maps,
240     SHADER_BUFFER* buffer,
241     WineD3D_GL_Info* gl_info) {
242
243     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
244     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
245     DWORD i, cur;
246     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
247     unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
248             (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
249     UINT extra_constants_needed = 0;
250     local_constant* lconst;
251
252     /* Temporary Output register */
253     shader_addline(buffer, "TEMP TMP_OUT;\n");
254
255     for(i = 0; i < This->baseShader.limits.temporary; i++) {
256         if (reg_maps->temporary[i])
257             shader_addline(buffer, "TEMP R%u;\n", i);
258     }
259
260     for (i = 0; i < This->baseShader.limits.address; i++) {
261         if (reg_maps->address[i])
262             shader_addline(buffer, "ADDRESS A%d;\n", i);
263     }
264
265     for(i = 0; i < This->baseShader.limits.texcoord; i++) {
266         if (reg_maps->texcoord[i])
267             shader_addline(buffer,"TEMP T%u;\n", i);
268     }
269
270     /* Texture coordinate registers must be pre-loaded */
271     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
272         if (reg_maps->texcoord[i])
273             shader_addline(buffer, "MOV T%u, fragment.texcoord[%u];\n", i, i);
274     }
275
276     for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
277         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) This;
278         if(!reg_maps->bumpmat[i]) continue;
279
280         cur = ps->numbumpenvmatconsts;
281         ps->bumpenvmatconst[cur].const_num = -1;
282         ps->bumpenvmatconst[cur].texunit = i;
283         ps->luminanceconst[cur].const_num = -1;
284         ps->luminanceconst[cur].texunit = i;
285
286         /* If the shader does not use all available constants, use the next free constant to load the bump mapping environment matrix from
287          * the stateblock into the shader. If no constant is available don't load, texbem will then just sample the texture without applying
288          * bump mapping.
289          */
290         if(max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
291             ps->bumpenvmatconst[cur].const_num = max_constantsF + extra_constants_needed;
292             shader_addline(buffer, "PARAM bumpenvmat%d = program.env[%d];\n",
293                            i, ps->bumpenvmatconst[cur].const_num);
294             extra_constants_needed++;
295
296             if(reg_maps->luminanceparams && max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
297                 ((IWineD3DPixelShaderImpl *)This)->luminanceconst[cur].const_num = max_constantsF + extra_constants_needed;
298                 shader_addline(buffer, "PARAM luminance%d = program.env[%d];\n",
299                                i, ps->luminanceconst[cur].const_num);
300                 extra_constants_needed++;
301             } else if(reg_maps->luminanceparams) {
302                 FIXME("No free constant to load the luminance parameters\n");
303             }
304         } else {
305             FIXME("No free constant found to load environemnt bump mapping matrix into the shader. texbem instruction will not apply bump mapping\n");
306         }
307
308         ps->numbumpenvmatconsts = cur + 1;
309     }
310
311     if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE] && pshader) {
312         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
313         /* If there are 2 constants left to use, use them to pass the sRGB correction values in. This way
314          * srgb write correction can be turned on and off dynamically without recompilation. Otherwise
315          * hardcode them. The drawback of hardcoding is that the shader needs recompilation to turn sRGB
316          * off again
317          */
318         if(max_constantsF + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF) && FALSE) {
319             /* The idea is that if srgb is enabled, then disabled, the constant loading code
320              * can effectively disable sRGB correction by passing 1.0 and INF as the multiplication
321              * and comparison constants. If it disables it that way, the shader won't be recompiled
322              * and the code will stay in, so sRGB writing can be turned on again by setting the
323              * constants from the spec
324              */
325             ps_impl->srgb_mode_hardcoded = 0;
326             ps_impl->srgb_low_const = GL_LIMITS(pshader_constantsF) - extra_constants_needed;
327             ps_impl->srgb_cmp_const = GL_LIMITS(pshader_constantsF) - extra_constants_needed - 1;
328             shader_addline(buffer, "PARAM srgb_mul_low = program.env[%d];\n", ps_impl->srgb_low_const);
329             shader_addline(buffer, "PARAM srgb_comparison = program.env[%d];\n", ps_impl->srgb_cmp_const);
330         } else {
331             shader_addline(buffer, "PARAM srgb_mul_low = {%f, %f, %f, 1.0};\n",
332                            srgb_mul_low, srgb_mul_low, srgb_mul_low);
333             shader_addline(buffer, "PARAM srgb_comparison =  {%f, %f, %f, %f};\n",
334                            srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
335             ps_impl->srgb_mode_hardcoded = 1;
336         }
337         /* These can be hardcoded, they do not cause any harm because no fragment will enter the high
338          * path if the comparison value is set to INF
339          */
340         shader_addline(buffer, "PARAM srgb_pow =  {%f, %f, %f, 1.0};\n",
341                        srgb_pow, srgb_pow, srgb_pow);
342         shader_addline(buffer, "PARAM srgb_mul_hi =  {%f, %f, %f, 1.0};\n",
343                        srgb_mul_high, srgb_mul_high, srgb_mul_high);
344         shader_addline(buffer, "PARAM srgb_sub_hi =  {%f, %f, %f, 0.0};\n",
345                        srgb_sub_high, srgb_sub_high, srgb_sub_high);
346         ps_impl->srgb_enabled = 1;
347     } else if(pshader) {
348         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
349
350         /* Do not write any srgb fixup into the shader to save shader size and processing time.
351          * As a consequence, we can't toggle srgb write on without recompilation
352          */
353         ps_impl->srgb_enabled = 0;
354         ps_impl->srgb_mode_hardcoded = 1;
355     }
356
357     /* Load local constants using the program-local space,
358      * this avoids reloading them each time the shader is used
359      */
360     if(!This->baseShader.load_local_constsF) {
361         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
362             shader_addline(buffer, "PARAM C%u = program.local[%u];\n", lconst->idx,
363                            lconst->idx);
364         }
365     }
366
367     /* we use the array-based constants array if the local constants are marked for loading,
368      * because then we use indirect addressing, or when the local constant list is empty,
369      * because then we don't know if we're using indirect addressing or not. If we're hardcoding
370      * local constants do not declare the loaded constants as an array because ARB compilers usually
371      * do not optimize unused constants away
372      */
373     if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
374         /* Need to PARAM the environment parameters (constants) so we can use relative addressing */
375         shader_addline(buffer, "PARAM C[%d] = { program.env[0..%d] };\n",
376                     max_constantsF, max_constantsF - 1);
377     } else {
378         for(i = 0; i < max_constantsF; i++) {
379             if(!shader_constant_is_local(This, i)) {
380                 shader_addline(buffer, "PARAM C%d = program.env[%d];\n",i, i);
381             }
382         }
383     }
384 }
385
386 static const char * const shift_tab[] = {
387     "dummy",     /*  0 (none) */
388     "coefmul.x", /*  1 (x2)   */
389     "coefmul.y", /*  2 (x4)   */
390     "coefmul.z", /*  3 (x8)   */
391     "coefmul.w", /*  4 (x16)  */
392     "dummy",     /*  5 (x32)  */
393     "dummy",     /*  6 (x64)  */
394     "dummy",     /*  7 (x128) */
395     "dummy",     /*  8 (d256) */
396     "dummy",     /*  9 (d128) */
397     "dummy",     /* 10 (d64)  */
398     "dummy",     /* 11 (d32)  */
399     "coefdiv.w", /* 12 (d16)  */
400     "coefdiv.z", /* 13 (d8)   */
401     "coefdiv.y", /* 14 (d4)   */
402     "coefdiv.x"  /* 15 (d2)   */
403 };
404
405 static void shader_arb_get_write_mask(SHADER_OPCODE_ARG* arg, const DWORD param, char *write_mask) {
406     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) arg->shader;
407     char *ptr = write_mask;
408     char vshader = shader_is_vshader_version(This->baseShader.hex_version);
409
410     if(vshader && shader_get_regtype(param) == WINED3DSPR_ADDR) {
411         *ptr++ = '.';
412         *ptr++ = 'x';
413     } else if ((param & WINED3DSP_WRITEMASK_ALL) != WINED3DSP_WRITEMASK_ALL) {
414         *ptr++ = '.';
415         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
416         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
417         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
418         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
419     }
420
421     *ptr = '\0';
422 }
423
424 static void shader_arb_get_swizzle(const DWORD param, BOOL fixup, char *swizzle_str) {
425     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
426      * but addressed as "rgba". To fix this we need to swap the register's x
427      * and z components. */
428     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
429     char *ptr = swizzle_str;
430
431     /* swizzle bits fields: wwzzyyxx */
432     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
433     DWORD swizzle_x = swizzle & 0x03;
434     DWORD swizzle_y = (swizzle >> 2) & 0x03;
435     DWORD swizzle_z = (swizzle >> 4) & 0x03;
436     DWORD swizzle_w = (swizzle >> 6) & 0x03;
437
438     /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
439      * generate a swizzle string. Unless we need to our own swizzling. */
440     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) != swizzle || fixup) {
441         *ptr++ = '.';
442         if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
443             *ptr++ = swizzle_chars[swizzle_x];
444         } else {
445             *ptr++ = swizzle_chars[swizzle_x];
446             *ptr++ = swizzle_chars[swizzle_y];
447             *ptr++ = swizzle_chars[swizzle_z];
448             *ptr++ = swizzle_chars[swizzle_w];
449         }
450     }
451
452     *ptr = '\0';
453 }
454
455 static void pshader_get_register_name(IWineD3DBaseShader* iface,
456     const DWORD param, char* regstr) {
457
458     DWORD reg = param & WINED3DSP_REGNUM_MASK;
459     DWORD regtype = shader_get_regtype(param);
460     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
461
462     switch (regtype) {
463     case WINED3DSPR_TEMP:
464         sprintf(regstr, "R%u", reg);
465     break;
466     case WINED3DSPR_INPUT:
467         if (reg==0) {
468             strcpy(regstr, "fragment.color.primary");
469         } else {
470             strcpy(regstr, "fragment.color.secondary");
471         }
472     break;
473     case WINED3DSPR_CONST:
474         if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
475             sprintf(regstr, "C[%u]", reg);
476         } else {
477             sprintf(regstr, "C%u", reg);
478         }
479     break;
480     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
481         sprintf(regstr,"T%u", reg);
482     break;
483     case WINED3DSPR_COLOROUT:
484         if (reg == 0)
485             sprintf(regstr, "TMP_COLOR");
486         else {
487             /* TODO: See GL_ARB_draw_buffers */
488             FIXME("Unsupported write to render target %u\n", reg);
489             sprintf(regstr, "unsupported_register");
490         }
491     break;
492     case WINED3DSPR_DEPTHOUT:
493         sprintf(regstr, "result.depth");
494     break;
495     case WINED3DSPR_ATTROUT:
496         sprintf(regstr, "oD[%u]", reg);
497     break;
498     case WINED3DSPR_TEXCRDOUT:
499         sprintf(regstr, "oT[%u]", reg);
500     break;
501     default:
502         FIXME("Unhandled register name Type(%d)\n", regtype);
503         sprintf(regstr, "unrecognized_register");
504     break;
505     }
506 }
507
508 /* TODO: merge with pixel shader */
509 static void vshader_program_add_param(SHADER_OPCODE_ARG *arg, const DWORD param, BOOL is_input, char *hwLine) {
510
511   IWineD3DVertexShaderImpl* This = (IWineD3DVertexShaderImpl*) arg->shader;
512
513   /* oPos, oFog and oPts in D3D */
514   static const char * const hwrastout_reg_names[] = { "TMP_OUT", "result.fogcoord", "result.pointsize" };
515
516   DWORD reg = param & WINED3DSP_REGNUM_MASK;
517   DWORD regtype = shader_get_regtype(param);
518   char  tmpReg[255];
519   BOOL is_color = FALSE;
520
521   if ((param & WINED3DSP_SRCMOD_MASK) == WINED3DSPSM_NEG) {
522       strcat(hwLine, " -");
523   } else {
524       strcat(hwLine, " ");
525   }
526
527   switch (regtype) {
528   case WINED3DSPR_TEMP:
529     sprintf(tmpReg, "R%u", reg);
530     strcat(hwLine, tmpReg);
531     break;
532   case WINED3DSPR_INPUT:
533
534     if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
535         is_color = TRUE;
536
537     sprintf(tmpReg, "vertex.attrib[%u]", reg);
538     strcat(hwLine, tmpReg);
539     break;
540   case WINED3DSPR_CONST:
541       if(param & WINED3DSHADER_ADDRMODE_RELATIVE) {
542           if(reg >= This->rel_offset) {
543               sprintf(tmpReg, "C[A0.x + %u]", reg - This->rel_offset);
544           } else {
545               sprintf(tmpReg, "C[A0.x - %u]", -reg + This->rel_offset);
546           }
547       } else {
548           if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
549               sprintf(tmpReg, "C[%u]", reg);
550           } else {
551               sprintf(tmpReg, "C%u", reg);
552           }
553       }
554     strcat(hwLine, tmpReg);
555     break;
556   case WINED3DSPR_ADDR: /*case D3DSPR_TEXTURE:*/
557     sprintf(tmpReg, "A%u", reg);
558     strcat(hwLine, tmpReg);
559     break;
560   case WINED3DSPR_RASTOUT:
561     sprintf(tmpReg, "%s", hwrastout_reg_names[reg]);
562     strcat(hwLine, tmpReg);
563     break;
564   case WINED3DSPR_ATTROUT:
565     if (reg==0) {
566        strcat(hwLine, "result.color.primary");
567     } else {
568        strcat(hwLine, "result.color.secondary");
569     }
570     break;
571   case WINED3DSPR_TEXCRDOUT:
572     sprintf(tmpReg, "result.texcoord[%u]", reg);
573     strcat(hwLine, tmpReg);
574     break;
575   default:
576     FIXME("Unknown reg type %d %d\n", regtype, reg);
577     strcat(hwLine, "unrecognized_register");
578     break;
579   }
580
581   if (!is_input) {
582     char write_mask[6];
583     shader_arb_get_write_mask(arg, param, write_mask);
584     strcat(hwLine, write_mask);
585   } else {
586     char swizzle[6];
587     shader_arb_get_swizzle(param, is_color, swizzle);
588     strcat(hwLine, swizzle);
589   }
590 }
591
592 static void shader_hw_sample(SHADER_OPCODE_ARG* arg, DWORD sampler_idx, const char *dst_str, const char *coord_reg, BOOL projected, BOOL bias) {
593     SHADER_BUFFER* buffer = arg->buffer;
594     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
595     const char *tex_type;
596
597     switch(sampler_type) {
598         case WINED3DSTT_1D:
599             tex_type = "1D";
600             break;
601
602         case WINED3DSTT_2D:
603         {
604             IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) arg->shader;
605             IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
606             if(device->stateBlock->textures[sampler_idx] &&
607                IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
608                 tex_type = "RECT";
609             } else {
610                 tex_type = "2D";
611             }
612             break;
613         }
614
615         case WINED3DSTT_VOLUME:
616             tex_type = "3D";
617             break;
618
619         case WINED3DSTT_CUBE:
620             tex_type = "CUBE";
621             break;
622
623         default:
624             ERR("Unexpected texture type %d\n", sampler_type);
625             tex_type = "";
626     }
627
628     if (bias) {
629         /* Shouldn't be possible, but let's check for it */
630         if(projected) FIXME("Biased and Projected texture sampling\n");
631         /* TXB takes the 4th component of the source vector automatically, as d3d. Nothing more to do */
632         shader_addline(buffer, "TXB %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
633     } else if (projected) {
634         shader_addline(buffer, "TXP %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
635     } else {
636         shader_addline(buffer, "TEX %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
637     }
638 }
639
640 static void gen_color_correction(SHADER_BUFFER *buffer, const char *reg, const char *writemask,
641                                  const char *one, const char *two, WINED3DFORMAT fmt,
642                                  WineD3D_GL_Info *gl_info) {
643     switch(fmt) {
644         case WINED3DFMT_V8U8:
645         case WINED3DFMT_V16U16:
646             if(GL_SUPPORT(NV_TEXTURE_SHADER) ||
647               (GL_SUPPORT(ATI_ENVMAP_BUMPMAP) && fmt == WINED3DFMT_V8U8)) {
648 #if 0
649                 /* The 3rd channel returns 1.0 in d3d, but 0.0 in gl. Fix this while we're at it :-)
650                  * disabled until an application that needs it is found because it causes unneeded
651                  * shader recompilation in some game
652                  */
653                 if(strlen(writemask) >= 4) {
654                     shader_addline(buffer, "MOV %s.%c, %s;\n", reg, one);
655                 }
656 #endif
657             } else {
658                 /* Correct the sign, but leave the blue as it is - it was loaded correctly already
659                  * ARB shaders are a bit picky wrt writemasks and swizzles. If we're free to scale
660                  * all registers, do so, this saves an instruction.
661                  */
662                 if(strlen(writemask) >= 5) {
663                     shader_addline(buffer, "MAD %s, %s, %s, -%s;\n", reg, reg, two, one);
664                 } else if(strlen(writemask) >= 3) {
665                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
666                                    reg, writemask[1],
667                                    reg, writemask[1],
668                                    two, one);
669                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
670                                    reg, writemask[2],
671                                    reg, writemask[2],
672                                    two, one);
673                 } else if(strlen(writemask) == 2) {
674                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n", reg, writemask[1],
675                                    reg, writemask[1], two, one);
676                 }
677             }
678             break;
679
680         case WINED3DFMT_X8L8V8U8:
681             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
682                 /* Red and blue are the signed channels, fix them up; Blue(=L) is correct already,
683                  * and a(X) is always 1.0. Cannot do a full conversion due to L(blue)
684                  */
685                 if(strlen(writemask) >= 3) {
686                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
687                                    reg, writemask[1],
688                                    reg, writemask[1],
689                                    two, one);
690                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
691                                    reg, writemask[2],
692                                    reg, writemask[2],
693                                    two, one);
694                 } else if(strlen(writemask) == 2) {
695                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
696                                    reg, writemask[1],
697                                    reg, writemask[1],
698                                    two, one);
699                 }
700             }
701             break;
702
703         case WINED3DFMT_L6V5U5:
704             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
705                 if(strlen(writemask) >= 4) {
706                     /* Swap y and z (U and L), and do a sign conversion on x and the new y(V and U) */
707                     shader_addline(buffer, "MOV TMP.g, %s.%c;\n",
708                                    reg, writemask[2]);
709                     shader_addline(buffer, "MAD %s.%c%c, %s.%c%c, %s, -%s;\n",
710                                    reg, writemask[1], writemask[1],
711                                    reg, writemask[1], writemask[3],
712                                    two, one);
713                     shader_addline(buffer, "MOV %s.%c, TMP.g;\n", reg,
714                                    writemask[3]);
715                 } else if(strlen(writemask) == 3) {
716                     /* This is bad: We have VL, but we need VU */
717                     FIXME("2 components sampled from a converted L6V5U5 texture\n");
718                 } else {
719                     shader_addline(buffer, "MAD %s.%c, %s.%c, %s, -%s;\n",
720                                    reg, writemask[1],
721                                    reg, writemask[1],
722                                    two, one);
723                 }
724             }
725             break;
726
727         case WINED3DFMT_Q8W8V8U8:
728             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
729                 /* Correct the sign in all channels */
730                 switch(strlen(writemask)) {
731                     case 4:
732                         shader_addline(buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
733                                        reg, writemask[3],
734                                        reg, writemask[3]);
735                         /* drop through */
736                     case 3:
737                         shader_addline(buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
738                                        reg, writemask[2],
739                                        reg, writemask[2]);
740                         /* drop through */
741                     case 2:
742                         shader_addline(buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
743                                        reg, writemask[1],
744                                        reg, writemask[1]);
745                         break;
746
747                         /* Should not occur, since it's at minimum '.' and a letter */
748                     case 1:
749                         ERR("Unexpected writemask: \"%s\"\n", writemask);
750                         break;
751
752                     case 5:
753                     default:
754                         shader_addline(buffer, "MAD %s, %s, coefmul.x, -one;\n", reg, reg);
755                 }
756             }
757             break;
758
759         case WINED3DFMT_ATI2N:
760             /* GL_ATI_texture_compression_3dc returns the two channels as luminance-alpha,
761              * which means the first one is replicated across .rgb, and the 2nd one is in
762              * .a. We need the 2nd in .g
763              *
764              * GL_EXT_texture_compression_rgtc returns the values in .rg, however, they
765              * are swapped compared to d3d. So swap red and green.
766              */
767             if(GL_SUPPORT(EXT_TEXTURE_COMPRESSION_RGTC)) {
768                 shader_addline(buffer, "SWZ %s, %s, %c, %c, 1, 0;\n",
769                                reg, reg, writemask[2], writemask[1]);
770             } else {
771                 if(strlen(writemask) == 5) {
772                     shader_addline(buffer, "MOV %s.%c, %s.%c;\n",
773                                 reg, writemask[2], reg, writemask[4]);
774                 } else if(strlen(writemask) == 2) {
775                     /* Nothing to do */
776                 } else {
777                     /* This is bad: We have VL, but we need VU */
778                     FIXME("2 or 3 components sampled from a converted ATI2N texture\n");
779                 }
780             }
781             break;
782
783             /* stupid compiler */
784         default:
785             break;
786     }
787 }
788
789 static void shader_arb_color_correction(SHADER_OPCODE_ARG* arg) {
790     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
791     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) shader->baseShader.device;
792     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
793     WINED3DFORMAT fmt;
794     WINED3DFORMAT conversion_group;
795     IWineD3DBaseTextureImpl *texture;
796     UINT i;
797     BOOL recorded = FALSE;
798     DWORD sampler_idx;
799     DWORD hex_version = shader->baseShader.hex_version;
800     char reg[256];
801     char writemask[6];
802
803     switch(arg->opcode->opcode) {
804         case WINED3DSIO_TEX:
805             if (hex_version < WINED3DPS_VERSION(2,0)) {
806                 sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
807             } else {
808                 sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
809             }
810             break;
811
812         case WINED3DSIO_TEXLDL:
813             FIXME("Add color fixup for vertex texture WINED3DSIO_TEXLDL\n");
814             return;
815
816         case WINED3DSIO_TEXDP3TEX:
817         case WINED3DSIO_TEXM3x3TEX:
818         case WINED3DSIO_TEXM3x3SPEC:
819         case WINED3DSIO_TEXM3x3VSPEC:
820         case WINED3DSIO_TEXBEM:
821         case WINED3DSIO_TEXREG2AR:
822         case WINED3DSIO_TEXREG2GB:
823         case WINED3DSIO_TEXREG2RGB:
824             sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
825             break;
826
827         default:
828             /* Not a texture sampling instruction, nothing to do */
829             return;
830     };
831
832     texture = (IWineD3DBaseTextureImpl *) deviceImpl->stateBlock->textures[sampler_idx];
833     if(texture) {
834         fmt = texture->resource.format;
835         conversion_group = texture->baseTexture.shader_conversion_group;
836     } else {
837         fmt = WINED3DFMT_UNKNOWN;
838         conversion_group = WINED3DFMT_UNKNOWN;
839     }
840
841     /* before doing anything, record the sampler with the format in the format conversion list,
842      * but check if it's not there already
843      */
844     for(i = 0; i < shader->baseShader.num_sampled_samplers; i++) {
845         if(shader->baseShader.sampled_samplers[i] == sampler_idx) {
846             recorded = TRUE;
847         }
848     }
849     if(!recorded) {
850         shader->baseShader.sampled_samplers[shader->baseShader.num_sampled_samplers] = sampler_idx;
851         shader->baseShader.num_sampled_samplers++;
852         shader->baseShader.sampled_format[sampler_idx] = conversion_group;
853     }
854
855     pshader_get_register_name(arg->shader, arg->dst, reg);
856     shader_arb_get_write_mask(arg, arg->dst, writemask);
857     if(strlen(writemask) == 0) strcpy(writemask, ".xyzw");
858
859     gen_color_correction(arg->buffer, reg, writemask, "one", "coefmul.x", fmt, gl_info);
860
861 }
862
863
864 static void pshader_gen_input_modifier_line (
865     IWineD3DBaseShader *iface,
866     SHADER_BUFFER* buffer,
867     const DWORD instr,
868     int tmpreg,
869     char *outregstr) {
870
871     /* Generate a line that does the input modifier computation and return the input register to use */
872     char regstr[256];
873     char swzstr[20];
874     int insert_line;
875
876     /* Assume a new line will be added */
877     insert_line = 1;
878
879     /* Get register name */
880     pshader_get_register_name(iface, instr, regstr);
881     shader_arb_get_swizzle(instr, FALSE, swzstr);
882
883     switch (instr & WINED3DSP_SRCMOD_MASK) {
884     case WINED3DSPSM_NONE:
885         sprintf(outregstr, "%s%s", regstr, swzstr);
886         insert_line = 0;
887         break;
888     case WINED3DSPSM_NEG:
889         sprintf(outregstr, "-%s%s", regstr, swzstr);
890         insert_line = 0;
891         break;
892     case WINED3DSPSM_BIAS:
893         shader_addline(buffer, "ADD T%c, %s, -coefdiv.x;\n", 'A' + tmpreg, regstr);
894         break;
895     case WINED3DSPSM_BIASNEG:
896         shader_addline(buffer, "ADD T%c, -%s, coefdiv.x;\n", 'A' + tmpreg, regstr);
897         break;
898     case WINED3DSPSM_SIGN:
899         shader_addline(buffer, "MAD T%c, %s, coefmul.x, -one.x;\n", 'A' + tmpreg, regstr);
900         break;
901     case WINED3DSPSM_SIGNNEG:
902         shader_addline(buffer, "MAD T%c, %s, -coefmul.x, one.x;\n", 'A' + tmpreg, regstr);
903         break;
904     case WINED3DSPSM_COMP:
905         shader_addline(buffer, "SUB T%c, one.x, %s;\n", 'A' + tmpreg, regstr);
906         break;
907     case WINED3DSPSM_X2:
908         shader_addline(buffer, "ADD T%c, %s, %s;\n", 'A' + tmpreg, regstr, regstr);
909         break;
910     case WINED3DSPSM_X2NEG:
911         shader_addline(buffer, "ADD T%c, -%s, -%s;\n", 'A' + tmpreg, regstr, regstr);
912         break;
913     case WINED3DSPSM_DZ:
914         shader_addline(buffer, "RCP T%c, %s.z;\n", 'A' + tmpreg, regstr);
915         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
916         break;
917     case WINED3DSPSM_DW:
918         shader_addline(buffer, "RCP T%c, %s.w;\n", 'A' + tmpreg, regstr);
919         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
920         break;
921     default:
922         sprintf(outregstr, "%s%s", regstr, swzstr);
923         insert_line = 0;
924     }
925
926     /* Return modified or original register, with swizzle */
927     if (insert_line)
928         sprintf(outregstr, "T%c%s", 'A' + tmpreg, swzstr);
929 }
930
931 static inline void pshader_gen_output_modifier_line(
932     SHADER_BUFFER* buffer,
933     int saturate,
934     char *write_mask,
935     int shift,
936     char *regstr) {
937
938     /* Generate a line that does the output modifier computation */
939     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", saturate ? "_SAT" : "",
940         regstr, write_mask, regstr, shift_tab[shift]);
941 }
942
943 void pshader_hw_bem(SHADER_OPCODE_ARG* arg) {
944     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
945
946     SHADER_BUFFER* buffer = arg->buffer;
947     char dst_name[50];
948     char src_name[2][50];
949     char dst_wmask[20];
950     DWORD sampler_code = arg->dst & WINED3DSP_REGNUM_MASK;
951     BOOL has_bumpmat = FALSE;
952     int i;
953
954     for(i = 0; i < This->numbumpenvmatconsts; i++) {
955         if(This->bumpenvmatconst[i].const_num != -1 && This->bumpenvmatconst[i].texunit == sampler_code) {
956             has_bumpmat = TRUE;
957             break;
958         }
959     }
960
961     pshader_get_register_name(arg->shader, arg->dst, dst_name);
962     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
963     strcat(dst_name, dst_wmask);
964
965     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
966     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
967
968     if(has_bumpmat) {
969         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
970         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", sampler_code);
971         shader_addline(buffer, "DP3 TMP.r, TMP2, %s;\n", src_name[1]);
972         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", sampler_code);
973         shader_addline(buffer, "DP3 TMP.g, TMP2, %s;\n", src_name[1]);
974
975         shader_addline(buffer, "ADD %s, %s, TMP;\n", dst_name, src_name[0]);
976     } else {
977         shader_addline(buffer, "MOV %s, %s;\n", dst_name, src_name[0]);
978     }
979 }
980
981 void pshader_hw_cnd(SHADER_OPCODE_ARG* arg) {
982
983     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
984     SHADER_BUFFER* buffer = arg->buffer;
985     char dst_wmask[20];
986     char dst_name[50];
987     char src_name[3][50];
988     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
989     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
990
991     /* FIXME: support output modifiers */
992
993     /* Handle output register */
994     pshader_get_register_name(arg->shader, arg->dst, dst_name);
995     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
996
997     /* Generate input register names (with modifiers) */
998     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
999     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
1000     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
1001
1002     /* The coissue flag changes the semantic of the cnd instruction in <= 1.3 shaders */
1003     if (shader->baseShader.hex_version <= WINED3DPS_VERSION(1, 3) &&
1004         arg->opcode_token & WINED3DSI_COISSUE) {
1005         shader_addline(buffer, "MOV%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1]);
1006     } else {
1007         shader_addline(buffer, "ADD TMP, -%s, coefdiv.x;\n", src_name[0]);
1008         shader_addline(buffer, "CMP%s %s%s, TMP, %s, %s;\n",
1009                                 sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1], src_name[2]);
1010     }
1011     if (shift != 0)
1012         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1013 }
1014
1015 void pshader_hw_cmp(SHADER_OPCODE_ARG* arg) {
1016
1017     SHADER_BUFFER* buffer = arg->buffer;
1018     char dst_wmask[20];
1019     char dst_name[50];
1020     char src_name[3][50];
1021     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1022     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1023
1024     /* FIXME: support output modifiers */
1025
1026     /* Handle output register */
1027     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1028     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1029
1030     /* Generate input register names (with modifiers) */
1031     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
1032     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
1033     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
1034
1035     shader_addline(buffer, "CMP%s %s%s, %s, %s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1036                    src_name[0], src_name[2], src_name[1]);
1037
1038     if (shift != 0)
1039         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1040 }
1041
1042 /** Process the WINED3DSIO_DP2ADD instruction in ARB.
1043  * dst = dot2(src0, src1) + src2 */
1044 void pshader_hw_dp2add(SHADER_OPCODE_ARG* arg) {
1045     SHADER_BUFFER* buffer = arg->buffer;
1046     char dst_wmask[20];
1047     char dst_name[50];
1048     char src_name[3][50];
1049     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1050     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1051
1052     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1053     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1054
1055     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
1056     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
1057     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
1058
1059     /* Emulate a DP2 with a DP3 and 0.0 */
1060     shader_addline(buffer, "MOV TMP, %s;\n", src_name[0]);
1061     shader_addline(buffer, "MOV TMP.z, 0.0;\n");
1062     shader_addline(buffer, "DP3 TMP2, TMP, %s;\n", src_name[1]);
1063     shader_addline(buffer, "ADD%s %s%s, TMP2, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[2]);
1064
1065     if (shift != 0)
1066         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1067 }
1068
1069 /* Map the opcode 1-to-1 to the GL code */
1070 void pshader_hw_map2gl(SHADER_OPCODE_ARG* arg) {
1071
1072      CONST SHADER_OPCODE* curOpcode = arg->opcode;
1073      SHADER_BUFFER* buffer = arg->buffer;
1074      DWORD dst = arg->dst;
1075      DWORD* src = arg->src;
1076
1077      unsigned int i;
1078      char tmpLine[256];
1079
1080      /* Output token related */
1081      char output_rname[256];
1082      char output_wmask[20];
1083      BOOL saturate = FALSE;
1084      BOOL centroid = FALSE;
1085      BOOL partialprecision = FALSE;
1086      DWORD shift;
1087
1088      strcpy(tmpLine, curOpcode->glname);
1089
1090      /* Process modifiers */
1091      if (0 != (dst & WINED3DSP_DSTMOD_MASK)) {
1092          DWORD mask = dst & WINED3DSP_DSTMOD_MASK;
1093
1094          saturate = mask & WINED3DSPDM_SATURATE;
1095          centroid = mask & WINED3DSPDM_MSAMPCENTROID;
1096          partialprecision = mask & WINED3DSPDM_PARTIALPRECISION;
1097          mask &= ~(WINED3DSPDM_MSAMPCENTROID | WINED3DSPDM_PARTIALPRECISION | WINED3DSPDM_SATURATE);
1098          if (mask)
1099             FIXME("Unrecognized modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
1100
1101          if (centroid)
1102              FIXME("Unhandled modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
1103      }
1104      shift = (dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1105
1106       /* Generate input and output registers */
1107       if (curOpcode->num_params > 0) {
1108           char operands[4][100];
1109
1110           /* Generate input register names (with modifiers) */
1111           for (i = 1; i < curOpcode->num_params; ++i)
1112               pshader_gen_input_modifier_line(arg->shader, buffer, src[i-1], i-1, operands[i]);
1113
1114           /* Handle output register */
1115           pshader_get_register_name(arg->shader, dst, output_rname);
1116           strcpy(operands[0], output_rname);
1117           shader_arb_get_write_mask(arg, dst, output_wmask);
1118           strcat(operands[0], output_wmask);
1119
1120           if (saturate && (shift == 0))
1121              strcat(tmpLine, "_SAT");
1122           strcat(tmpLine, " ");
1123           strcat(tmpLine, operands[0]);
1124           for (i = 1; i < curOpcode->num_params; i++) {
1125               strcat(tmpLine, ", ");
1126               strcat(tmpLine, operands[i]);
1127           }
1128           strcat(tmpLine,";\n");
1129           shader_addline(buffer, tmpLine);
1130
1131           /* A shift requires another line. */
1132           if (shift != 0)
1133               pshader_gen_output_modifier_line(buffer, saturate, output_wmask, shift, output_rname);
1134       }
1135 }
1136
1137 void pshader_hw_texkill(SHADER_OPCODE_ARG* arg) {
1138     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1139     DWORD hex_version = This->baseShader.hex_version;
1140     SHADER_BUFFER* buffer = arg->buffer;
1141     char reg_dest[40];
1142
1143     /* No swizzles are allowed in d3d's texkill. PS 1.x ignores the 4th component as documented,
1144      * but >= 2.0 honors it(undocumented, but tested by the d3d9 testsuit)
1145      */
1146     pshader_get_register_name(arg->shader, arg->dst, reg_dest);
1147
1148     if(hex_version >= WINED3DPS_VERSION(2,0)) {
1149         /* The arb backend doesn't claim ps 2.0 support, but try to eat what the app feeds to us */
1150         shader_addline(buffer, "KIL %s;\n", reg_dest);
1151     } else {
1152         /* ARB fp doesn't like swizzles on the parameter of the KIL instruction. To mask the 4th component,
1153          * copy the register into our general purpose TMP variable, overwrite .w and pass TMP to KIL
1154          */
1155         shader_addline(buffer, "MOV TMP, %s;\n", reg_dest);
1156         shader_addline(buffer, "MOV TMP.w, one.w;\n");
1157         shader_addline(buffer, "KIL TMP;\n");
1158     }
1159 }
1160
1161 void pshader_hw_tex(SHADER_OPCODE_ARG* arg) {
1162     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1163     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1164
1165     DWORD dst = arg->dst;
1166     DWORD* src = arg->src;
1167     SHADER_BUFFER* buffer = arg->buffer;
1168     DWORD hex_version = This->baseShader.hex_version;
1169     BOOL projected = FALSE, bias = FALSE;
1170
1171     char reg_dest[40];
1172     char reg_coord[40];
1173     DWORD reg_dest_code;
1174     DWORD reg_sampler_code;
1175
1176     /* All versions have a destination register */
1177     reg_dest_code = dst & WINED3DSP_REGNUM_MASK;
1178     pshader_get_register_name(arg->shader, dst, reg_dest);
1179
1180     /* 1.0-1.3: Use destination register as coordinate source.
1181        1.4+: Use provided coordinate source register. */
1182    if (hex_version < WINED3DPS_VERSION(1,4))
1183       strcpy(reg_coord, reg_dest);
1184    else
1185       pshader_gen_input_modifier_line(arg->shader, buffer, src[0], 0, reg_coord);
1186
1187   /* 1.0-1.4: Use destination register number as texture code.
1188      2.0+: Use provided sampler number as texure code. */
1189   if (hex_version < WINED3DPS_VERSION(2,0))
1190      reg_sampler_code = reg_dest_code;
1191   else
1192      reg_sampler_code = src[1] & WINED3DSP_REGNUM_MASK;
1193
1194   /* projection flag:
1195    * 1.1, 1.2, 1.3: Use WINED3DTSS_TEXTURETRANSFORMFLAGS
1196    * 1.4: Use WINED3DSPSM_DZ or WINED3DSPSM_DW on src[0]
1197    * 2.0+: Use WINED3DSI_TEXLD_PROJECT on the opcode
1198    */
1199   if(hex_version < WINED3DPS_VERSION(1,4)) {
1200       DWORD flags = 0;
1201       if(reg_sampler_code < MAX_TEXTURES) {
1202         flags = deviceImpl->stateBlock->textureState[reg_sampler_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1203       }
1204       if (flags & WINED3DTTFF_PROJECTED) {
1205           projected = TRUE;
1206       }
1207   } else if(hex_version < WINED3DPS_VERSION(2,0)) {
1208       DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1209       if (src_mod == WINED3DSPSM_DZ) {
1210           projected = TRUE;
1211       } else if(src_mod == WINED3DSPSM_DW) {
1212           projected = TRUE;
1213       }
1214   } else {
1215       if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
1216           projected = TRUE;
1217       }
1218       if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
1219           bias = TRUE;
1220       }
1221   }
1222   shader_hw_sample(arg, reg_sampler_code, reg_dest, reg_coord, projected, bias);
1223 }
1224
1225 void pshader_hw_texcoord(SHADER_OPCODE_ARG* arg) {
1226
1227     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1228     DWORD dst = arg->dst;
1229     SHADER_BUFFER* buffer = arg->buffer;
1230     DWORD hex_version = This->baseShader.hex_version;
1231
1232     char tmp[20];
1233     shader_arb_get_write_mask(arg, dst, tmp);
1234     if (hex_version != WINED3DPS_VERSION(1,4)) {
1235         DWORD reg = dst & WINED3DSP_REGNUM_MASK;
1236         shader_addline(buffer, "MOV_SAT T%u%s, fragment.texcoord[%u];\n", reg, tmp, reg);
1237     } else {
1238         DWORD reg1 = dst & WINED3DSP_REGNUM_MASK;
1239         char reg_src[40];
1240
1241         pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, reg_src);
1242         shader_addline(buffer, "MOV R%u%s, %s;\n", reg1, tmp, reg_src);
1243    }
1244 }
1245
1246 void pshader_hw_texreg2ar(SHADER_OPCODE_ARG* arg) {
1247
1248      SHADER_BUFFER* buffer = arg->buffer;
1249      IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1250      IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1251      DWORD flags;
1252
1253      DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1254      char dst_str[8];
1255      char src_str[50];
1256
1257      sprintf(dst_str, "T%u", reg1);
1258      pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1259      shader_addline(buffer, "MOV TMP.r, %s.a;\n", src_str);
1260      shader_addline(buffer, "MOV TMP.g, %s.r;\n", src_str);
1261      flags = reg1 < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg1][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1262      shader_hw_sample(arg, reg1, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1263 }
1264
1265 void pshader_hw_texreg2gb(SHADER_OPCODE_ARG* arg) {
1266
1267      SHADER_BUFFER* buffer = arg->buffer;
1268
1269      DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1270      char dst_str[8];
1271      char src_str[50];
1272
1273      sprintf(dst_str, "T%u", reg1);
1274      pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1275      shader_addline(buffer, "MOV TMP.r, %s.g;\n", src_str);
1276      shader_addline(buffer, "MOV TMP.g, %s.b;\n", src_str);
1277      shader_hw_sample(arg, reg1, dst_str, "TMP", FALSE, FALSE);
1278 }
1279
1280 void pshader_hw_texreg2rgb(SHADER_OPCODE_ARG* arg) {
1281
1282     SHADER_BUFFER* buffer = arg->buffer;
1283     DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1284     char dst_str[8];
1285     char src_str[50];
1286
1287     sprintf(dst_str, "T%u", reg1);
1288     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1289     shader_hw_sample(arg, reg1, dst_str, src_str, FALSE, FALSE);
1290 }
1291
1292 void pshader_hw_texbem(SHADER_OPCODE_ARG* arg) {
1293     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1294     BOOL has_bumpmat = FALSE;
1295     BOOL has_luminance = FALSE;
1296     int i;
1297
1298     DWORD dst = arg->dst;
1299     DWORD src = arg->src[0] & WINED3DSP_REGNUM_MASK;
1300     SHADER_BUFFER* buffer = arg->buffer;
1301
1302     char reg_coord[40];
1303     DWORD reg_dest_code;
1304
1305     /* All versions have a destination register */
1306     reg_dest_code = dst & WINED3DSP_REGNUM_MASK;
1307     /* Can directly use the name because texbem is only valid for <= 1.3 shaders */
1308     pshader_get_register_name(arg->shader, dst, reg_coord);
1309
1310     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1311         if(This->bumpenvmatconst[i].const_num != -1 && reg_dest_code == This->bumpenvmatconst[i].texunit) {
1312             has_bumpmat = TRUE;
1313             break;
1314         }
1315     }
1316     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1317         if(This->luminanceconst[i].const_num != -1 && reg_dest_code == This->luminanceconst[i].texunit) {
1318             has_luminance = TRUE;
1319             break;
1320         }
1321     }
1322
1323     if(has_bumpmat) {
1324         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
1325
1326         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", reg_dest_code);
1327         shader_addline(buffer, "DP3 TMP.r, TMP2, T%u;\n", src);
1328         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", reg_dest_code);
1329         shader_addline(buffer, "DP3 TMP.g, TMP2, T%u;\n", src);
1330
1331         /* with projective textures, texbem only divides the static texture coord, not the displacement,
1332          * so we can't let the GL handle this.
1333          */
1334         if (((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS]
1335               & WINED3DTTFF_PROJECTED) {
1336             shader_addline(buffer, "RCP TMP2.a, %s.a;\n", reg_coord);
1337             shader_addline(buffer, "MUL TMP2.rg, %s, TMP2.a;\n", reg_coord);
1338             shader_addline(buffer, "ADD TMP.rg, TMP, TMP2;\n");
1339         } else {
1340             shader_addline(buffer, "ADD TMP.rg, TMP, %s;\n", reg_coord);
1341         }
1342
1343         shader_hw_sample(arg, reg_dest_code, reg_coord, "TMP", FALSE, FALSE);
1344
1345         if(arg->opcode->opcode == WINED3DSIO_TEXBEML && has_luminance) {
1346             shader_addline(buffer, "MAD TMP, T%u.z, luminance%d.x, luminance%d.y;\n",
1347                            src, reg_dest_code, reg_dest_code);
1348             shader_addline(buffer, "MUL %s, %s, TMP;\n", reg_coord, reg_coord);
1349         }
1350
1351     } else {
1352         DWORD tf;
1353         if(reg_dest_code < MAX_TEXTURES) {
1354             tf = ((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1355         } else {
1356             tf = 0;
1357         }
1358         /* Without a bump matrix loaded, just sample with the unmodified coordinates */
1359         shader_hw_sample(arg, reg_dest_code, reg_coord, reg_coord, tf & WINED3DTTFF_PROJECTED, FALSE);
1360     }
1361 }
1362
1363 void pshader_hw_texm3x2pad(SHADER_OPCODE_ARG* arg) {
1364
1365     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1366     SHADER_BUFFER* buffer = arg->buffer;
1367     char src0_name[50];
1368
1369     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1370     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", reg, src0_name);
1371 }
1372
1373 void pshader_hw_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1374
1375     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1376     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1377     DWORD flags;
1378     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1379     SHADER_BUFFER* buffer = arg->buffer;
1380     char dst_str[8];
1381     char src0_name[50];
1382
1383     sprintf(dst_str, "T%u", reg);
1384     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1385     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", reg, src0_name);
1386     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1387     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1388 }
1389
1390 void pshader_hw_texm3x3pad(SHADER_OPCODE_ARG* arg) {
1391
1392     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1393     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1394     SHADER_BUFFER* buffer = arg->buffer;
1395     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1396     char src0_name[50];
1397
1398     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1399     shader_addline(buffer, "DP3 TMP.%c, T%u, %s;\n", 'x' + current_state->current_row, reg, src0_name);
1400     current_state->texcoord_w[current_state->current_row++] = reg;
1401 }
1402
1403 void pshader_hw_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1404
1405     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1406     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1407     DWORD flags;
1408     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1409     SHADER_BUFFER* buffer = arg->buffer;
1410     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1411     char dst_str[8];
1412     char src0_name[50];
1413
1414     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1415     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1416
1417     /* Sample the texture using the calculated coordinates */
1418     sprintf(dst_str, "T%u", reg);
1419     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1420     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1421     current_state->current_row = 0;
1422 }
1423
1424 void pshader_hw_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
1425
1426     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1427     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1428     DWORD flags;
1429     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1430     SHADER_BUFFER* buffer = arg->buffer;
1431     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1432     char dst_str[8];
1433     char src0_name[50];
1434
1435     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1436     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1437
1438     /* Construct the eye-ray vector from w coordinates */
1439     shader_addline(buffer, "MOV TMP2.x, fragment.texcoord[%u].w;\n", current_state->texcoord_w[0]);
1440     shader_addline(buffer, "MOV TMP2.y, fragment.texcoord[%u].w;\n", current_state->texcoord_w[1]);
1441     shader_addline(buffer, "MOV TMP2.z, fragment.texcoord[%u].w;\n", reg);
1442
1443     /* Calculate reflection vector
1444      */
1445     shader_addline(buffer, "DP3 TMP.w, TMP, TMP2;\n");
1446     /* The .w is ignored when sampling, so I can use TMP2.w to calculate dot(N, N) */
1447     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1448     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1449     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1450     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1451     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -TMP2;\n");
1452
1453     /* Sample the texture using the calculated coordinates */
1454     sprintf(dst_str, "T%u", reg);
1455     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1456     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1457     current_state->current_row = 0;
1458 }
1459
1460 void pshader_hw_texm3x3spec(SHADER_OPCODE_ARG* arg) {
1461
1462     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1463     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1464     DWORD flags;
1465     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1466     DWORD reg3 = arg->src[1] & WINED3DSP_REGNUM_MASK;
1467     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1468     SHADER_BUFFER* buffer = arg->buffer;
1469     char dst_str[8];
1470     char src0_name[50];
1471
1472     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1473     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1474
1475     /* Calculate reflection vector.
1476      *
1477      *               dot(N, E)
1478      * TMP.xyz = 2 * --------- * N - E
1479      *               dot(N, N)
1480      *
1481      * Which normalizes the normal vector
1482      */
1483     shader_addline(buffer, "DP3 TMP.w, TMP, C[%u];\n", reg3);
1484     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1485     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1486     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1487     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1488     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -C[%u];\n", reg3);
1489
1490     /* Sample the texture using the calculated coordinates */
1491     sprintf(dst_str, "T%u", reg);
1492     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1493     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1494     current_state->current_row = 0;
1495 }
1496
1497 void pshader_hw_texdepth(SHADER_OPCODE_ARG* arg) {
1498     SHADER_BUFFER* buffer = arg->buffer;
1499     char dst_name[50];
1500
1501     /* texdepth has an implicit destination, the fragment depth value. It's only parameter,
1502      * which is essentially an input, is the destination register because it is the first
1503      * parameter. According to the msdn, this must be register r5, but let's keep it more flexible
1504      * here
1505      */
1506     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1507
1508     /* According to the msdn, the source register(must be r5) is unusable after
1509      * the texdepth instruction, so we're free to modify it
1510      */
1511     shader_addline(buffer, "MIN %s.g, %s.g, one.g;\n", dst_name, dst_name);
1512
1513     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1514      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1515      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1516      */
1517     shader_addline(buffer, "RCP %s.g, %s.g;\n", dst_name, dst_name);
1518     shader_addline(buffer, "MUL TMP.x, %s.r, %s.g;\n", dst_name, dst_name);
1519     shader_addline(buffer, "MIN TMP.x, TMP.x, one.r;\n");
1520     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1521 }
1522
1523 /** Process the WINED3DSIO_TEXDP3TEX instruction in ARB:
1524  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1525  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1526 void pshader_hw_texdp3tex(SHADER_OPCODE_ARG* arg) {
1527     SHADER_BUFFER* buffer = arg->buffer;
1528     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1529     char src0[50];
1530     char dst_str[8];
1531
1532     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1533     shader_addline(buffer, "MOV TMP, 0.0;\n");
1534     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", sampler_idx, src0);
1535
1536     sprintf(dst_str, "T%u", sampler_idx);
1537     shader_hw_sample(arg, sampler_idx, dst_str, "TMP", FALSE /* Only one coord, can't be projected */, FALSE);
1538 }
1539
1540 /** Process the WINED3DSIO_TEXDP3 instruction in ARB:
1541  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1542 void pshader_hw_texdp3(SHADER_OPCODE_ARG* arg) {
1543     char src0[50];
1544     char dst_str[50];
1545     char dst_mask[6];
1546     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1547     SHADER_BUFFER* buffer = arg->buffer;
1548
1549     /* Handle output register */
1550     pshader_get_register_name(arg->shader, arg->dst, dst_str);
1551     shader_arb_get_write_mask(arg, arg->dst, dst_mask);
1552
1553     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1554     shader_addline(buffer, "DP3 %s%s, T%u, %s;\n", dst_str, dst_mask, dstreg, src0);
1555
1556     /* TODO: Handle output modifiers */
1557 }
1558
1559 /** Process the WINED3DSIO_TEXM3X3 instruction in ARB
1560  * Perform the 3rd row of a 3x3 matrix multiply */
1561 void pshader_hw_texm3x3(SHADER_OPCODE_ARG* arg) {
1562     SHADER_BUFFER* buffer = arg->buffer;
1563     char dst_str[50];
1564     char dst_mask[6];
1565     char src0[50];
1566     DWORD dst_reg = arg->dst & WINED3DSP_REGNUM_MASK;
1567
1568     pshader_get_register_name(arg->shader, arg->dst, dst_str);
1569     shader_arb_get_write_mask(arg, arg->dst, dst_mask);
1570
1571     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1572     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", dst_reg, src0);
1573     shader_addline(buffer, "MOV %s%s, TMP;\n", dst_str, dst_mask);
1574
1575     /* TODO: Handle output modifiers */
1576 }
1577
1578 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in ARB:
1579  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1580  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1581  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1582  */
1583 void pshader_hw_texm3x2depth(SHADER_OPCODE_ARG* arg) {
1584     SHADER_BUFFER* buffer = arg->buffer;
1585     DWORD dst_reg = arg->dst & WINED3DSP_REGNUM_MASK;
1586     char src0[50];
1587
1588     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1589     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", dst_reg, src0);
1590
1591     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1592      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1593      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1594      */
1595     shader_addline(buffer, "RCP TMP.y, TMP.y;\n");
1596     shader_addline(buffer, "MUL TMP.x, TMP.x, TMP.y;\n");
1597     shader_addline(buffer, "MIN TMP.x, TMP.x, one.r;\n");
1598     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1599 }
1600
1601 /** Handles transforming all WINED3DSIO_M?x? opcodes for
1602     Vertex/Pixel shaders to ARB_vertex_program codes */
1603 void shader_hw_mnxn(SHADER_OPCODE_ARG* arg) {
1604
1605     int i;
1606     int nComponents = 0;
1607     SHADER_OPCODE_ARG tmpArg;
1608
1609     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1610
1611     /* Set constants for the temporary argument */
1612     tmpArg.shader      = arg->shader;
1613     tmpArg.buffer      = arg->buffer;
1614     tmpArg.src[0]      = arg->src[0];
1615     tmpArg.src_addr[0] = arg->src_addr[0];
1616     tmpArg.src_addr[1] = arg->src_addr[1];
1617     tmpArg.reg_maps = arg->reg_maps;
1618
1619     switch(arg->opcode->opcode) {
1620     case WINED3DSIO_M4x4:
1621         nComponents = 4;
1622         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1623         break;
1624     case WINED3DSIO_M4x3:
1625         nComponents = 3;
1626         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1627         break;
1628     case WINED3DSIO_M3x4:
1629         nComponents = 4;
1630         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1631         break;
1632     case WINED3DSIO_M3x3:
1633         nComponents = 3;
1634         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1635         break;
1636     case WINED3DSIO_M3x2:
1637         nComponents = 2;
1638         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1639         break;
1640     default:
1641         break;
1642     }
1643
1644     for (i = 0; i < nComponents; i++) {
1645         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1646         tmpArg.src[1] = arg->src[1]+i;
1647         vshader_hw_map2gl(&tmpArg);
1648     }
1649 }
1650
1651 void vshader_hw_rsq_rcp(SHADER_OPCODE_ARG* arg) {
1652     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1653     SHADER_BUFFER* buffer = arg->buffer;
1654     DWORD dst = arg->dst;
1655     DWORD src = arg->src[0];
1656     DWORD swizzle = (src & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
1657
1658     char tmpLine[256];
1659
1660     strcpy(tmpLine, curOpcode->glname); /* Opcode */
1661     vshader_program_add_param(arg, dst, FALSE, tmpLine); /* Destination */
1662     strcat(tmpLine, ",");
1663     vshader_program_add_param(arg, src, TRUE, tmpLine);
1664     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) == swizzle) {
1665         /* Dx sdk says .x is used if no swizzle is given, but our test shows that
1666          * .w is used
1667          */
1668         strcat(tmpLine, ".w");
1669     }
1670
1671     shader_addline(buffer, "%s;\n", tmpLine);
1672 }
1673
1674 void shader_hw_nrm(SHADER_OPCODE_ARG* arg) {
1675     SHADER_BUFFER* buffer = arg->buffer;
1676     char dst_name[50];
1677     char src_name[50];
1678     char dst_wmask[20];
1679     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1680     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1681
1682     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1683     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1684
1685     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name);
1686     shader_addline(buffer, "DP3 TMP, %s, %s;\n", src_name, src_name);
1687     shader_addline(buffer, "RSQ TMP, TMP.x;\n");
1688     /* dst.w = src[0].w * 1 / (src.x^2 + src.y^2 + src.z^2)^(1/2) according to msdn*/
1689     shader_addline(buffer, "MUL%s %s%s, %s, TMP;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1690                    src_name);
1691
1692     if (shift != 0)
1693         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1694 }
1695
1696 void shader_hw_sincos(SHADER_OPCODE_ARG* arg) {
1697     /* This instruction exists in ARB, but the d3d instruction takes two extra parameters which
1698      * must contain fixed constants. So we need a separate function to filter those constants and
1699      * can't use map2gl
1700      */
1701     SHADER_BUFFER* buffer = arg->buffer;
1702     char dst_name[50];
1703     char src_name[50];
1704     char dst_wmask[20];
1705     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1706     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1707
1708     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1709     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1710
1711     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name);
1712     shader_addline(buffer, "SCS%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1713                    src_name);
1714
1715     if (shift != 0)
1716         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1717
1718 }
1719
1720 /* TODO: merge with pixel shader */
1721 /* Map the opcode 1-to-1 to the GL code */
1722 void vshader_hw_map2gl(SHADER_OPCODE_ARG* arg) {
1723
1724     IWineD3DVertexShaderImpl *shader = (IWineD3DVertexShaderImpl*) arg->shader;
1725     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1726     SHADER_BUFFER* buffer = arg->buffer;
1727     DWORD dst = arg->dst;
1728     DWORD* src = arg->src;
1729
1730     DWORD dst_regtype = shader_get_regtype(dst);
1731     char tmpLine[256];
1732     unsigned int i;
1733
1734     if ((curOpcode->opcode == WINED3DSIO_MOV && dst_regtype == WINED3DSPR_ADDR) || curOpcode->opcode == WINED3DSIO_MOVA) {
1735         memset(tmpLine, 0, sizeof(tmpLine));
1736         if(shader->rel_offset) {
1737             vshader_program_add_param(arg, src[0], TRUE, tmpLine);
1738             shader_addline(buffer, "ADD TMP.x, %s, helper_const.z;\n", tmpLine);
1739             shader_addline(buffer, "ARL A0.x, TMP.x;\n");
1740         } else {
1741             /* Apple's ARB_vertex_program implementation does not accept an ARL source argument
1742              * with more than one component. Thus replicate the first source argument over all
1743              * 4 components. For example, .xyzw -> .x (or better: .xxxx), .zwxy -> .z, etc)
1744              */
1745             DWORD parm = src[0] & ~(WINED3DVS_SWIZZLE_MASK);
1746                    if((src[0] & WINED3DVS_X_W) == WINED3DVS_X_W) {
1747                 parm |= WINED3DVS_X_W | WINED3DVS_Y_W | WINED3DVS_Z_W | WINED3DVS_W_W;
1748             } else if((src[0] & WINED3DVS_X_Z) == WINED3DVS_X_Z) {
1749                 parm |= WINED3DVS_X_Z | WINED3DVS_Y_Z | WINED3DVS_Z_Z | WINED3DVS_W_Z;
1750             } else if((src[0] & WINED3DVS_X_Y) == WINED3DVS_X_Y) {
1751                 parm |= WINED3DVS_X_Y | WINED3DVS_Y_Y | WINED3DVS_Z_Y | WINED3DVS_W_Y;
1752             } else if((src[0] & WINED3DVS_X_X) == WINED3DVS_X_X) {
1753                 parm |= WINED3DVS_X_X | WINED3DVS_Y_X | WINED3DVS_Z_X | WINED3DVS_W_X;
1754             }
1755             vshader_program_add_param(arg, parm, TRUE, tmpLine);
1756             shader_addline(buffer, "ARL A0.x, %s;\n", tmpLine);
1757         }
1758         return;
1759     } else
1760         strcpy(tmpLine, curOpcode->glname);
1761
1762     if (curOpcode->num_params > 0) {
1763         vshader_program_add_param(arg, dst, FALSE, tmpLine);
1764         for (i = 1; i < curOpcode->num_params; ++i) {
1765            strcat(tmpLine, ",");
1766            vshader_program_add_param(arg, src[i-1], TRUE, tmpLine);
1767         }
1768     }
1769    shader_addline(buffer, "%s;\n", tmpLine);
1770 }
1771
1772 static GLuint create_arb_blt_vertex_program(WineD3D_GL_Info *gl_info) {
1773     GLuint program_id = 0;
1774     const char *blt_vprogram =
1775         "!!ARBvp1.0\n"
1776         "PARAM c[1] = { { 1, 0.5 } };\n"
1777         "MOV result.position, vertex.position;\n"
1778         "MOV result.color, c[0].x;\n"
1779         "MAD result.texcoord[0].y, -vertex.position, c[0], c[0];\n"
1780         "MAD result.texcoord[0].x, vertex.position, c[0].y, c[0].y;\n"
1781         "END\n";
1782
1783     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1784     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, program_id));
1785     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_vprogram), blt_vprogram));
1786
1787     if (glGetError() == GL_INVALID_OPERATION) {
1788         GLint pos;
1789         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1790         FIXME("Vertex program error at position %d: %s\n", pos,
1791             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1792     }
1793
1794     return program_id;
1795 }
1796
1797 static GLuint create_arb_blt_fragment_program(WineD3D_GL_Info *gl_info) {
1798     GLuint program_id = 0;
1799     const char *blt_fprogram =
1800         "!!ARBfp1.0\n"
1801         "TEMP R0;\n"
1802         "TEX R0.x, fragment.texcoord[0], texture[0], 2D;\n"
1803         "MOV result.depth.z, R0.x;\n"
1804         "END\n";
1805
1806     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1807     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
1808     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_fprogram), blt_fprogram));
1809
1810     if (glGetError() == GL_INVALID_OPERATION) {
1811         GLint pos;
1812         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1813         FIXME("Fragment program error at position %d: %s\n", pos,
1814             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1815     }
1816
1817     return program_id;
1818 }
1819
1820 static void shader_arb_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
1821     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1822     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1823     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1824
1825     if (useVS) {
1826         TRACE("Using vertex shader\n");
1827
1828         priv->current_vprogram_id = ((IWineD3DVertexShaderImpl *)This->stateBlock->vertexShader)->baseShader.prgId;
1829
1830         /* Bind the vertex program */
1831         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
1832         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
1833
1834         /* Enable OpenGL vertex programs */
1835         glEnable(GL_VERTEX_PROGRAM_ARB);
1836         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
1837         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
1838     } else if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
1839         priv->current_vprogram_id = 0;
1840         glDisable(GL_VERTEX_PROGRAM_ARB);
1841         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
1842     }
1843
1844     if (usePS) {
1845         TRACE("Using pixel shader\n");
1846
1847         priv->current_fprogram_id = ((IWineD3DPixelShaderImpl *)This->stateBlock->pixelShader)->baseShader.prgId;
1848
1849         /* Bind the fragment program */
1850         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
1851         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
1852
1853         /* Enable OpenGL fragment programs */
1854         glEnable(GL_FRAGMENT_PROGRAM_ARB);
1855         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
1856         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
1857     } else {
1858         priv->current_fprogram_id = 0;
1859
1860         if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && !priv->use_arbfp_fixed_func) {
1861             /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
1862              * keep GL_FRAGMENT_PROGRAM_ARB enabled, and the fixed function pipeline will bind the fixed function
1863              * replacement shader
1864              */
1865             glDisable(GL_FRAGMENT_PROGRAM_ARB);
1866             checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
1867         }
1868     }
1869 }
1870
1871 static void shader_arb_select_depth_blt(IWineD3DDevice *iface) {
1872     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1873     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1874     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1875
1876     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
1877     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
1878     glEnable(GL_VERTEX_PROGRAM_ARB);
1879
1880     if (!priv->depth_blt_fprogram_id) priv->depth_blt_fprogram_id = create_arb_blt_fragment_program(gl_info);
1881     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->depth_blt_fprogram_id));
1882     glEnable(GL_FRAGMENT_PROGRAM_ARB);
1883 }
1884
1885 static void shader_arb_deselect_depth_blt(IWineD3DDevice *iface) {
1886     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1887     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1888     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1889
1890     if (priv->current_vprogram_id) {
1891         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
1892         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
1893
1894         glEnable(GL_VERTEX_PROGRAM_ARB);
1895         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
1896
1897         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
1898     } else {
1899         glDisable(GL_VERTEX_PROGRAM_ARB);
1900         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
1901     }
1902
1903     if (priv->current_fprogram_id) {
1904         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
1905         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
1906
1907         glEnable(GL_FRAGMENT_PROGRAM_ARB);
1908         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
1909
1910         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
1911     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1912         glDisable(GL_FRAGMENT_PROGRAM_ARB);
1913         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
1914     }
1915 }
1916
1917 static void shader_arb_cleanup(IWineD3DDevice *iface) {
1918     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1919     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1920     if (GL_SUPPORT(ARB_VERTEX_PROGRAM)) glDisable(GL_VERTEX_PROGRAM_ARB);
1921     if (GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) glDisable(GL_FRAGMENT_PROGRAM_ARB);
1922 }
1923
1924 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
1925     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
1926     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *) This->baseShader.device)->adapter->gl_info;
1927
1928     ENTER_GL();
1929     GL_EXTCALL(glDeleteProgramsARB(1, &This->baseShader.prgId));
1930     checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &This->baseShader.prgId))");
1931     LEAVE_GL();
1932     This->baseShader.prgId = 0;
1933     This->baseShader.is_compiled = FALSE;
1934 }
1935
1936 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
1937     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1938     This->shader_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
1939     return WINED3D_OK;
1940 }
1941
1942 static void shader_arb_free(IWineD3DDevice *iface) {
1943     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1944     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1945     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1946
1947     if(priv->depth_blt_vprogram_id) {
1948         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
1949     }
1950     if(priv->depth_blt_fprogram_id) {
1951         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id));
1952     }
1953
1954     HeapFree(GetProcessHeap(), 0, This->shader_priv);
1955 }
1956
1957 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
1958     return TRUE;
1959 }
1960
1961 static void shader_arb_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer) {
1962     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
1963     shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
1964     CONST DWORD *function = This->baseShader.function;
1965     const char *fragcolor;
1966     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
1967     local_constant* lconst;
1968
1969     /*  Create the hw ARB shader */
1970     shader_addline(buffer, "!!ARBfp1.0\n");
1971
1972     shader_addline(buffer, "TEMP TMP;\n");     /* Used in matrix ops */
1973     shader_addline(buffer, "TEMP TMP2;\n");    /* Used in matrix ops */
1974     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
1975     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
1976     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
1977     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
1978     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
1979     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
1980
1981     /* Base Declarations */
1982     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
1983
1984     /* We need two variables for fog blending */
1985     shader_addline(buffer, "TEMP TMP_FOG;\n");
1986     if (This->baseShader.hex_version >= WINED3DPS_VERSION(2,0)) {
1987         shader_addline(buffer, "TEMP TMP_COLOR;\n");
1988     }
1989
1990     /* Base Shader Body */
1991     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
1992
1993     /* calculate fog and blend it
1994      * NOTE: state.fog.params.y and state.fog.params.z don't hold fog start s and end e but
1995      * -1/(e-s) and e/(e-s) respectively.
1996      */
1997     shader_addline(buffer, "MAD_SAT TMP_FOG, fragment.fogcoord, state.fog.params.y, state.fog.params.z;\n");
1998
1999     if (This->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
2000         fragcolor = "R0";
2001     } else {
2002         fragcolor = "TMP_COLOR";
2003     }
2004     if(This->srgb_enabled) {
2005         /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
2006
2007         /* Calculate the > 0.0031308 case */
2008         shader_addline(buffer, "POW TMP.x, %s.x, srgb_pow.x;\n", fragcolor);
2009         shader_addline(buffer, "POW TMP.y, %s.y, srgb_pow.y;\n", fragcolor);
2010         shader_addline(buffer, "POW TMP.z, %s.z, srgb_pow.z;\n", fragcolor);
2011         shader_addline(buffer, "MUL TMP, TMP, srgb_mul_hi;\n");
2012         shader_addline(buffer, "SUB TMP, TMP, srgb_sub_hi;\n");
2013         /* Calculate the < case */
2014         shader_addline(buffer, "MUL TMP2, srgb_mul_low, %s;\n", fragcolor);
2015         /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
2016         shader_addline(buffer, "SLT TA, srgb_comparison, %s;\n", fragcolor);
2017         shader_addline(buffer, "SGE TB, srgb_comparison, %s;\n", fragcolor);
2018         /* Store the components > 0.0031308 in the destination */
2019         shader_addline(buffer, "MUL %s, TMP, TA;\n", fragcolor);
2020         /* Add the components that are < 0.0031308 */
2021         shader_addline(buffer, "MAD result.color.xyz, TMP2, TB, %s;\n", fragcolor);
2022         /* [0.0;1.0] clamping. Not needed, this is done implicitly */
2023     }
2024     if (This->baseShader.hex_version < WINED3DPS_VERSION(3,0)) {
2025         shader_addline(buffer, "LRP result.color.rgb, TMP_FOG.x, %s, state.fog.color;\n", fragcolor);
2026         shader_addline(buffer, "MOV result.color.a, %s.a;\n", fragcolor);
2027     }
2028
2029     shader_addline(buffer, "END\n");
2030
2031     /* TODO: change to resource.glObjectHandle or something like that */
2032     GL_EXTCALL(glGenProgramsARB(1, &This->baseShader.prgId));
2033
2034     TRACE("Creating a hw pixel shader, prg=%d\n", This->baseShader.prgId);
2035     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, This->baseShader.prgId));
2036
2037     TRACE("Created hw pixel shader, prg=%d\n", This->baseShader.prgId);
2038     /* Create the program and check for errors */
2039     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2040                buffer->bsize, buffer->buffer));
2041
2042     if (glGetError() == GL_INVALID_OPERATION) {
2043         GLint errPos;
2044         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2045         FIXME("HW PixelShader Error at position %d: %s\n",
2046               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2047         This->baseShader.prgId = -1;
2048     }
2049
2050     /* Load immediate constants */
2051     if(!This->baseShader.load_local_constsF) {
2052         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2053             float *value = (float *) lconst->value;
2054             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst->idx, value));
2055             checkGLcall("glProgramLocalParameter4fvARB");
2056         }
2057     }
2058 }
2059
2060 static void shader_arb_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer) {
2061     IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
2062     shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
2063     CONST DWORD *function = This->baseShader.function;
2064     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
2065     local_constant* lconst;
2066
2067     /*  Create the hw ARB shader */
2068     shader_addline(buffer, "!!ARBvp1.0\n");
2069     shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
2070
2071     /* Mesa supports only 95 constants */
2072     if (GL_VEND(MESA) || GL_VEND(WINE))
2073         This->baseShader.limits.constant_float =
2074                 min(95, This->baseShader.limits.constant_float);
2075
2076     shader_addline(buffer, "TEMP TMP;\n");
2077
2078     /* Base Declarations */
2079     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
2080
2081     /* We need a constant to fixup the final position */
2082     shader_addline(buffer, "PARAM posFixup = program.env[%d];\n", ARB_SHADER_PRIVCONST_POS);
2083
2084     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
2085      * for output parameters. D3D in theory does not do that either, but some applications depend on a
2086      * proper initialization of the secondary color, and programs using the fixed function pipeline without
2087      * a replacement shader depend on the texcoord.w being set properly.
2088      *
2089      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
2090      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
2091      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
2092      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
2093      * this can eat a number of instructions, so skip it unless this cap is set as well
2094      */
2095     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)) {
2096         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
2097
2098         if((GLINFO_LOCATION).set_texcoord_w) {
2099             int i;
2100             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
2101                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
2102                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
2103                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
2104                 }
2105             }
2106         }
2107     }
2108
2109     /* Base Shader Body */
2110     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
2111
2112     /* If this shader doesn't use fog copy the z coord to the fog coord so that we can use table fog */
2113     if (!reg_maps->fog)
2114         shader_addline(buffer, "MOV result.fogcoord, TMP_OUT.z;\n");
2115
2116     /* Write the final position.
2117      *
2118      * OpenGL coordinates specify the center of the pixel while d3d coords specify
2119      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
2120      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
2121      * contains 1.0 to allow a mad, but arb vs swizzles are too restricted for that.
2122      */
2123     shader_addline(buffer, "MUL TMP, posFixup, TMP_OUT.w;\n");
2124     shader_addline(buffer, "ADD TMP_OUT.x, TMP_OUT.x, TMP.z;\n");
2125     shader_addline(buffer, "MAD TMP_OUT.y, TMP_OUT.y, posFixup.y, TMP.w;\n");
2126
2127     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
2128      * and the glsl equivalent
2129      */
2130     shader_addline(buffer, "MAD TMP_OUT.z, TMP_OUT.z, helper_const.x, -TMP_OUT.w;\n");
2131
2132     shader_addline(buffer, "MOV result.position, TMP_OUT;\n");
2133
2134     shader_addline(buffer, "END\n");
2135
2136     /* TODO: change to resource.glObjectHandle or something like that */
2137     GL_EXTCALL(glGenProgramsARB(1, &This->baseShader.prgId));
2138
2139     TRACE("Creating a hw vertex shader, prg=%d\n", This->baseShader.prgId);
2140     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, This->baseShader.prgId));
2141
2142     TRACE("Created hw vertex shader, prg=%d\n", This->baseShader.prgId);
2143     /* Create the program and check for errors */
2144     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2145                buffer->bsize, buffer->buffer));
2146
2147     if (glGetError() == GL_INVALID_OPERATION) {
2148         GLint errPos;
2149         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2150         FIXME("HW VertexShader Error at position %d: %s\n",
2151               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2152         This->baseShader.prgId = -1;
2153     }
2154
2155     /* Load immediate constants */
2156     if(!This->baseShader.load_local_constsF) {
2157         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2158             float *value = (float *) lconst->value;
2159             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst->idx, value));
2160         }
2161     }
2162 }
2163
2164 static void shader_arb_get_caps(WINED3DDEVTYPE devtype, WineD3D_GL_Info *gl_info, struct shader_caps *pCaps) {
2165     /* We don't have an ARB fixed function pipeline yet, so let the none backend set its caps,
2166      * then overwrite the shader specific ones
2167      */
2168     none_shader_backend.shader_get_caps(devtype, gl_info, pCaps);
2169
2170     if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
2171         pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
2172         TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
2173         pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
2174     }
2175
2176     if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
2177         pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
2178         pCaps->PixelShader1xMaxValue = 8.0;
2179         TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
2180     }
2181 }
2182
2183 static BOOL shader_arb_conv_supported(WINED3DFORMAT fmt) {
2184     TRACE("Checking shader format support for format %s:", debug_d3dformat(fmt));
2185     switch(fmt) {
2186         case WINED3DFMT_V8U8:
2187         case WINED3DFMT_V16U16:
2188         case WINED3DFMT_X8L8V8U8:
2189         case WINED3DFMT_L6V5U5:
2190         case WINED3DFMT_Q8W8V8U8:
2191         case WINED3DFMT_ATI2N:
2192             TRACE("[OK]\n");
2193             return TRUE;
2194         default:
2195             TRACE("[FAILED\n");
2196             return FALSE;
2197     }
2198 }
2199
2200 const shader_backend_t arb_program_shader_backend = {
2201     shader_arb_select,
2202     shader_arb_select_depth_blt,
2203     shader_arb_deselect_depth_blt,
2204     shader_arb_load_constants,
2205     shader_arb_cleanup,
2206     shader_arb_color_correction,
2207     shader_arb_destroy,
2208     shader_arb_alloc,
2209     shader_arb_free,
2210     shader_arb_dirty_const,
2211     shader_arb_generate_pshader,
2212     shader_arb_generate_vshader,
2213     shader_arb_get_caps,
2214     shader_arb_conv_supported,
2215 };
2216
2217 /* ARB_fragment_program fixed function pipeline replacement definitions */
2218 #define ARB_FFP_CONST_TFACTOR     0
2219 #define ARB_FFP_CONST_CONSTANT(i) ((ARB_FFP_CONST_TFACTOR) + 1 + i)
2220 #define ARB_FFP_CONST_BUMPMAT(i)  ((ARB_FFP_CONST_CONSTANT(7)) + 1 + i)
2221
2222 struct arbfp_ffp_desc
2223 {
2224     struct ffp_desc parent;
2225     GLuint shader;
2226     unsigned int num_textures_used;
2227 };
2228
2229 static void arbfp_enable(IWineD3DDevice *iface, BOOL enable) {
2230     if(enable) {
2231         glEnable(GL_FRAGMENT_PROGRAM_ARB);
2232         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
2233     } else {
2234         glDisable(GL_FRAGMENT_PROGRAM_ARB);
2235         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
2236     }
2237 }
2238
2239 static HRESULT arbfp_alloc(IWineD3DDevice *iface) {
2240     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
2241     struct shader_arb_priv *priv;
2242     /* Share private data between the shader backend and the pipeline replacement, if both
2243      * are the arb implementation. This is needed to figure out whether ARBfp should be disabled
2244      * if no pixel shader is bound or not
2245      */
2246     if(This->shader_backend == &arb_program_shader_backend) {
2247         This->fragment_priv = This->shader_priv;
2248     } else {
2249         This->fragment_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
2250         if(!This->fragment_priv) return E_OUTOFMEMORY;
2251     }
2252     priv = (struct shader_arb_priv *) This->fragment_priv;
2253     priv->fragment_shaders = hash_table_create(ffp_program_key_hash, ffp_program_key_compare);
2254     priv->use_arbfp_fixed_func = TRUE;
2255     return WINED3D_OK;
2256 }
2257
2258 static void arbfp_free_ffpshader(void *value, void *gli) {
2259     WineD3D_GL_Info *gl_info = gli;
2260     struct arbfp_ffp_desc *entry_arb = value;
2261
2262     ENTER_GL();
2263     GL_EXTCALL(glDeleteProgramsARB(1, &entry_arb->shader));
2264     checkGLcall("glDeleteProgramsARB(1, &entry_arb->shader)");
2265     HeapFree(GetProcessHeap(), 0, entry_arb);
2266     LEAVE_GL();
2267 }
2268
2269 static void arbfp_free(IWineD3DDevice *iface) {
2270     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
2271     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->fragment_priv;
2272
2273     hash_table_destroy(priv->fragment_shaders, arbfp_free_ffpshader, &This->adapter->gl_info);
2274     priv->use_arbfp_fixed_func = FALSE;
2275
2276     if(This->shader_backend != &arb_program_shader_backend) {
2277         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
2278     }
2279 }
2280
2281 static void arbfp_get_caps(WINED3DDEVTYPE devtype, WineD3D_GL_Info *gl_info, struct fragment_caps *caps) {
2282     caps->TextureOpCaps =  WINED3DTEXOPCAPS_DISABLE                     |
2283                            WINED3DTEXOPCAPS_SELECTARG1                  |
2284                            WINED3DTEXOPCAPS_SELECTARG2                  |
2285                            WINED3DTEXOPCAPS_MODULATE4X                  |
2286                            WINED3DTEXOPCAPS_MODULATE2X                  |
2287                            WINED3DTEXOPCAPS_MODULATE                    |
2288                            WINED3DTEXOPCAPS_ADDSIGNED2X                 |
2289                            WINED3DTEXOPCAPS_ADDSIGNED                   |
2290                            WINED3DTEXOPCAPS_ADD                         |
2291                            WINED3DTEXOPCAPS_SUBTRACT                    |
2292                            WINED3DTEXOPCAPS_ADDSMOOTH                   |
2293                            WINED3DTEXOPCAPS_BLENDCURRENTALPHA           |
2294                            WINED3DTEXOPCAPS_BLENDFACTORALPHA            |
2295                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHA           |
2296                            WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA           |
2297                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM         |
2298                            WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR      |
2299                            WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA      |
2300                            WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA   |
2301                            WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR   |
2302                            WINED3DTEXOPCAPS_DOTPRODUCT3                 |
2303                            WINED3DTEXOPCAPS_MULTIPLYADD                 |
2304                            WINED3DTEXOPCAPS_LERP                        |
2305                            WINED3DTEXOPCAPS_BUMPENVMAP;
2306
2307     /* TODO: Implement WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE
2308     and WINED3DTEXOPCAPS_PREMODULATE */
2309
2310     caps->MaxTextureBlendStages   = 8;
2311     caps->MaxSimultaneousTextures = min(GL_LIMITS(fragment_samplers), 8);
2312
2313     caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_TSSARGTEMP;
2314 }
2315 #undef GLINFO_LOCATION
2316
2317 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
2318 static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2319     float col[4];
2320     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2321
2322     /* Do not overwrite pixel shader constants if a pshader is in use */
2323     if(use_ps(device)) return;
2324
2325     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
2326     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col));
2327     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col)");
2328
2329     if(device->shader_backend == &arb_program_shader_backend) {
2330         device = stateblock->wineD3DDevice;
2331         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
2332         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
2333     }
2334 }
2335
2336 static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2337     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / WINED3D_HIGHEST_TEXTURE_STATE;
2338     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2339     float mat[2][2];
2340
2341     if(use_ps(device)) {
2342         if(stage != 0 &&
2343            ((IWineD3DPixelShaderImpl *) stateblock->pixelShader)->baseShader.reg_maps.bumpmat[stage]) {
2344             /* The pixel shader has to know the bump env matrix. Do a constants update if it isn't scheduled
2345              * anyway
2346              */
2347             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
2348                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
2349             }
2350         }
2351         /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
2352         return;
2353     }
2354
2355     mat[0][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT00]);
2356     mat[0][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT01]);
2357     mat[1][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT10]);
2358     mat[1][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT11]);
2359
2360     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0]));
2361     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0])");
2362
2363     if(device->shader_backend == &arb_program_shader_backend) {
2364         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
2365         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
2366     }
2367 }
2368
2369 static const char *get_argreg(SHADER_BUFFER *buffer, DWORD argnum, unsigned int stage, DWORD arg) {
2370     const char *ret;
2371
2372     if(arg == ARG_UNUSED) return "unused"; /* This is the marker for unused registers */
2373
2374     switch(arg & WINED3DTA_SELECTMASK) {
2375         case WINED3DTA_DIFFUSE:
2376             ret = "fragment.color.primary"; break;
2377
2378         case WINED3DTA_CURRENT:
2379             if(stage == 0) ret = "fragment.color.primary";
2380             else ret = "ret";
2381             break;
2382
2383         case WINED3DTA_TEXTURE:
2384             switch(stage) {
2385                 case 0: ret = "tex0"; break;
2386                 case 1: ret = "tex1"; break;
2387                 case 2: ret = "tex2"; break;
2388                 case 3: ret = "tex3"; break;
2389                 case 4: ret = "tex4"; break;
2390                 case 5: ret = "tex5"; break;
2391                 case 6: ret = "tex6"; break;
2392                 case 7: ret = "tex7"; break;
2393                 default: ret = "unknown texture";
2394             }
2395             break;
2396
2397         case WINED3DTA_TFACTOR:
2398             ret = "tfactor"; break;
2399
2400         case WINED3DTA_SPECULAR:
2401             ret = "fragment.color.secondary"; break;
2402
2403         case WINED3DTA_TEMP:
2404             ret = "tempreg"; break;
2405
2406         case WINED3DTA_CONSTANT:
2407             FIXME("Implement perstage constants\n");
2408             switch(stage) {
2409                 case 0: ret = "const0"; break;
2410                 case 1: ret = "const1"; break;
2411                 case 2: ret = "const2"; break;
2412                 case 3: ret = "const3"; break;
2413                 case 4: ret = "const4"; break;
2414                 case 5: ret = "const5"; break;
2415                 case 6: ret = "const6"; break;
2416                 case 7: ret = "const7"; break;
2417             }
2418         default:
2419             return "unknown";
2420     }
2421
2422     if(arg & WINED3DTA_COMPLEMENT) {
2423         shader_addline(buffer, "SUB arg%u, const.x, %s;\n", argnum, ret);
2424         if(argnum == 0) ret = "arg0";
2425         if(argnum == 1) ret = "arg1";
2426         if(argnum == 2) ret = "arg2";
2427     }
2428     return ret;
2429 }
2430
2431 static void gen_ffp_instr(SHADER_BUFFER *buffer, unsigned int stage, BOOL color, BOOL alpha, BOOL last,
2432                           DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2) {
2433     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
2434     unsigned int mul = 1;
2435     BOOL mul_final_dest = FALSE;
2436
2437     if(color && alpha) dstmask = "";
2438     else if(color) dstmask = ".rgb";
2439     else dstmask = ".a";
2440
2441     if(dst == tempreg && last) FIXME("Last texture stage writes to D3DTA_TEMP\n");
2442     if(dst == tempreg) dstreg = "tempreg";
2443     else if(last) dstreg = "result.color";
2444     else dstreg = "ret";
2445
2446     arg0 = get_argreg(buffer, 0, stage, dw_arg0);
2447     arg1 = get_argreg(buffer, 1, stage, dw_arg1);
2448     arg2 = get_argreg(buffer, 2, stage, dw_arg2);
2449
2450     switch(op) {
2451         case WINED3DTOP_DISABLE:
2452             if(stage == 1) shader_addline(buffer, "MOV %s%s, fragment.color.primary;\n", dstreg, dstmask);
2453             break;
2454
2455         case WINED3DTOP_SELECTARG2:
2456             arg1 = arg2;
2457         case WINED3DTOP_SELECTARG1:
2458             shader_addline(buffer, "MOV %s%s, %s;\n", dstreg, dstmask, arg1);
2459             break;
2460
2461         case WINED3DTOP_MODULATE4X:
2462             mul = 2;
2463         case WINED3DTOP_MODULATE2X:
2464             mul *= 2;
2465             if(strcmp(dstreg, "result.color") == 0) {
2466                 dstreg = "ret";
2467                 mul_final_dest = TRUE;
2468             }
2469         case WINED3DTOP_MODULATE:
2470             shader_addline(buffer, "MUL %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2471             break;
2472
2473         case WINED3DTOP_ADDSIGNED2X:
2474             mul = 2;
2475             if(strcmp(dstreg, "result.color") == 0) {
2476                 dstreg = "ret";
2477                 mul_final_dest = TRUE;
2478             }
2479         case WINED3DTOP_ADDSIGNED:
2480             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
2481             arg2 = "arg2";
2482         case WINED3DTOP_ADD:
2483             shader_addline(buffer, "ADD_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2484             break;
2485
2486         case WINED3DTOP_SUBTRACT:
2487             shader_addline(buffer, "SUB_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2488             break;
2489
2490         case WINED3DTOP_ADDSMOOTH:
2491             shader_addline(buffer, "SUB arg1, const.x, %s;\n", arg1);
2492             shader_addline(buffer, "MAD_SAT %s%s, arg1, %s, %s;\n", dstreg, dstmask, arg2, arg1);
2493             break;
2494
2495         case WINED3DTOP_BLENDCURRENTALPHA:
2496             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_CURRENT);
2497             shader_addline(buffer, "LRP %s%s, %s.a, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2498             break;
2499         case WINED3DTOP_BLENDFACTORALPHA:
2500             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TFACTOR);
2501             shader_addline(buffer, "LRP %s%s, %s.a, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2502             break;
2503         case WINED3DTOP_BLENDTEXTUREALPHA:
2504             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
2505             shader_addline(buffer, "LRP %s%s, %s.a, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2506             break;
2507         case WINED3DTOP_BLENDDIFFUSEALPHA:
2508             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_DIFFUSE);
2509             shader_addline(buffer, "LRP %s%s, %s.a, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2510             break;
2511
2512         case WINED3DTOP_BLENDTEXTUREALPHAPM:
2513             shader_addline(buffer, "SUB arg0.a, const.x, %s;\n", arg1);
2514             shader_addline(buffer, "MAD_SAT %s%s, %s, arg0.a, %s;\n", dstreg, dstmask, arg2, arg1);
2515             break;
2516
2517         /* D3DTOP_PREMODULATE ???? */
2518
2519         case WINED3DTOP_MODULATEINVALPHA_ADDCOLOR:
2520             shader_addline(buffer, "SUB arg0.a, const.x, %s;\n", arg1);
2521             shader_addline(buffer, "MAD_SAT %s%s, arg0.a, %s, %s;\n", dstreg, dstmask, arg2, arg1);
2522             break;
2523         case WINED3DTOP_MODULATEALPHA_ADDCOLOR:
2524             shader_addline(buffer, "MAD_SAT %s%s, %s.a, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg1);
2525             break;
2526         case WINED3DTOP_MODULATEINVCOLOR_ADDALPHA:
2527             shader_addline(buffer, "SUB arg0, const.x, %s;\n", arg1);
2528             shader_addline(buffer, "MAD_SAT %s%s, arg0, %s, %s.a;\n", dstreg, dstmask, arg2, arg1);
2529             break;
2530         case WINED3DTOP_MODULATECOLOR_ADDALPHA:
2531             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s.a;\n", dstreg, dstmask, arg1, arg2, arg1);
2532             break;
2533
2534         case WINED3DTOP_DOTPRODUCT3:
2535             mul = 4;
2536             if(strcmp(dstreg, "result.color") == 0) {
2537                 dstreg = "ret";
2538                 mul_final_dest = TRUE;
2539             }
2540             shader_addline(buffer, "SUB arg1, %s, const.w;\n", arg1);
2541             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
2542             shader_addline(buffer, "DP3_SAT %s%s, arg1, arg2;\n", dstreg, dstmask);
2543             break;
2544
2545         case WINED3DTOP_MULTIPLYADD:
2546             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg0);
2547             break;
2548
2549         case WINED3DTOP_LERP:
2550             /* The msdn is not quite right here */
2551             shader_addline(buffer, "LRP %s%s, %s, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2552             break;
2553
2554         case WINED3DTOP_BUMPENVMAP:
2555         case WINED3DTOP_BUMPENVMAPLUMINANCE:
2556             /* Those are handled in the first pass of the shader(generation pass 1 and 2) already */
2557             break;
2558
2559         default:
2560             FIXME("Unhandled texture op %08x\n", op);
2561     }
2562
2563     if(mul == 2) {
2564         shader_addline(buffer, "MUL_SAT %s%s, %s, const.y;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
2565     } else if(mul == 4) {
2566         shader_addline(buffer, "MUL_SAT %s%s, %s, const.z;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
2567     }
2568 }
2569
2570 /* The stateblock is passed for GLINFO_LOCATION */
2571 static GLuint gen_arbfp_ffp_shader(struct ffp_settings *settings, IWineD3DStateBlockImpl *stateblock) {
2572     unsigned int stage;
2573     SHADER_BUFFER buffer;
2574     BOOL tex_read[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
2575     BOOL bump_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
2576     const char *textype;
2577     const char *instr, *sat;
2578     char colorcor_dst[8];
2579     GLuint ret;
2580     DWORD arg0, arg1, arg2;
2581     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
2582     BOOL last = FALSE;
2583
2584     /* Find out which textures are read */
2585     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2586         if(settings->op[stage].cop == WINED3DTOP_DISABLE) break;
2587         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
2588         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
2589         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
2590         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2591         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2592         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2593
2594         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHA) tex_read[stage] = TRUE;
2595         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP) {
2596             bump_used[stage] = TRUE;
2597             tex_read[stage] = TRUE;
2598         }
2599         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
2600             bump_used[stage] = TRUE;
2601             tex_read[stage] = TRUE;
2602         }
2603
2604         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
2605             tfactor_used = TRUE;
2606         }
2607
2608         if(settings->op[stage].dst == tempreg) tempreg_used = TRUE;
2609         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
2610             tempreg_used = TRUE;
2611         }
2612
2613         if(settings->op[stage].aop == WINED3DTOP_DISABLE) continue;
2614         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
2615         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
2616         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
2617         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2618         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2619         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2620
2621         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
2622             tempreg_used = TRUE;
2623         }
2624         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
2625             tfactor_used = TRUE;
2626         }
2627     }
2628
2629     /* Shader header */
2630     buffer.bsize = 0;
2631     buffer.lineNo = 0;
2632     buffer.newline = TRUE;
2633     buffer.buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SHADER_PGMSIZE);
2634
2635     shader_addline(&buffer, "!!ARBfp1.0\n");
2636
2637     switch(settings->fog) {
2638         case FOG_OFF:                                                         break;
2639         case FOG_LINEAR: shader_addline(&buffer, "OPTION ARB_fog_linear;\n"); break;
2640         case FOG_EXP:    shader_addline(&buffer, "OPTION ARB_fog_exp;\n");    break;
2641         case FOG_EXP2:   shader_addline(&buffer, "OPTION ARB_fog_exp2;\n");   break;
2642         default: FIXME("Unexpected fog setting %d\n", settings->fog);
2643     }
2644
2645     shader_addline(&buffer, "PARAM const = {1, 2, 4, 0.5};\n");
2646     shader_addline(&buffer, "TEMP ret;\n");
2647     if(tempreg_used) shader_addline(&buffer, "TEMP tempreg;\n");
2648     shader_addline(&buffer, "TEMP arg0;\n");
2649     shader_addline(&buffer, "TEMP arg1;\n");
2650     shader_addline(&buffer, "TEMP arg2;\n");
2651     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2652         if(!tex_read[stage]) continue;
2653         shader_addline(&buffer, "TEMP tex%u;\n", stage);
2654         if(!bump_used[stage]) continue;
2655         shader_addline(&buffer, "PARAM bumpmat%u = program.env[%u];\n", stage, ARB_FFP_CONST_BUMPMAT(stage));
2656     }
2657     if(tfactor_used) {
2658         shader_addline(&buffer, "PARAM tfactor = program.env[%u];\n", ARB_FFP_CONST_TFACTOR);
2659     }
2660
2661     /* Generate texture sampling instructions) */
2662     for(stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3DTOP_DISABLE; stage++) {
2663         if(!tex_read[stage]) continue;
2664
2665         switch(settings->op[stage].tex_type) {
2666             case tex_1d:                    textype = "1D";     break;
2667             case tex_2d:                    textype = "2D";     break;
2668             case tex_3d:                    textype = "3D";     break;
2669             case tex_cube:                  textype = "CUBE";   break;
2670             case tex_rect:                  textype = "RECT";   break;
2671             default: textype = "unexpected_textype";   break;
2672         }
2673
2674         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP ||
2675            settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
2676             sat = "";
2677         } else {
2678             sat = "_SAT";
2679         }
2680
2681         if(settings->op[stage].projected == proj_none) {
2682             instr = "TEX";
2683         } else if(settings->op[stage].projected == proj_count4) {
2684             instr = "TXP";
2685         } else {
2686             instr = "TXP";
2687             ERR("Implement proj_count3\n");
2688         }
2689
2690         if(stage > 0 &&
2691            (settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAP ||
2692             settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE)) {
2693             shader_addline(&buffer, "SWZ arg1, bumpmat%u, x, z, 0, 0;\n", stage - 1);
2694             shader_addline(&buffer, "DP3 ret.r, arg1, tex%u;\n", stage - 1);
2695             shader_addline(&buffer, "SWZ arg1, bumpmat%u, y, w, 0, 0;\n", stage - 1);
2696             shader_addline(&buffer, "DP3 ret.g, arg1, tex%u;\n", stage - 1);
2697             shader_addline(&buffer, "ADD ret, ret, fragment.texcoord[%u];\n", stage);
2698             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
2699                             instr, sat, stage, stage, textype);
2700         } else {
2701             shader_addline(&buffer, "%s%s tex%u, fragment.texcoord[%u], texture[%u], %s;\n",
2702                             instr, sat, stage, stage, stage, textype);
2703         }
2704
2705         sprintf(colorcor_dst, "tex%u", stage);
2706         gen_color_correction(&buffer, colorcor_dst, ".rgba", "const.x", "const.y",
2707                                 settings->op[stage].color_correction, &GLINFO_LOCATION);
2708     }
2709
2710     /* Generate the main shader */
2711     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2712         if(settings->op[stage].cop == WINED3DTOP_DISABLE) {
2713             if(stage == 0) {
2714                 shader_addline(&buffer, "MOV result.color, fragment.color.primary;\n");
2715             }
2716             break;
2717         } else if(stage == (MAX_TEXTURES - 1)) {
2718             last = TRUE;
2719         } else if(settings->op[stage + 1].cop == WINED3DTOP_DISABLE) {
2720             last = TRUE;
2721         }
2722
2723         if(settings->op[stage].aop == WINED3DTOP_DISABLE) {
2724             gen_ffp_instr(&buffer, stage, TRUE, FALSE, last, settings->op[stage].dst,
2725                           settings->op[stage].cop, settings->op[stage].carg0,
2726                           settings->op[stage].carg1, settings->op[stage].carg2);
2727             if(last && stage == 0) {
2728                 shader_addline(&buffer, "MOV result.color.a, fragment.color.primary.a;\n");
2729             } else if(last) {
2730                 shader_addline(&buffer, "MOV result.color.a, ret.a;\n");
2731             } else if(stage == 0) {
2732                 shader_addline(&buffer, "MOV ret.a, fragment.color.primary.a;\n");
2733             }
2734         } else if(settings->op[stage].aop   == settings->op[stage].cop &&
2735                   settings->op[stage].carg0 == settings->op[stage].aarg0 &&
2736                   settings->op[stage].carg1 == settings->op[stage].aarg1 &&
2737                   settings->op[stage].carg2 == settings->op[stage].aarg2) {
2738             gen_ffp_instr(&buffer, stage, TRUE, TRUE, last, settings->op[stage].dst,
2739                           settings->op[stage].cop, settings->op[stage].carg0,
2740                           settings->op[stage].carg1, settings->op[stage].carg2);
2741         } else {
2742             gen_ffp_instr(&buffer, stage, TRUE, FALSE, last, settings->op[stage].dst,
2743                           settings->op[stage].cop, settings->op[stage].carg0,
2744                           settings->op[stage].carg1, settings->op[stage].carg2);
2745             gen_ffp_instr(&buffer, stage, FALSE, TRUE, last, settings->op[stage].dst,
2746                           settings->op[stage].aop, settings->op[stage].aarg0,
2747                           settings->op[stage].aarg1, settings->op[stage].aarg2);
2748         }
2749     }
2750
2751     /* TODO: Generate sRGB write color correction */
2752
2753     /* Footer */
2754     shader_addline(&buffer, "END\n");
2755
2756     /* Generate the shader */
2757     GL_EXTCALL(glGenProgramsARB(1, &ret));
2758     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret));
2759     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
2760
2761     if (glGetError() == GL_INVALID_OPERATION) {
2762         GLint pos;
2763         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
2764         FIXME("Vertex program error at position %d: %s\n", pos,
2765               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2766     }
2767     return ret;
2768 }
2769
2770 static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2771     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2772     struct shader_arb_priv *priv = (struct shader_arb_priv *) device->fragment_priv;
2773     BOOL use_pshader = use_ps(device);
2774     BOOL use_vshader = use_vs(device);
2775     struct ffp_settings settings;
2776     struct arbfp_ffp_desc *desc;
2777     unsigned int i;
2778
2779     if(isStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE))) return;
2780
2781     if(use_pshader) {
2782         IWineD3DPixelShader_CompileShader(stateblock->pixelShader);
2783     } else {
2784         /* Find or create a shader implementing the fixed function pipeline settings, then activate it */
2785         gen_ffp_op(stateblock, &settings, FALSE);
2786         desc = (struct arbfp_ffp_desc *) find_ffp_shader(priv->fragment_shaders, &settings);
2787         if(!desc) {
2788             desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*desc));
2789             if(!desc) {
2790                 ERR("Out of memory\n");
2791                 return;
2792             }
2793             desc->num_textures_used = 0;
2794             for(i = 0; i < GL_LIMITS(texture_stages); i++) {
2795                 if(settings.op[i].cop == WINED3DTOP_DISABLE) break;
2796                 desc->num_textures_used = i;
2797             }
2798
2799             memcpy(&desc->parent.settings, &settings, sizeof(settings));
2800             desc->shader = gen_arbfp_ffp_shader(&settings, stateblock);
2801             add_ffp_shader(priv->fragment_shaders, &desc->parent);
2802             TRACE("Allocated fixed function replacement shader descriptor %p\n", desc);
2803         }
2804
2805         /* Now activate the replacement program. GL_FRAGMENT_PROGRAM_ARB is already active(however, note the
2806          * comment above the shader_select call below). If e.g. GLSL is active, the shader_select call will
2807          * deactivate it.
2808          */
2809         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader));
2810         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader)");
2811
2812         if(device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
2813             /* Reload fixed function constants since they collide with the pixel shader constants */
2814             for(i = 0; i < MAX_TEXTURES; i++) {
2815                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
2816             }
2817             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
2818         }
2819     }
2820
2821     /* Finally, select the shader. If a pixel shader is used, it will be set and enabled by the shader backend.
2822      * If this shader backend is arbfp(most likely), then it will simply overwrite the last fixed function replace-
2823      * ment shader. If the shader backend is not ARB, it currently is important that the opengl implementation
2824      * type overwrites GL_ARB_fragment_program. This is currently the case with GLSL. If we really want to use
2825      * atifs or nvrc pixel shaders with arb fragment programs we'd have to disable GL_FRAGMENT_PROGRAM_ARB here
2826      *
2827      * Don't call shader_select if the vertex shader is dirty, because some shader backends(GLSL) need both shaders
2828      * to be compiled before activating them(needs some cleanups in the shader backend interface)
2829      */
2830     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
2831         device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
2832
2833         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
2834             device->StateTable[STATE_VERTEXSHADERCONSTANT].apply(STATE_VERTEXSHADERCONSTANT, stateblock, context);
2835         }
2836     }
2837     if(use_pshader) {
2838         device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
2839     }
2840 }
2841
2842 /* We can't link the fog states to the fragment state directly since the vertex pipeline links them
2843  * to FOGENABLE. A different linking in different pipeline parts can't be expressed in the combined
2844  * state table, so we need to handle that with a forwarding function. The other invisible side effect
2845  * is that changing the fog start and fog end(which links to FOGENABLE in vertex) results in the
2846  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
2847  */
2848 static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2849     if(!isStateDirty(context, STATE_PIXELSHADER)) {
2850         fragment_prog_arbfp(state, stateblock, context);
2851     }
2852 }
2853
2854 #undef GLINFO_LOCATION
2855
2856 static const struct StateEntryTemplate arbfp_fragmentstate_template[] = {
2857     {STATE_RENDER(WINED3DRS_TEXTUREFACTOR),               { STATE_RENDER(WINED3DRS_TEXTUREFACTOR),              state_texfactor_arbfp   }, 0                               },
2858     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2859     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2860     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2861     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2862     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2863     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2864     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2865     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2866     {STATE_TEXTURESTAGE(0, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2867     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2868     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2869     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2870     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2871     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2872     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2873     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2874     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2875     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2876     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2877     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2878     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2879     {STATE_TEXTURESTAGE(1, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2880     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2881     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2882     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2883     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2884     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2885     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2886     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2887     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2888     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2889     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2890     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2891     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2892     {STATE_TEXTURESTAGE(2, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2893     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2894     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2895     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2896     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2897     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2898     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2899     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2900     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2901     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2902     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2903     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2904     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2905     {STATE_TEXTURESTAGE(3, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2906     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2907     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2908     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2909     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2910     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2911     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2912     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2913     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2914     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2915     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2916     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2917     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2918     {STATE_TEXTURESTAGE(4, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2919     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2920     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2921     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2922     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2923     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2924     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2925     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2926     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2927     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2928     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2929     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2930     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2931     {STATE_TEXTURESTAGE(5, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2932     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2933     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2934     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2935     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2936     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2937     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2938     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2939     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2940     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2941     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2942     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2943     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2944     {STATE_TEXTURESTAGE(6, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2945     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2946     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2947     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2948     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2949     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2950     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2951     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2952     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2953     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2954     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2955     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2956     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2957     {STATE_TEXTURESTAGE(7, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2958     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2959     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2960     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2961     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
2962     { STATE_SAMPLER(0),                                   { STATE_SAMPLER(0),                                   sampler_texdim          }, 0                               },
2963     { STATE_SAMPLER(1),                                   { STATE_SAMPLER(1),                                   sampler_texdim          }, 0                               },
2964     { STATE_SAMPLER(2),                                   { STATE_SAMPLER(2),                                   sampler_texdim          }, 0                               },
2965     { STATE_SAMPLER(3),                                   { STATE_SAMPLER(3),                                   sampler_texdim          }, 0                               },
2966     { STATE_SAMPLER(4),                                   { STATE_SAMPLER(4),                                   sampler_texdim          }, 0                               },
2967     { STATE_SAMPLER(5),                                   { STATE_SAMPLER(5),                                   sampler_texdim          }, 0                               },
2968     { STATE_SAMPLER(6),                                   { STATE_SAMPLER(6),                                   sampler_texdim          }, 0                               },
2969     { STATE_SAMPLER(7),                                   { STATE_SAMPLER(7),                                   sampler_texdim          }, 0                               },
2970     { STATE_PIXELSHADER,                                  { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
2971     { STATE_RENDER(WINED3DRS_FOGENABLE),                  { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
2972     { STATE_RENDER(WINED3DRS_FOGTABLEMODE),               { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
2973     { STATE_RENDER(WINED3DRS_FOGVERTEXMODE),              { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
2974     {0 /* Terminate */,                                   { 0,                                                  0                       }, 0                               },
2975 };
2976
2977 const struct fragment_pipeline arbfp_fragment_pipeline = {
2978     arbfp_enable,
2979     arbfp_get_caps,
2980     arbfp_alloc,
2981     arbfp_free,
2982     shader_arb_conv_supported,
2983     arbfp_fragmentstate_template
2984 };
2985
2986 #define GLINFO_LOCATION device->adapter->gl_info
2987
2988 struct arbfp_blit_priv {
2989     GLenum yuy2_rect_shader, yuy2_2d_shader;
2990     GLenum uyvy_rect_shader, uyvy_2d_shader;
2991 };
2992
2993 static HRESULT arbfp_blit_alloc(IWineD3DDevice *iface) {
2994     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
2995     device->blit_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct arbfp_blit_priv));
2996     if(!device->blit_priv) {
2997         ERR("Out of memory\n");
2998         return E_OUTOFMEMORY;
2999     }
3000     return WINED3D_OK;
3001 }
3002 static void arbfp_blit_free(IWineD3DDevice *iface) {
3003     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3004     struct arbfp_blit_priv *priv = (struct arbfp_blit_priv *) device->blit_priv;
3005
3006     ENTER_GL();
3007     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_rect_shader));
3008     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_2d_shader));
3009     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_rect_shader));
3010     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_2d_shader));
3011     checkGLcall("Delete yuv programs\n");
3012     LEAVE_GL();
3013 }
3014
3015 GLenum gen_yuv_shader(IWineD3DDeviceImpl *device, WINED3DFORMAT fmt, GLenum textype) {
3016     GLenum shader;
3017     SHADER_BUFFER buffer;
3018     const char *tex, *texinstr;
3019     char chroma, luminance;
3020     struct arbfp_blit_priv *priv = (struct arbfp_blit_priv *) device->blit_priv;
3021
3022     /* Shader header */
3023     buffer.bsize = 0;
3024     buffer.lineNo = 0;
3025     buffer.newline = TRUE;
3026     buffer.buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SHADER_PGMSIZE);
3027
3028     switch(textype) {
3029         case GL_TEXTURE_2D:             tex = "2D";     texinstr = "TXP"; break;
3030         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   texinstr = "TEX"; break;
3031         default:
3032             /* This is more tricky than just replacing the texture type - we have to navigate
3033              * properly in the texture to find the correct chroma values
3034              */
3035             FIXME("Implement yuv correction for non-2d, non-rect textures\n");
3036             return 0;
3037     }
3038
3039     if(fmt == WINED3DFMT_UYVY) {
3040         chroma = 'r';
3041         luminance = 'a';
3042     } else {
3043         chroma = 'a';
3044         luminance = 'r';
3045     }
3046
3047     GL_EXTCALL(glGenProgramsARB(1, &shader));
3048     checkGLcall("GL_EXTCALL(glGenProgramsARB(1, &shader))");
3049     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
3050     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
3051     if(!shader) return 0;
3052
3053     /* The YUY2 and UYVY formats contain two pixels packed into a 32 bit macropixel,
3054      * giving effectively 16 bit per pixel. The color consists of a luminance(Y) and
3055      * two chroma(U and V) values. Each macropixel has two luminance values, one for
3056      * each single pixel it contains, and one U and one V value shared between both
3057      * pixels.
3058      *
3059      * The data is loaded into an A8L8 texture. With YUY2, the luminance component
3060      * contains the luminance and alpha the chroma. With UYVY it is vice versa. Thus
3061      * take the format into account when generating the read swizzles
3062      *
3063      * Reading the Y value is streightforward - just sample the texture. The hardware
3064      * takes care of filtering in the horizontal and vertical direction.
3065      *
3066      * Reading the U and V values is harder. We have to avoid filtering horizontally,
3067      * because that would mix the U and V values of one pixel or two adjacent pixels.
3068      * Thus floor the texture coordinate and add 0.5 to get an unfiltered read,
3069      * regardless of the filtering setting. Vertical filtering works automatically
3070      * though - the U and V values of two rows are mixed nicely.
3071      *
3072      * Appart of avoiding filtering issues, the code has to know which value it just
3073      * read, and where it can find the other one. To determine this, it checks if
3074      * it sampled an even or odd pixel, and shifts the 2nd read accordingly.
3075      *
3076      * Handling horizontal filtering of U and V values requires reading a 2nd pair
3077      * of pixels, extracting U and V and mixing them. This is not implemented yet.
3078      *
3079      * An alternative implementation idea is to load the texture as A8R8G8B8 texture,
3080      * with width / 2. This way one read gives all 3 values, finding U and V is easy
3081      * in an unfiltered situation. Finding the luminance on the other hand requires
3082      * finding out if it is an odd or even pixel. The real drawback of this approach
3083      * is filtering. This would have to be emulated completely in the shader, reading
3084      * up two 2 packed pixels in up to 2 rows and interpolating both horizontally and
3085      * vertically. Beyond that it would require adjustments to the texture handling
3086      * code to deal with the width scaling
3087      */
3088     shader_addline(&buffer, "!!ARBfp1.0\n");
3089     shader_addline(&buffer, "TEMP luminance;\n");
3090     shader_addline(&buffer, "TEMP temp;\n");
3091     shader_addline(&buffer, "TEMP chroma;\n");
3092     shader_addline(&buffer, "TEMP texcrd;\n");
3093     shader_addline(&buffer, "TEMP texcrd2;\n");
3094     shader_addline(&buffer, "PARAM coef = {1.0, 0.5, 2.0, 0.0};\n");
3095     shader_addline(&buffer, "PARAM yuv_coef = {1.403, 0.344, 0.714, 1.770};\n");
3096     shader_addline(&buffer, "PARAM size = program.local[0];\n");
3097
3098     /* First we have to read the chroma values. This means we need at least two pixels(no filtering),
3099      * or 4 pixels(with filtering). To get the unmodified chromas, we have to rid ourselves of the
3100      * filtering when we sample the texture.
3101      *
3102      * These are the rules for reading the chroma:
3103      *
3104      * Even pixel: Cr
3105      * Even pixel: U
3106      * Odd pixel: V
3107      *
3108      * So we have to get the sampling x position in non-normalized coordinates in integers
3109      */
3110     if(textype != GL_TEXTURE_RECTANGLE_ARB) {
3111         shader_addline(&buffer, "MUL texcrd.rg, fragment.texcoord[0], size.x;\n");
3112         shader_addline(&buffer, "MOV texcrd.a, size.x;\n");
3113     } else {
3114         shader_addline(&buffer, "MOV texcrd, fragment.texcoord[0];\n");
3115     }
3116     /* We must not allow filtering between pixel x and x+1, this would mix U and V
3117      * Vertical filtering is ok. However, bear in mind that the pixel center is at
3118      * 0.5, so add 0.5.
3119      */
3120     shader_addline(&buffer, "FLR texcrd.x, texcrd.x;\n");
3121     shader_addline(&buffer, "ADD texcrd.x, texcrd.x, coef.y;\n");
3122
3123     /* Divide the x coordinate by 0.5 and get the fraction. This gives 0.25 and 0.75 for the
3124      * even and odd pixels respectively
3125      */
3126     shader_addline(&buffer, "MUL texcrd2, texcrd, coef.y;\n");
3127     shader_addline(&buffer, "FRC texcrd2, texcrd2;\n");
3128
3129     /* Sample Pixel 1 */
3130     shader_addline(&buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
3131
3132     /* Put the value into either of the chroma values */
3133     shader_addline(&buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
3134     shader_addline(&buffer, "MUL chroma.r, luminance.%c, temp.x;\n", chroma);
3135     shader_addline(&buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
3136     shader_addline(&buffer, "MUL chroma.g, luminance.%c, temp.x;\n", chroma);
3137
3138     /* Sample pixel 2. If we read an even pixel(SLT above returned 1), sample
3139      * the pixel right to the current one. Otherwise, sample the left pixel.
3140      * Bias and scale the SLT result to -1;1 and add it to the texcrd.x.
3141      */
3142     shader_addline(&buffer, "MAD temp.x, temp.x, coef.z, -coef.x;\n");
3143     shader_addline(&buffer, "ADD texcrd.x, texcrd, temp.x;\n");
3144     shader_addline(&buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
3145
3146     /* Put the value into the other chroma */
3147     shader_addline(&buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
3148     shader_addline(&buffer, "MAD chroma.g, luminance.%c, temp.x, chroma.g;\n", chroma);
3149     shader_addline(&buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
3150     shader_addline(&buffer, "MAD chroma.r, luminance.%c, temp.x, chroma.r;\n", chroma);
3151
3152     /* TODO: If filtering is enabled, sample a 2nd pair of pixels left or right of
3153      * the current one and lerp the two U and V values
3154      */
3155
3156     /* This gives the correctly filtered luminance value */
3157     shader_addline(&buffer, "TEX luminance, fragment.texcoord[0], texture[0], %s;\n", tex);
3158
3159     /* Calculate the final result. Formula is taken from
3160      * http://www.fourcc.org/fccyvrgb.php. Note that the chroma
3161      * ranges from -0.5 to 0.5
3162      */
3163     shader_addline(&buffer, "SUB chroma.rg, chroma, coef.y;\n");
3164
3165     shader_addline(&buffer, "MAD result.color.r, chroma.r, yuv_coef.x, luminance.%c;\n", luminance);
3166     shader_addline(&buffer, "MAD temp.r, -chroma.g, yuv_coef.y, luminance.%c;\n", luminance);
3167     shader_addline(&buffer, "MAD result.color.g, -chroma.r, yuv_coef.z, temp.r;\n");
3168     shader_addline(&buffer, "MAD result.color.b, chroma.g, yuv_coef.w, luminance.%c;\n", luminance);
3169     shader_addline(&buffer, "END\n");
3170
3171     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
3172
3173     if (glGetError() == GL_INVALID_OPERATION) {
3174         GLint pos;
3175         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
3176         FIXME("Fragment program error at position %d: %s\n", pos,
3177               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3178     }
3179
3180     if(fmt == WINED3DFMT_YUY2) {
3181         if(textype == GL_TEXTURE_RECTANGLE_ARB) {
3182             priv->yuy2_rect_shader = shader;
3183         } else {
3184             priv->yuy2_2d_shader = shader;
3185         }
3186     } else {
3187         if(textype == GL_TEXTURE_RECTANGLE_ARB) {
3188             priv->uyvy_rect_shader = shader;
3189         } else {
3190             priv->uyvy_2d_shader = shader;
3191         }
3192     }
3193     return shader;
3194 }
3195
3196 static HRESULT arbfp_blit_set(IWineD3DDevice *iface, WINED3DFORMAT fmt, GLenum textype, UINT width, UINT height) {
3197     GLenum shader;
3198     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3199     float size[4] = {width, height, 1, 1};
3200     struct arbfp_blit_priv *priv = (struct arbfp_blit_priv *) device->blit_priv;
3201     const GlPixelFormatDesc *glDesc;
3202
3203     getFormatDescEntry(fmt, &GLINFO_LOCATION, &glDesc);
3204
3205     if(glDesc->conversion_group != WINED3DFMT_YUY2 && glDesc->conversion_group != WINED3DFMT_UYVY) {
3206         /* Don't bother setting up a shader for unconverted formats */
3207         glEnable(textype);
3208         checkGLcall("glEnable(textype)");
3209         return WINED3D_OK;
3210     }
3211
3212     if(glDesc->conversion_group == WINED3DFMT_YUY2) {
3213         if(textype == GL_TEXTURE_RECTANGLE_ARB) {
3214             shader = priv->yuy2_rect_shader;
3215         } else {
3216             shader = priv->yuy2_2d_shader;
3217         }
3218     } else {
3219         if(textype == GL_TEXTURE_RECTANGLE_ARB) {
3220             shader = priv->uyvy_rect_shader;
3221         } else {
3222             shader = priv->uyvy_2d_shader;
3223         }
3224     }
3225
3226     if(!shader) {
3227         shader = gen_yuv_shader(device, glDesc->conversion_group, textype);
3228     }
3229
3230     glEnable(GL_FRAGMENT_PROGRAM_ARB);
3231     checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
3232     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
3233     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
3234     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, size));
3235     checkGLcall("glProgramLocalParameter4fvARB");
3236
3237     return WINED3D_OK;
3238 }
3239
3240 static void arbfp_blit_unset(IWineD3DDevice *iface) {
3241     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3242     glDisable(GL_FRAGMENT_PROGRAM_ARB);
3243     checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
3244     glDisable(GL_TEXTURE_2D);
3245     checkGLcall("glDisable(GL_TEXTURE_2D)");
3246     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
3247         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
3248         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
3249     }
3250     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3251         glDisable(GL_TEXTURE_RECTANGLE_ARB);
3252         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
3253     }
3254 }
3255
3256 static BOOL arbfp_blit_conv_supported(WINED3DFORMAT fmt) {
3257     TRACE("Checking blit format support for format %s:", debug_d3dformat(fmt));
3258     switch(fmt) {
3259         case WINED3DFMT_YUY2:
3260         case WINED3DFMT_UYVY:
3261             TRACE("[OK]\n");
3262             return TRUE;
3263         default:
3264             TRACE("[FAILED]\n");
3265             return FALSE;
3266     }
3267 }
3268
3269 const struct blit_shader arbfp_blit = {
3270     arbfp_blit_alloc,
3271     arbfp_blit_free,
3272     arbfp_blit_set,
3273     arbfp_blit_unset,
3274     arbfp_blit_conv_supported
3275 };
3276
3277 #undef GLINFO_LOCATION