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