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