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