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