wined3d: Explicitly pass gl_info to stateblock_savedstates_set().
[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 struct wined3d_gl_info *gl_info)
46 {
47     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) shader;
48     if(!This->baseShader.reg_maps.usesmova) return FALSE;
49     return !GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION);
50 }
51
52 /* Returns TRUE if result.clip from GL_NV_vertex_program2 should be used and FALSE otherwise */
53 static inline BOOL use_nv_clip(const struct wined3d_gl_info *gl_info)
54 {
55     return GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION) &&
56            !(GLINFO_LOCATION.quirks & WINED3D_QUIRK_NV_CLIP_BROKEN);
57 }
58
59 static BOOL need_helper_const(const struct wined3d_gl_info *gl_info)
60 {
61     if (!GL_SUPPORT(NV_VERTEX_PROGRAM) /* Need to init colors. */
62         || gl_info->quirks & WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT /* Load the immval offset. */
63         || gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W /* Have to init texcoords. */
64         || (!use_nv_clip(gl_info)) /* Init the clip texcoord */)
65     {
66         return TRUE;
67     }
68     return FALSE;
69 }
70
71 static unsigned int reserved_vs_const(IWineD3DBaseShader *shader, const struct wined3d_gl_info *gl_info)
72 {
73     unsigned int ret = 1;
74     /* We use one PARAM for the pos fixup, and in some cases one to load
75      * some immediate values into the shader
76      */
77     if(need_helper_const(gl_info)) ret++;
78     if(need_mova_const(shader, gl_info)) ret++;
79     return ret;
80 }
81
82 static inline BOOL ffp_clip_emul(IWineD3DStateBlockImpl *stateblock)
83 {
84     return stateblock->lowest_disabled_stage < 7;
85 }
86
87 /* Internally used shader constants. Applications can use constants 0 to GL_LIMITS(vshader_constantsF) - 1,
88  * so upload them above that
89  */
90 #define ARB_SHADER_PRIVCONST_BASE (GL_LIMITS(vshader_constantsF) - 1)
91 #define ARB_SHADER_PRIVCONST_POS ARB_SHADER_PRIVCONST_BASE + 0
92
93 /* ARB_program_shader private data */
94
95 struct control_frame
96 {
97     struct                          list entry;
98     enum
99     {
100         IF,
101         IFC,
102         LOOP,
103         REP
104     } type;
105     BOOL                            muting;
106     BOOL                            outer_loop;
107     union
108     {
109         unsigned int                loop_no;
110         unsigned int                ifc_no;
111     };
112     struct wined3d_shader_loop_control loop_control;
113     BOOL                            had_else;
114 };
115
116 struct arb_ps_np2fixup_info
117 {
118     struct ps_np2fixup_info         super;
119     /* For ARB we need a offset value:
120      * With both GLSL and ARB mode the NP2 fixup information (the texture dimensions) are stored in a
121      * consecutive way (GLSL uses a uniform array). Since ARB doesn't know the notion of a "standalone"
122      * array we need an offset to the index inside the program local parameter array. */
123     UINT                            offset;
124 };
125
126 struct arb_ps_compile_args
127 {
128     struct ps_compile_args          super;
129     WORD                            bools;
130     WORD                            clip;  /* only a boolean, use a WORD for alignment */
131     unsigned char                   loop_ctrl[MAX_CONST_I][3];
132 };
133
134 struct stb_const_desc
135 {
136     unsigned char           texunit;
137     UINT                    const_num;
138 };
139
140 struct arb_ps_compiled_shader
141 {
142     struct arb_ps_compile_args      args;
143     struct arb_ps_np2fixup_info     np2fixup_info;
144     struct stb_const_desc           bumpenvmatconst[MAX_TEXTURES];
145     struct stb_const_desc           luminanceconst[MAX_TEXTURES];
146     UINT                            int_consts[MAX_CONST_I];
147     GLuint                          prgId;
148     UINT                            ycorrection;
149     unsigned char                   numbumpenvmatconsts;
150     char                            num_int_consts;
151 };
152
153 struct arb_vs_compile_args
154 {
155     struct vs_compile_args          super;
156     union
157     {
158         struct
159         {
160             WORD                    bools;
161             char                    clip_control[2];
162         }                           boolclip;
163         DWORD                       boolclip_compare;
164     };
165     DWORD                           ps_signature;
166     union
167     {
168         unsigned char               vertex_samplers[4];
169         DWORD                       vertex_samplers_compare;
170     };
171     unsigned char                   loop_ctrl[MAX_CONST_I][3];
172 };
173
174 struct arb_vs_compiled_shader
175 {
176     struct arb_vs_compile_args      args;
177     GLuint                          prgId;
178     UINT                            int_consts[MAX_CONST_I];
179     char                            num_int_consts;
180     char                            need_color_unclamp;
181     UINT                            pos_fixup;
182 };
183
184 struct recorded_instruction
185 {
186     struct wined3d_shader_instruction ins;
187     struct list entry;
188 };
189
190 struct shader_arb_ctx_priv
191 {
192     char addr_reg[20];
193     enum
194     {
195         /* plain GL_ARB_vertex_program or GL_ARB_fragment_program */
196         ARB,
197         /* GL_NV_vertex_progam2_option or GL_NV_fragment_program_option */
198         NV2,
199         /* GL_NV_vertex_program3 or GL_NV_fragment_program2 */
200         NV3
201     } target_version;
202
203     const struct arb_vs_compile_args    *cur_vs_args;
204     const struct arb_ps_compile_args    *cur_ps_args;
205     const struct arb_ps_compiled_shader *compiled_fprog;
206     const struct arb_vs_compiled_shader *compiled_vprog;
207     struct arb_ps_np2fixup_info         *cur_np2fixup_info;
208     struct list                         control_frames;
209     struct list                         record;
210     BOOL                                recording;
211     BOOL                                muted;
212     unsigned int                        num_loops, loop_depth, num_ifcs;
213     int                                 aL;
214
215     unsigned int                        vs_clipplanes;
216     BOOL                                footer_written;
217     BOOL                                in_main_func;
218
219     /* For 3.0 vertex shaders */
220     const char                          *vs_output[MAX_REG_OUTPUT];
221     /* For 2.x and earlier vertex shaders */
222     const char                          *texcrd_output[8], *color_output[2], *fog_output;
223
224     /* 3.0 pshader input for compatibility with fixed function */
225     const char                          *ps_input[MAX_REG_INPUT];
226 };
227
228 struct ps_signature
229 {
230     struct wined3d_shader_signature_element *sig;
231     DWORD                               idx;
232     struct wine_rb_entry                entry;
233 };
234
235 struct arb_pshader_private {
236     struct arb_ps_compiled_shader   *gl_shaders;
237     UINT                            num_gl_shaders, shader_array_size;
238     BOOL                            has_signature_idx;
239     DWORD                           input_signature_idx;
240     DWORD                           clipplane_emulation;
241     BOOL                            clamp_consts;
242 };
243
244 struct arb_vshader_private {
245     struct arb_vs_compiled_shader   *gl_shaders;
246     UINT                            num_gl_shaders, shader_array_size;
247 };
248
249 struct shader_arb_priv
250 {
251     GLuint                  current_vprogram_id;
252     GLuint                  current_fprogram_id;
253     const struct arb_ps_compiled_shader *compiled_fprog;
254     const struct arb_vs_compiled_shader *compiled_vprog;
255     GLuint                  depth_blt_vprogram_id;
256     GLuint                  depth_blt_fprogram_id[tex_type_count];
257     BOOL                    use_arbfp_fixed_func;
258     struct wine_rb_tree     fragment_shaders;
259     BOOL                    last_ps_const_clamped;
260     BOOL                    last_vs_color_unclamp;
261
262     struct wine_rb_tree     signature_tree;
263     DWORD ps_sig_number;
264 };
265
266 /********************************************************
267  * ARB_[vertex/fragment]_program helper functions follow
268  ********************************************************/
269
270 /* Loads floating point constants into the currently set ARB_vertex/fragment_program.
271  * When constant_list == NULL, it will load all the constants.
272  *
273  * @target_type should be either GL_VERTEX_PROGRAM_ARB (for vertex shaders)
274  *  or GL_FRAGMENT_PROGRAM_ARB (for pixel shaders)
275  */
276 /* GL locking is done by the caller */
277 static unsigned int shader_arb_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
278         GLuint target_type, unsigned int max_constants, const float *constants, char *dirty_consts)
279 {
280     local_constant* lconst;
281     DWORD i, j;
282     unsigned int ret;
283
284     if (TRACE_ON(d3d_constants))
285     {
286         for(i = 0; i < max_constants; i++) {
287             if(!dirty_consts[i]) continue;
288             TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
289                         constants[i * 4 + 0], constants[i * 4 + 1],
290                         constants[i * 4 + 2], constants[i * 4 + 3]);
291         }
292     }
293
294     i = 0;
295
296     /* In 1.X pixel shaders constants are implicitly clamped in the range [-1;1] */
297     if (target_type == GL_FRAGMENT_PROGRAM_ARB && This->baseShader.reg_maps.shader_version.major == 1)
298     {
299         float lcl_const[4];
300         /* ps 1.x supports only 8 constants, clamp only those. When switching between 1.x and higher
301          * shaders, the first 8 constants are marked dirty for reload
302          */
303         for(; i < min(8, max_constants); i++) {
304             if(!dirty_consts[i]) continue;
305             dirty_consts[i] = 0;
306
307             j = 4 * i;
308             if (constants[j + 0] > 1.0f) lcl_const[0] = 1.0f;
309             else if (constants[j + 0] < -1.0f) lcl_const[0] = -1.0f;
310             else lcl_const[0] = constants[j + 0];
311
312             if (constants[j + 1] > 1.0f) lcl_const[1] = 1.0f;
313             else if (constants[j + 1] < -1.0f) lcl_const[1] = -1.0f;
314             else lcl_const[1] = constants[j + 1];
315
316             if (constants[j + 2] > 1.0f) lcl_const[2] = 1.0f;
317             else if (constants[j + 2] < -1.0f) lcl_const[2] = -1.0f;
318             else lcl_const[2] = constants[j + 2];
319
320             if (constants[j + 3] > 1.0f) lcl_const[3] = 1.0f;
321             else if (constants[j + 3] < -1.0f) lcl_const[3] = -1.0f;
322             else lcl_const[3] = constants[j + 3];
323
324             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
325         }
326
327         /* If further constants are dirty, reload them without clamping.
328          *
329          * The alternative is not to touch them, but then we cannot reset the dirty constant count
330          * to zero. That's bad for apps that only use PS 1.x shaders, because in that case the code
331          * above would always re-check the first 8 constants since max_constant remains at the init
332          * value
333          */
334     }
335
336     if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
337         /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
338          * or just reloading *all* constants at once
339          *
340         GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, i, max_constants, constants + (i * 4)));
341          */
342         for(; i < max_constants; i++) {
343             if(!dirty_consts[i]) continue;
344
345             /* Find the next block of dirty constants */
346             dirty_consts[i] = 0;
347             j = i;
348             for(i++; (i < max_constants) && dirty_consts[i]; i++) {
349                 dirty_consts[i] = 0;
350             }
351
352             GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
353         }
354     } else {
355         for(; i < max_constants; i++) {
356             if(dirty_consts[i]) {
357                 dirty_consts[i] = 0;
358                 GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
359             }
360         }
361     }
362     checkGLcall("glProgramEnvParameter4fvARB()");
363
364     /* Load immediate constants */
365     if(This->baseShader.load_local_constsF) {
366         if (TRACE_ON(d3d_shader)) {
367             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
368                 GLfloat* values = (GLfloat*)lconst->value;
369                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
370                         values[0], values[1], values[2], values[3]);
371             }
372         }
373         /* Immediate constants are clamped for 1.X shaders at loading times */
374         ret = 0;
375         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
376             dirty_consts[lconst->idx] = 1; /* Dirtify so the non-immediate constant overwrites it next time */
377             ret = max(ret, lconst->idx + 1);
378             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, lconst->idx, (GLfloat*)lconst->value));
379         }
380         checkGLcall("glProgramEnvParameter4fvARB()");
381         return ret; /* The loaded immediate constants need reloading for the next shader */
382     } else {
383         return 0; /* No constants are dirty now */
384     }
385 }
386
387 /**
388  * Loads the texture dimensions for NP2 fixup into the currently set ARB_[vertex/fragment]_programs.
389  */
390 static void shader_arb_load_np2fixup_constants(
391     IWineD3DDevice* device,
392     char usePixelShader,
393     char useVertexShader) {
394
395     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl *) device;
396     const struct shader_arb_priv* const priv = (const struct shader_arb_priv *) deviceImpl->shader_priv;
397     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
398     const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
399
400     if (!usePixelShader) {
401         /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
402         return;
403     }
404
405     if (priv->compiled_fprog && priv->compiled_fprog->np2fixup_info.super.active) {
406         const struct arb_ps_np2fixup_info* const fixup = &priv->compiled_fprog->np2fixup_info;
407         UINT i;
408         WORD active = fixup->super.active;
409         GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
410
411         for (i = 0; active; active >>= 1, ++i) {
412             const unsigned char idx = fixup->super.idx[i];
413             const IWineD3DTextureImpl* const tex = (const IWineD3DTextureImpl*) stateBlock->textures[i];
414             GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
415
416             if (!(active & 1)) continue;
417
418             if (!tex) {
419                 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
420                 continue;
421             }
422
423             if (idx % 2) {
424                 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
425             } else {
426                 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
427             }
428         }
429
430         for (i = 0; i < fixup->super.num_consts; ++i) {
431             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB,
432                                                    fixup->offset + i, &np2fixup_constants[i * 4]));
433         }
434     }
435 }
436
437 /* GL locking is done by the caller. */
438 static inline void shader_arb_ps_local_constants(IWineD3DDeviceImpl* deviceImpl)
439 {
440     const struct wined3d_context *context = context_get_current();
441     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
442     const struct wined3d_gl_info *gl_info = context->gl_info;
443     unsigned char i;
444     struct shader_arb_priv *priv = deviceImpl->shader_priv;
445     const struct arb_ps_compiled_shader *gl_shader = priv->compiled_fprog;
446
447     for(i = 0; i < gl_shader->numbumpenvmatconsts; i++)
448     {
449         int texunit = gl_shader->bumpenvmatconst[i].texunit;
450
451         /* The state manager takes care that this function is always called if the bump env matrix changes */
452         const float *data = (const float *)&stateBlock->textureState[texunit][WINED3DTSS_BUMPENVMAT00];
453         GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->bumpenvmatconst[i].const_num, data));
454
455         if (gl_shader->luminanceconst[i].const_num != WINED3D_CONST_NUM_UNUSED)
456         {
457             /* WINED3DTSS_BUMPENVLSCALE and WINED3DTSS_BUMPENVLOFFSET are next to each other.
458              * point gl to the scale, and load 4 floats. x = scale, y = offset, z and w are junk, we
459              * don't care about them. The pointers are valid for sure because the stateblock is bigger.
460              * (they're WINED3DTSS_TEXTURETRANSFORMFLAGS and WINED3DTSS_ADDRESSW, so most likely 0 or NaN
461             */
462             const float *scale = (const float *)&stateBlock->textureState[texunit][WINED3DTSS_BUMPENVLSCALE];
463             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->luminanceconst[i].const_num, scale));
464         }
465     }
466     checkGLcall("Load bumpmap consts");
467
468     if(gl_shader->ycorrection != WINED3D_CONST_NUM_UNUSED)
469     {
470         /* ycorrection.x: Backbuffer height(onscreen) or 0(offscreen).
471         * ycorrection.y: -1.0(onscreen), 1.0(offscreen)
472         * ycorrection.z: 1.0
473         * ycorrection.w: 0.0
474         */
475         float val[4];
476         val[0] = context->render_offscreen ? 0.0f
477                 : ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
478         val[1] = context->render_offscreen ? 1.0f : -1.0f;
479         val[2] = 1.0f;
480         val[3] = 0.0f;
481         GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->ycorrection, val));
482         checkGLcall("y correction loading");
483     }
484
485     if(gl_shader->num_int_consts == 0) return;
486
487     for(i = 0; i < MAX_CONST_I; i++)
488     {
489         if(gl_shader->int_consts[i] != WINED3D_CONST_NUM_UNUSED)
490         {
491             float val[4];
492             val[0] = stateBlock->pixelShaderConstantI[4 * i];
493             val[1] = stateBlock->pixelShaderConstantI[4 * i + 1];
494             val[2] = stateBlock->pixelShaderConstantI[4 * i + 2];
495             val[3] = -1.0f;
496
497             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->int_consts[i], val));
498         }
499     }
500     checkGLcall("Load ps int consts");
501 }
502
503 /* GL locking is done by the caller. */
504 static inline void shader_arb_vs_local_constants(IWineD3DDeviceImpl* deviceImpl)
505 {
506     IWineD3DStateBlockImpl* stateBlock;
507     const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
508     unsigned char i;
509     struct shader_arb_priv *priv = deviceImpl->shader_priv;
510     const struct arb_vs_compiled_shader *gl_shader = priv->compiled_vprog;
511
512     /* Upload the position fixup */
513     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, gl_shader->pos_fixup, deviceImpl->posFixup));
514
515     if(gl_shader->num_int_consts == 0) return;
516
517     stateBlock = deviceImpl->stateBlock;
518
519     for(i = 0; i < MAX_CONST_I; i++)
520     {
521         if(gl_shader->int_consts[i] != WINED3D_CONST_NUM_UNUSED)
522         {
523             float val[4];
524             val[0] = stateBlock->vertexShaderConstantI[4 * i];
525             val[1] = stateBlock->vertexShaderConstantI[4 * i + 1];
526             val[2] = stateBlock->vertexShaderConstantI[4 * i + 2];
527             val[3] = -1.0f;
528
529             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, gl_shader->int_consts[i], val));
530         }
531     }
532     checkGLcall("Load vs int consts");
533 }
534
535 /**
536  * Loads the app-supplied constants into the currently set ARB_[vertex/fragment]_programs.
537  *
538  * We only support float constants in ARB at the moment, so don't
539  * worry about the Integers or Booleans
540  */
541 /* GL locking is done by the caller (state handler) */
542 static void shader_arb_load_constants(const struct wined3d_context *context, char usePixelShader, char useVertexShader)
543 {
544     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
545     IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
546     const struct wined3d_gl_info *gl_info = context->gl_info;
547
548     if (useVertexShader) {
549         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
550
551         /* Load DirectX 9 float constants for vertex shader */
552         device->highest_dirty_vs_const = shader_arb_load_constantsF(vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
553                 device->highest_dirty_vs_const, stateBlock->vertexShaderConstantF, context->vshader_const_dirty);
554         shader_arb_vs_local_constants(device);
555     }
556
557     if (usePixelShader) {
558         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
559
560         /* Load DirectX 9 float constants for pixel shader */
561         device->highest_dirty_ps_const = shader_arb_load_constantsF(pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
562                 device->highest_dirty_ps_const, stateBlock->pixelShaderConstantF, context->pshader_const_dirty);
563         shader_arb_ps_local_constants(device);
564     }
565 }
566
567 static void shader_arb_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
568 {
569     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
570     struct wined3d_context *context = context_get_current();
571
572     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
573      * context. On a context switch the old context will be fully dirtified */
574     if (!context || ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice != This) return;
575
576     memset(context->vshader_const_dirty + start, 1, sizeof(*context->vshader_const_dirty) * count);
577     This->highest_dirty_vs_const = max(This->highest_dirty_vs_const, start + count);
578 }
579
580 static void shader_arb_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
581 {
582     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
583     struct wined3d_context *context = context_get_current();
584
585     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
586      * context. On a context switch the old context will be fully dirtified */
587     if (!context || ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice != This) return;
588
589     memset(context->pshader_const_dirty + start, 1, sizeof(*context->pshader_const_dirty) * count);
590     This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, start + count);
591 }
592
593 static DWORD *local_const_mapping(IWineD3DBaseShaderImpl *This)
594 {
595     DWORD *ret;
596     DWORD idx = 0;
597     const local_constant *lconst;
598
599     if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) return NULL;
600
601     ret = HeapAlloc(GetProcessHeap(), 0, sizeof(DWORD) * This->baseShader.limits.constant_float);
602     if(!ret) {
603         ERR("Out of memory\n");
604         return NULL;
605     }
606
607     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
608         ret[lconst->idx] = idx++;
609     }
610     return ret;
611 }
612
613 /* Generate the variable & register declarations for the ARB_vertex_program output target */
614 static DWORD shader_generate_arb_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
615         struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, DWORD *lconst_map,
616         DWORD *num_clipplanes, struct shader_arb_ctx_priv *ctx)
617 {
618     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
619     DWORD i, next_local = 0;
620     char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
621     unsigned max_constantsF;
622     const local_constant *lconst;
623     DWORD map;
624
625     /* In pixel shaders, all private constants are program local, we don't need anything
626      * from program.env. Thus we can advertise the full set of constants in pixel shaders.
627      * If we need a private constant the GL implementation will squeeze it in somewhere
628      *
629      * With vertex shaders we need the posFixup and on some GL implementations 4 helper
630      * immediate values. The posFixup is loaded using program.env for now, so always
631      * subtract one from the number of constants. If the shader uses indirect addressing,
632      * account for the helper const too because we have to declare all availabke d3d constants
633      * and don't know which are actually used.
634      */
635     if(pshader) {
636         max_constantsF = GL_LIMITS(pshader_constantsF);
637     } else {
638         if(This->baseShader.reg_maps.usesrelconstF) {
639             DWORD highest_constf = 0, clip_limit;
640             max_constantsF = GL_LIMITS(vshader_constantsF) - reserved_vs_const(iface, gl_info);
641             max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
642
643             for(i = 0; i < This->baseShader.limits.constant_float; i++)
644             {
645                 DWORD idx = i >> 5;
646                 DWORD shift = i & 0x1f;
647                 if(reg_maps->constf[idx] & (1 << shift)) highest_constf = i;
648             }
649
650             clip_limit = GL_LIMITS(clipplanes);
651             if(ctx->target_version == ARB) clip_limit = min(clip_limit, 4);
652             *num_clipplanes = min(clip_limit, max_constantsF - highest_constf - 1);
653             max_constantsF -= *num_clipplanes;
654             if(*num_clipplanes < clip_limit)
655             {
656                 WARN("Only %u clipplanes out of %u enabled\n", *num_clipplanes, GL_LIMITS(clipplanes));
657             }
658         }
659         else
660         {
661             if(ctx->target_version >= NV2) *num_clipplanes = GL_LIMITS(clipplanes);
662             else *num_clipplanes = min(GL_LIMITS(clipplanes), 4);
663             max_constantsF = GL_LIMITS(vshader_constantsF);
664         }
665     }
666
667     for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
668     {
669         if (map & 1) shader_addline(buffer, "TEMP R%u;\n", i);
670     }
671
672     for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
673     {
674         if (map & 1) shader_addline(buffer, "ADDRESS A%u;\n", i);
675     }
676
677     if (pshader && reg_maps->shader_version.major == 1 && reg_maps->shader_version.minor <= 3)
678     {
679         for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
680         {
681             if (map & 1) shader_addline(buffer, "TEMP T%u;\n", i);
682         }
683     }
684
685     /* Load local constants using the program-local space,
686      * this avoids reloading them each time the shader is used
687      */
688     if(lconst_map) {
689         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
690             shader_addline(buffer, "PARAM C%u = program.local[%u];\n", lconst->idx,
691                            lconst_map[lconst->idx]);
692             next_local = max(next_local, lconst_map[lconst->idx] + 1);
693         }
694     }
695
696     /* we use the array-based constants array if the local constants are marked for loading,
697      * because then we use indirect addressing, or when the local constant list is empty,
698      * because then we don't know if we're using indirect addressing or not. If we're hardcoding
699      * local constants do not declare the loaded constants as an array because ARB compilers usually
700      * do not optimize unused constants away
701      */
702     if(This->baseShader.reg_maps.usesrelconstF) {
703         /* Need to PARAM the environment parameters (constants) so we can use relative addressing */
704         shader_addline(buffer, "PARAM C[%d] = { program.env[0..%d] };\n",
705                     max_constantsF, max_constantsF - 1);
706     } else {
707         for(i = 0; i < max_constantsF; i++) {
708             DWORD idx, mask;
709             idx = i >> 5;
710             mask = 1 << (i & 0x1f);
711             if(!shader_constant_is_local(This, i) && (This->baseShader.reg_maps.constf[idx] & mask)) {
712                 shader_addline(buffer, "PARAM C%d = program.env[%d];\n",i, i);
713             }
714         }
715     }
716
717     return next_local;
718 }
719
720 static const char * const shift_tab[] = {
721     "dummy",     /*  0 (none) */
722     "coefmul.x", /*  1 (x2)   */
723     "coefmul.y", /*  2 (x4)   */
724     "coefmul.z", /*  3 (x8)   */
725     "coefmul.w", /*  4 (x16)  */
726     "dummy",     /*  5 (x32)  */
727     "dummy",     /*  6 (x64)  */
728     "dummy",     /*  7 (x128) */
729     "dummy",     /*  8 (d256) */
730     "dummy",     /*  9 (d128) */
731     "dummy",     /* 10 (d64)  */
732     "dummy",     /* 11 (d32)  */
733     "coefdiv.w", /* 12 (d16)  */
734     "coefdiv.z", /* 13 (d8)   */
735     "coefdiv.y", /* 14 (d4)   */
736     "coefdiv.x"  /* 15 (d2)   */
737 };
738
739 static void shader_arb_get_write_mask(const struct wined3d_shader_instruction *ins,
740         const struct wined3d_shader_dst_param *dst, char *write_mask)
741 {
742     char *ptr = write_mask;
743
744     if (dst->write_mask != WINED3DSP_WRITEMASK_ALL)
745     {
746         *ptr++ = '.';
747         if (dst->write_mask & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
748         if (dst->write_mask & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
749         if (dst->write_mask & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
750         if (dst->write_mask & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
751     }
752
753     *ptr = '\0';
754 }
755
756 static void shader_arb_get_swizzle(const struct wined3d_shader_src_param *param, BOOL fixup, char *swizzle_str)
757 {
758     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
759      * but addressed as "rgba". To fix this we need to swap the register's x
760      * and z components. */
761     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
762     char *ptr = swizzle_str;
763
764     /* swizzle bits fields: wwzzyyxx */
765     DWORD swizzle = param->swizzle;
766     DWORD swizzle_x = swizzle & 0x03;
767     DWORD swizzle_y = (swizzle >> 2) & 0x03;
768     DWORD swizzle_z = (swizzle >> 4) & 0x03;
769     DWORD swizzle_w = (swizzle >> 6) & 0x03;
770
771     /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
772      * generate a swizzle string. Unless we need to our own swizzling. */
773     if (swizzle != WINED3DSP_NOSWIZZLE || fixup)
774     {
775         *ptr++ = '.';
776         if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
777             *ptr++ = swizzle_chars[swizzle_x];
778         } else {
779             *ptr++ = swizzle_chars[swizzle_x];
780             *ptr++ = swizzle_chars[swizzle_y];
781             *ptr++ = swizzle_chars[swizzle_z];
782             *ptr++ = swizzle_chars[swizzle_w];
783         }
784     }
785
786     *ptr = '\0';
787 }
788
789 static void shader_arb_request_a0(const struct wined3d_shader_instruction *ins, const char *src)
790 {
791     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
792     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
793
794     if(strcmp(priv->addr_reg, src) == 0) return;
795
796     strcpy(priv->addr_reg, src);
797     shader_addline(buffer, "ARL A0.x, %s;\n", src);
798 }
799
800 static void shader_arb_get_src_param(const struct wined3d_shader_instruction *ins,
801         const struct wined3d_shader_src_param *src, unsigned int tmpreg, char *outregstr);
802
803 static void shader_arb_get_register_name(const struct wined3d_shader_instruction *ins,
804         const struct wined3d_shader_register *reg, char *register_name, BOOL *is_color)
805 {
806     /* oPos, oFog and oPts in D3D */
807     static const char * const rastout_reg_names[] = {"TMP_OUT", "result.fogcoord", "result.pointsize"};
808     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
809     BOOL pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
810     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
811
812     *is_color = FALSE;
813
814     switch (reg->type)
815     {
816         case WINED3DSPR_TEMP:
817             sprintf(register_name, "R%u", reg->idx);
818             break;
819
820         case WINED3DSPR_INPUT:
821             if (pshader)
822             {
823                 if(This->baseShader.reg_maps.shader_version.major < 3)
824                 {
825                     if (reg->idx == 0) strcpy(register_name, "fragment.color.primary");
826                     else strcpy(register_name, "fragment.color.secondary");
827                 }
828                 else
829                 {
830                     if(reg->rel_addr)
831                     {
832                         char rel_reg[50];
833                         shader_arb_get_src_param(ins, reg->rel_addr, 0, rel_reg);
834
835                         if(strcmp(rel_reg, "**aL_emul**") == 0)
836                         {
837                             DWORD idx = ctx->aL + reg->idx;
838                             if(idx < MAX_REG_INPUT)
839                             {
840                                 strcpy(register_name, ctx->ps_input[idx]);
841                             }
842                             else
843                             {
844                                 ERR("Pixel shader input register out of bounds: %u\n", idx);
845                                 sprintf(register_name, "out_of_bounds_%u", idx);
846                             }
847                         }
848                         else if(This->baseShader.reg_maps.input_registers & 0x0300)
849                         {
850                             /* There are two ways basically:
851                              *
852                              * 1) Use the unrolling code that is used for loop emulation and unroll the loop.
853                              *    That means trouble if the loop also contains a breakc or if the control values
854                              *    aren't local constants.
855                              * 2) Generate an if block that checks if aL.y < 8, == 8 or == 9 and selects the
856                              *    source dynamically. The trouble is that we cannot simply read aL.y because it
857                              *    is an ADDRESS register. We could however push it, load .zw with a value and use
858                              *    ADAC to load the condition code register and pop it again afterwards
859                              */
860                             FIXME("Relative input register addressing with more than 8 registers\n");
861
862                             /* This is better than nothing for now */
863                             sprintf(register_name, "fragment.texcoord[%s + %u]", rel_reg, reg->idx);
864                         }
865                         else if(ctx->cur_ps_args->super.vp_mode != vertexshader)
866                         {
867                             /* This is problematic because we'd have to consult the ctx->ps_input strings
868                              * for where to find the varying. Some may be "0.0", others can be texcoords or
869                              * colors. This needs either a pipeline replacement to make the vertex shader feed
870                              * proper varyings, or loop unrolling
871                              *
872                              * For now use the texcoords and hope for the best
873                              */
874                             FIXME("Non-vertex shader varying input with indirect addressing\n");
875                             sprintf(register_name, "fragment.texcoord[%s + %u]", rel_reg, reg->idx);
876                         }
877                         else
878                         {
879                             /* D3D supports indirect addressing only with aL in loop registers. The loop instruction
880                              * pulls GL_NV_fragment_program2 in
881                              */
882                             sprintf(register_name, "fragment.texcoord[%s + %u]", rel_reg, reg->idx);
883                         }
884                     }
885                     else
886                     {
887                         if(reg->idx < MAX_REG_INPUT)
888                         {
889                             strcpy(register_name, ctx->ps_input[reg->idx]);
890                         }
891                         else
892                         {
893                             ERR("Pixel shader input register out of bounds: %u\n", reg->idx);
894                             sprintf(register_name, "out_of_bounds_%u", reg->idx);
895                         }
896                     }
897                 }
898             }
899             else
900             {
901                 if (ctx->cur_vs_args->super.swizzle_map & (1 << reg->idx)) *is_color = TRUE;
902                 sprintf(register_name, "vertex.attrib[%u]", reg->idx);
903             }
904             break;
905
906         case WINED3DSPR_CONST:
907             if (!pshader && reg->rel_addr)
908             {
909                 BOOL aL = FALSE;
910                 char rel_reg[50];
911                 UINT rel_offset = ((IWineD3DVertexShaderImpl *)This)->rel_offset;
912                 if(This->baseShader.reg_maps.shader_version.major < 2) {
913                     sprintf(rel_reg, "A0.x");
914                 } else {
915                     shader_arb_get_src_param(ins, reg->rel_addr, 0, rel_reg);
916                     if(ctx->target_version == ARB) {
917                         if(strcmp(rel_reg, "**aL_emul**") == 0) {
918                             aL = TRUE;
919                         } else {
920                             shader_arb_request_a0(ins, rel_reg);
921                             sprintf(rel_reg, "A0.x");
922                         }
923                     }
924                 }
925                 if(aL)
926                     sprintf(register_name, "C[%u]", ctx->aL + reg->idx);
927                 else if (reg->idx >= rel_offset)
928                     sprintf(register_name, "C[%s + %u]", rel_reg, reg->idx - rel_offset);
929                 else
930                     sprintf(register_name, "C[%s - %u]", rel_reg, -reg->idx + rel_offset);
931             }
932             else
933             {
934                 if (This->baseShader.reg_maps.usesrelconstF)
935                     sprintf(register_name, "C[%u]", reg->idx);
936                 else
937                     sprintf(register_name, "C%u", reg->idx);
938             }
939             break;
940
941         case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
942             if (pshader) {
943                 if(This->baseShader.reg_maps.shader_version.major == 1 &&
944                    This->baseShader.reg_maps.shader_version.minor <= 3) {
945                     /* In ps <= 1.3, Tx is a temporary register as destination to all instructions,
946                      * and as source to most instructions. For some instructions it is the texcoord
947                      * input. Those instructions know about the special use
948                      */
949                     sprintf(register_name, "T%u", reg->idx);
950                 } else {
951                     /* in ps 1.4 and 2.x Tx is always a (read-only) varying */
952                     sprintf(register_name, "fragment.texcoord[%u]", reg->idx);
953                 }
954             }
955             else
956             {
957                 if(This->baseShader.reg_maps.shader_version.major == 1 || ctx->target_version >= NV2)
958                 {
959                     sprintf(register_name, "A%u", reg->idx);
960                 }
961                 else
962                 {
963                     sprintf(register_name, "A%u_SHADOW", reg->idx);
964                 }
965             }
966             break;
967
968         case WINED3DSPR_COLOROUT:
969             if(ctx->cur_ps_args->super.srgb_correction && reg->idx == 0)
970             {
971                 strcpy(register_name, "TMP_COLOR");
972             }
973             else
974             {
975                 if(ctx->cur_ps_args->super.srgb_correction) FIXME("sRGB correction on higher render targets\n");
976                 if(This->baseShader.reg_maps.highest_render_target > 0)
977                 {
978                     sprintf(register_name, "result.color[%u]", reg->idx);
979                 }
980                 else
981                 {
982                     strcpy(register_name, "result.color");
983                 }
984             }
985             break;
986
987         case WINED3DSPR_RASTOUT:
988             if(reg->idx == 1) sprintf(register_name, "%s", ctx->fog_output);
989             else sprintf(register_name, "%s", rastout_reg_names[reg->idx]);
990             break;
991
992         case WINED3DSPR_DEPTHOUT:
993             strcpy(register_name, "result.depth");
994             break;
995
996         case WINED3DSPR_ATTROUT:
997         /* case WINED3DSPR_OUTPUT: */
998             if (pshader) sprintf(register_name, "oD[%u]", reg->idx);
999             else strcpy(register_name, ctx->color_output[reg->idx]);
1000             break;
1001
1002         case WINED3DSPR_TEXCRDOUT:
1003             if (pshader)
1004             {
1005                 sprintf(register_name, "oT[%u]", reg->idx);
1006             }
1007             else
1008             {
1009                 if(This->baseShader.reg_maps.shader_version.major < 3)
1010                 {
1011                     strcpy(register_name, ctx->texcrd_output[reg->idx]);
1012                 }
1013                 else
1014                 {
1015                     strcpy(register_name, ctx->vs_output[reg->idx]);
1016                 }
1017             }
1018             break;
1019
1020         case WINED3DSPR_LOOP:
1021             if(ctx->target_version >= NV2)
1022             {
1023                 /* Pshader has an implicitly declared loop index counter A0.x that cannot be renamed */
1024                 if(pshader) sprintf(register_name, "A0.x");
1025                 else sprintf(register_name, "aL.y");
1026             }
1027             else
1028             {
1029                 /* Unfortunately this code cannot return the value of ctx->aL here. An immediate value
1030                  * would be valid, but if aL is used for indexing(its only use), there's likely an offset,
1031                  * thus the result would be something like C[15 + 30], which is not valid in the ARB program
1032                  * grammar. So return a marker for the emulated aL and intercept it in constant and varying
1033                  * indexing
1034                  */
1035                 sprintf(register_name, "**aL_emul**");
1036             }
1037
1038             break;
1039
1040         case WINED3DSPR_CONSTINT:
1041             sprintf(register_name, "I%u", reg->idx);
1042             break;
1043
1044         case WINED3DSPR_MISCTYPE:
1045             if(reg->idx == 0)
1046             {
1047                 sprintf(register_name, "vpos");
1048             }
1049             else if(reg->idx == 1)
1050             {
1051                 sprintf(register_name, "fragment.facing.x");
1052             }
1053             else
1054             {
1055                 FIXME("Unknown MISCTYPE register index %u\n", reg->idx);
1056             }
1057             break;
1058
1059         default:
1060             FIXME("Unhandled register type %#x[%u]\n", reg->type, reg->idx);
1061             sprintf(register_name, "unrecognized_register[%u]", reg->idx);
1062             break;
1063     }
1064 }
1065
1066 static void shader_arb_get_dst_param(const struct wined3d_shader_instruction *ins,
1067         const struct wined3d_shader_dst_param *wined3d_dst, char *str)
1068 {
1069     char register_name[255];
1070     char write_mask[6];
1071     BOOL is_color;
1072
1073     shader_arb_get_register_name(ins, &wined3d_dst->reg, register_name, &is_color);
1074     strcpy(str, register_name);
1075
1076     shader_arb_get_write_mask(ins, wined3d_dst, write_mask);
1077     strcat(str, write_mask);
1078 }
1079
1080 static const char *shader_arb_get_fixup_swizzle(enum fixup_channel_source channel_source)
1081 {
1082     switch(channel_source)
1083     {
1084         case CHANNEL_SOURCE_ZERO: return "0";
1085         case CHANNEL_SOURCE_ONE: return "1";
1086         case CHANNEL_SOURCE_X: return "x";
1087         case CHANNEL_SOURCE_Y: return "y";
1088         case CHANNEL_SOURCE_Z: return "z";
1089         case CHANNEL_SOURCE_W: return "w";
1090         default:
1091             FIXME("Unhandled channel source %#x\n", channel_source);
1092             return "undefined";
1093     }
1094 }
1095
1096 static void gen_color_correction(struct wined3d_shader_buffer *buffer, const char *reg,
1097         DWORD dst_mask, const char *one, const char *two, struct color_fixup_desc fixup)
1098 {
1099     DWORD mask;
1100
1101     if (is_yuv_fixup(fixup))
1102     {
1103         enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1104         FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1105         return;
1106     }
1107
1108     mask = 0;
1109     if (fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1110     if (fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1111     if (fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1112     if (fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1113     mask &= dst_mask;
1114
1115     if (mask)
1116     {
1117         shader_addline(buffer, "SWZ %s, %s, %s, %s, %s, %s;\n", reg, reg,
1118                 shader_arb_get_fixup_swizzle(fixup.x_source), shader_arb_get_fixup_swizzle(fixup.y_source),
1119                 shader_arb_get_fixup_swizzle(fixup.z_source), shader_arb_get_fixup_swizzle(fixup.w_source));
1120     }
1121
1122     mask = 0;
1123     if (fixup.x_sign_fixup) mask |= WINED3DSP_WRITEMASK_0;
1124     if (fixup.y_sign_fixup) mask |= WINED3DSP_WRITEMASK_1;
1125     if (fixup.z_sign_fixup) mask |= WINED3DSP_WRITEMASK_2;
1126     if (fixup.w_sign_fixup) mask |= WINED3DSP_WRITEMASK_3;
1127     mask &= dst_mask;
1128
1129     if (mask)
1130     {
1131         char reg_mask[6];
1132         char *ptr = reg_mask;
1133
1134         if (mask != WINED3DSP_WRITEMASK_ALL)
1135         {
1136             *ptr++ = '.';
1137             if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
1138             if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
1139             if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
1140             if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
1141         }
1142         *ptr = '\0';
1143
1144         shader_addline(buffer, "MAD %s%s, %s, %s, -%s;\n", reg, reg_mask, reg, two, one);
1145     }
1146 }
1147
1148 static const char *shader_arb_get_modifier(const struct wined3d_shader_instruction *ins)
1149 {
1150     DWORD mod;
1151     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
1152     if (!ins->dst_count) return "";
1153
1154     mod = ins->dst[0].modifiers;
1155
1156     /* Silently ignore PARTIALPRECISION if its not supported */
1157     if(priv->target_version == ARB) mod &= ~WINED3DSPDM_PARTIALPRECISION;
1158
1159     if(mod & WINED3DSPDM_MSAMPCENTROID)
1160     {
1161         FIXME("Unhandled modifier WINED3DSPDM_MSAMPCENTROID\n");
1162         mod &= ~WINED3DSPDM_MSAMPCENTROID;
1163     }
1164
1165     switch(mod)
1166     {
1167         case WINED3DSPDM_SATURATE | WINED3DSPDM_PARTIALPRECISION:
1168             return "H_SAT";
1169
1170         case WINED3DSPDM_SATURATE:
1171             return "_SAT";
1172
1173         case WINED3DSPDM_PARTIALPRECISION:
1174             return "H";
1175
1176         case 0:
1177             return "";
1178
1179         default:
1180             FIXME("Unknown modifiers 0x%08x\n", mod);
1181             return "";
1182     }
1183 }
1184
1185 #define TEX_PROJ        0x1
1186 #define TEX_BIAS        0x2
1187 #define TEX_LOD         0x4
1188 #define TEX_DERIV       0x10
1189
1190 static void shader_hw_sample(const struct wined3d_shader_instruction *ins, DWORD sampler_idx,
1191         const char *dst_str, const char *coord_reg, WORD flags, const char *dsx, const char *dsy)
1192 {
1193     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1194     DWORD sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
1195     const char *tex_type;
1196     BOOL np2_fixup = FALSE;
1197     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1198     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
1199     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
1200     const char *mod;
1201     BOOL pshader = shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type);
1202
1203     /* D3D vertex shader sampler IDs are vertex samplers(0-3), not global d3d samplers */
1204     if(!pshader) sampler_idx += MAX_FRAGMENT_SAMPLERS;
1205
1206     switch(sampler_type) {
1207         case WINED3DSTT_1D:
1208             tex_type = "1D";
1209             break;
1210
1211         case WINED3DSTT_2D:
1212             if(device->stateBlock->textures[sampler_idx] &&
1213                IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
1214                 tex_type = "RECT";
1215             } else {
1216                 tex_type = "2D";
1217             }
1218             if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1219             {
1220                 if (priv->cur_np2fixup_info->super.active & (1 << sampler_idx))
1221                 {
1222                     if (flags) FIXME("Only ordinary sampling from NP2 textures is supported.\n");
1223                     else np2_fixup = TRUE;
1224                 }
1225             }
1226             break;
1227
1228         case WINED3DSTT_VOLUME:
1229             tex_type = "3D";
1230             break;
1231
1232         case WINED3DSTT_CUBE:
1233             tex_type = "CUBE";
1234             break;
1235
1236         default:
1237             ERR("Unexpected texture type %d\n", sampler_type);
1238             tex_type = "";
1239     }
1240
1241     /* TEX, TXL, TXD and TXP do not support the "H" modifier,
1242      * so don't use shader_arb_get_modifier
1243      */
1244     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE) mod = "_SAT";
1245     else mod = "";
1246
1247     /* Fragment samplers always have indentity mapping */
1248     if(sampler_idx >= MAX_FRAGMENT_SAMPLERS)
1249     {
1250         sampler_idx = priv->cur_vs_args->vertex_samplers[sampler_idx - MAX_FRAGMENT_SAMPLERS];
1251     }
1252
1253     if (flags & TEX_DERIV)
1254     {
1255         if(flags & TEX_PROJ) FIXME("Projected texture sampling with custom derivatives\n");
1256         if(flags & TEX_BIAS) FIXME("Biased texture sampling with custom derivatives\n");
1257         shader_addline(buffer, "TXD%s %s, %s, %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg,
1258                        dsx, dsy,sampler_idx, tex_type);
1259     }
1260     else if(flags & TEX_LOD)
1261     {
1262         if(flags & TEX_PROJ) FIXME("Projected texture sampling with explicit lod\n");
1263         if(flags & TEX_BIAS) FIXME("Biased texture sampling with explicit lod\n");
1264         shader_addline(buffer, "TXL%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg,
1265                        sampler_idx, tex_type);
1266     }
1267     else if (flags & TEX_BIAS)
1268     {
1269         /* Shouldn't be possible, but let's check for it */
1270         if(flags & TEX_PROJ) FIXME("Biased and Projected texture sampling\n");
1271         /* TXB takes the 4th component of the source vector automatically, as d3d. Nothing more to do */
1272         shader_addline(buffer, "TXB%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1273     }
1274     else if (flags & TEX_PROJ)
1275     {
1276         shader_addline(buffer, "TXP%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1277     }
1278     else
1279     {
1280         if (np2_fixup)
1281         {
1282             const unsigned char idx = priv->cur_np2fixup_info->super.idx[sampler_idx];
1283             shader_addline(buffer, "MUL TA, np2fixup[%u].%s, %s;\n", idx >> 1,
1284                            (idx % 2) ? "zwxy" : "xyzw", coord_reg);
1285
1286             shader_addline(buffer, "TEX%s %s, TA, texture[%u], %s;\n", mod, dst_str, sampler_idx, tex_type);
1287         }
1288         else
1289             shader_addline(buffer, "TEX%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1290     }
1291
1292     if (pshader)
1293     {
1294         gen_color_correction(buffer, dst_str, ins->dst[0].write_mask,
1295                 "one", "coefmul.x", priv->cur_ps_args->super.color_fixup[sampler_idx]);
1296     }
1297 }
1298
1299 static void shader_arb_get_src_param(const struct wined3d_shader_instruction *ins,
1300         const struct wined3d_shader_src_param *src, unsigned int tmpreg, char *outregstr)
1301 {
1302     /* Generate a line that does the input modifier computation and return the input register to use */
1303     BOOL is_color = FALSE;
1304     char regstr[256];
1305     char swzstr[20];
1306     int insert_line;
1307     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1308     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1309
1310     /* Assume a new line will be added */
1311     insert_line = 1;
1312
1313     /* Get register name */
1314     shader_arb_get_register_name(ins, &src->reg, regstr, &is_color);
1315     shader_arb_get_swizzle(src, is_color, swzstr);
1316
1317     switch (src->modifiers)
1318     {
1319     case WINED3DSPSM_NONE:
1320         sprintf(outregstr, "%s%s", regstr, swzstr);
1321         insert_line = 0;
1322         break;
1323     case WINED3DSPSM_NEG:
1324         sprintf(outregstr, "-%s%s", regstr, swzstr);
1325         insert_line = 0;
1326         break;
1327     case WINED3DSPSM_BIAS:
1328         shader_addline(buffer, "ADD T%c, %s, -coefdiv.x;\n", 'A' + tmpreg, regstr);
1329         break;
1330     case WINED3DSPSM_BIASNEG:
1331         shader_addline(buffer, "ADD T%c, -%s, coefdiv.x;\n", 'A' + tmpreg, regstr);
1332         break;
1333     case WINED3DSPSM_SIGN:
1334         shader_addline(buffer, "MAD T%c, %s, coefmul.x, -one.x;\n", 'A' + tmpreg, regstr);
1335         break;
1336     case WINED3DSPSM_SIGNNEG:
1337         shader_addline(buffer, "MAD T%c, %s, -coefmul.x, one.x;\n", 'A' + tmpreg, regstr);
1338         break;
1339     case WINED3DSPSM_COMP:
1340         shader_addline(buffer, "SUB T%c, one.x, %s;\n", 'A' + tmpreg, regstr);
1341         break;
1342     case WINED3DSPSM_X2:
1343         shader_addline(buffer, "ADD T%c, %s, %s;\n", 'A' + tmpreg, regstr, regstr);
1344         break;
1345     case WINED3DSPSM_X2NEG:
1346         shader_addline(buffer, "ADD T%c, -%s, -%s;\n", 'A' + tmpreg, regstr, regstr);
1347         break;
1348     case WINED3DSPSM_DZ:
1349         shader_addline(buffer, "RCP T%c, %s.z;\n", 'A' + tmpreg, regstr);
1350         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
1351         break;
1352     case WINED3DSPSM_DW:
1353         shader_addline(buffer, "RCP T%c, %s.w;\n", 'A' + tmpreg, regstr);
1354         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
1355         break;
1356     case WINED3DSPSM_ABS:
1357         if(ctx->target_version >= NV2) {
1358             sprintf(outregstr, "|%s%s|", regstr, swzstr);
1359             insert_line = 0;
1360         } else {
1361             shader_addline(buffer, "ABS T%c, %s;\n", 'A' + tmpreg, regstr);
1362         }
1363         break;
1364     case WINED3DSPSM_ABSNEG:
1365         if(ctx->target_version >= NV2) {
1366             sprintf(outregstr, "-|%s%s|", regstr, swzstr);
1367         } else {
1368             shader_addline(buffer, "ABS T%c, %s;\n", 'A' + tmpreg, regstr);
1369             sprintf(outregstr, "-T%c%s", 'A' + tmpreg, swzstr);
1370         }
1371         insert_line = 0;
1372         break;
1373     default:
1374         sprintf(outregstr, "%s%s", regstr, swzstr);
1375         insert_line = 0;
1376     }
1377
1378     /* Return modified or original register, with swizzle */
1379     if (insert_line)
1380         sprintf(outregstr, "T%c%s", 'A' + tmpreg, swzstr);
1381 }
1382
1383 static void pshader_hw_bem(const struct wined3d_shader_instruction *ins)
1384 {
1385     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1386     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1387     char dst_name[50];
1388     char src_name[2][50];
1389     DWORD sampler_code = dst->reg.idx;
1390
1391     shader_arb_get_dst_param(ins, dst, dst_name);
1392
1393     /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed
1394      *
1395      * Keep in mind that src_name[1] can be "TB" and src_name[0] can be "TA" because modifiers like _x2 are valid
1396      * with bem. So delay loading the first parameter until after the perturbation calculation which needs two
1397      * temps is done.
1398      */
1399     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1400     shader_addline(buffer, "SWZ TA, bumpenvmat%d, x, z, 0, 0;\n", sampler_code);
1401     shader_addline(buffer, "DP3 TC.r, TA, %s;\n", src_name[1]);
1402     shader_addline(buffer, "SWZ TA, bumpenvmat%d, y, w, 0, 0;\n", sampler_code);
1403     shader_addline(buffer, "DP3 TC.g, TA, %s;\n", src_name[1]);
1404
1405     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1406     shader_addline(buffer, "ADD %s, %s, TC;\n", dst_name, src_name[0]);
1407 }
1408
1409 static DWORD negate_modifiers(DWORD mod, char *extra_char)
1410 {
1411     *extra_char = ' ';
1412     switch(mod)
1413     {
1414         case WINED3DSPSM_NONE:      return WINED3DSPSM_NEG;
1415         case WINED3DSPSM_NEG:       return WINED3DSPSM_NONE;
1416         case WINED3DSPSM_BIAS:      return WINED3DSPSM_BIASNEG;
1417         case WINED3DSPSM_BIASNEG:   return WINED3DSPSM_BIAS;
1418         case WINED3DSPSM_SIGN:      return WINED3DSPSM_SIGNNEG;
1419         case WINED3DSPSM_SIGNNEG:   return WINED3DSPSM_SIGN;
1420         case WINED3DSPSM_COMP:      *extra_char = '-'; return WINED3DSPSM_COMP;
1421         case WINED3DSPSM_X2:        return WINED3DSPSM_X2NEG;
1422         case WINED3DSPSM_X2NEG:     return WINED3DSPSM_X2;
1423         case WINED3DSPSM_DZ:        *extra_char = '-'; return WINED3DSPSM_DZ;
1424         case WINED3DSPSM_DW:        *extra_char = '-'; return WINED3DSPSM_DW;
1425         case WINED3DSPSM_ABS:       return WINED3DSPSM_ABSNEG;
1426         case WINED3DSPSM_ABSNEG:    return WINED3DSPSM_ABS;
1427     }
1428     FIXME("Unknown modifier %u\n", mod);
1429     return mod;
1430 }
1431
1432 static void pshader_hw_cnd(const struct wined3d_shader_instruction *ins)
1433 {
1434     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1435     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1436     char dst_name[50];
1437     char src_name[3][50];
1438     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1439             ins->ctx->reg_maps->shader_version.minor);
1440     BOOL is_color;
1441
1442     shader_arb_get_dst_param(ins, dst, dst_name);
1443     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1444
1445     /* The coissue flag changes the semantic of the cnd instruction in <= 1.3 shaders */
1446     if (shader_version <= WINED3D_SHADER_VERSION(1, 3) && ins->coissue)
1447     {
1448         shader_addline(buffer, "MOV%s %s, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name[1]);
1449     } else {
1450         struct wined3d_shader_src_param src0_copy = ins->src[0];
1451         char extra_neg;
1452
1453         /* src0 may have a negate srcmod set, so we can't blindly add "-" to the name */
1454         src0_copy.modifiers = negate_modifiers(src0_copy.modifiers, &extra_neg);
1455
1456         shader_arb_get_src_param(ins, &src0_copy, 0, src_name[0]);
1457         shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1458         shader_addline(buffer, "ADD TA, %c%s, coefdiv.x;\n", extra_neg, src_name[0]);
1459         /* No modifiers supported on CMP */
1460         shader_addline(buffer, "CMP %s, TA, %s, %s;\n", dst_name, src_name[1], src_name[2]);
1461
1462         /* _SAT on CMP doesn't make much sense, but it is not a pure NOP */
1463         if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
1464         {
1465             shader_arb_get_register_name(ins, &dst->reg, src_name[0], &is_color);
1466             shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, dst_name);
1467         }
1468     }
1469 }
1470
1471 static void pshader_hw_cmp(const struct wined3d_shader_instruction *ins)
1472 {
1473     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1474     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1475     char dst_name[50];
1476     char src_name[3][50];
1477     BOOL is_color;
1478
1479     shader_arb_get_dst_param(ins, dst, dst_name);
1480
1481     /* Generate input register names (with modifiers) */
1482     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1483     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1484     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1485
1486     /* No modifiers are supported on CMP */
1487     shader_addline(buffer, "CMP %s, %s, %s, %s;\n", dst_name,
1488                    src_name[0], src_name[2], src_name[1]);
1489
1490     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
1491     {
1492         shader_arb_get_register_name(ins, &dst->reg, src_name[0], &is_color);
1493         shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, src_name[0]);
1494     }
1495 }
1496
1497 /** Process the WINED3DSIO_DP2ADD instruction in ARB.
1498  * dst = dot2(src0, src1) + src2 */
1499 static void pshader_hw_dp2add(const struct wined3d_shader_instruction *ins)
1500 {
1501     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1502     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1503     char dst_name[50];
1504     char src_name[3][50];
1505     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1506
1507     shader_arb_get_dst_param(ins, dst, dst_name);
1508     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1509     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1510
1511     if(ctx->target_version >= NV3)
1512     {
1513         /* GL_NV_fragment_program2 has a 1:1 matching instruction */
1514         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1515         shader_addline(buffer, "DP2A%s %s, %s, %s, %s;\n", shader_arb_get_modifier(ins),
1516                        dst_name, src_name[0], src_name[1], src_name[2]);
1517     }
1518     else if(ctx->target_version >= NV2)
1519     {
1520         /* dst.x = src2.?, src0.x, src1.x + src0.y * src1.y
1521          * dst.y = src2.?, src0.x, src1.z + src0.y * src1.w
1522          * dst.z = src2.?, src0.x, src1.x + src0.y * src1.y
1523          * dst.z = src2.?, src0.x, src1.z + src0.y * src1.w
1524          *
1525          * Make sure that src1.zw = src1.xy, then we get a classic dp2add
1526          *
1527          * .xyxy and other swizzles that we could get with this are not valid in
1528          * plain ARBfp, but luckily the NV extension grammar lifts this limitation.
1529          */
1530         struct wined3d_shader_src_param tmp_param = ins->src[1];
1531         DWORD swizzle = tmp_param.swizzle & 0xf; /* Selects .xy */
1532         tmp_param.swizzle = swizzle | (swizzle << 4); /* Creates .xyxy */
1533
1534         shader_arb_get_src_param(ins, &tmp_param, 1, src_name[1]);
1535
1536         shader_addline(buffer, "X2D%s %s, %s, %s, %s;\n", shader_arb_get_modifier(ins),
1537                        dst_name, src_name[2], src_name[0], src_name[1]);
1538     }
1539     else
1540     {
1541         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1542         /* 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]
1543         * src_name[0] can be TA, but TA is a private temp for modifiers, so it is save to overwrite
1544         */
1545         shader_addline(buffer, "MOV TA, %s;\n", src_name[0]);
1546         shader_addline(buffer, "MOV TA.z, 0.0;\n");
1547         shader_addline(buffer, "DP3 TA, TA, %s;\n", src_name[1]);
1548         shader_addline(buffer, "ADD%s %s, TA, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name[2]);
1549     }
1550 }
1551
1552 /* Map the opcode 1-to-1 to the GL code */
1553 static void shader_hw_map2gl(const struct wined3d_shader_instruction *ins)
1554 {
1555     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1556     const char *instruction;
1557     char arguments[256], dst_str[50];
1558     unsigned int i;
1559     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1560
1561     switch (ins->handler_idx)
1562     {
1563         case WINED3DSIH_ABS: instruction = "ABS"; break;
1564         case WINED3DSIH_ADD: instruction = "ADD"; break;
1565         case WINED3DSIH_CRS: instruction = "XPD"; break;
1566         case WINED3DSIH_DP3: instruction = "DP3"; break;
1567         case WINED3DSIH_DP4: instruction = "DP4"; break;
1568         case WINED3DSIH_DST: instruction = "DST"; break;
1569         case WINED3DSIH_FRC: instruction = "FRC"; break;
1570         case WINED3DSIH_LIT: instruction = "LIT"; break;
1571         case WINED3DSIH_LRP: instruction = "LRP"; break;
1572         case WINED3DSIH_MAD: instruction = "MAD"; break;
1573         case WINED3DSIH_MAX: instruction = "MAX"; break;
1574         case WINED3DSIH_MIN: instruction = "MIN"; break;
1575         case WINED3DSIH_MOV: instruction = "MOV"; break;
1576         case WINED3DSIH_MUL: instruction = "MUL"; break;
1577         case WINED3DSIH_SGE: instruction = "SGE"; break;
1578         case WINED3DSIH_SLT: instruction = "SLT"; break;
1579         case WINED3DSIH_SUB: instruction = "SUB"; break;
1580         case WINED3DSIH_MOVA:instruction = "ARR"; break;
1581         case WINED3DSIH_SGN: instruction = "SSG"; break;
1582         case WINED3DSIH_DSX: instruction = "DDX"; break;
1583         default: instruction = "";
1584             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1585             break;
1586     }
1587
1588     /* Note that shader_arb_add_dst_param() adds spaces. */
1589     arguments[0] = '\0';
1590     shader_arb_get_dst_param(ins, dst, dst_str);
1591     for (i = 0; i < ins->src_count; ++i)
1592     {
1593         char operand[100];
1594         strcat(arguments, ", ");
1595         shader_arb_get_src_param(ins, &ins->src[i], i, operand);
1596         strcat(arguments, operand);
1597     }
1598     shader_addline(buffer, "%s%s %s%s;\n", instruction, shader_arb_get_modifier(ins), dst_str, arguments);
1599 }
1600
1601 static void shader_hw_nop(const struct wined3d_shader_instruction *ins)
1602 {
1603     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1604     shader_addline(buffer, "NOP;\n");
1605 }
1606
1607 static void shader_hw_mov(const struct wined3d_shader_instruction *ins)
1608 {
1609     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1610     BOOL pshader = shader_is_pshader_version(shader->baseShader.reg_maps.shader_version.type);
1611     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1612
1613     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1614     char src0_param[256];
1615
1616     if(ins->handler_idx == WINED3DSIH_MOVA) {
1617         char write_mask[6];
1618
1619         if(ctx->target_version >= NV2) {
1620             shader_hw_map2gl(ins);
1621             return;
1622         }
1623         shader_arb_get_src_param(ins, &ins->src[0], 0, src0_param);
1624         shader_arb_get_write_mask(ins, &ins->dst[0], write_mask);
1625
1626         /* This implements the mova formula used in GLSL. The first two instructions
1627          * prepare the sign() part. Note that it is fine to have my_sign(0.0) = 1.0
1628          * in this case:
1629          * mova A0.x, 0.0
1630          *
1631          * A0.x = arl(floor(abs(0.0) + 0.5) * 1.0) = floor(0.5) = 0.0 since arl does a floor
1632          *
1633          * The ARL is performed when A0 is used - the requested component is read from A0_SHADOW into
1634          * A0.x. We can use the overwritten component of A0_shadow as temporary storage for the sign.
1635          */
1636         shader_addline(buffer, "SGE A0_SHADOW%s, %s, mova_const.y;\n", write_mask, src0_param);
1637         shader_addline(buffer, "MAD A0_SHADOW%s, A0_SHADOW, mova_const.z, -mova_const.w;\n", write_mask);
1638
1639         shader_addline(buffer, "ABS TA%s, %s;\n", write_mask, src0_param);
1640         shader_addline(buffer, "ADD TA%s, TA, mova_const.x;\n", write_mask);
1641         shader_addline(buffer, "FLR TA%s, TA;\n", write_mask);
1642         if (((IWineD3DVertexShaderImpl *)shader)->rel_offset)
1643         {
1644             shader_addline(buffer, "ADD TA%s, TA, helper_const.z;\n", write_mask);
1645         }
1646         shader_addline(buffer, "MUL A0_SHADOW%s, TA, A0_SHADOW;\n", write_mask);
1647
1648         ((struct shader_arb_ctx_priv *)ins->ctx->backend_data)->addr_reg[0] = '\0';
1649     } else if (ins->ctx->reg_maps->shader_version.major == 1
1650           && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1651           && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1652     {
1653         src0_param[0] = '\0';
1654         if (((IWineD3DVertexShaderImpl *)shader)->rel_offset)
1655         {
1656             shader_arb_get_src_param(ins, &ins->src[0], 0, src0_param);
1657             shader_addline(buffer, "ADD TA.x, %s, helper_const.z;\n", src0_param);
1658             shader_addline(buffer, "ARL A0.x, TA.x;\n");
1659         }
1660         else
1661         {
1662             /* Apple's ARB_vertex_program implementation does not accept an ARL source argument
1663              * with more than one component. Thus replicate the first source argument over all
1664              * 4 components. For example, .xyzw -> .x (or better: .xxxx), .zwxy -> .z, etc) */
1665             struct wined3d_shader_src_param tmp_src = ins->src[0];
1666             tmp_src.swizzle = (tmp_src.swizzle & 0x3) * 0x55;
1667             shader_arb_get_src_param(ins, &tmp_src, 0, src0_param);
1668             shader_addline(buffer, "ARL A0.x, %s;\n", src0_param);
1669         }
1670     }
1671     else if(ins->dst[0].reg.type == WINED3DSPR_COLOROUT && ins->dst[0].reg.idx == 0 && pshader)
1672     {
1673         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) shader;
1674         if(ctx->cur_ps_args->super.srgb_correction && ps->color0_mov)
1675         {
1676             shader_addline(buffer, "#mov handled in srgb write code\n");
1677             return;
1678         }
1679         shader_hw_map2gl(ins);
1680     }
1681     else
1682     {
1683         shader_hw_map2gl(ins);
1684     }
1685 }
1686
1687 static void pshader_hw_texkill(const struct wined3d_shader_instruction *ins)
1688 {
1689     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1690     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1691     char reg_dest[40];
1692
1693     /* No swizzles are allowed in d3d's texkill. PS 1.x ignores the 4th component as documented,
1694      * but >= 2.0 honors it(undocumented, but tested by the d3d9 testsuit)
1695      */
1696     shader_arb_get_dst_param(ins, dst, reg_dest);
1697
1698     if (ins->ctx->reg_maps->shader_version.major >= 2)
1699     {
1700         const char *kilsrc = "TA";
1701         BOOL is_color;
1702
1703         shader_arb_get_register_name(ins, &dst->reg, reg_dest, &is_color);
1704         if(dst->write_mask == WINED3DSP_WRITEMASK_ALL)
1705         {
1706             kilsrc = reg_dest;
1707         }
1708         else
1709         {
1710             /* Sigh. KIL doesn't support swizzles/writemasks. KIL passes a writemask, but ".xy" for example
1711              * is not valid as a swizzle in ARB (needs ".xyyy"). Use SWZ to load the register properly, and set
1712              * masked out components to 0(won't kill)
1713              */
1714             char x = '0', y = '0', z = '0', w = '0';
1715             if(dst->write_mask & WINED3DSP_WRITEMASK_0) x = 'x';
1716             if(dst->write_mask & WINED3DSP_WRITEMASK_1) y = 'y';
1717             if(dst->write_mask & WINED3DSP_WRITEMASK_2) z = 'z';
1718             if(dst->write_mask & WINED3DSP_WRITEMASK_3) w = 'w';
1719             shader_addline(buffer, "SWZ TA, %s, %c, %c, %c, %c;\n", reg_dest, x, y, z, w);
1720         }
1721         shader_addline(buffer, "KIL %s;\n", kilsrc);
1722     } else {
1723         /* ARB fp doesn't like swizzles on the parameter of the KIL instruction. To mask the 4th component,
1724          * copy the register into our general purpose TMP variable, overwrite .w and pass TMP to KIL
1725          *
1726          * ps_1_3 shaders use the texcoord incarnation of the Tx register. ps_1_4 shaders can use the same,
1727          * or pass in any temporary register(in shader phase 2)
1728          */
1729         if(ins->ctx->reg_maps->shader_version.minor <= 3) {
1730             sprintf(reg_dest, "fragment.texcoord[%u]", dst->reg.idx);
1731         } else {
1732             shader_arb_get_dst_param(ins, dst, reg_dest);
1733         }
1734         shader_addline(buffer, "SWZ TA, %s, x, y, z, 1;\n", reg_dest);
1735         shader_addline(buffer, "KIL TA;\n");
1736     }
1737 }
1738
1739 static void pshader_hw_tex(const struct wined3d_shader_instruction *ins)
1740 {
1741     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1742     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1743     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1744     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1745             ins->ctx->reg_maps->shader_version.minor);
1746     struct wined3d_shader_src_param src;
1747
1748     char reg_dest[40];
1749     char reg_coord[40];
1750     DWORD reg_sampler_code;
1751     DWORD myflags = 0;
1752
1753     /* All versions have a destination register */
1754     shader_arb_get_dst_param(ins, dst, reg_dest);
1755
1756     /* 1.0-1.4: Use destination register number as texture code.
1757        2.0+: Use provided sampler number as texure code. */
1758     if (shader_version < WINED3D_SHADER_VERSION(2,0))
1759         reg_sampler_code = dst->reg.idx;
1760     else
1761         reg_sampler_code = ins->src[1].reg.idx;
1762
1763     /* 1.0-1.3: Use the texcoord varying.
1764        1.4+: Use provided coordinate source register. */
1765     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1766         sprintf(reg_coord, "fragment.texcoord[%u]", reg_sampler_code);
1767     else {
1768         /* TEX is the only instruction that can handle DW and DZ natively */
1769         src = ins->src[0];
1770         if(src.modifiers == WINED3DSPSM_DW) src.modifiers = WINED3DSPSM_NONE;
1771         if(src.modifiers == WINED3DSPSM_DZ) src.modifiers = WINED3DSPSM_NONE;
1772         shader_arb_get_src_param(ins, &src, 0, reg_coord);
1773     }
1774
1775     /* projection flag:
1776      * 1.1, 1.2, 1.3: Use WINED3DTSS_TEXTURETRANSFORMFLAGS
1777      * 1.4: Use WINED3DSPSM_DZ or WINED3DSPSM_DW on src[0]
1778      * 2.0+: Use WINED3DSI_TEXLD_PROJECT on the opcode
1779      */
1780     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1781     {
1782         DWORD flags = 0;
1783         if(reg_sampler_code < MAX_TEXTURES) {
1784             flags = deviceImpl->stateBlock->textureState[reg_sampler_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1785         }
1786         if (flags & WINED3DTTFF_PROJECTED) {
1787             myflags |= TEX_PROJ;
1788         }
1789     }
1790     else if (shader_version < WINED3D_SHADER_VERSION(2,0))
1791     {
1792         DWORD src_mod = ins->src[0].modifiers;
1793         if (src_mod == WINED3DSPSM_DZ) {
1794             /* TXP cannot handle DZ natively, so move the z coordinate to .w. reg_coord is a read-only
1795              * varying register, so we need a temp reg
1796              */
1797             shader_addline(ins->ctx->buffer, "SWZ TA, %s, x, y, z, z;\n", reg_coord);
1798             strcpy(reg_coord, "TA");
1799             myflags |= TEX_PROJ;
1800         } else if(src_mod == WINED3DSPSM_DW) {
1801             myflags |= TEX_PROJ;
1802         }
1803     } else {
1804         if (ins->flags & WINED3DSI_TEXLD_PROJECT) myflags |= TEX_PROJ;
1805         if (ins->flags & WINED3DSI_TEXLD_BIAS) myflags |= TEX_BIAS;
1806     }
1807     shader_hw_sample(ins, reg_sampler_code, reg_dest, reg_coord, myflags, NULL, NULL);
1808 }
1809
1810 static void pshader_hw_texcoord(const struct wined3d_shader_instruction *ins)
1811 {
1812     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1813     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1814     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1815             ins->ctx->reg_maps->shader_version.minor);
1816     char dst_str[50];
1817
1818     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1819     {
1820         DWORD reg = dst->reg.idx;
1821
1822         shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1823         shader_addline(buffer, "MOV_SAT %s, fragment.texcoord[%u];\n", dst_str, reg);
1824     } else {
1825         char reg_src[40];
1826
1827         shader_arb_get_src_param(ins, &ins->src[0], 0, reg_src);
1828         shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1829         shader_addline(buffer, "MOV %s, %s;\n", dst_str, reg_src);
1830    }
1831 }
1832
1833 static void pshader_hw_texreg2ar(const struct wined3d_shader_instruction *ins)
1834 {
1835      struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1836      IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1837      IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1838      DWORD flags;
1839
1840      DWORD reg1 = ins->dst[0].reg.idx;
1841      char dst_str[50];
1842      char src_str[50];
1843
1844      /* Note that texreg2ar treats Tx as a temporary register, not as a varying */
1845      shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1846      shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1847      /* Move .x first in case src_str is "TA" */
1848      shader_addline(buffer, "MOV TA.y, %s.x;\n", src_str);
1849      shader_addline(buffer, "MOV TA.x, %s.w;\n", src_str);
1850      flags = reg1 < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg1][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1851      shader_hw_sample(ins, reg1, dst_str, "TA", flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1852 }
1853
1854 static void pshader_hw_texreg2gb(const struct wined3d_shader_instruction *ins)
1855 {
1856      struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1857
1858      DWORD reg1 = ins->dst[0].reg.idx;
1859      char dst_str[50];
1860      char src_str[50];
1861
1862      /* Note that texreg2gb treats Tx as a temporary register, not as a varying */
1863      shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1864      shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1865      shader_addline(buffer, "MOV TA.x, %s.y;\n", src_str);
1866      shader_addline(buffer, "MOV TA.y, %s.z;\n", src_str);
1867      shader_hw_sample(ins, reg1, dst_str, "TA", 0, NULL, NULL);
1868 }
1869
1870 static void pshader_hw_texreg2rgb(const struct wined3d_shader_instruction *ins)
1871 {
1872     DWORD reg1 = ins->dst[0].reg.idx;
1873     char dst_str[50];
1874     char src_str[50];
1875
1876     /* Note that texreg2rg treats Tx as a temporary register, not as a varying */
1877     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1878     shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1879     shader_hw_sample(ins, reg1, dst_str, src_str, 0, NULL, NULL);
1880 }
1881
1882 static void pshader_hw_texbem(const struct wined3d_shader_instruction *ins)
1883 {
1884     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1885     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1886     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1887     char reg_coord[40], dst_reg[50], src_reg[50];
1888     DWORD reg_dest_code;
1889
1890     /* All versions have a destination register. The Tx where the texture coordinates come
1891      * from is the varying incarnation of the texture register
1892      */
1893     reg_dest_code = dst->reg.idx;
1894     shader_arb_get_dst_param(ins, &ins->dst[0], dst_reg);
1895     shader_arb_get_src_param(ins, &ins->src[0], 0, src_reg);
1896     sprintf(reg_coord, "fragment.texcoord[%u]", reg_dest_code);
1897
1898     /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed
1899      * The Tx in which the perturbation map is stored is the tempreg incarnation of the texture register
1900      *
1901      * GL_NV_fragment_program_option could handle this in one instruction via X2D:
1902      * X2D TA.xy, fragment.texcoord, T%u, bumpenvmat%u.xzyw
1903      *
1904      * However, the NV extensions are never enabled for <= 2.0 shaders because of the performance penalty that
1905      * comes with it, and texbem is an 1.x only instruction. No 1.x instruction forces us to enable the NV
1906      * extension.
1907      */
1908     shader_addline(buffer, "SWZ TB, bumpenvmat%d, x, z, 0, 0;\n", reg_dest_code);
1909     shader_addline(buffer, "DP3 TA.x, TB, %s;\n", src_reg);
1910     shader_addline(buffer, "SWZ TB, bumpenvmat%d, y, w, 0, 0;\n", reg_dest_code);
1911     shader_addline(buffer, "DP3 TA.y, TB, %s;\n", src_reg);
1912
1913     /* with projective textures, texbem only divides the static texture coord, not the displacement,
1914      * so we can't let the GL handle this.
1915      */
1916     if (((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS]
1917             & WINED3DTTFF_PROJECTED) {
1918         shader_addline(buffer, "RCP TB.w, %s.w;\n", reg_coord);
1919         shader_addline(buffer, "MUL TB.xy, %s, TB.w;\n", reg_coord);
1920         shader_addline(buffer, "ADD TA.xy, TA, TB;\n");
1921     } else {
1922         shader_addline(buffer, "ADD TA.xy, TA, %s;\n", reg_coord);
1923     }
1924
1925     shader_hw_sample(ins, reg_dest_code, dst_reg, "TA", 0, NULL, NULL);
1926
1927     if (ins->handler_idx == WINED3DSIH_TEXBEML)
1928     {
1929         /* No src swizzles are allowed, so this is ok */
1930         shader_addline(buffer, "MAD TA, %s.z, luminance%d.x, luminance%d.y;\n",
1931                        src_reg, reg_dest_code, reg_dest_code);
1932         shader_addline(buffer, "MUL %s, %s, TA;\n", dst_reg, dst_reg);
1933     }
1934 }
1935
1936 static void pshader_hw_texm3x2pad(const struct wined3d_shader_instruction *ins)
1937 {
1938     DWORD reg = ins->dst[0].reg.idx;
1939     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1940     char src0_name[50], dst_name[50];
1941     BOOL is_color;
1942     struct wined3d_shader_register tmp_reg = ins->dst[0].reg;
1943
1944     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1945     /* The next instruction will be a texm3x2tex or texm3x2depth that writes to the uninitialized
1946      * T<reg+1> register. Use this register to store the calculated vector
1947      */
1948     tmp_reg.idx = reg + 1;
1949     shader_arb_get_register_name(ins, &tmp_reg, dst_name, &is_color);
1950     shader_addline(buffer, "DP3 %s.x, fragment.texcoord[%u], %s;\n", dst_name, reg, src0_name);
1951 }
1952
1953 static void pshader_hw_texm3x2tex(const struct wined3d_shader_instruction *ins)
1954 {
1955     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1956     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1957     DWORD flags;
1958     DWORD reg = ins->dst[0].reg.idx;
1959     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1960     char dst_str[50];
1961     char src0_name[50];
1962     char dst_reg[50];
1963     BOOL is_color;
1964
1965     /* We know that we're writing to the uninitialized T<reg> register, so use it for temporary storage */
1966     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
1967
1968     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1969     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1970     shader_addline(buffer, "DP3 %s.y, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
1971     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1972     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1973 }
1974
1975 static void pshader_hw_texm3x3pad(const struct wined3d_shader_instruction *ins)
1976 {
1977     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1978     DWORD reg = ins->dst[0].reg.idx;
1979     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1980     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1981     char src0_name[50], dst_name[50];
1982     struct wined3d_shader_register tmp_reg = ins->dst[0].reg;
1983     BOOL is_color;
1984
1985     /* There are always 2 texm3x3pad instructions followed by one texm3x3[tex,vspec, ...] instruction, with
1986      * incrementing ins->dst[0].register_idx numbers. So the pad instruction already knows the final destination
1987      * register, and this register is uninitialized(otherwise the assembler complains that it is 'redeclared')
1988      */
1989     tmp_reg.idx = reg + 2 - current_state->current_row;
1990     shader_arb_get_register_name(ins, &tmp_reg, dst_name, &is_color);
1991
1992     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1993     shader_addline(buffer, "DP3 %s.%c, fragment.texcoord[%u], %s;\n",
1994                    dst_name, 'x' + current_state->current_row, reg, src0_name);
1995     current_state->texcoord_w[current_state->current_row++] = reg;
1996 }
1997
1998 static void pshader_hw_texm3x3tex(const struct wined3d_shader_instruction *ins)
1999 {
2000     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2001     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2002     DWORD flags;
2003     DWORD reg = ins->dst[0].reg.idx;
2004     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2005     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2006     char dst_str[50];
2007     char src0_name[50], dst_name[50];
2008     BOOL is_color;
2009
2010     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
2011     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
2012     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_name, reg, src0_name);
2013
2014     /* Sample the texture using the calculated coordinates */
2015     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
2016     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
2017     shader_hw_sample(ins, reg, dst_str, dst_name, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
2018     current_state->current_row = 0;
2019 }
2020
2021 static void pshader_hw_texm3x3vspec(const struct wined3d_shader_instruction *ins)
2022 {
2023     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2024     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2025     DWORD flags;
2026     DWORD reg = ins->dst[0].reg.idx;
2027     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2028     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2029     char dst_str[50];
2030     char src0_name[50];
2031     char dst_reg[50];
2032     BOOL is_color;
2033
2034     /* Get the dst reg without writemask strings. We know this register is uninitialized, so we can use all
2035      * components for temporary data storage
2036      */
2037     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
2038     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
2039     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
2040
2041     /* Construct the eye-ray vector from w coordinates */
2042     shader_addline(buffer, "MOV TB.x, fragment.texcoord[%u].w;\n", current_state->texcoord_w[0]);
2043     shader_addline(buffer, "MOV TB.y, fragment.texcoord[%u].w;\n", current_state->texcoord_w[1]);
2044     shader_addline(buffer, "MOV TB.z, fragment.texcoord[%u].w;\n", reg);
2045
2046     /* Calculate reflection vector
2047      */
2048     shader_addline(buffer, "DP3 %s.w, %s, TB;\n", dst_reg, dst_reg);
2049     /* The .w is ignored when sampling, so I can use TB.w to calculate dot(N, N) */
2050     shader_addline(buffer, "DP3 TB.w, %s, %s;\n", dst_reg, dst_reg);
2051     shader_addline(buffer, "RCP TB.w, TB.w;\n");
2052     shader_addline(buffer, "MUL %s.w, %s.w, TB.w;\n", dst_reg, dst_reg);
2053     shader_addline(buffer, "MUL %s, %s.w, %s;\n", dst_reg, dst_reg, dst_reg);
2054     shader_addline(buffer, "MAD %s, coefmul.x, %s, -TB;\n", dst_reg, dst_reg);
2055
2056     /* Sample the texture using the calculated coordinates */
2057     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
2058     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
2059     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
2060     current_state->current_row = 0;
2061 }
2062
2063 static void pshader_hw_texm3x3spec(const struct wined3d_shader_instruction *ins)
2064 {
2065     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2066     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2067     DWORD flags;
2068     DWORD reg = ins->dst[0].reg.idx;
2069     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2070     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2071     char dst_str[50];
2072     char src0_name[50];
2073     char src1_name[50];
2074     char dst_reg[50];
2075     BOOL is_color;
2076
2077     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
2078     shader_arb_get_src_param(ins, &ins->src[0], 1, src1_name);
2079     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
2080     /* Note: dst_reg.xy is input here, generated by two texm3x3pad instructions */
2081     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
2082
2083     /* Calculate reflection vector.
2084      *
2085      *                   dot(N, E)
2086      * dst_reg.xyz = 2 * --------- * N - E
2087      *                   dot(N, N)
2088      *
2089      * Which normalizes the normal vector
2090      */
2091     shader_addline(buffer, "DP3 %s.w, %s, %s;\n", dst_reg, dst_reg, src1_name);
2092     shader_addline(buffer, "DP3 TC.w, %s, %s;\n", dst_reg, dst_reg);
2093     shader_addline(buffer, "RCP TC.w, TC.w;\n");
2094     shader_addline(buffer, "MUL %s.w, %s.w, TC.w;\n", dst_reg, dst_reg);
2095     shader_addline(buffer, "MUL %s, %s.w, %s;\n", dst_reg, dst_reg, dst_reg);
2096     shader_addline(buffer, "MAD %s, coefmul.x, %s, -%s;\n", dst_reg, dst_reg, src1_name);
2097
2098     /* Sample the texture using the calculated coordinates */
2099     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
2100     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
2101     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
2102     current_state->current_row = 0;
2103 }
2104
2105 static void pshader_hw_texdepth(const struct wined3d_shader_instruction *ins)
2106 {
2107     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2108     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2109     char dst_name[50];
2110
2111     /* texdepth has an implicit destination, the fragment depth value. It's only parameter,
2112      * which is essentially an input, is the destination register because it is the first
2113      * parameter. According to the msdn, this must be register r5, but let's keep it more flexible
2114      * here(writemasks/swizzles are not valid on texdepth)
2115      */
2116     shader_arb_get_dst_param(ins, dst, dst_name);
2117
2118     /* According to the msdn, the source register(must be r5) is unusable after
2119      * the texdepth instruction, so we're free to modify it
2120      */
2121     shader_addline(buffer, "MIN %s.y, %s.y, one.y;\n", dst_name, dst_name);
2122
2123     /* How to deal with the special case dst_name.g == 0? if r != 0, then
2124      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
2125      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
2126      */
2127     shader_addline(buffer, "RCP %s.y, %s.y;\n", dst_name, dst_name);
2128     shader_addline(buffer, "MUL TA.x, %s.x, %s.y;\n", dst_name, dst_name);
2129     shader_addline(buffer, "MIN TA.x, TA.x, one.x;\n");
2130     shader_addline(buffer, "MAX result.depth, TA.x, 0.0;\n");
2131 }
2132
2133 /** Process the WINED3DSIO_TEXDP3TEX instruction in ARB:
2134  * Take a 3-component dot product of the TexCoord[dstreg] and src,
2135  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2136 static void pshader_hw_texdp3tex(const struct wined3d_shader_instruction *ins)
2137 {
2138     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2139     DWORD sampler_idx = ins->dst[0].reg.idx;
2140     char src0[50];
2141     char dst_str[50];
2142
2143     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
2144     shader_addline(buffer, "MOV TB, 0.0;\n");
2145     shader_addline(buffer, "DP3 TB.x, fragment.texcoord[%u], %s;\n", sampler_idx, src0);
2146
2147     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
2148     shader_hw_sample(ins, sampler_idx, dst_str, "TB", 0 /* Only one coord, can't be projected */, NULL, NULL);
2149 }
2150
2151 /** Process the WINED3DSIO_TEXDP3 instruction in ARB:
2152  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2153 static void pshader_hw_texdp3(const struct wined3d_shader_instruction *ins)
2154 {
2155     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2156     char src0[50];
2157     char dst_str[50];
2158     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2159
2160     /* Handle output register */
2161     shader_arb_get_dst_param(ins, dst, dst_str);
2162     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
2163     shader_addline(buffer, "DP3 %s, fragment.texcoord[%u], %s;\n", dst_str, dst->reg.idx, src0);
2164 }
2165
2166 /** Process the WINED3DSIO_TEXM3X3 instruction in ARB
2167  * Perform the 3rd row of a 3x3 matrix multiply */
2168 static void pshader_hw_texm3x3(const struct wined3d_shader_instruction *ins)
2169 {
2170     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2171     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2172     char dst_str[50], dst_name[50];
2173     char src0[50];
2174     BOOL is_color;
2175
2176     shader_arb_get_dst_param(ins, dst, dst_str);
2177     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
2178     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
2179     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_name, dst->reg.idx, src0);
2180     shader_addline(buffer, "MOV %s, %s;\n", dst_str, dst_name);
2181 }
2182
2183 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in ARB:
2184  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2185  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
2186  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2187  */
2188 static void pshader_hw_texm3x2depth(const struct wined3d_shader_instruction *ins)
2189 {
2190     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2191     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2192     char src0[50], dst_name[50];
2193     BOOL is_color;
2194
2195     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
2196     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
2197     shader_addline(buffer, "DP3 %s.y, fragment.texcoord[%u], %s;\n", dst_name, dst->reg.idx, src0);
2198
2199     /* How to deal with the special case dst_name.g == 0? if r != 0, then
2200      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
2201      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
2202      */
2203     shader_addline(buffer, "RCP %s.y, %s.y;\n", dst_name, dst_name);
2204     shader_addline(buffer, "MUL %s.x, %s.x, %s.y;\n", dst_name, dst_name, dst_name);
2205     shader_addline(buffer, "MIN %s.x, %s.x, one.x;\n", dst_name, dst_name);
2206     shader_addline(buffer, "MAX result.depth, %s.x, 0.0;\n", dst_name);
2207 }
2208
2209 /** Handles transforming all WINED3DSIO_M?x? opcodes for
2210     Vertex/Pixel shaders to ARB_vertex_program codes */
2211 static void shader_hw_mnxn(const struct wined3d_shader_instruction *ins)
2212 {
2213     int i;
2214     int nComponents = 0;
2215     struct wined3d_shader_dst_param tmp_dst = {{0}};
2216     struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2217     struct wined3d_shader_instruction tmp_ins;
2218
2219     memset(&tmp_ins, 0, sizeof(tmp_ins));
2220
2221     /* Set constants for the temporary argument */
2222     tmp_ins.ctx = ins->ctx;
2223     tmp_ins.dst_count = 1;
2224     tmp_ins.dst = &tmp_dst;
2225     tmp_ins.src_count = 2;
2226     tmp_ins.src = tmp_src;
2227
2228     switch(ins->handler_idx)
2229     {
2230         case WINED3DSIH_M4x4:
2231             nComponents = 4;
2232             tmp_ins.handler_idx = WINED3DSIH_DP4;
2233             break;
2234         case WINED3DSIH_M4x3:
2235             nComponents = 3;
2236             tmp_ins.handler_idx = WINED3DSIH_DP4;
2237             break;
2238         case WINED3DSIH_M3x4:
2239             nComponents = 4;
2240             tmp_ins.handler_idx = WINED3DSIH_DP3;
2241             break;
2242         case WINED3DSIH_M3x3:
2243             nComponents = 3;
2244             tmp_ins.handler_idx = WINED3DSIH_DP3;
2245             break;
2246         case WINED3DSIH_M3x2:
2247             nComponents = 2;
2248             tmp_ins.handler_idx = WINED3DSIH_DP3;
2249             break;
2250         default:
2251             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
2252             break;
2253     }
2254
2255     tmp_dst = ins->dst[0];
2256     tmp_src[0] = ins->src[0];
2257     tmp_src[1] = ins->src[1];
2258     for (i = 0; i < nComponents; i++) {
2259         tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2260         shader_hw_map2gl(&tmp_ins);
2261         ++tmp_src[1].reg.idx;
2262     }
2263 }
2264
2265 static void shader_hw_scalar_op(const struct wined3d_shader_instruction *ins)
2266 {
2267     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2268     const char *instruction;
2269
2270     char dst[50];
2271     char src[50];
2272
2273     switch(ins->handler_idx)
2274     {
2275         case WINED3DSIH_RSQ:  instruction = "RSQ"; break;
2276         case WINED3DSIH_RCP:  instruction = "RCP"; break;
2277         case WINED3DSIH_EXP:  instruction = "EX2"; break;
2278         case WINED3DSIH_EXPP: instruction = "EXP"; break;
2279         default: instruction = "";
2280             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
2281             break;
2282     }
2283
2284     shader_arb_get_dst_param(ins, &ins->dst[0], dst); /* Destination */
2285     shader_arb_get_src_param(ins, &ins->src[0], 0, src);
2286     if (ins->src[0].swizzle == WINED3DSP_NOSWIZZLE)
2287     {
2288         /* Dx sdk says .x is used if no swizzle is given, but our test shows that
2289          * .w is used
2290          */
2291         strcat(src, ".w");
2292     }
2293
2294     shader_addline(buffer, "%s%s %s, %s;\n", instruction, shader_arb_get_modifier(ins), dst, src);
2295 }
2296
2297 static void shader_hw_nrm(const struct wined3d_shader_instruction *ins)
2298 {
2299     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2300     char dst_name[50];
2301     char src_name[50];
2302     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2303     BOOL pshader = shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type);
2304
2305     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2306     shader_arb_get_src_param(ins, &ins->src[0], 1 /* Use TB */, src_name);
2307
2308     if(pshader && priv->target_version >= NV3)
2309     {
2310         shader_addline(buffer, "NRM%s %s, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name);
2311     }
2312     else
2313     {
2314         shader_addline(buffer, "DP3 TA, %s, %s;\n", src_name, src_name);
2315         shader_addline(buffer, "RSQ TA, TA.x;\n");
2316         /* dst.w = src[0].w * 1 / (src.x^2 + src.y^2 + src.z^2)^(1/2) according to msdn*/
2317         shader_addline(buffer, "MUL%s %s, %s, TA;\n", shader_arb_get_modifier(ins), dst_name,
2318                     src_name);
2319     }
2320 }
2321
2322 static void shader_hw_lrp(const struct wined3d_shader_instruction *ins)
2323 {
2324     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2325     char dst_name[50];
2326     char src_name[3][50];
2327
2328     /* ARB_fragment_program has a convenient LRP instruction */
2329     if(shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)) {
2330         shader_hw_map2gl(ins);
2331         return;
2332     }
2333
2334     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2335     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
2336     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
2337     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
2338
2339     shader_addline(buffer, "SUB TA, %s, %s;\n", src_name[1], src_name[2]);
2340     shader_addline(buffer, "MAD%s %s, %s, TA, %s;\n", shader_arb_get_modifier(ins),
2341                    dst_name, src_name[0], src_name[2]);
2342 }
2343
2344 static void shader_hw_sincos(const struct wined3d_shader_instruction *ins)
2345 {
2346     /* This instruction exists in ARB, but the d3d instruction takes two extra parameters which
2347      * must contain fixed constants. So we need a separate function to filter those constants and
2348      * can't use map2gl
2349      */
2350     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2351     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2352     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2353     char dst_name[50];
2354     char src_name0[50], src_name1[50], src_name2[50];
2355     BOOL is_color;
2356
2357     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2358     if(shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)) {
2359         shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2360         /* No modifiers are supported on SCS */
2361         shader_addline(buffer, "SCS %s, %s;\n", dst_name, src_name0);
2362
2363         if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
2364         {
2365             shader_arb_get_register_name(ins, &dst->reg, src_name0, &is_color);
2366             shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, src_name0);
2367         }
2368     } else if(priv->target_version >= NV2) {
2369         shader_arb_get_register_name(ins, &dst->reg, dst_name, &is_color);
2370
2371         /* Sincos writemask must be .x, .y or .xy */
2372         if(dst->write_mask & WINED3DSP_WRITEMASK_0)
2373             shader_addline(buffer, "COS%s %s.x, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name0);
2374         if(dst->write_mask & WINED3DSP_WRITEMASK_1)
2375             shader_addline(buffer, "SIN%s %s.y, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name0);
2376     } else {
2377         /* Approximate sine and cosine with a taylor series, as per math textbook. The application passes 8
2378          * helper constants(D3DSINCOSCONST1 and D3DSINCOSCONST2) in src1 and src2.
2379          *
2380          * sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
2381          * cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + ...
2382          *
2383          * The constants we get are:
2384          *
2385          *  +1   +1,     -1     -1     +1      +1      -1       -1
2386          *      ---- ,  ---- , ---- , ----- , ----- , ----- , ------
2387          *      1!*2    2!*4   3!*8   4!*16   5!*32   6!*64   7!*128
2388          *
2389          * If used with x^2, x^3, x^4 etc they calculate sin(x/2) and cos(x/2):
2390          *
2391          * (x/2)^2 = x^2 / 4
2392          * (x/2)^3 = x^3 / 8
2393          * (x/2)^4 = x^4 / 16
2394          * (x/2)^5 = x^5 / 32
2395          * etc
2396          *
2397          * To get the final result:
2398          * sin(x) = 2 * sin(x/2) * cos(x/2)
2399          * cos(x) = cos(x/2)^2 - sin(x/2)^2
2400          * (from sin(x+y) and cos(x+y) rules)
2401          *
2402          * As per MSDN, dst.z is undefined after the operation, and so is
2403          * dst.x and dst.y if they're masked out by the writemask. Ie
2404          * sincos dst.y, src1, c0, c1
2405          * returns the sine in dst.y. dst.x and dst.z are undefined, dst.w is not touched. The assembler
2406          * vsa.exe also stops with an error if the dest register is the same register as the source
2407          * register. This means we can use dest.xyz as temporary storage. The assembler vsa.exe output also
2408          * indicates that sincos consumes 8 instruction slots in vs_2_0(and, strangely, in vs_3_0).
2409          */
2410         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2411         shader_arb_get_src_param(ins, &ins->src[2], 2, src_name2);
2412         shader_arb_get_register_name(ins, &dst->reg, dst_name, &is_color);
2413
2414         shader_addline(buffer, "MUL %s.x, %s, %s;\n", dst_name, src_name0, src_name0);  /* x ^ 2 */
2415         shader_addline(buffer, "MUL TA.y, %s.x, %s;\n", dst_name, src_name0);           /* x ^ 3 */
2416         shader_addline(buffer, "MUL %s.y, TA.y, %s;\n", dst_name, src_name0);           /* x ^ 4 */
2417         shader_addline(buffer, "MUL TA.z, %s.y, %s;\n", dst_name, src_name0);           /* x ^ 5 */
2418         shader_addline(buffer, "MUL %s.z, TA.z, %s;\n", dst_name, src_name0);           /* x ^ 6 */
2419         shader_addline(buffer, "MUL TA.w, %s.z, %s;\n", dst_name, src_name0);           /* x ^ 7 */
2420
2421         /* sin(x/2)
2422          *
2423          * Unfortunately we don't get the constants in a DP4-capable form. Is there a way to
2424          * properly merge that with MULs in the code above?
2425          * The swizzles .yz and xw however fit into the .yzxw swizzle added to ps_2_0. Maybe
2426          * we can merge the sine and cosine MAD rows to calculate them together.
2427          */
2428         shader_addline(buffer, "MUL TA.x, %s, %s.w;\n", src_name0, src_name2); /* x^1, +1/(1!*2) */
2429         shader_addline(buffer, "MAD TA.x, TA.y, %s.x, TA.x;\n", src_name2); /* -1/(3!*8) */
2430         shader_addline(buffer, "MAD TA.x, TA.z, %s.w, TA.x;\n", src_name1); /* +1/(5!*32) */
2431         shader_addline(buffer, "MAD TA.x, TA.w, %s.x, TA.x;\n", src_name1); /* -1/(7!*128) */
2432
2433         /* cos(x/2) */
2434         shader_addline(buffer, "MAD TA.y, %s.x, %s.y, %s.z;\n", dst_name, src_name2, src_name2); /* -1/(2!*4), +1.0 */
2435         shader_addline(buffer, "MAD TA.y, %s.y, %s.z, TA.y;\n", dst_name, src_name1); /* +1/(4!*16) */
2436         shader_addline(buffer, "MAD TA.y, %s.z, %s.y, TA.y;\n", dst_name, src_name1); /* -1/(6!*64) */
2437
2438         if(dst->write_mask & WINED3DSP_WRITEMASK_0) {
2439             /* cos x */
2440             shader_addline(buffer, "MUL TA.z, TA.y, TA.y;\n");
2441             shader_addline(buffer, "MAD %s.x, -TA.x, TA.x, TA.z;\n", dst_name);
2442         }
2443         if(dst->write_mask & WINED3DSP_WRITEMASK_1) {
2444             /* sin x */
2445             shader_addline(buffer, "MUL %s.y, TA.x, TA.y;\n", dst_name);
2446             shader_addline(buffer, "ADD %s.y, %s.y, %s.y;\n", dst_name, dst_name, dst_name);
2447         }
2448     }
2449 }
2450
2451 static void shader_hw_sgn(const struct wined3d_shader_instruction *ins)
2452 {
2453     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2454     char dst_name[50];
2455     char src_name[50];
2456     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
2457
2458     /* SGN is only valid in vertex shaders */
2459     if(ctx->target_version == NV2) {
2460         shader_hw_map2gl(ins);
2461         return;
2462     }
2463     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2464     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name);
2465
2466     /* If SRC > 0.0, -SRC < SRC = TRUE, otherwise false.
2467      * if SRC < 0.0,  SRC < -SRC = TRUE. If neither is true, src = 0.0
2468      */
2469     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE) {
2470         shader_addline(buffer, "SLT %s, -%s, %s;\n", dst_name, src_name, src_name);
2471     } else {
2472         /* src contains TA? Write to the dest first. This won't overwrite our destination.
2473          * Then use TA, and calculate the final result
2474          *
2475          * Not reading from TA? Store the first result in TA to avoid overwriting the
2476          * destination if src reg = dst reg
2477          */
2478         if(strstr(src_name, "TA"))
2479         {
2480             shader_addline(buffer, "SLT %s,  %s, -%s;\n", dst_name, src_name, src_name);
2481             shader_addline(buffer, "SLT TA, -%s, %s;\n", src_name, src_name);
2482             shader_addline(buffer, "ADD %s, %s, -TA;\n", dst_name, dst_name);
2483         }
2484         else
2485         {
2486             shader_addline(buffer, "SLT TA, -%s, %s;\n", src_name, src_name);
2487             shader_addline(buffer, "SLT %s,  %s, -%s;\n", dst_name, src_name, src_name);
2488             shader_addline(buffer, "ADD %s, TA, -%s;\n", dst_name, dst_name);
2489         }
2490     }
2491 }
2492
2493 static void shader_hw_dsy(const struct wined3d_shader_instruction *ins)
2494 {
2495     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2496     char src[50];
2497     char dst[50];
2498     char dst_name[50];
2499     BOOL is_color;
2500
2501     shader_arb_get_dst_param(ins, &ins->dst[0], dst);
2502     shader_arb_get_src_param(ins, &ins->src[0], 0, src);
2503     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
2504
2505     shader_addline(buffer, "DDY %s, %s;\n", dst, src);
2506     shader_addline(buffer, "MUL%s %s, %s, ycorrection.y;\n", shader_arb_get_modifier(ins), dst, dst_name);
2507 }
2508
2509 static DWORD abs_modifier(DWORD mod, BOOL *need_abs)
2510 {
2511     *need_abs = FALSE;
2512
2513     switch(mod)
2514     {
2515         case WINED3DSPSM_NONE:      return WINED3DSPSM_ABS;
2516         case WINED3DSPSM_NEG:       return WINED3DSPSM_ABS;
2517         case WINED3DSPSM_BIAS:      *need_abs = TRUE; return WINED3DSPSM_BIAS;
2518         case WINED3DSPSM_BIASNEG:   *need_abs = TRUE; return WINED3DSPSM_BIASNEG;
2519         case WINED3DSPSM_SIGN:      *need_abs = TRUE; return WINED3DSPSM_SIGN;
2520         case WINED3DSPSM_SIGNNEG:   *need_abs = TRUE; return WINED3DSPSM_SIGNNEG;
2521         case WINED3DSPSM_COMP:      *need_abs = TRUE; return WINED3DSPSM_COMP;
2522         case WINED3DSPSM_X2:        *need_abs = TRUE; return WINED3DSPSM_X2;
2523         case WINED3DSPSM_X2NEG:     *need_abs = TRUE; return WINED3DSPSM_X2NEG;
2524         case WINED3DSPSM_DZ:        *need_abs = TRUE; return WINED3DSPSM_DZ;
2525         case WINED3DSPSM_DW:        *need_abs = TRUE; return WINED3DSPSM_DW;
2526         case WINED3DSPSM_ABS:       return WINED3DSPSM_ABS;
2527         case WINED3DSPSM_ABSNEG:    return WINED3DSPSM_ABS;
2528     }
2529     FIXME("Unknown modifier %u\n", mod);
2530     return mod;
2531 }
2532
2533 static void shader_hw_log_pow(const struct wined3d_shader_instruction *ins)
2534 {
2535     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2536     char src0[50], src1[50], dst[50];
2537     struct wined3d_shader_src_param src0_copy = ins->src[0];
2538     BOOL need_abs = FALSE;
2539     const char *instr;
2540     BOOL arg2 = FALSE;
2541
2542     switch(ins->handler_idx)
2543     {
2544         case WINED3DSIH_LOG:  instr = "LG2"; break;
2545         case WINED3DSIH_LOGP: instr = "LOG"; break;
2546         case WINED3DSIH_POW:  instr = "POW"; arg2 = TRUE; break;
2547         default:
2548             ERR("Unexpected instruction %d\n", ins->handler_idx);
2549             return;
2550     }
2551
2552     /* LOG, LOGP and POW operate on the absolute value of the input */
2553     src0_copy.modifiers = abs_modifier(src0_copy.modifiers, &need_abs);
2554
2555     shader_arb_get_dst_param(ins, &ins->dst[0], dst);
2556     shader_arb_get_src_param(ins, &src0_copy, 0, src0);
2557     if(arg2) shader_arb_get_src_param(ins, &ins->src[1], 1, src1);
2558
2559     if(need_abs)
2560     {
2561         shader_addline(buffer, "ABS TA, %s;\n", src0);
2562         if(arg2)
2563         {
2564             shader_addline(buffer, "%s%s %s, TA, %s;\n", instr, shader_arb_get_modifier(ins), dst, src1);
2565         }
2566         else
2567         {
2568             shader_addline(buffer, "%s%s %s, TA;\n", instr, shader_arb_get_modifier(ins), dst);
2569         }
2570     }
2571     else if(arg2)
2572     {
2573         shader_addline(buffer, "%s%s %s, %s, %s;\n", instr, shader_arb_get_modifier(ins), dst, src0, src1);
2574     }
2575     else
2576     {
2577         shader_addline(buffer, "%s%s %s, %s;\n", instr, shader_arb_get_modifier(ins), dst, src0);
2578     }
2579 }
2580
2581 static void shader_hw_loop(const struct wined3d_shader_instruction *ins)
2582 {
2583     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2584     char src_name[50];
2585     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2586
2587     /* src0 is aL */
2588     shader_arb_get_src_param(ins, &ins->src[1], 0, src_name);
2589
2590     if(vshader)
2591     {
2592         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2593         struct list *e = list_head(&priv->control_frames);
2594         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2595
2596         if(priv->loop_depth > 1) shader_addline(buffer, "PUSHA aL;\n");
2597         /* The constant loader makes sure to load -1 into iX.w */
2598         shader_addline(buffer, "ARLC aL, %s.xywz;\n", src_name);
2599         shader_addline(buffer, "BRA loop_%u_end (LE.x);\n", control_frame->loop_no);
2600         shader_addline(buffer, "loop_%u_start:\n", control_frame->loop_no);
2601     }
2602     else
2603     {
2604         shader_addline(buffer, "LOOP %s;\n", src_name);
2605     }
2606 }
2607
2608 static void shader_hw_rep(const struct wined3d_shader_instruction *ins)
2609 {
2610     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2611     char src_name[50];
2612     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2613
2614     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name);
2615
2616     /* The constant loader makes sure to load -1 into iX.w */
2617     if(vshader)
2618     {
2619         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2620         struct list *e = list_head(&priv->control_frames);
2621         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2622
2623         if(priv->loop_depth > 1) shader_addline(buffer, "PUSHA aL;\n");
2624
2625         shader_addline(buffer, "ARLC aL, %s.xywz;\n", src_name);
2626         shader_addline(buffer, "BRA loop_%u_end (LE.x);\n", control_frame->loop_no);
2627         shader_addline(buffer, "loop_%u_start:\n", control_frame->loop_no);
2628     }
2629     else
2630     {
2631         shader_addline(buffer, "REP %s;\n", src_name);
2632     }
2633 }
2634
2635 static void shader_hw_endloop(const struct wined3d_shader_instruction *ins)
2636 {
2637     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2638     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2639
2640     if(vshader)
2641     {
2642         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2643         struct list *e = list_head(&priv->control_frames);
2644         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2645
2646         shader_addline(buffer, "ARAC aL.xy, aL;\n");
2647         shader_addline(buffer, "BRA loop_%u_start (GT.x);\n", control_frame->loop_no);
2648         shader_addline(buffer, "loop_%u_end:\n", control_frame->loop_no);
2649
2650         if(priv->loop_depth > 1) shader_addline(buffer, "POPA aL;\n");
2651     }
2652     else
2653     {
2654         shader_addline(buffer, "ENDLOOP;\n");
2655     }
2656 }
2657
2658 static void shader_hw_endrep(const struct wined3d_shader_instruction *ins)
2659 {
2660     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2661     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2662
2663     if(vshader)
2664     {
2665         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2666         struct list *e = list_head(&priv->control_frames);
2667         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2668
2669         shader_addline(buffer, "ARAC aL.xy, aL;\n");
2670         shader_addline(buffer, "BRA loop_%u_start (GT.x);\n", control_frame->loop_no);
2671         shader_addline(buffer, "loop_%u_end:\n", control_frame->loop_no);
2672
2673         if(priv->loop_depth > 1) shader_addline(buffer, "POPA aL;\n");
2674     }
2675     else
2676     {
2677         shader_addline(buffer, "ENDREP;\n");
2678     }
2679 }
2680
2681 static const struct control_frame *find_last_loop(const struct shader_arb_ctx_priv *priv)
2682 {
2683     struct control_frame *control_frame;
2684
2685     LIST_FOR_EACH_ENTRY(control_frame, &priv->control_frames, struct control_frame, entry)
2686     {
2687         if(control_frame->type == LOOP || control_frame->type == REP) return control_frame;
2688     }
2689     ERR("Could not find loop for break\n");
2690     return NULL;
2691 }
2692
2693 static void shader_hw_break(const struct wined3d_shader_instruction *ins)
2694 {
2695     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2696     const struct control_frame *control_frame = find_last_loop(ins->ctx->backend_data);
2697     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2698
2699     if(vshader)
2700     {
2701         shader_addline(buffer, "BRA loop_%u_end;\n", control_frame->loop_no);
2702     }
2703     else
2704     {
2705         shader_addline(buffer, "BRK;\n");
2706     }
2707 }
2708
2709 static const char *get_compare(COMPARISON_TYPE flags)
2710 {
2711     switch (flags)
2712     {
2713         case COMPARISON_GT: return "GT";
2714         case COMPARISON_EQ: return "EQ";
2715         case COMPARISON_GE: return "GE";
2716         case COMPARISON_LT: return "LT";
2717         case COMPARISON_NE: return "NE";
2718         case COMPARISON_LE: return "LE";
2719         default:
2720             FIXME("Unrecognized comparison value: %u\n", flags);
2721             return "(\?\?)";
2722     }
2723 }
2724
2725 static COMPARISON_TYPE invert_compare(COMPARISON_TYPE flags)
2726 {
2727     switch (flags)
2728     {
2729         case COMPARISON_GT: return COMPARISON_LE;
2730         case COMPARISON_EQ: return COMPARISON_NE;
2731         case COMPARISON_GE: return COMPARISON_LT;
2732         case COMPARISON_LT: return COMPARISON_GE;
2733         case COMPARISON_NE: return COMPARISON_EQ;
2734         case COMPARISON_LE: return COMPARISON_GT;
2735         default:
2736             FIXME("Unrecognized comparison value: %u\n", flags);
2737             return -1;
2738     }
2739 }
2740
2741 static void shader_hw_breakc(const struct wined3d_shader_instruction *ins)
2742 {
2743     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2744     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2745     const struct control_frame *control_frame = find_last_loop(ins->ctx->backend_data);
2746     char src_name0[50];
2747     char src_name1[50];
2748     const char *comp = get_compare(ins->flags);
2749
2750     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2751     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2752
2753     if(vshader)
2754     {
2755         /* SUBC CC, src0, src1" works only in pixel shaders, so use TA to throw
2756          * away the subtraction result
2757          */
2758         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2759         shader_addline(buffer, "BRA loop_%u_end (%s.x);\n", control_frame->loop_no, comp);
2760     }
2761     else
2762     {
2763         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2764         shader_addline(buffer, "BRK (%s.x);\n", comp);
2765     }
2766 }
2767
2768 static void shader_hw_ifc(const struct wined3d_shader_instruction *ins)
2769 {
2770     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2771     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2772     struct list *e = list_head(&priv->control_frames);
2773     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2774     const char *comp;
2775     char src_name0[50];
2776     char src_name1[50];
2777     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2778
2779     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2780     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2781
2782     if(vshader)
2783     {
2784         /* Invert the flag. We jump to the else label if the condition is NOT true */
2785         comp = get_compare(invert_compare(ins->flags));
2786         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2787         shader_addline(buffer, "BRA ifc_%u_else (%s.x);\n", control_frame->ifc_no, comp);
2788     }
2789     else
2790     {
2791         comp = get_compare(ins->flags);
2792         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2793         shader_addline(buffer, "IF %s.x;\n", comp);
2794     }
2795 }
2796
2797 static void shader_hw_else(const struct wined3d_shader_instruction *ins)
2798 {
2799     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2800     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2801     struct list *e = list_head(&priv->control_frames);
2802     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2803     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2804
2805     if(vshader)
2806     {
2807         shader_addline(buffer, "BRA ifc_%u_endif;\n", control_frame->ifc_no);
2808         shader_addline(buffer, "ifc_%u_else:\n", control_frame->ifc_no);
2809         control_frame->had_else = TRUE;
2810     }
2811     else
2812     {
2813         shader_addline(buffer, "ELSE;\n");
2814     }
2815 }
2816
2817 static void shader_hw_endif(const struct wined3d_shader_instruction *ins)
2818 {
2819     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2820     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2821     struct list *e = list_head(&priv->control_frames);
2822     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2823     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2824
2825     if(vshader)
2826     {
2827         if(control_frame->had_else)
2828         {
2829             shader_addline(buffer, "ifc_%u_endif:\n", control_frame->ifc_no);
2830         }
2831         else
2832         {
2833             shader_addline(buffer, "#No else branch. else is endif\n");
2834             shader_addline(buffer, "ifc_%u_else:\n", control_frame->ifc_no);
2835         }
2836     }
2837     else
2838     {
2839         shader_addline(buffer, "ENDIF;\n");
2840     }
2841 }
2842
2843 static void shader_hw_texldd(const struct wined3d_shader_instruction *ins)
2844 {
2845     DWORD sampler_idx = ins->src[1].reg.idx;
2846     char reg_dest[40];
2847     char reg_src[3][40];
2848     DWORD flags = TEX_DERIV;
2849
2850     shader_arb_get_dst_param(ins, &ins->dst[0], reg_dest);
2851     shader_arb_get_src_param(ins, &ins->src[0], 0, reg_src[0]);
2852     shader_arb_get_src_param(ins, &ins->src[2], 1, reg_src[1]);
2853     shader_arb_get_src_param(ins, &ins->src[3], 2, reg_src[2]);
2854
2855     if (ins->flags & WINED3DSI_TEXLD_PROJECT) flags |= TEX_PROJ;
2856     if (ins->flags & WINED3DSI_TEXLD_BIAS) flags |= TEX_BIAS;
2857
2858     shader_hw_sample(ins, sampler_idx, reg_dest, reg_src[0], flags, reg_src[1], reg_src[2]);
2859 }
2860
2861 static void shader_hw_texldl(const struct wined3d_shader_instruction *ins)
2862 {
2863     DWORD sampler_idx = ins->src[1].reg.idx;
2864     char reg_dest[40];
2865     char reg_coord[40];
2866     DWORD flags = TEX_LOD;
2867
2868     shader_arb_get_dst_param(ins, &ins->dst[0], reg_dest);
2869     shader_arb_get_src_param(ins, &ins->src[0], 0, reg_coord);
2870
2871     if (ins->flags & WINED3DSI_TEXLD_PROJECT) flags |= TEX_PROJ;
2872     if (ins->flags & WINED3DSI_TEXLD_BIAS) flags |= TEX_BIAS;
2873
2874     shader_hw_sample(ins, sampler_idx, reg_dest, reg_coord, flags, NULL, NULL);
2875 }
2876
2877 static void shader_hw_label(const struct wined3d_shader_instruction *ins)
2878 {
2879     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2880     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2881
2882     priv->in_main_func = FALSE;
2883     /* Call instructions activate the NV extensions, not labels and rets. If there is an uncalled
2884      * subroutine, don't generate a label that will make GL complain
2885      */
2886     if(priv->target_version == ARB) return;
2887
2888     shader_addline(buffer, "l%u:\n", ins->src[0].reg.idx);
2889 }
2890
2891 static void vshader_add_footer(IWineD3DVertexShaderImpl *This, struct wined3d_shader_buffer *buffer,
2892         const struct arb_vs_compile_args *args, struct shader_arb_ctx_priv *priv_ctx)
2893 {
2894     const shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
2895     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
2896     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2897     unsigned int i;
2898
2899     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
2900      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
2901      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
2902      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
2903      */
2904     if(args->super.fog_src == VS_FOG_Z) {
2905         shader_addline(buffer, "MOV result.fogcoord, TMP_OUT.z;\n");
2906     } else if (!reg_maps->fog) {
2907         /* posFixup.x is always 1.0, so we can savely use it */
2908         shader_addline(buffer, "ADD result.fogcoord, posFixup.x, -posFixup.x;\n");
2909     }
2910
2911     /* Write the final position.
2912      *
2913      * OpenGL coordinates specify the center of the pixel while d3d coords specify
2914      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
2915      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
2916      * contains 1.0 to allow a mad, but arb vs swizzles are too restricted for that.
2917      */
2918     shader_addline(buffer, "MUL TA, posFixup, TMP_OUT.w;\n");
2919     shader_addline(buffer, "ADD TMP_OUT.x, TMP_OUT.x, TA.z;\n");
2920     shader_addline(buffer, "MAD TMP_OUT.y, TMP_OUT.y, posFixup.y, TA.w;\n");
2921
2922     if(use_nv_clip(gl_info) && priv_ctx->target_version >= NV2)
2923     {
2924         for(i = 0; i < priv_ctx->vs_clipplanes; i++)
2925         {
2926             shader_addline(buffer, "DP4 result.clip[%u].x, TMP_OUT, state.clip[%u].plane;\n", i, i);
2927         }
2928     }
2929     else if(args->boolclip.clip_control[0])
2930     {
2931         unsigned int cur_clip = 0;
2932         char component[4] = {'x', 'y', 'z', 'w'};
2933
2934         for(i = 0; i < GL_LIMITS(clipplanes); i++)
2935         {
2936             if(args->boolclip.clip_control[1] & (1 << i))
2937             {
2938                 shader_addline(buffer, "DP4 TA.%c, TMP_OUT, state.clip[%u].plane;\n",
2939                                component[cur_clip++], i);
2940             }
2941         }
2942         switch(cur_clip)
2943         {
2944             case 0:
2945                 shader_addline(buffer, "MOV TA, -helper_const.w;\n");
2946                 break;
2947             case 1:
2948                 shader_addline(buffer, "MOV TA.yzw, -helper_const.w;\n");
2949                 break;
2950             case 2:
2951                 shader_addline(buffer, "MOV TA.zw, -helper_const.w;\n");
2952                 break;
2953             case 3:
2954                 shader_addline(buffer, "MOV TA.w, -helper_const.w;\n");
2955                 break;
2956         }
2957         shader_addline(buffer, "MOV result.texcoord[%u], TA;\n",
2958                        args->boolclip.clip_control[0] - 1);
2959     }
2960
2961     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
2962      * and the glsl equivalent
2963      */
2964     if(need_helper_const(gl_info)) {
2965         shader_addline(buffer, "MAD TMP_OUT.z, TMP_OUT.z, helper_const.x, -TMP_OUT.w;\n");
2966     } else {
2967         shader_addline(buffer, "ADD TMP_OUT.z, TMP_OUT.z, TMP_OUT.z;\n");
2968         shader_addline(buffer, "ADD TMP_OUT.z, TMP_OUT.z, -TMP_OUT.w;\n");
2969     }
2970
2971     shader_addline(buffer, "MOV result.position, TMP_OUT;\n");
2972
2973     priv_ctx->footer_written = TRUE;
2974 }
2975
2976 static void shader_hw_ret(const struct wined3d_shader_instruction *ins)
2977 {
2978     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2979     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2980     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *) ins->ctx->shader;
2981     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2982
2983     if(priv->target_version == ARB) return;
2984
2985     if(vshader)
2986     {
2987         if(priv->in_main_func) vshader_add_footer((IWineD3DVertexShaderImpl *) shader, buffer, priv->cur_vs_args, priv);
2988     }
2989
2990     shader_addline(buffer, "RET;\n");
2991 }
2992
2993 static void shader_hw_call(const struct wined3d_shader_instruction *ins)
2994 {
2995     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2996     shader_addline(buffer, "CAL l%u;\n", ins->src[0].reg.idx);
2997 }
2998
2999 /* GL locking is done by the caller */
3000 static GLuint create_arb_blt_vertex_program(const struct wined3d_gl_info *gl_info)
3001 {
3002     GLuint program_id = 0;
3003     GLint pos;
3004
3005     const char *blt_vprogram =
3006         "!!ARBvp1.0\n"
3007         "PARAM c[1] = { { 1, 0.5 } };\n"
3008         "MOV result.position, vertex.position;\n"
3009         "MOV result.color, c[0].x;\n"
3010         "MOV result.texcoord[0], vertex.texcoord[0];\n"
3011         "END\n";
3012
3013     GL_EXTCALL(glGenProgramsARB(1, &program_id));
3014     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, program_id));
3015     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3016             strlen(blt_vprogram), blt_vprogram));
3017     checkGLcall("glProgramStringARB()");
3018
3019     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
3020     if (pos != -1)
3021     {
3022         FIXME("Vertex program error at position %d: %s\n", pos,
3023             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3024     }
3025     else
3026     {
3027         GLint native;
3028
3029         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3030         checkGLcall("glGetProgramivARB()");
3031         if (!native) WARN("Program exceeds native resource limits.\n");
3032     }
3033
3034     return program_id;
3035 }
3036
3037 /* GL locking is done by the caller */
3038 static GLuint create_arb_blt_fragment_program(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
3039 {
3040     GLuint program_id = 0;
3041     GLint pos;
3042
3043     static const char * const blt_fprograms[tex_type_count] =
3044     {
3045         /* tex_1d */
3046         NULL,
3047         /* tex_2d */
3048         "!!ARBfp1.0\n"
3049         "TEMP R0;\n"
3050         "TEX R0.x, fragment.texcoord[0], texture[0], 2D;\n"
3051         "MOV result.depth.z, R0.x;\n"
3052         "END\n",
3053         /* tex_3d */
3054         NULL,
3055         /* tex_cube */
3056         "!!ARBfp1.0\n"
3057         "TEMP R0;\n"
3058         "TEX R0.x, fragment.texcoord[0], texture[0], CUBE;\n"
3059         "MOV result.depth.z, R0.x;\n"
3060         "END\n",
3061         /* tex_rect */
3062         "!!ARBfp1.0\n"
3063         "TEMP R0;\n"
3064         "TEX R0.x, fragment.texcoord[0], texture[0], RECT;\n"
3065         "MOV result.depth.z, R0.x;\n"
3066         "END\n",
3067     };
3068
3069     if (!blt_fprograms[tex_type])
3070     {
3071         FIXME("tex_type %#x not supported\n", tex_type);
3072         tex_type = tex_2d;
3073     }
3074
3075     GL_EXTCALL(glGenProgramsARB(1, &program_id));
3076     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
3077     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3078             strlen(blt_fprograms[tex_type]), blt_fprograms[tex_type]));
3079     checkGLcall("glProgramStringARB()");
3080
3081     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
3082     if (pos != -1)
3083     {
3084         FIXME("Fragment program error at position %d: %s\n", pos,
3085             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3086     }
3087     else
3088     {
3089         GLint native;
3090
3091         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3092         checkGLcall("glGetProgramivARB()");
3093         if (!native) WARN("Program exceeds native resource limits.\n");
3094     }
3095
3096     return program_id;
3097 }
3098
3099 static void arbfp_add_sRGB_correction(struct wined3d_shader_buffer *buffer, const char *fragcolor,
3100         const char *tmp1, const char *tmp2, const char *tmp3, const char *tmp4, BOOL condcode)
3101 {
3102     /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
3103
3104     if(condcode)
3105     {
3106         /* Sigh. MOVC CC doesn't work, so use one of the temps as dummy dest */
3107         shader_addline(buffer, "SUBC %s, %s.x, srgb_consts1.y;\n", tmp1, fragcolor);
3108         /* Calculate the > 0.0031308 case */
3109         shader_addline(buffer, "POW %s.x (GE), %s.x, srgb_consts1.z;\n", fragcolor, fragcolor);
3110         shader_addline(buffer, "POW %s.y (GE), %s.y, srgb_consts1.z;\n", fragcolor, fragcolor);
3111         shader_addline(buffer, "POW %s.z (GE), %s.z, srgb_consts1.z;\n", fragcolor, fragcolor);
3112         shader_addline(buffer, "MUL %s.xyz (GE), %s, srgb_consts1.w;\n", fragcolor, fragcolor);
3113         shader_addline(buffer, "SUB %s.xyz (GE), %s, srgb_consts2.x;\n", fragcolor, fragcolor);
3114         /* Calculate the < case */
3115         shader_addline(buffer, "MUL %s.xyz (LT), srgb_consts1.x, %s;\n", fragcolor, fragcolor);
3116     }
3117     else
3118     {
3119         /* Calculate the > 0.0031308 case */
3120         shader_addline(buffer, "POW %s.x, %s.x, srgb_consts1.z;\n", tmp1, fragcolor);
3121         shader_addline(buffer, "POW %s.y, %s.y, srgb_consts1.z;\n", tmp1, fragcolor);
3122         shader_addline(buffer, "POW %s.z, %s.z, srgb_consts1.z;\n", tmp1, fragcolor);
3123         shader_addline(buffer, "MUL %s, %s, srgb_consts1.w;\n", tmp1, tmp1);
3124         shader_addline(buffer, "SUB %s, %s, srgb_consts2.x;\n", tmp1, tmp1);
3125         /* Calculate the < case */
3126         shader_addline(buffer, "MUL %s, srgb_consts1.x, %s;\n", tmp2, fragcolor);
3127         /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
3128         shader_addline(buffer, "SLT %s, srgb_consts1.y, %s;\n", tmp3, fragcolor);
3129         shader_addline(buffer, "SGE %s, srgb_consts1.y, %s;\n", tmp4, fragcolor);
3130         /* Store the components > 0.0031308 in the destination */
3131         shader_addline(buffer, "MUL %s.xyz, %s, %s;\n", fragcolor, tmp1, tmp3);
3132         /* Add the components that are < 0.0031308 */
3133         shader_addline(buffer, "MAD %s.xyz, %s, %s, %s;\n", fragcolor, tmp2, tmp4, fragcolor);
3134         /* Move everything into result.color at once. Nvidia hardware cannot handle partial
3135         * result.color writes(.rgb first, then .a), or handle overwriting already written
3136         * components. The assembler uses a temporary register in this case, which is usually
3137         * not allocated from one of our registers that were used earlier.
3138         */
3139     }
3140     shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
3141     /* [0.0;1.0] clamping. Not needed, this is done implicitly */
3142 }
3143
3144 static const DWORD *find_loop_control_values(IWineD3DBaseShaderImpl *This, DWORD idx)
3145 {
3146     const local_constant *constant;
3147
3148     LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
3149     {
3150         if (constant->idx == idx)
3151         {
3152             return constant->value;
3153         }
3154     }
3155     return NULL;
3156 }
3157
3158 static void init_ps_input(const IWineD3DPixelShaderImpl *This, const struct arb_ps_compile_args *args,
3159                           struct shader_arb_ctx_priv *priv)
3160 {
3161     const char *texcoords[8] =
3162     {
3163         "fragment.texcoord[0]", "fragment.texcoord[1]", "fragment.texcoord[2]", "fragment.texcoord[3]",
3164         "fragment.texcoord[4]", "fragment.texcoord[5]", "fragment.texcoord[6]", "fragment.texcoord[7]"
3165     };
3166     unsigned int i;
3167     const struct wined3d_shader_signature_element *sig = This->input_signature;
3168     const char *semantic_name;
3169     DWORD semantic_idx;
3170
3171     switch(args->super.vp_mode)
3172     {
3173         case pretransformed:
3174         case fixedfunction:
3175             /* The pixelshader has to collect the varyings on its own. In any case properly load
3176              * color0 and color1. In the case of pretransformed vertices also load texcoords. Set
3177              * other attribs to 0.0.
3178              *
3179              * For fixedfunction this behavior is correct, according to the tests. For pretransformed
3180              * we'd either need a replacement shader that can load other attribs like BINORMAL, or
3181              * load the texcoord attrib pointers to match the pixel shader signature
3182              */
3183             for(i = 0; i < MAX_REG_INPUT; i++)
3184             {
3185                 semantic_name = sig[i].semantic_name;
3186                 semantic_idx = sig[i].semantic_idx;
3187                 if(semantic_name == NULL) continue;
3188
3189                 if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3190                 {
3191                     if(semantic_idx == 0) priv->ps_input[i] = "fragment.color.primary";
3192                     else if(semantic_idx == 1) priv->ps_input[i] = "fragment.color.secondary";
3193                     else priv->ps_input[i] = "0.0";
3194                 }
3195                 else if(args->super.vp_mode == fixedfunction)
3196                 {
3197                     priv->ps_input[i] = "0.0";
3198                 }
3199                 else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3200                 {
3201                     if(semantic_idx < 8) priv->ps_input[i] = texcoords[semantic_idx];
3202                     else priv->ps_input[i] = "0.0";
3203                 }
3204                 else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3205                 {
3206                     if(semantic_idx == 0) priv->ps_input[i] = "fragment.fogcoord";
3207                     else priv->ps_input[i] = "0.0";
3208                 }
3209                 else
3210                 {
3211                     priv->ps_input[i] = "0.0";
3212                 }
3213
3214                 TRACE("v%u, semantic %s%u is %s\n", i, semantic_name, semantic_idx, priv->ps_input[i]);
3215             }
3216             break;
3217
3218         case vertexshader:
3219             /* That one is easy. The vertex shaders provide v0-v7 in fragment.texcoord and v8 and v9 in
3220              * fragment.color
3221              */
3222             for(i = 0; i < 8; i++)
3223             {
3224                 priv->ps_input[i] = texcoords[i];
3225             }
3226             priv->ps_input[8] = "fragment.color.primary";
3227             priv->ps_input[9] = "fragment.color.secondary";
3228             break;
3229     }
3230 }
3231
3232 /* GL locking is done by the caller */
3233 static GLuint shader_arb_generate_pshader(IWineD3DPixelShaderImpl *This, struct wined3d_shader_buffer *buffer,
3234         const struct arb_ps_compile_args *args, struct arb_ps_compiled_shader *compiled)
3235 {
3236     const shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
3237     CONST DWORD *function = This->baseShader.function;
3238     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3239     const local_constant *lconst;
3240     GLuint retval;
3241     char fragcolor[16];
3242     DWORD *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This), next_local, cur;
3243     struct shader_arb_ctx_priv priv_ctx;
3244     BOOL dcl_tmp = args->super.srgb_correction, dcl_td = FALSE;
3245     BOOL want_nv_prog = FALSE;
3246     struct arb_pshader_private *shader_priv = This->baseShader.backend_data;
3247     GLint errPos;
3248     DWORD map;
3249
3250     char srgbtmp[4][4];
3251     unsigned int i, found = 0;
3252
3253     for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
3254     {
3255         if (!(map & 1)
3256                 || (This->color0_mov && i == This->color0_reg)
3257                 || (reg_maps->shader_version.major < 2 && i == 0))
3258             continue;
3259
3260         sprintf(srgbtmp[found], "R%u", i);
3261         ++found;
3262         if (found == 4) break;
3263     }
3264
3265     switch(found) {
3266         case 4: dcl_tmp = FALSE; break;
3267         case 0:
3268             sprintf(srgbtmp[0], "TA");
3269             sprintf(srgbtmp[1], "TB");
3270             sprintf(srgbtmp[2], "TC");
3271             sprintf(srgbtmp[3], "TD");
3272             dcl_td = TRUE;
3273             break;
3274         case 1:
3275             sprintf(srgbtmp[1], "TA");
3276             sprintf(srgbtmp[2], "TB");
3277             sprintf(srgbtmp[3], "TC");
3278             break;
3279         case 2:
3280             sprintf(srgbtmp[2], "TA");
3281             sprintf(srgbtmp[3], "TB");
3282             break;
3283         case 3:
3284             sprintf(srgbtmp[3], "TA");
3285             break;
3286     }
3287
3288     /*  Create the hw ARB shader */
3289     memset(&priv_ctx, 0, sizeof(priv_ctx));
3290     priv_ctx.cur_ps_args = args;
3291     priv_ctx.compiled_fprog = compiled;
3292     priv_ctx.cur_np2fixup_info = &compiled->np2fixup_info;
3293     init_ps_input(This, args, &priv_ctx);
3294     list_init(&priv_ctx.control_frames);
3295
3296     /* Avoid enabling NV_fragment_program* if we do not need it.
3297      *
3298      * Enabling GL_NV_fragment_program_option causes the driver to occupy a temporary register,
3299      * and it slows down the shader execution noticeably(about 5%). Usually our instruction emulation
3300      * is faster than what we gain from using higher native instructions. There are some things though
3301      * that cannot be emulated. In that case enable the extensions.
3302      * If the extension is enabled, instruction handlers that support both ways will use it.
3303      *
3304      * Testing shows no performance difference between OPTION NV_fragment_program2 and NV_fragment_program.
3305      * So enable the best we can get.
3306      */
3307     if(reg_maps->usesdsx || reg_maps->usesdsy || reg_maps->loop_depth > 0 || reg_maps->usestexldd ||
3308        reg_maps->usestexldl || reg_maps->usesfacing || reg_maps->usesifc || reg_maps->usescall)
3309     {
3310         want_nv_prog = TRUE;
3311     }
3312
3313     shader_addline(buffer, "!!ARBfp1.0\n");
3314     if(want_nv_prog && GL_SUPPORT(NV_FRAGMENT_PROGRAM2)) {
3315         shader_addline(buffer, "OPTION NV_fragment_program2;\n");
3316         priv_ctx.target_version = NV3;
3317     } else if(want_nv_prog && GL_SUPPORT(NV_FRAGMENT_PROGRAM_OPTION)) {
3318         shader_addline(buffer, "OPTION NV_fragment_program;\n");
3319         priv_ctx.target_version = NV2;
3320     } else {
3321         if(want_nv_prog)
3322         {
3323             /* This is an error - either we're advertising the wrong shader version, or aren't enforcing some
3324              * limits properly
3325              */
3326             ERR("The shader requires instructions that are not available in plain GL_ARB_fragment_program\n");
3327             ERR("Try GLSL\n");
3328         }
3329         priv_ctx.target_version = ARB;
3330     }
3331
3332     if(This->baseShader.reg_maps.highest_render_target > 0)
3333     {
3334         shader_addline(buffer, "OPTION ARB_draw_buffers;\n");
3335     }
3336
3337     if (reg_maps->shader_version.major < 3)
3338     {
3339         switch(args->super.fog) {
3340             case FOG_OFF:
3341                 break;
3342             case FOG_LINEAR:
3343                 shader_addline(buffer, "OPTION ARB_fog_linear;\n");
3344                 break;
3345             case FOG_EXP:
3346                 shader_addline(buffer, "OPTION ARB_fog_exp;\n");
3347                 break;
3348             case FOG_EXP2:
3349                 shader_addline(buffer, "OPTION ARB_fog_exp2;\n");
3350                 break;
3351         }
3352     }
3353
3354     /* For now always declare the temps. At least the Nvidia assembler optimizes completely
3355      * unused temps away(but occupies them for the whole shader if they're used once). Always
3356      * declaring them avoids tricky bookkeeping work
3357      */
3358     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
3359     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
3360     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
3361     if(dcl_td) shader_addline(buffer, "TEMP TD;\n"); /* Used for sRGB writing */
3362     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
3363     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
3364     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
3365
3366     if (reg_maps->shader_version.major < 2)
3367     {
3368         strcpy(fragcolor, "R0");
3369     } else {
3370         if(args->super.srgb_correction) {
3371             if(This->color0_mov) {
3372                 sprintf(fragcolor, "R%u", This->color0_reg);
3373             } else {
3374                 shader_addline(buffer, "TEMP TMP_COLOR;\n");
3375                 strcpy(fragcolor, "TMP_COLOR");
3376             }
3377         } else {
3378             strcpy(fragcolor, "result.color");
3379         }
3380     }
3381
3382     if(args->super.srgb_correction) {
3383         shader_addline(buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
3384                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
3385         shader_addline(buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
3386                        srgb_sub_high, 0.0, 0.0, 0.0);
3387     }
3388
3389     /* Base Declarations */
3390     next_local = shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION,
3391             lconst_map, NULL, &priv_ctx);
3392
3393     for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
3394     {
3395         if (!(map & 1)) continue;
3396
3397         cur = compiled->numbumpenvmatconsts;
3398         compiled->bumpenvmatconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
3399         compiled->bumpenvmatconst[cur].texunit = i;
3400         compiled->luminanceconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
3401         compiled->luminanceconst[cur].texunit = i;
3402
3403         /* We can fit the constants into the constant limit for sure because texbem, texbeml, bem and beml are only supported
3404          * in 1.x shaders, and GL_ARB_fragment_program has a constant limit of 24 constants. So in the worst case we're loading
3405          * 8 shader constants, 8 bump matrices and 8 luminance parameters and are perfectly fine. (No NP2 fixup on bumpmapped
3406          * textures due to conditional NP2 restrictions)
3407          *
3408          * Use local constants to load the bump env parameters, not program.env. This avoids collisions with d3d constants of
3409          * shaders in newer shader models. Since the bump env parameters have to share their space with NP2 fixup constants,
3410          * their location is shader dependent anyway and they cannot be loaded globally.
3411          */
3412         compiled->bumpenvmatconst[cur].const_num = next_local++;
3413         shader_addline(buffer, "PARAM bumpenvmat%d = program.local[%d];\n",
3414                        i, compiled->bumpenvmatconst[cur].const_num);
3415         compiled->numbumpenvmatconsts = cur + 1;
3416
3417         if (!(reg_maps->luminanceparams & (1 << i))) continue;
3418
3419         compiled->luminanceconst[cur].const_num = next_local++;
3420         shader_addline(buffer, "PARAM luminance%d = program.local[%d];\n",
3421                        i, compiled->luminanceconst[cur].const_num);
3422     }
3423
3424     for(i = 0; i < MAX_CONST_I; i++)
3425     {
3426         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
3427         if (reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
3428         {
3429             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
3430
3431             if(control_values)
3432             {
3433                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
3434                                 control_values[0], control_values[1], control_values[2]);
3435             }
3436             else
3437             {
3438                 compiled->int_consts[i] = next_local;
3439                 compiled->num_int_consts++;
3440                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
3441             }
3442         }
3443     }
3444
3445     if(reg_maps->vpos || reg_maps->usesdsy)
3446     {
3447         compiled->ycorrection = next_local;
3448         shader_addline(buffer, "PARAM ycorrection = program.local[%u];\n", next_local++);
3449
3450         if(reg_maps->vpos)
3451         {
3452             shader_addline(buffer, "TEMP vpos;\n");
3453             /* ycorrection.x: Backbuffer height(onscreen) or 0(offscreen).
3454              * ycorrection.y: -1.0(onscreen), 1.0(offscreen)
3455              * ycorrection.z: 1.0
3456              * ycorrection.w: 0.0
3457              */
3458             shader_addline(buffer, "MAD vpos, fragment.position, ycorrection.zyww, ycorrection.wxww;\n");
3459             shader_addline(buffer, "FLR vpos.xy, vpos;\n");
3460         }
3461     }
3462     else
3463     {
3464         compiled->ycorrection = WINED3D_CONST_NUM_UNUSED;
3465     }
3466
3467     /* Load constants to fixup NP2 texcoords if there are still free constants left:
3468      * Constants (texture dimensions) for the NP2 fixup are loaded as local program parameters. This will consume
3469      * at most 8 (MAX_FRAGMENT_SAMPLERS / 2) parameters, which is highly unlikely, since the application had to
3470      * use 16 NP2 textures at the same time. In case that we run out of constants the fixup is simply not
3471      * applied / activated. This will probably result in wrong rendering of the texture, but will save us from
3472      * shader compilation errors and the subsequent errors when drawing with this shader. */
3473     if (priv_ctx.cur_ps_args->super.np2_fixup) {
3474
3475         struct arb_ps_np2fixup_info* const fixup = priv_ctx.cur_np2fixup_info;
3476         const WORD map = priv_ctx.cur_ps_args->super.np2_fixup;
3477         const UINT max_lconsts = gl_info->ps_arb_max_local_constants;
3478
3479         fixup->offset = next_local;
3480         fixup->super.active = 0;
3481
3482         cur = 0;
3483         for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3484             if (!(map & (1 << i))) continue;
3485
3486             if (fixup->offset + (cur >> 1) < max_lconsts) {
3487                 fixup->super.active |= (1 << i);
3488                 fixup->super.idx[i] = cur++;
3489             } else {
3490                 FIXME("No free constant found to load NP2 fixup data into shader. "
3491                       "Sampling from this texture will probably look wrong.\n");
3492                 break;
3493             }
3494         }
3495
3496         fixup->super.num_consts = (cur + 1) >> 1;
3497         if (fixup->super.num_consts) {
3498             shader_addline(buffer, "PARAM np2fixup[%u] = { program.env[%u..%u] };\n",
3499                            fixup->super.num_consts, fixup->offset, fixup->super.num_consts + fixup->offset - 1);
3500         }
3501
3502         next_local += fixup->super.num_consts;
3503     }
3504
3505     if (shader_priv->clipplane_emulation != ~0U && args->clip)
3506     {
3507         shader_addline(buffer, "KIL fragment.texcoord[%u];\n", shader_priv->clipplane_emulation);
3508     }
3509
3510     /* Base Shader Body */
3511     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3512
3513     if(args->super.srgb_correction) {
3514         arbfp_add_sRGB_correction(buffer, fragcolor, srgbtmp[0], srgbtmp[1], srgbtmp[2], srgbtmp[3],
3515                                   priv_ctx.target_version >= NV2);
3516     } else if(reg_maps->shader_version.major < 2) {
3517         shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
3518     }
3519     shader_addline(buffer, "END\n");
3520
3521     /* TODO: change to resource.glObjectHandle or something like that */
3522     GL_EXTCALL(glGenProgramsARB(1, &retval));
3523
3524     TRACE("Creating a hw pixel shader, prg=%d\n", retval);
3525     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, retval));
3526
3527     TRACE("Created hw pixel shader, prg=%d\n", retval);
3528     /* Create the program and check for errors */
3529     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3530                buffer->bsize, buffer->buffer));
3531     checkGLcall("glProgramStringARB()");
3532
3533     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
3534     if (errPos != -1)
3535     {
3536         FIXME("HW PixelShader Error at position %d: %s\n",
3537               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3538         retval = 0;
3539     }
3540     else
3541     {
3542         GLint native;
3543
3544         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3545         checkGLcall("glGetProgramivARB()");
3546         if (!native) WARN("Program exceeds native resource limits.\n");
3547     }
3548
3549     /* Load immediate constants */
3550     if(lconst_map) {
3551         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
3552             const float *value = (const float *)lconst->value;
3553             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst_map[lconst->idx], value));
3554             checkGLcall("glProgramLocalParameter4fvARB");
3555         }
3556         HeapFree(GetProcessHeap(), 0, lconst_map);
3557     }
3558
3559     return retval;
3560 }
3561
3562 static int compare_sig(const struct wined3d_shader_signature_element *sig1, const struct wined3d_shader_signature_element *sig2)
3563 {
3564     unsigned int i;
3565     int ret;
3566
3567     for(i = 0; i < MAX_REG_INPUT; i++)
3568     {
3569         if(sig1[i].semantic_name == NULL || sig2[i].semantic_name == NULL)
3570         {
3571             /* Compare pointers, not contents. One string is NULL(element does not exist), the other one is not NULL */
3572             if(sig1[i].semantic_name != sig2[i].semantic_name) return sig1[i].semantic_name < sig2[i].semantic_name ? -1 : 1;
3573             continue;
3574         }
3575
3576         ret = strcmp(sig1[i].semantic_name, sig2[i].semantic_name);
3577         if(ret != 0) return ret;
3578         if(sig1[i].semantic_idx    != sig2[i].semantic_idx)    return sig1[i].semantic_idx    < sig2[i].semantic_idx    ? -1 : 1;
3579         if(sig1[i].sysval_semantic != sig2[i].sysval_semantic) return sig1[i].sysval_semantic < sig2[i].sysval_semantic ? -1 : 1;
3580         if(sig1[i].component_type  != sig2[i].component_type)  return sig1[i].sysval_semantic < sig2[i].component_type  ? -1 : 1;
3581         if(sig1[i].register_idx    != sig2[i].register_idx)    return sig1[i].register_idx    < sig2[i].register_idx    ? -1 : 1;
3582         if(sig1[i].mask            != sig2->mask)              return sig1[i].mask            < sig2[i].mask            ? -1 : 1;
3583     }
3584     return 0;
3585 }
3586
3587 static struct wined3d_shader_signature_element *clone_sig(const struct wined3d_shader_signature_element *sig)
3588 {
3589     struct wined3d_shader_signature_element *new;
3590     int i;
3591     char *name;
3592
3593     new = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*new) * MAX_REG_INPUT);
3594     for(i = 0; i < MAX_REG_INPUT; i++)
3595     {
3596         if(sig[i].semantic_name == NULL)
3597         {
3598             continue;
3599         }
3600
3601         new[i] = sig[i];
3602         /* Clone the semantic string */
3603         name = HeapAlloc(GetProcessHeap(), 0, strlen(sig[i].semantic_name) + 1);
3604         strcpy(name, sig[i].semantic_name);
3605         new[i].semantic_name = name;
3606     }
3607     return new;
3608 }
3609
3610 static DWORD find_input_signature(struct shader_arb_priv *priv, const struct wined3d_shader_signature_element *sig)
3611 {
3612     struct wine_rb_entry *entry = wine_rb_get(&priv->signature_tree, sig);
3613     struct ps_signature *found_sig;
3614
3615     if(entry != NULL)
3616     {
3617         found_sig = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
3618         TRACE("Found existing signature %u\n", found_sig->idx);
3619         return found_sig->idx;
3620     }
3621     found_sig = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*sig));
3622     found_sig->sig = clone_sig(sig);
3623     found_sig->idx = priv->ps_sig_number++;
3624     TRACE("New signature stored and assigned number %u\n", found_sig->idx);
3625     if(wine_rb_put(&priv->signature_tree, sig, &found_sig->entry) == -1)
3626     {
3627         ERR("Failed to insert program entry.\n");
3628     }
3629     return found_sig->idx;
3630 }
3631
3632 static void init_output_registers(IWineD3DVertexShaderImpl *shader, DWORD sig_num, struct shader_arb_ctx_priv *priv_ctx,
3633                                   struct arb_vs_compiled_shader *compiled)
3634 {
3635     unsigned int i, j;
3636     static const char *texcoords[8] =
3637     {
3638         "result.texcoord[0]", "result.texcoord[1]", "result.texcoord[2]", "result.texcoord[3]",
3639         "result.texcoord[4]", "result.texcoord[5]", "result.texcoord[6]", "result.texcoord[7]"
3640     };
3641     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) shader->baseShader.device;
3642     const struct wined3d_shader_signature_element *sig;
3643     const char *semantic_name;
3644     DWORD semantic_idx, reg_idx;
3645
3646     /* Write generic input varyings 0 to 7 to result.texcoord[], varying 8 to result.color.primary
3647      * and varying 9 to result.color.secondary
3648      */
3649     const char *decl_idx_to_string[MAX_REG_INPUT] =
3650     {
3651         texcoords[0], texcoords[1], texcoords[2], texcoords[3],
3652         texcoords[4], texcoords[5], texcoords[6], texcoords[7],
3653         "result.color.primary", "result.color.secondary"
3654     };
3655
3656     if(sig_num == ~0)
3657     {
3658         TRACE("Pixel shader uses builtin varyings\n");
3659         /* Map builtins to builtins */
3660         for(i = 0; i < 8; i++)
3661         {
3662             priv_ctx->texcrd_output[i] = texcoords[i];
3663         }
3664         priv_ctx->color_output[0] = "result.color.primary";
3665         priv_ctx->color_output[1] = "result.color.secondary";
3666         priv_ctx->fog_output = "result.fogcoord";
3667
3668         /* Map declared regs to builtins. Use "TA" to /dev/null unread output */
3669         for(i = 0; i < (sizeof(shader->output_signature) / sizeof(*shader->output_signature)); i++)
3670         {
3671             semantic_name = shader->output_signature[i].semantic_name;
3672             if(semantic_name == NULL) continue;
3673
3674             if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3675             {
3676                 TRACE("o%u is TMP_OUT\n", i);
3677                 if(shader->output_signature[i].semantic_idx == 0) priv_ctx->vs_output[i] = "TMP_OUT";
3678                 else priv_ctx->vs_output[i] = "TA";
3679             }
3680             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3681             {
3682                 TRACE("o%u is result.pointsize\n", i);
3683                 if(shader->output_signature[i].semantic_idx == 0) priv_ctx->vs_output[i] = "result.pointsize";
3684                 else priv_ctx->vs_output[i] = "TA";
3685             }
3686             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3687             {
3688                 TRACE("o%u is result.color.?, idx %u\n", i, shader->output_signature[i].semantic_idx);
3689                 if(shader->output_signature[i].semantic_idx == 0) priv_ctx->vs_output[i] = "result.color.primary";
3690                 else if(shader->output_signature[i].semantic_idx == 1) priv_ctx->vs_output[i] = "result.color.secondary";
3691                 else priv_ctx->vs_output[i] = "TA";
3692             }
3693             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3694             {
3695                 TRACE("o%u is %s\n", i, texcoords[shader->output_signature[i].semantic_idx]);
3696                 if(shader->output_signature[i].semantic_idx >= 8) priv_ctx->vs_output[i] = "TA";
3697                 else priv_ctx->vs_output[i] = texcoords[shader->output_signature[i].semantic_idx];
3698             }
3699             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3700             {
3701                 TRACE("o%u is result.fogcoord\n", i);
3702                 if(shader->output_signature[i].semantic_idx > 0) priv_ctx->vs_output[i] = "TA";
3703                 else priv_ctx->vs_output[i] = "result.fogcoord";
3704             }
3705             else
3706             {
3707                 priv_ctx->vs_output[i] = "TA";
3708             }
3709         }
3710         return;
3711     }
3712
3713     /* Instead of searching for the signature in the signature list, read the one from the current pixel shader.
3714      * Its maybe not the shader where the signature came from, but it is the same signature and faster to find
3715      */
3716     sig = ((IWineD3DPixelShaderImpl *)device->stateBlock->pixelShader)->input_signature;
3717     TRACE("Pixel shader uses declared varyings\n");
3718
3719     /* Map builtin to declared. /dev/null the results by default to the TA temp reg */
3720     for(i = 0; i < 8; i++)
3721     {
3722         priv_ctx->texcrd_output[i] = "TA";
3723     }
3724     priv_ctx->color_output[0] = "TA";
3725     priv_ctx->color_output[1] = "TA";
3726     priv_ctx->fog_output = "TA";
3727
3728     for(i = 0; i < MAX_REG_INPUT; i++)
3729     {
3730         semantic_name = sig[i].semantic_name;
3731         semantic_idx = sig[i].semantic_idx;
3732         reg_idx = sig[i].register_idx;
3733         if(semantic_name == NULL) continue;
3734
3735         /* If a declared input register is not written by builtin arguments, don't write to it.
3736          * GL_NV_vertex_program makes sure the input defaults to 0.0, which is correct with D3D
3737          *
3738          * Don't care about POSITION and PSIZE here - this is a builtin vertex shader, position goes
3739          * to TMP_OUT in any case
3740          */
3741         if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3742         {
3743             if(semantic_idx < 8) priv_ctx->texcrd_output[semantic_idx] = decl_idx_to_string[reg_idx];
3744         }
3745         else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3746         {
3747             if(semantic_idx < 2) priv_ctx->color_output[semantic_idx] = decl_idx_to_string[reg_idx];
3748         }
3749         else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3750         {
3751             if(semantic_idx == 0) priv_ctx->fog_output = decl_idx_to_string[reg_idx];
3752         }
3753         else
3754         {
3755             continue;
3756         }
3757
3758         if(strcmp(decl_idx_to_string[reg_idx], "result.color.primary") == 0 ||
3759            strcmp(decl_idx_to_string[reg_idx], "result.color.secondary") == 0)
3760         {
3761             compiled->need_color_unclamp = TRUE;
3762         }
3763     }
3764
3765     /* Map declared to declared */
3766     for(i = 0; i < (sizeof(shader->output_signature) / sizeof(*shader->output_signature)); i++)
3767     {
3768         /* Write unread output to TA to throw them away */
3769         priv_ctx->vs_output[i] = "TA";
3770         semantic_name = shader->output_signature[i].semantic_name;
3771         if(semantic_name == NULL)
3772         {
3773             continue;
3774         }
3775
3776         if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION) &&
3777            shader->output_signature[i].semantic_idx == 0)
3778         {
3779             priv_ctx->vs_output[i] = "TMP_OUT";
3780             continue;
3781         }
3782         else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE) &&
3783            shader->output_signature[i].semantic_idx == 0)
3784         {
3785             priv_ctx->vs_output[i] = "result.pointsize";
3786             continue;
3787         }
3788
3789         for(j = 0; j < MAX_REG_INPUT; j++)
3790         {
3791             if(sig[j].semantic_name == NULL)
3792             {
3793                 continue;
3794             }
3795
3796             if(strcmp(sig[j].semantic_name, semantic_name) == 0 &&
3797                sig[j].semantic_idx == shader->output_signature[i].semantic_idx)
3798             {
3799                 priv_ctx->vs_output[i] = decl_idx_to_string[sig[j].register_idx];
3800
3801                 if(strcmp(priv_ctx->vs_output[i], "result.color.primary") == 0 ||
3802                    strcmp(priv_ctx->vs_output[i], "result.color.secondary") == 0)
3803                 {
3804                     compiled->need_color_unclamp = TRUE;
3805                 }
3806             }
3807         }
3808     }
3809 }
3810
3811 /* GL locking is done by the caller */
3812 static GLuint shader_arb_generate_vshader(IWineD3DVertexShaderImpl *This, struct wined3d_shader_buffer *buffer,
3813         const struct arb_vs_compile_args *args, struct arb_vs_compiled_shader *compiled)
3814 {
3815     const shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3816     CONST DWORD *function = This->baseShader.function;
3817     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3818     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3819     const local_constant *lconst;
3820     GLuint ret;
3821     DWORD next_local, *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This);
3822     struct shader_arb_ctx_priv priv_ctx;
3823     unsigned int i;
3824     GLint errPos;
3825
3826     memset(&priv_ctx, 0, sizeof(priv_ctx));
3827     priv_ctx.cur_vs_args = args;
3828     list_init(&priv_ctx.control_frames);
3829     init_output_registers(This, args->ps_signature, &priv_ctx, compiled);
3830
3831     /*  Create the hw ARB shader */
3832     shader_addline(buffer, "!!ARBvp1.0\n");
3833
3834     /* Always enable the NV extension if available. Unlike fragment shaders, there is no
3835      * mesurable performance penalty, and we can always make use of it for clipplanes.
3836      */
3837     if(GL_SUPPORT(NV_VERTEX_PROGRAM3)) {
3838         shader_addline(buffer, "OPTION NV_vertex_program3;\n");
3839         priv_ctx.target_version = NV3;
3840         shader_addline(buffer, "ADDRESS aL;\n");
3841     } else if(GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION)) {
3842         shader_addline(buffer, "OPTION NV_vertex_program2;\n");
3843         priv_ctx.target_version = NV2;
3844         shader_addline(buffer, "ADDRESS aL;\n");
3845     } else {
3846         priv_ctx.target_version = ARB;
3847     }
3848
3849     shader_addline(buffer, "TEMP TMP_OUT;\n");
3850     if(need_helper_const(gl_info)) {
3851         shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
3852     }
3853     if(need_mova_const((IWineD3DBaseShader *) This, gl_info)) {
3854         shader_addline(buffer, "PARAM mova_const = { 0.5, 0.0, 2.0, 1.0 };\n");
3855         shader_addline(buffer, "TEMP A0_SHADOW;\n");
3856     }
3857
3858     shader_addline(buffer, "TEMP TA;\n");
3859
3860     /* Base Declarations */
3861     next_local = shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION,
3862             lconst_map, &priv_ctx.vs_clipplanes, &priv_ctx);
3863
3864     for(i = 0; i < MAX_CONST_I; i++)
3865     {
3866         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
3867         if(reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
3868         {
3869             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
3870
3871             if(control_values)
3872             {
3873                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
3874                                 control_values[0], control_values[1], control_values[2]);
3875             }
3876             else
3877             {
3878                 compiled->int_consts[i] = next_local;
3879                 compiled->num_int_consts++;
3880                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
3881             }
3882         }
3883     }
3884
3885     /* We need a constant to fixup the final position */
3886     shader_addline(buffer, "PARAM posFixup = program.local[%u];\n", next_local);
3887     compiled->pos_fixup = next_local++;
3888
3889     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
3890      * for output parameters. D3D in theory does not do that either, but some applications depend on a
3891      * proper initialization of the secondary color, and programs using the fixed function pipeline without
3892      * a replacement shader depend on the texcoord.w being set properly.
3893      *
3894      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
3895      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
3896      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
3897      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
3898      * this can eat a number of instructions, so skip it unless this cap is set as well
3899      */
3900     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)) {
3901         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
3902
3903         if ((GLINFO_LOCATION).quirks & WINED3D_QUIRK_SET_TEXCOORD_W && !device->frag_pipe->ffp_proj_control)
3904         {
3905             int i;
3906             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3907                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3908                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3909                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
3910                 }
3911             }
3912         }
3913     }
3914
3915     /* The shader starts with the main function */
3916     priv_ctx.in_main_func = TRUE;
3917     /* Base Shader Body */
3918     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3919
3920     if(!priv_ctx.footer_written) vshader_add_footer(This, buffer, args, &priv_ctx);
3921
3922     shader_addline(buffer, "END\n");
3923
3924     /* TODO: change to resource.glObjectHandle or something like that */
3925     GL_EXTCALL(glGenProgramsARB(1, &ret));
3926
3927     TRACE("Creating a hw vertex shader, prg=%d\n", ret);
3928     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ret));
3929
3930     TRACE("Created hw vertex shader, prg=%d\n", ret);
3931     /* Create the program and check for errors */
3932     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3933                buffer->bsize, buffer->buffer));
3934     checkGLcall("glProgramStringARB()");
3935
3936     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
3937     if (errPos != -1)
3938     {
3939         FIXME("HW VertexShader Error at position %d: %s\n",
3940               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3941         ret = -1;
3942     }
3943     else
3944     {
3945         GLint native;
3946
3947         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3948         checkGLcall("glGetProgramivARB()");
3949         if (!native) WARN("Program exceeds native resource limits.\n");
3950
3951         /* Load immediate constants */
3952         if(lconst_map) {
3953             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
3954                 const float *value = (const float *)lconst->value;
3955                 GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst_map[lconst->idx], value));
3956             }
3957         }
3958     }
3959     HeapFree(GetProcessHeap(), 0, lconst_map);
3960
3961     return ret;
3962 }
3963
3964 /* GL locking is done by the caller */
3965 static struct arb_ps_compiled_shader *find_arb_pshader(IWineD3DPixelShaderImpl *shader, const struct arb_ps_compile_args *args)
3966 {
3967     UINT i;
3968     DWORD new_size;
3969     struct arb_ps_compiled_shader *new_array;
3970     struct wined3d_shader_buffer buffer;
3971     struct arb_pshader_private *shader_data;
3972     GLuint ret;
3973
3974     if (!shader->baseShader.backend_data)
3975     {
3976         IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) shader->baseShader.device;
3977         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3978         struct shader_arb_priv *priv = device->shader_priv;
3979
3980         shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3981         shader_data = shader->baseShader.backend_data;
3982         shader_data->clamp_consts = shader->baseShader.reg_maps.shader_version.major == 1;
3983
3984         if(shader->baseShader.reg_maps.shader_version.major < 3) shader_data->input_signature_idx = ~0;
3985         else shader_data->input_signature_idx = find_input_signature(priv, shader->input_signature);
3986
3987         shader_data->has_signature_idx = TRUE;
3988         TRACE("Shader got assigned input signature index %u\n", shader_data->input_signature_idx);
3989
3990         if (!device->vs_clipping)
3991             shader_data->clipplane_emulation = shader_find_free_input_register(&shader->baseShader.reg_maps,
3992                     GL_LIMITS(texture_stages) - 1);
3993         else
3994             shader_data->clipplane_emulation = ~0U;
3995     }
3996     shader_data = shader->baseShader.backend_data;
3997
3998     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3999      * so a linear search is more performant than a hashmap or a binary search
4000      * (cache coherency etc)
4001      */
4002     for(i = 0; i < shader_data->num_gl_shaders; i++) {
4003         if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4004             return &shader_data->gl_shaders[i];
4005         }
4006     }
4007
4008     TRACE("No matching GL shader found, compiling a new shader\n");
4009     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4010         if (shader_data->num_gl_shaders)
4011         {
4012             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4013             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
4014                                     new_size * sizeof(*shader_data->gl_shaders));
4015         } else {
4016             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4017             new_size = 1;
4018         }
4019
4020         if(!new_array) {
4021             ERR("Out of memory\n");
4022             return 0;
4023         }
4024         shader_data->gl_shaders = new_array;
4025         shader_data->shader_array_size = new_size;
4026     }
4027
4028     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4029
4030     pixelshader_update_samplers(&shader->baseShader.reg_maps,
4031             ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4032
4033     if (!shader_buffer_init(&buffer))
4034     {
4035         ERR("Failed to initialize shader buffer.\n");
4036         return 0;
4037     }
4038
4039     ret = shader_arb_generate_pshader(shader, &buffer, args,
4040                                       &shader_data->gl_shaders[shader_data->num_gl_shaders]);
4041     shader_buffer_free(&buffer);
4042     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
4043
4044     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
4045 }
4046
4047 static inline BOOL vs_args_equal(const struct arb_vs_compile_args *stored, const struct arb_vs_compile_args *new,
4048                                  const DWORD use_map, BOOL skip_int) {
4049     if((stored->super.swizzle_map & use_map) != new->super.swizzle_map) return FALSE;
4050     if(stored->super.fog_src != new->super.fog_src) return FALSE;
4051     if(stored->boolclip_compare != new->boolclip_compare) return FALSE;
4052     if(stored->ps_signature != new->ps_signature) return FALSE;
4053     if(stored->vertex_samplers_compare != new->vertex_samplers_compare) return FALSE;
4054     if(skip_int) return TRUE;
4055
4056     return memcmp(stored->loop_ctrl, new->loop_ctrl, sizeof(stored->loop_ctrl)) == 0;
4057 }
4058
4059 static struct arb_vs_compiled_shader *find_arb_vshader(IWineD3DVertexShaderImpl *shader, const struct arb_vs_compile_args *args)
4060 {
4061     UINT i;
4062     DWORD new_size;
4063     struct arb_vs_compiled_shader *new_array;
4064     DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4065     struct wined3d_shader_buffer buffer;
4066     struct arb_vshader_private *shader_data;
4067     GLuint ret;
4068     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
4069
4070     if (!shader->baseShader.backend_data)
4071     {
4072         shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4073     }
4074     shader_data = shader->baseShader.backend_data;
4075
4076     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4077      * so a linear search is more performant than a hashmap or a binary search
4078      * (cache coherency etc)
4079      */
4080     for(i = 0; i < shader_data->num_gl_shaders; i++) {
4081         if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map, GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION))) {
4082             return &shader_data->gl_shaders[i];
4083         }
4084     }
4085
4086     TRACE("No matching GL shader found, compiling a new shader\n");
4087
4088     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4089         if (shader_data->num_gl_shaders)
4090         {
4091             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4092             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
4093                                     new_size * sizeof(*shader_data->gl_shaders));
4094         } else {
4095             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4096             new_size = 1;
4097         }
4098
4099         if(!new_array) {
4100             ERR("Out of memory\n");
4101             return 0;
4102         }
4103         shader_data->gl_shaders = new_array;
4104         shader_data->shader_array_size = new_size;
4105     }
4106
4107     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4108
4109     if (!shader_buffer_init(&buffer))
4110     {
4111         ERR("Failed to initialize shader buffer.\n");
4112         return 0;
4113     }
4114
4115     ret = shader_arb_generate_vshader(shader, &buffer, args,
4116             &shader_data->gl_shaders[shader_data->num_gl_shaders]);
4117     shader_buffer_free(&buffer);
4118     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
4119
4120     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
4121 }
4122
4123 static inline void find_arb_ps_compile_args(IWineD3DPixelShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
4124         struct arb_ps_compile_args *args)
4125 {
4126     int i;
4127     WORD int_skip;
4128     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
4129     find_ps_compile_args(shader, stateblock, &args->super);
4130
4131     /* This forces all local boolean constants to 1 to make them stateblock independent */
4132     args->bools = shader->baseShader.reg_maps.local_bool_consts;
4133
4134     for(i = 0; i < MAX_CONST_B; i++)
4135     {
4136         if(stateblock->pixelShaderConstantB[i]) args->bools |= ( 1 << i);
4137     }
4138
4139     /* Only enable the clip plane emulation KIL if at least one clipplane is enabled. The KIL instruction
4140      * is quite expensive because it forces the driver to disable early Z discards. It is cheaper to
4141      * duplicate the shader than have a no-op KIL instruction in every shader
4142      */
4143     if((!((IWineD3DDeviceImpl *) shader->baseShader.device)->vs_clipping) && use_vs(stateblock) &&
4144        stateblock->renderState[WINED3DRS_CLIPPING] && stateblock->renderState[WINED3DRS_CLIPPLANEENABLE])
4145     {
4146         args->clip = 1;
4147     }
4148     else
4149     {
4150         args->clip = 0;
4151     }
4152
4153     /* Skip if unused or local, or supported natively */
4154     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
4155     if(int_skip == 0xffff || GL_SUPPORT(NV_FRAGMENT_PROGRAM_OPTION))
4156     {
4157         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
4158         return;
4159     }
4160
4161     for(i = 0; i < MAX_CONST_I; i++)
4162     {
4163         if(int_skip & (1 << i))
4164         {
4165             args->loop_ctrl[i][0] = 0;
4166             args->loop_ctrl[i][1] = 0;
4167             args->loop_ctrl[i][2] = 0;
4168         }
4169         else
4170         {
4171             args->loop_ctrl[i][0] = stateblock->pixelShaderConstantI[i * 4];
4172             args->loop_ctrl[i][1] = stateblock->pixelShaderConstantI[i * 4 + 1];
4173             args->loop_ctrl[i][2] = stateblock->pixelShaderConstantI[i * 4 + 2];
4174         }
4175     }
4176 }
4177
4178 static inline void find_arb_vs_compile_args(IWineD3DVertexShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
4179         struct arb_vs_compile_args *args)
4180 {
4181     int i;
4182     WORD int_skip;
4183     IWineD3DDeviceImpl *dev = (IWineD3DDeviceImpl *)shader->baseShader.device;
4184     const struct wined3d_gl_info *gl_info = &dev->adapter->gl_info;
4185     find_vs_compile_args(shader, stateblock, &args->super);
4186
4187     args->boolclip_compare = 0;
4188     if(use_ps(stateblock))
4189     {
4190         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) stateblock->pixelShader;
4191         struct arb_pshader_private *shader_priv = ps->baseShader.backend_data;
4192         args->ps_signature = shader_priv->input_signature_idx;
4193
4194         args->boolclip.clip_control[0] = shader_priv->clipplane_emulation + 1;
4195     }
4196     else
4197     {
4198         args->ps_signature = ~0;
4199         if(!dev->vs_clipping)
4200         {
4201             args->boolclip.clip_control[0] = ffp_clip_emul(stateblock) ? GL_LIMITS(texture_stages) : 0;
4202         }
4203         /* Otherwise: Setting boolclip_compare set clip_control[0] to 0 */
4204     }
4205
4206     if(args->boolclip.clip_control[0])
4207     {
4208         if(stateblock->renderState[WINED3DRS_CLIPPING])
4209         {
4210             args->boolclip.clip_control[1] = stateblock->renderState[WINED3DRS_CLIPPLANEENABLE];
4211         }
4212         /* clip_control[1] was set to 0 by setting boolclip_compare to 0 */
4213     }
4214
4215     /* This forces all local boolean constants to 1 to make them stateblock independent */
4216     args->boolclip.bools = shader->baseShader.reg_maps.local_bool_consts;
4217     /* TODO: Figure out if it would be better to store bool constants as bitmasks in the stateblock */
4218     for(i = 0; i < MAX_CONST_B; i++)
4219     {
4220         if(stateblock->vertexShaderConstantB[i]) args->boolclip.bools |= ( 1 << i);
4221     }
4222
4223     args->vertex_samplers[0] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 0];
4224     args->vertex_samplers[1] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 1];
4225     args->vertex_samplers[2] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 2];
4226     args->vertex_samplers[3] = 0;
4227
4228     /* Skip if unused or local */
4229     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
4230     if(int_skip == 0xffff || GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION)) /* This is about flow control, not clipping */
4231     {
4232         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
4233         return;
4234     }
4235
4236     for(i = 0; i < MAX_CONST_I; i++)
4237     {
4238         if(int_skip & (1 << i))
4239         {
4240             args->loop_ctrl[i][0] = 0;
4241             args->loop_ctrl[i][1] = 0;
4242             args->loop_ctrl[i][2] = 0;
4243         }
4244         else
4245         {
4246             args->loop_ctrl[i][0] = stateblock->vertexShaderConstantI[i * 4];
4247             args->loop_ctrl[i][1] = stateblock->vertexShaderConstantI[i * 4 + 1];
4248             args->loop_ctrl[i][2] = stateblock->vertexShaderConstantI[i * 4 + 2];
4249         }
4250     }
4251 }
4252
4253 /* GL locking is done by the caller */
4254 static void shader_arb_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4255 {
4256     IWineD3DDeviceImpl *This = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
4257     struct shader_arb_priv *priv = This->shader_priv;
4258     const struct wined3d_gl_info *gl_info = context->gl_info;
4259     int i;
4260
4261     /* Deal with pixel shaders first so the vertex shader arg function has the input signature ready */
4262     if (usePS) {
4263         struct arb_ps_compile_args compile_args;
4264         struct arb_ps_compiled_shader *compiled;
4265         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader;
4266
4267         TRACE("Using pixel shader %p\n", This->stateBlock->pixelShader);
4268         find_arb_ps_compile_args(ps, This->stateBlock, &compile_args);
4269         compiled = find_arb_pshader(ps, &compile_args);
4270         priv->current_fprogram_id = compiled->prgId;
4271         priv->compiled_fprog = compiled;
4272
4273         /* Bind the fragment program */
4274         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
4275         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id);");
4276
4277         if(!priv->use_arbfp_fixed_func) {
4278             /* Enable OpenGL fragment programs */
4279             glEnable(GL_FRAGMENT_PROGRAM_ARB);
4280             checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
4281         }
4282         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
4283
4284         /* Pixel Shader 1.x constants are clamped to [-1;1], Pixel Shader 2.0 constants are not. If switching between
4285          * a 1.x and newer shader, reload the first 8 constants
4286          */
4287         if(priv->last_ps_const_clamped != ((struct arb_pshader_private *)ps->baseShader.backend_data)->clamp_consts)
4288         {
4289             priv->last_ps_const_clamped = ((struct arb_pshader_private *)ps->baseShader.backend_data)->clamp_consts;
4290             This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, 8);
4291             for(i = 0; i < 8; i++)
4292             {
4293                 context->pshader_const_dirty[i] = 1;
4294             }
4295             /* Also takes care of loading local constants */
4296             shader_arb_load_constants(context, TRUE, FALSE);
4297         }
4298         else
4299         {
4300             shader_arb_ps_local_constants(This);
4301         }
4302
4303         /* Force constant reloading for the NP2 fixup (see comment in shader_glsl_select for more info) */
4304         if (compiled->np2fixup_info.super.active)
4305             shader_arb_load_np2fixup_constants((IWineD3DDevice *)This, usePS, useVS);
4306     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && !priv->use_arbfp_fixed_func) {
4307         /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
4308         * keep GL_FRAGMENT_PROGRAM_ARB enabled, and the fixed function pipeline will bind the fixed function
4309         * replacement shader
4310         */
4311         glDisable(GL_FRAGMENT_PROGRAM_ARB);
4312         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
4313         priv->current_fprogram_id = 0;
4314     }
4315
4316     if (useVS) {
4317         struct arb_vs_compile_args compile_args;
4318         struct arb_vs_compiled_shader *compiled;
4319         IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader;
4320
4321         TRACE("Using vertex shader %p\n", This->stateBlock->vertexShader);
4322         find_arb_vs_compile_args(vs, This->stateBlock, &compile_args);
4323         compiled = find_arb_vshader(vs, &compile_args);
4324         priv->current_vprogram_id = compiled->prgId;
4325         priv->compiled_vprog = compiled;
4326
4327         /* Bind the vertex program */
4328         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
4329         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id);");
4330
4331         /* Enable OpenGL vertex programs */
4332         glEnable(GL_VERTEX_PROGRAM_ARB);
4333         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
4334         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
4335         shader_arb_vs_local_constants(This);
4336
4337         if(priv->last_vs_color_unclamp != compiled->need_color_unclamp) {
4338             priv->last_vs_color_unclamp = compiled->need_color_unclamp;
4339
4340             if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
4341                 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, !compiled->need_color_unclamp));
4342                 checkGLcall("glClampColorARB");
4343             } else {
4344                 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4345             }
4346         }
4347     } else if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
4348         priv->current_vprogram_id = 0;
4349         glDisable(GL_VERTEX_PROGRAM_ARB);
4350         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
4351     }
4352 }
4353
4354 /* GL locking is done by the caller */
4355 static void shader_arb_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4356     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4357     struct shader_arb_priv *priv = This->shader_priv;
4358     GLuint *blt_fprogram = &priv->depth_blt_fprogram_id[tex_type];
4359     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4360
4361     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
4362     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
4363     glEnable(GL_VERTEX_PROGRAM_ARB);
4364
4365     if (!*blt_fprogram) *blt_fprogram = create_arb_blt_fragment_program(gl_info, tex_type);
4366     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, *blt_fprogram));
4367     glEnable(GL_FRAGMENT_PROGRAM_ARB);
4368 }
4369
4370 /* GL locking is done by the caller */
4371 static void shader_arb_deselect_depth_blt(IWineD3DDevice *iface) {
4372     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4373     struct shader_arb_priv *priv = This->shader_priv;
4374     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4375
4376     if (priv->current_vprogram_id) {
4377         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
4378         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
4379
4380         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
4381     } else {
4382         glDisable(GL_VERTEX_PROGRAM_ARB);
4383         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
4384     }
4385
4386     if (priv->current_fprogram_id) {
4387         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
4388         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
4389
4390         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
4391     } else if(!priv->use_arbfp_fixed_func) {
4392         glDisable(GL_FRAGMENT_PROGRAM_ARB);
4393         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
4394     }
4395 }
4396
4397 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
4398     IWineD3DBaseShaderImpl *baseShader = (IWineD3DBaseShaderImpl *) iface;
4399     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)baseShader->baseShader.device;
4400     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4401
4402     if (shader_is_pshader_version(baseShader->baseShader.reg_maps.shader_version.type))
4403     {
4404         IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
4405         struct arb_pshader_private *shader_data = This->baseShader.backend_data;
4406         UINT i;
4407
4408         if(!shader_data) return; /* This can happen if a shader was never compiled */
4409         ENTER_GL();
4410
4411         if(shader_data->num_gl_shaders) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
4412
4413         for(i = 0; i < shader_data->num_gl_shaders; i++) {
4414             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
4415             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
4416         }
4417         LEAVE_GL();
4418         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4419         HeapFree(GetProcessHeap(), 0, shader_data);
4420         This->baseShader.backend_data = NULL;
4421     } else {
4422         IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *) iface;
4423         struct arb_vshader_private *shader_data = This->baseShader.backend_data;
4424         UINT i;
4425
4426         if(!shader_data) return; /* This can happen if a shader was never compiled */
4427         ENTER_GL();
4428
4429         if(shader_data->num_gl_shaders) ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
4430
4431         for(i = 0; i < shader_data->num_gl_shaders; i++) {
4432             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
4433             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
4434         }
4435         LEAVE_GL();
4436         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4437         HeapFree(GetProcessHeap(), 0, shader_data);
4438         This->baseShader.backend_data = NULL;
4439     }
4440 }
4441
4442 static int sig_tree_compare(const void *key, const struct wine_rb_entry *entry)
4443 {
4444     struct ps_signature *e = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
4445     return compare_sig(key, e->sig);
4446 }
4447
4448 static const struct wine_rb_functions sig_tree_functions =
4449 {
4450     wined3d_rb_alloc,
4451     wined3d_rb_realloc,
4452     wined3d_rb_free,
4453     sig_tree_compare
4454 };
4455
4456 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
4457     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4458     struct shader_arb_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*priv));
4459     if(wine_rb_init(&priv->signature_tree, &sig_tree_functions) == -1)
4460     {
4461         ERR("RB tree init failed\n");
4462         HeapFree(GetProcessHeap(), 0, priv);
4463         return E_OUTOFMEMORY;
4464     }
4465     This->shader_priv = priv;
4466     return WINED3D_OK;
4467 }
4468
4469 static void release_signature(struct wine_rb_entry *entry, void *context)
4470 {
4471     struct ps_signature *sig = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
4472     int i;
4473     for(i = 0; i < MAX_REG_INPUT; i++)
4474     {
4475         HeapFree(GetProcessHeap(), 0, (char *) sig->sig[i].semantic_name);
4476     }
4477     HeapFree(GetProcessHeap(), 0, sig->sig);
4478     HeapFree(GetProcessHeap(), 0, sig);
4479 }
4480
4481 /* Context activation is done by the caller. */
4482 static void shader_arb_free(IWineD3DDevice *iface) {
4483     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4484     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4485     struct shader_arb_priv *priv = This->shader_priv;
4486     int i;
4487
4488     ENTER_GL();
4489     if(priv->depth_blt_vprogram_id) {
4490         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
4491     }
4492     for (i = 0; i < tex_type_count; ++i) {
4493         if (priv->depth_blt_fprogram_id[i]) {
4494             GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id[i]));
4495         }
4496     }
4497     LEAVE_GL();
4498
4499     wine_rb_destroy(&priv->signature_tree, release_signature, NULL);
4500     HeapFree(GetProcessHeap(), 0, This->shader_priv);
4501 }
4502
4503 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
4504     return TRUE;
4505 }
4506
4507 static void shader_arb_get_caps(WINED3DDEVTYPE devtype, const struct wined3d_gl_info *gl_info,
4508         struct shader_caps *pCaps)
4509 {
4510     /* We don't have an ARB fixed function pipeline yet, so let the none backend set its caps,
4511      * then overwrite the shader specific ones
4512      */
4513     none_shader_backend.shader_get_caps(devtype, gl_info, pCaps);
4514
4515     if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
4516         if(GL_SUPPORT(NV_VERTEX_PROGRAM3))
4517         {
4518             pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4519             TRACE_(d3d_caps)("Hardware vertex shader version 3.0 enabled (NV_VERTEX_PROGRAM3)\n");
4520         }
4521         else if(GL_LIMITS(vshader_constantsF) >= 256)
4522         {
4523             /* Shader Model 2.0 requires at least 256 vertex shader constants */
4524             pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4525             TRACE_(d3d_caps)("Hardware vertex shader version 2.0 enabled (ARB_PROGRAM)\n");
4526         }
4527         else
4528         {
4529             pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
4530             TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
4531         }
4532         pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4533     }
4534
4535     if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
4536         if(GL_SUPPORT(NV_FRAGMENT_PROGRAM2))
4537         {
4538             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(3,0);
4539             TRACE_(d3d_caps)("Hardware pixel shader version 3.0 enabled (NV_FRAGMENT_PROGRAM2)\n");
4540         }
4541         else if(GL_LIMITS(pshader_constantsF) >= 32)
4542         {
4543             /* Shader Model 2.0 requires at least 32 pixel shader constants */
4544             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(2,0);
4545             TRACE_(d3d_caps)("Hardware pixel shader version 2.0 enabled (ARB_PROGRAM)\n");
4546         }
4547         else
4548         {
4549             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
4550             TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
4551         }
4552         pCaps->PixelShader1xMaxValue = 8.0f;
4553         pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
4554     }
4555
4556     pCaps->VSClipping = use_nv_clip(gl_info);
4557 }
4558
4559 static BOOL shader_arb_color_fixup_supported(struct color_fixup_desc fixup)
4560 {
4561     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4562     {
4563         TRACE("Checking support for color_fixup:\n");
4564         dump_color_fixup_desc(fixup);
4565     }
4566
4567     /* We support everything except YUV conversions. */
4568     if (!is_yuv_fixup(fixup))
4569     {
4570         TRACE("[OK]\n");
4571         return TRUE;
4572     }
4573
4574     TRACE("[FAILED]\n");
4575     return FALSE;
4576 }
4577
4578 static void shader_arb_add_instruction_modifiers(const struct wined3d_shader_instruction *ins) {
4579     DWORD shift;
4580     char write_mask[20], regstr[50];
4581     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
4582     BOOL is_color = FALSE;
4583     const struct wined3d_shader_dst_param *dst;
4584
4585     if (!ins->dst_count) return;
4586
4587     dst = &ins->dst[0];
4588     shift = dst->shift;
4589     if(shift == 0) return; /* Saturate alone is handled by the instructions */
4590
4591     shader_arb_get_write_mask(ins, dst, write_mask);
4592     shader_arb_get_register_name(ins, &dst->reg, regstr, &is_color);
4593
4594     /* Generate a line that does the output modifier computation
4595      * FIXME: _SAT vs shift? _SAT alone is already handled in the instructions, if this
4596      * maps problems in e.g. _d4_sat modify shader_arb_get_modifier
4597      */
4598     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", shader_arb_get_modifier(ins),
4599                    regstr, write_mask, regstr, shift_tab[shift]);
4600 }
4601
4602 static const SHADER_HANDLER shader_arb_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4603 {
4604     /* WINED3DSIH_ABS           */ shader_hw_map2gl,
4605     /* WINED3DSIH_ADD           */ shader_hw_map2gl,
4606     /* WINED3DSIH_BEM           */ pshader_hw_bem,
4607     /* WINED3DSIH_BREAK         */ shader_hw_break,
4608     /* WINED3DSIH_BREAKC        */ shader_hw_breakc,
4609     /* WINED3DSIH_BREAKP        */ NULL,
4610     /* WINED3DSIH_CALL          */ shader_hw_call,
4611     /* WINED3DSIH_CALLNZ        */ NULL,
4612     /* WINED3DSIH_CMP           */ pshader_hw_cmp,
4613     /* WINED3DSIH_CND           */ pshader_hw_cnd,
4614     /* WINED3DSIH_CRS           */ shader_hw_map2gl,
4615     /* WINED3DSIH_DCL           */ NULL,
4616     /* WINED3DSIH_DEF           */ NULL,
4617     /* WINED3DSIH_DEFB          */ NULL,
4618     /* WINED3DSIH_DEFI          */ NULL,
4619     /* WINED3DSIH_DP2ADD        */ pshader_hw_dp2add,
4620     /* WINED3DSIH_DP3           */ shader_hw_map2gl,
4621     /* WINED3DSIH_DP4           */ shader_hw_map2gl,
4622     /* WINED3DSIH_DST           */ shader_hw_map2gl,
4623     /* WINED3DSIH_DSX           */ shader_hw_map2gl,
4624     /* WINED3DSIH_DSY           */ shader_hw_dsy,
4625     /* WINED3DSIH_ELSE          */ shader_hw_else,
4626     /* WINED3DSIH_ENDIF         */ shader_hw_endif,
4627     /* WINED3DSIH_ENDLOOP       */ shader_hw_endloop,
4628     /* WINED3DSIH_ENDREP        */ shader_hw_endrep,
4629     /* WINED3DSIH_EXP           */ shader_hw_scalar_op,
4630     /* WINED3DSIH_EXPP          */ shader_hw_scalar_op,
4631     /* WINED3DSIH_FRC           */ shader_hw_map2gl,
4632     /* WINED3DSIH_IF            */ NULL /* Hardcoded into the shader */,
4633     /* WINED3DSIH_IFC           */ shader_hw_ifc,
4634     /* WINED3DSIH_LABEL         */ shader_hw_label,
4635     /* WINED3DSIH_LIT           */ shader_hw_map2gl,
4636     /* WINED3DSIH_LOG           */ shader_hw_log_pow,
4637     /* WINED3DSIH_LOGP          */ shader_hw_log_pow,
4638     /* WINED3DSIH_LOOP          */ shader_hw_loop,
4639     /* WINED3DSIH_LRP           */ shader_hw_lrp,
4640     /* WINED3DSIH_M3x2          */ shader_hw_mnxn,
4641     /* WINED3DSIH_M3x3          */ shader_hw_mnxn,
4642     /* WINED3DSIH_M3x4          */ shader_hw_mnxn,
4643     /* WINED3DSIH_M4x3          */ shader_hw_mnxn,
4644     /* WINED3DSIH_M4x4          */ shader_hw_mnxn,
4645     /* WINED3DSIH_MAD           */ shader_hw_map2gl,
4646     /* WINED3DSIH_MAX           */ shader_hw_map2gl,
4647     /* WINED3DSIH_MIN           */ shader_hw_map2gl,
4648     /* WINED3DSIH_MOV           */ shader_hw_mov,
4649     /* WINED3DSIH_MOVA          */ shader_hw_mov,
4650     /* WINED3DSIH_MUL           */ shader_hw_map2gl,
4651     /* WINED3DSIH_NOP           */ shader_hw_nop,
4652     /* WINED3DSIH_NRM           */ shader_hw_nrm,
4653     /* WINED3DSIH_PHASE         */ NULL,
4654     /* WINED3DSIH_POW           */ shader_hw_log_pow,
4655     /* WINED3DSIH_RCP           */ shader_hw_scalar_op,
4656     /* WINED3DSIH_REP           */ shader_hw_rep,
4657     /* WINED3DSIH_RET           */ shader_hw_ret,
4658     /* WINED3DSIH_RSQ           */ shader_hw_scalar_op,
4659     /* WINED3DSIH_SETP          */ NULL,
4660     /* WINED3DSIH_SGE           */ shader_hw_map2gl,
4661     /* WINED3DSIH_SGN           */ shader_hw_sgn,
4662     /* WINED3DSIH_SINCOS        */ shader_hw_sincos,
4663     /* WINED3DSIH_SLT           */ shader_hw_map2gl,
4664     /* WINED3DSIH_SUB           */ shader_hw_map2gl,
4665     /* WINED3DSIH_TEX           */ pshader_hw_tex,
4666     /* WINED3DSIH_TEXBEM        */ pshader_hw_texbem,
4667     /* WINED3DSIH_TEXBEML       */ pshader_hw_texbem,
4668     /* WINED3DSIH_TEXCOORD      */ pshader_hw_texcoord,
4669     /* WINED3DSIH_TEXDEPTH      */ pshader_hw_texdepth,
4670     /* WINED3DSIH_TEXDP3        */ pshader_hw_texdp3,
4671     /* WINED3DSIH_TEXDP3TEX     */ pshader_hw_texdp3tex,
4672     /* WINED3DSIH_TEXKILL       */ pshader_hw_texkill,
4673     /* WINED3DSIH_TEXLDD        */ shader_hw_texldd,
4674     /* WINED3DSIH_TEXLDL        */ shader_hw_texldl,
4675     /* WINED3DSIH_TEXM3x2DEPTH  */ pshader_hw_texm3x2depth,
4676     /* WINED3DSIH_TEXM3x2PAD    */ pshader_hw_texm3x2pad,
4677     /* WINED3DSIH_TEXM3x2TEX    */ pshader_hw_texm3x2tex,
4678     /* WINED3DSIH_TEXM3x3       */ pshader_hw_texm3x3,
4679     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
4680     /* WINED3DSIH_TEXM3x3PAD    */ pshader_hw_texm3x3pad,
4681     /* WINED3DSIH_TEXM3x3SPEC   */ pshader_hw_texm3x3spec,
4682     /* WINED3DSIH_TEXM3x3TEX    */ pshader_hw_texm3x3tex,
4683     /* WINED3DSIH_TEXM3x3VSPEC  */ pshader_hw_texm3x3vspec,
4684     /* WINED3DSIH_TEXREG2AR     */ pshader_hw_texreg2ar,
4685     /* WINED3DSIH_TEXREG2GB     */ pshader_hw_texreg2gb,
4686     /* WINED3DSIH_TEXREG2RGB    */ pshader_hw_texreg2rgb,
4687 };
4688
4689 static inline BOOL get_bool_const(const struct wined3d_shader_instruction *ins, IWineD3DBaseShaderImpl *This, DWORD idx)
4690 {
4691     BOOL vshader = shader_is_vshader_version(This->baseShader.reg_maps.shader_version.type);
4692     WORD bools = 0;
4693     WORD flag = (1 << idx);
4694     const local_constant *constant;
4695     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
4696
4697     if(This->baseShader.reg_maps.local_bool_consts & flag)
4698     {
4699         /* What good is a if(bool) with a hardcoded local constant? I don't know, but handle it */
4700         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsB, local_constant, entry)
4701         {
4702             if (constant->idx == idx)
4703             {
4704                 return constant->value[0];
4705             }
4706         }
4707         ERR("Local constant not found\n");
4708         return FALSE;
4709     }
4710     else
4711     {
4712         if(vshader) bools = priv->cur_vs_args->boolclip.bools;
4713         else bools = priv->cur_ps_args->bools;
4714         return bools & flag;
4715     }
4716 }
4717
4718 static void get_loop_control_const(const struct wined3d_shader_instruction *ins,
4719         IWineD3DBaseShaderImpl *This, UINT idx, struct wined3d_shader_loop_control *loop_control)
4720 {
4721     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
4722
4723     /* Integer constants can either be a local constant, or they can be stored in the shader
4724      * type specific compile args. */
4725     if (This->baseShader.reg_maps.local_int_consts & (1 << idx))
4726     {
4727         const local_constant *constant;
4728
4729         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
4730         {
4731             if (constant->idx == idx)
4732             {
4733                 loop_control->count = constant->value[0];
4734                 loop_control->start = constant->value[1];
4735                 /* Step is signed. */
4736                 loop_control->step = (int)constant->value[2];
4737                 return;
4738             }
4739         }
4740         /* If this happens the flag was set incorrectly */
4741         ERR("Local constant not found\n");
4742         loop_control->count = 0;
4743         loop_control->start = 0;
4744         loop_control->step = 0;
4745         return;
4746     }
4747
4748     switch (This->baseShader.reg_maps.shader_version.type)
4749     {
4750         case WINED3D_SHADER_TYPE_VERTEX:
4751             /* Count and aL start value are unsigned */
4752             loop_control->count = priv->cur_vs_args->loop_ctrl[idx][0];
4753             loop_control->start = priv->cur_vs_args->loop_ctrl[idx][1];
4754             /* Step is signed. */
4755             loop_control->step = ((char)priv->cur_vs_args->loop_ctrl[idx][2]);
4756             break;
4757
4758         case WINED3D_SHADER_TYPE_PIXEL:
4759             loop_control->count = priv->cur_ps_args->loop_ctrl[idx][0];
4760             loop_control->start = priv->cur_ps_args->loop_ctrl[idx][1];
4761             loop_control->step = ((char)priv->cur_ps_args->loop_ctrl[idx][2]);
4762             break;
4763
4764         default:
4765             FIXME("Unhandled shader type %#x.\n", This->baseShader.reg_maps.shader_version.type);
4766             break;
4767     }
4768 }
4769
4770 static void record_instruction(struct list *list, const struct wined3d_shader_instruction *ins)
4771 {
4772     unsigned int i;
4773     struct wined3d_shader_dst_param *dst_param = NULL;
4774     struct wined3d_shader_src_param *src_param = NULL, *rel_addr = NULL;
4775     struct recorded_instruction *rec = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rec));
4776     if(!rec)
4777     {
4778         ERR("Out of memory\n");
4779         return;
4780     }
4781
4782     rec->ins = *ins;
4783     dst_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param));
4784     if(!dst_param) goto free;
4785     *dst_param = *ins->dst;
4786     if(ins->dst->reg.rel_addr)
4787     {
4788         rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param->reg.rel_addr));
4789         if(!rel_addr) goto free;
4790         *rel_addr = *ins->dst->reg.rel_addr;
4791         dst_param->reg.rel_addr = rel_addr;
4792     }
4793     rec->ins.dst = dst_param;
4794
4795     src_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*src_param) * ins->src_count);
4796     if(!src_param) goto free;
4797     for(i = 0; i < ins->src_count; i++)
4798     {
4799         src_param[i] = ins->src[i];
4800         if(ins->src[i].reg.rel_addr)
4801         {
4802             rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*rel_addr));
4803             if(!rel_addr) goto free;
4804             *rel_addr = *ins->src[i].reg.rel_addr;
4805             src_param[i].reg.rel_addr = rel_addr;
4806         }
4807     }
4808     rec->ins.src = src_param;
4809     list_add_tail(list, &rec->entry);
4810     return;
4811
4812 free:
4813     ERR("Out of memory\n");
4814     if(dst_param)
4815     {
4816         HeapFree(GetProcessHeap(), 0, (void *) dst_param->reg.rel_addr);
4817         HeapFree(GetProcessHeap(), 0, dst_param);
4818     }
4819     if(src_param)
4820     {
4821         for(i = 0; i < ins->src_count; i++)
4822         {
4823             HeapFree(GetProcessHeap(), 0, (void *) src_param[i].reg.rel_addr);
4824         }
4825         HeapFree(GetProcessHeap(), 0, src_param);
4826     }
4827     HeapFree(GetProcessHeap(), 0, rec);
4828 }
4829
4830 static void free_recorded_instruction(struct list *list)
4831 {
4832     struct recorded_instruction *rec_ins, *entry2;
4833     unsigned int i;
4834
4835     LIST_FOR_EACH_ENTRY_SAFE(rec_ins, entry2, list, struct recorded_instruction, entry)
4836     {
4837         list_remove(&rec_ins->entry);
4838         if(rec_ins->ins.dst)
4839         {
4840             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst->reg.rel_addr);
4841             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst);
4842         }
4843         if(rec_ins->ins.src)
4844         {
4845             for(i = 0; i < rec_ins->ins.src_count; i++)
4846             {
4847                 HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src[i].reg.rel_addr);
4848             }
4849             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src);
4850         }
4851         HeapFree(GetProcessHeap(), 0, rec_ins);
4852     }
4853 }
4854
4855 static void shader_arb_handle_instruction(const struct wined3d_shader_instruction *ins) {
4856     SHADER_HANDLER hw_fct;
4857     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
4858     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
4859     struct control_frame *control_frame;
4860     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
4861     BOOL bool_const;
4862
4863     if(ins->handler_idx == WINED3DSIH_LOOP || ins->handler_idx == WINED3DSIH_REP)
4864     {
4865         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
4866         list_add_head(&priv->control_frames, &control_frame->entry);
4867
4868         if(ins->handler_idx == WINED3DSIH_LOOP) control_frame->type = LOOP;
4869         if(ins->handler_idx == WINED3DSIH_REP) control_frame->type = REP;
4870
4871         if(priv->target_version >= NV2)
4872         {
4873             control_frame->loop_no = priv->num_loops++;
4874             priv->loop_depth++;
4875         }
4876         else
4877         {
4878             /* Don't bother recording when we're in a not used if branch */
4879             if(priv->muted)
4880             {
4881                 return;
4882             }
4883
4884             if(!priv->recording)
4885             {
4886                 list_init(&priv->record);
4887                 priv->recording = TRUE;
4888                 control_frame->outer_loop = TRUE;
4889                 get_loop_control_const(ins, This, ins->src[0].reg.idx, &control_frame->loop_control);
4890                 return; /* Instruction is handled */
4891             }
4892             /* Record this loop in the outer loop's recording */
4893         }
4894     }
4895     else if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
4896     {
4897         if(priv->target_version >= NV2)
4898         {
4899             /* Nothing to do. The control frame is popped after the HW instr handler */
4900         }
4901         else
4902         {
4903             struct list *e = list_head(&priv->control_frames);
4904             control_frame = LIST_ENTRY(e, struct control_frame, entry);
4905             list_remove(&control_frame->entry);
4906
4907             if(control_frame->outer_loop)
4908             {
4909                 int iteration, aL = 0;
4910                 struct list copy;
4911
4912                 /* Turn off recording before playback */
4913                 priv->recording = FALSE;
4914
4915                 /* Move the recorded instructions to a separate list and get them out of the private data
4916                  * structure. If there are nested loops, the shader_arb_handle_instruction below will
4917                  * be recorded again, thus priv->record might be overwritten
4918                  */
4919                 list_init(&copy);
4920                 list_move_tail(&copy, &priv->record);
4921                 list_init(&priv->record);
4922
4923                 if(ins->handler_idx == WINED3DSIH_ENDLOOP)
4924                 {
4925                     shader_addline(buffer, "#unrolling loop: %u iterations, aL=%u, inc %d\n",
4926                                    control_frame->loop_control.count, control_frame->loop_control.start,
4927                                    control_frame->loop_control.step);
4928                     aL = control_frame->loop_control.start;
4929                 }
4930                 else
4931                 {
4932                     shader_addline(buffer, "#unrolling rep: %u iterations\n", control_frame->loop_control.count);
4933                 }
4934
4935                 for (iteration = 0; iteration < control_frame->loop_control.count; ++iteration)
4936                 {
4937                     struct recorded_instruction *rec_ins;
4938                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
4939                     {
4940                         priv->aL = aL;
4941                         shader_addline(buffer, "#Iteration %d, aL=%d\n", iteration, aL);
4942                     }
4943                     else
4944                     {
4945                         shader_addline(buffer, "#Iteration %d\n", iteration);
4946                     }
4947
4948                     LIST_FOR_EACH_ENTRY(rec_ins, &copy, struct recorded_instruction, entry)
4949                     {
4950                         shader_arb_handle_instruction(&rec_ins->ins);
4951                     }
4952
4953                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
4954                     {
4955                         aL += control_frame->loop_control.step;
4956                     }
4957                 }
4958                 shader_addline(buffer, "#end loop/rep\n");
4959
4960                 free_recorded_instruction(&copy);
4961                 HeapFree(GetProcessHeap(), 0, control_frame);
4962                 return; /* Instruction is handled */
4963             }
4964             else
4965             {
4966                 /* This is a nested loop. Proceed to the normal recording function */
4967                 HeapFree(GetProcessHeap(), 0, control_frame);
4968             }
4969         }
4970     }
4971
4972     if(priv->recording)
4973     {
4974         record_instruction(&priv->record, ins);
4975         return;
4976     }
4977
4978     /* boolean if */
4979     if(ins->handler_idx == WINED3DSIH_IF)
4980     {
4981         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
4982         list_add_head(&priv->control_frames, &control_frame->entry);
4983         control_frame->type = IF;
4984
4985         bool_const = get_bool_const(ins, This, ins->src[0].reg.idx);
4986         if(ins->src[0].modifiers == WINED3DSPSM_NOT) bool_const = !bool_const;
4987         if(!priv->muted && bool_const == FALSE)
4988         {
4989             shader_addline(buffer, "#if(FALSE){\n");
4990             priv->muted = TRUE;
4991             control_frame->muting = TRUE;
4992         }
4993         else shader_addline(buffer, "#if(TRUE) {\n");
4994
4995         return; /* Instruction is handled */
4996     }
4997     else if(ins->handler_idx == WINED3DSIH_IFC)
4998     {
4999         /* IF(bool) and if_cond(a, b) use the same ELSE and ENDIF tokens */
5000         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
5001         control_frame->type = IFC;
5002         control_frame->ifc_no = priv->num_ifcs++;
5003         list_add_head(&priv->control_frames, &control_frame->entry);
5004     }
5005     else if(ins->handler_idx == WINED3DSIH_ELSE)
5006     {
5007         struct list *e = list_head(&priv->control_frames);
5008         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5009
5010         if(control_frame->type == IF)
5011         {
5012             shader_addline(buffer, "#} else {\n");
5013             if(!priv->muted && !control_frame->muting)
5014             {
5015                 priv->muted = TRUE;
5016                 control_frame->muting = TRUE;
5017             }
5018             else if(control_frame->muting) priv->muted = FALSE;
5019             return; /* Instruction is handled. */
5020         }
5021         /* In case of an ifc, generate a HW shader instruction */
5022     }
5023     else if(ins->handler_idx == WINED3DSIH_ENDIF)
5024     {
5025         struct list *e = list_head(&priv->control_frames);
5026         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5027
5028         if(control_frame->type == IF)
5029         {
5030             shader_addline(buffer, "#} endif\n");
5031             if(control_frame->muting) priv->muted = FALSE;
5032             list_remove(&control_frame->entry);
5033             HeapFree(GetProcessHeap(), 0, control_frame);
5034             return; /* Instruction is handled */
5035         }
5036     }
5037
5038     if(priv->muted) return;
5039
5040     /* Select handler */
5041     hw_fct = shader_arb_instruction_handler_table[ins->handler_idx];
5042
5043     /* Unhandled opcode */
5044     if (!hw_fct)
5045     {
5046         FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5047         return;
5048     }
5049     hw_fct(ins);
5050
5051     if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
5052     {
5053         struct list *e = list_head(&priv->control_frames);
5054         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5055         list_remove(&control_frame->entry);
5056         HeapFree(GetProcessHeap(), 0, control_frame);
5057         priv->loop_depth--;
5058     }
5059     else if(ins->handler_idx == WINED3DSIH_ENDIF)
5060     {
5061         /* Non-ifc ENDIFs don't reach that place because of the return in the if block above */
5062         struct list *e = list_head(&priv->control_frames);
5063         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5064         list_remove(&control_frame->entry);
5065         HeapFree(GetProcessHeap(), 0, control_frame);
5066     }
5067
5068
5069     shader_arb_add_instruction_modifiers(ins);
5070 }
5071
5072 const shader_backend_t arb_program_shader_backend = {
5073     shader_arb_handle_instruction,
5074     shader_arb_select,
5075     shader_arb_select_depth_blt,
5076     shader_arb_deselect_depth_blt,
5077     shader_arb_update_float_vertex_constants,
5078     shader_arb_update_float_pixel_constants,
5079     shader_arb_load_constants,
5080     shader_arb_load_np2fixup_constants,
5081     shader_arb_destroy,
5082     shader_arb_alloc,
5083     shader_arb_free,
5084     shader_arb_dirty_const,
5085     shader_arb_get_caps,
5086     shader_arb_color_fixup_supported,
5087 };
5088
5089 /* ARB_fragment_program fixed function pipeline replacement definitions */
5090 #define ARB_FFP_CONST_TFACTOR           0
5091 #define ARB_FFP_CONST_SPECULAR_ENABLE   ((ARB_FFP_CONST_TFACTOR) + 1)
5092 #define ARB_FFP_CONST_CONSTANT(i)       ((ARB_FFP_CONST_SPECULAR_ENABLE) + 1 + i)
5093 #define ARB_FFP_CONST_BUMPMAT(i)        ((ARB_FFP_CONST_CONSTANT(7)) + 1 + i)
5094 #define ARB_FFP_CONST_LUMINANCE(i)      ((ARB_FFP_CONST_BUMPMAT(7)) + 1 + i)
5095
5096 struct arbfp_ffp_desc
5097 {
5098     struct ffp_frag_desc parent;
5099     GLuint shader;
5100     unsigned int num_textures_used;
5101 };
5102
5103 /* Context activation is done by the caller. */
5104 static void arbfp_enable(IWineD3DDevice *iface, BOOL enable) {
5105     ENTER_GL();
5106     if(enable) {
5107         glEnable(GL_FRAGMENT_PROGRAM_ARB);
5108         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
5109     } else {
5110         glDisable(GL_FRAGMENT_PROGRAM_ARB);
5111         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
5112     }
5113     LEAVE_GL();
5114 }
5115
5116 static HRESULT arbfp_alloc(IWineD3DDevice *iface) {
5117     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5118     struct shader_arb_priv *priv;
5119     /* Share private data between the shader backend and the pipeline replacement, if both
5120      * are the arb implementation. This is needed to figure out whether ARBfp should be disabled
5121      * if no pixel shader is bound or not
5122      */
5123     if(This->shader_backend == &arb_program_shader_backend) {
5124         This->fragment_priv = This->shader_priv;
5125     } else {
5126         This->fragment_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
5127         if(!This->fragment_priv) return E_OUTOFMEMORY;
5128     }
5129     priv = This->fragment_priv;
5130     if (wine_rb_init(&priv->fragment_shaders, &wined3d_ffp_frag_program_rb_functions) == -1)
5131     {
5132         ERR("Failed to initialize rbtree.\n");
5133         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
5134         return E_OUTOFMEMORY;
5135     }
5136     priv->use_arbfp_fixed_func = TRUE;
5137     return WINED3D_OK;
5138 }
5139
5140 /* Context activation is done by the caller. */
5141 static void arbfp_free_ffpshader(struct wine_rb_entry *entry, void *context)
5142 {
5143     const struct wined3d_gl_info *gl_info = context;
5144     struct arbfp_ffp_desc *entry_arb = WINE_RB_ENTRY_VALUE(entry, struct arbfp_ffp_desc, parent.entry);
5145
5146     ENTER_GL();
5147     GL_EXTCALL(glDeleteProgramsARB(1, &entry_arb->shader));
5148     checkGLcall("glDeleteProgramsARB(1, &entry_arb->shader)");
5149     HeapFree(GetProcessHeap(), 0, entry_arb);
5150     LEAVE_GL();
5151 }
5152
5153 /* Context activation is done by the caller. */
5154 static void arbfp_free(IWineD3DDevice *iface) {
5155     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5156     struct shader_arb_priv *priv = This->fragment_priv;
5157
5158     wine_rb_destroy(&priv->fragment_shaders, arbfp_free_ffpshader, &This->adapter->gl_info);
5159     priv->use_arbfp_fixed_func = FALSE;
5160
5161     if(This->shader_backend != &arb_program_shader_backend) {
5162         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
5163     }
5164 }
5165
5166 static void arbfp_get_caps(WINED3DDEVTYPE devtype, const struct wined3d_gl_info *gl_info, struct fragment_caps *caps)
5167 {
5168     caps->TextureOpCaps =  WINED3DTEXOPCAPS_DISABLE                     |
5169                            WINED3DTEXOPCAPS_SELECTARG1                  |
5170                            WINED3DTEXOPCAPS_SELECTARG2                  |
5171                            WINED3DTEXOPCAPS_MODULATE4X                  |
5172                            WINED3DTEXOPCAPS_MODULATE2X                  |
5173                            WINED3DTEXOPCAPS_MODULATE                    |
5174                            WINED3DTEXOPCAPS_ADDSIGNED2X                 |
5175                            WINED3DTEXOPCAPS_ADDSIGNED                   |
5176                            WINED3DTEXOPCAPS_ADD                         |
5177                            WINED3DTEXOPCAPS_SUBTRACT                    |
5178                            WINED3DTEXOPCAPS_ADDSMOOTH                   |
5179                            WINED3DTEXOPCAPS_BLENDCURRENTALPHA           |
5180                            WINED3DTEXOPCAPS_BLENDFACTORALPHA            |
5181                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHA           |
5182                            WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA           |
5183                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM         |
5184                            WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR      |
5185                            WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA      |
5186                            WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA   |
5187                            WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR   |
5188                            WINED3DTEXOPCAPS_DOTPRODUCT3                 |
5189                            WINED3DTEXOPCAPS_MULTIPLYADD                 |
5190                            WINED3DTEXOPCAPS_LERP                        |
5191                            WINED3DTEXOPCAPS_BUMPENVMAP                  |
5192                            WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE;
5193
5194     /* TODO: Implement WINED3DTEXOPCAPS_PREMODULATE */
5195
5196     caps->MaxTextureBlendStages   = 8;
5197     caps->MaxSimultaneousTextures = min(GL_LIMITS(fragment_samplers), 8);
5198
5199     caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_TSSARGTEMP;
5200 }
5201 #undef GLINFO_LOCATION
5202
5203 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
5204 static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5205 {
5206     float col[4];
5207     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
5208
5209     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
5210      * application provided constants
5211      */
5212     if(device->shader_backend == &arb_program_shader_backend) {
5213         if (use_ps(stateblock)) return;
5214
5215         device = stateblock->wineD3DDevice;
5216         context->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
5217         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
5218     }
5219
5220     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
5221     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col));
5222     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col)");
5223
5224 }
5225
5226 static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5227 {
5228     float col[4];
5229     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
5230
5231     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
5232      * application provided constants
5233      */
5234     if(device->shader_backend == &arb_program_shader_backend) {
5235         if (use_ps(stateblock)) return;
5236
5237         device = stateblock->wineD3DDevice;
5238         context->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
5239         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_SPECULAR_ENABLE + 1);
5240     }
5241
5242     if(stateblock->renderState[WINED3DRS_SPECULARENABLE]) {
5243         /* The specular color has no alpha */
5244         col[0] = 1.0f; col[1] = 1.0f;
5245         col[2] = 1.0f; col[3] = 0.0f;
5246     } else {
5247         col[0] = 0.0f; col[1] = 0.0f;
5248         col[2] = 0.0f; col[3] = 0.0f;
5249     }
5250     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col));
5251     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col)");
5252 }
5253
5254 static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5255 {
5256     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
5257     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
5258     float mat[2][2];
5259
5260     if (use_ps(stateblock))
5261     {
5262         if (stage != 0
5263                 && (((IWineD3DPixelShaderImpl *)stateblock->pixelShader)->baseShader.reg_maps.bumpmat & (1 << stage)))
5264         {
5265             /* The pixel shader has to know the bump env matrix. Do a constants update if it isn't scheduled
5266              * anyway
5267              */
5268             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
5269                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
5270             }
5271         }
5272
5273         if(device->shader_backend == &arb_program_shader_backend) {
5274             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
5275             return;
5276         }
5277     } else if(device->shader_backend == &arb_program_shader_backend) {
5278         context->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
5279         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
5280     }
5281
5282     mat[0][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT00]);
5283     mat[0][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT01]);
5284     mat[1][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT10]);
5285     mat[1][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT11]);
5286
5287     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0]));
5288     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0])");
5289 }
5290
5291 static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5292 {
5293     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
5294     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
5295     float param[4];
5296
5297     if (use_ps(stateblock))
5298     {
5299         if (stage != 0
5300                 && (((IWineD3DPixelShaderImpl *)stateblock->pixelShader)->baseShader.reg_maps.luminanceparams & (1 << stage)))
5301         {
5302             /* The pixel shader has to know the luminance offset. Do a constants update if it
5303              * isn't scheduled anyway
5304              */
5305             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
5306                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
5307             }
5308         }
5309
5310         if(device->shader_backend == &arb_program_shader_backend) {
5311             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
5312             return;
5313         }
5314     } else if(device->shader_backend == &arb_program_shader_backend) {
5315         context->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
5316         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_LUMINANCE(stage) + 1);
5317     }
5318
5319     param[0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLSCALE]);
5320     param[1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET]);
5321     param[2] = 0.0f;
5322     param[3] = 0.0f;
5323
5324     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param));
5325     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param)");
5326 }
5327
5328 static const char *get_argreg(struct wined3d_shader_buffer *buffer, DWORD argnum, unsigned int stage, DWORD arg)
5329 {
5330     const char *ret;
5331
5332     if(arg == ARG_UNUSED) return "unused"; /* This is the marker for unused registers */
5333
5334     switch(arg & WINED3DTA_SELECTMASK) {
5335         case WINED3DTA_DIFFUSE:
5336             ret = "fragment.color.primary"; break;
5337
5338         case WINED3DTA_CURRENT:
5339             if(stage == 0) ret = "fragment.color.primary";
5340             else ret = "ret";
5341             break;
5342
5343         case WINED3DTA_TEXTURE:
5344             switch(stage) {
5345                 case 0: ret = "tex0"; break;
5346                 case 1: ret = "tex1"; break;
5347                 case 2: ret = "tex2"; break;
5348                 case 3: ret = "tex3"; break;
5349                 case 4: ret = "tex4"; break;
5350                 case 5: ret = "tex5"; break;
5351                 case 6: ret = "tex6"; break;
5352                 case 7: ret = "tex7"; break;
5353                 default: ret = "unknown texture";
5354             }
5355             break;
5356
5357         case WINED3DTA_TFACTOR:
5358             ret = "tfactor"; break;
5359
5360         case WINED3DTA_SPECULAR:
5361             ret = "fragment.color.secondary"; break;
5362
5363         case WINED3DTA_TEMP:
5364             ret = "tempreg"; break;
5365
5366         case WINED3DTA_CONSTANT:
5367             FIXME("Implement perstage constants\n");
5368             switch(stage) {
5369                 case 0: ret = "const0"; break;
5370                 case 1: ret = "const1"; break;
5371                 case 2: ret = "const2"; break;
5372                 case 3: ret = "const3"; break;
5373                 case 4: ret = "const4"; break;
5374                 case 5: ret = "const5"; break;
5375                 case 6: ret = "const6"; break;
5376                 case 7: ret = "const7"; break;
5377                 default: ret = "unknown constant";
5378             }
5379             break;
5380
5381         default:
5382             return "unknown";
5383     }
5384
5385     if(arg & WINED3DTA_COMPLEMENT) {
5386         shader_addline(buffer, "SUB arg%u, const.x, %s;\n", argnum, ret);
5387         if(argnum == 0) ret = "arg0";
5388         if(argnum == 1) ret = "arg1";
5389         if(argnum == 2) ret = "arg2";
5390     }
5391     if(arg & WINED3DTA_ALPHAREPLICATE) {
5392         shader_addline(buffer, "MOV arg%u, %s.w;\n", argnum, ret);
5393         if(argnum == 0) ret = "arg0";
5394         if(argnum == 1) ret = "arg1";
5395         if(argnum == 2) ret = "arg2";
5396     }
5397     return ret;
5398 }
5399
5400 static void gen_ffp_instr(struct wined3d_shader_buffer *buffer, unsigned int stage, BOOL color,
5401         BOOL alpha, DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2)
5402 {
5403     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
5404     unsigned int mul = 1;
5405     BOOL mul_final_dest = FALSE;
5406
5407     if(color && alpha) dstmask = "";
5408     else if(color) dstmask = ".xyz";
5409     else dstmask = ".w";
5410
5411     if(dst == tempreg) dstreg = "tempreg";
5412     else dstreg = "ret";
5413
5414     arg0 = get_argreg(buffer, 0, stage, dw_arg0);
5415     arg1 = get_argreg(buffer, 1, stage, dw_arg1);
5416     arg2 = get_argreg(buffer, 2, stage, dw_arg2);
5417
5418     switch(op) {
5419         case WINED3DTOP_DISABLE:
5420             if(stage == 0) shader_addline(buffer, "MOV %s%s, fragment.color.primary;\n", dstreg, dstmask);
5421             break;
5422
5423         case WINED3DTOP_SELECTARG2:
5424             arg1 = arg2;
5425         case WINED3DTOP_SELECTARG1:
5426             shader_addline(buffer, "MOV %s%s, %s;\n", dstreg, dstmask, arg1);
5427             break;
5428
5429         case WINED3DTOP_MODULATE4X:
5430             mul = 2;
5431         case WINED3DTOP_MODULATE2X:
5432             mul *= 2;
5433             if(strcmp(dstreg, "result.color") == 0) {
5434                 dstreg = "ret";
5435                 mul_final_dest = TRUE;
5436             }
5437         case WINED3DTOP_MODULATE:
5438             shader_addline(buffer, "MUL %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5439             break;
5440
5441         case WINED3DTOP_ADDSIGNED2X:
5442             mul = 2;
5443             if(strcmp(dstreg, "result.color") == 0) {
5444                 dstreg = "ret";
5445                 mul_final_dest = TRUE;
5446             }
5447         case WINED3DTOP_ADDSIGNED:
5448             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
5449             arg2 = "arg2";
5450         case WINED3DTOP_ADD:
5451             shader_addline(buffer, "ADD_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5452             break;
5453
5454         case WINED3DTOP_SUBTRACT:
5455             shader_addline(buffer, "SUB_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5456             break;
5457
5458         case WINED3DTOP_ADDSMOOTH:
5459             shader_addline(buffer, "SUB arg1, const.x, %s;\n", arg1);
5460             shader_addline(buffer, "MAD_SAT %s%s, arg1, %s, %s;\n", dstreg, dstmask, arg2, arg1);
5461             break;
5462
5463         case WINED3DTOP_BLENDCURRENTALPHA:
5464             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_CURRENT);
5465             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5466             break;
5467         case WINED3DTOP_BLENDFACTORALPHA:
5468             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TFACTOR);
5469             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5470             break;
5471         case WINED3DTOP_BLENDTEXTUREALPHA:
5472             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
5473             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5474             break;
5475         case WINED3DTOP_BLENDDIFFUSEALPHA:
5476             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_DIFFUSE);
5477             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5478             break;
5479
5480         case WINED3DTOP_BLENDTEXTUREALPHAPM:
5481             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
5482             shader_addline(buffer, "SUB arg0.w, const.x, %s.w;\n", arg0);
5483             shader_addline(buffer, "MAD_SAT %s%s, %s, arg0.w, %s;\n", dstreg, dstmask, arg2, arg1);
5484             break;
5485
5486         /* D3DTOP_PREMODULATE ???? */
5487
5488         case WINED3DTOP_MODULATEINVALPHA_ADDCOLOR:
5489             shader_addline(buffer, "SUB arg0.w, const.x, %s;\n", arg1);
5490             shader_addline(buffer, "MAD_SAT %s%s, arg0.w, %s, %s;\n", dstreg, dstmask, arg2, arg1);
5491             break;
5492         case WINED3DTOP_MODULATEALPHA_ADDCOLOR:
5493             shader_addline(buffer, "MAD_SAT %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg1);
5494             break;
5495         case WINED3DTOP_MODULATEINVCOLOR_ADDALPHA:
5496             shader_addline(buffer, "SUB arg0, const.x, %s;\n", arg1);
5497             shader_addline(buffer, "MAD_SAT %s%s, arg0, %s, %s.w;\n", dstreg, dstmask, arg2, arg1);
5498             break;
5499         case WINED3DTOP_MODULATECOLOR_ADDALPHA:
5500             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s.w;\n", dstreg, dstmask, arg1, arg2, arg1);
5501             break;
5502
5503         case WINED3DTOP_DOTPRODUCT3:
5504             mul = 4;
5505             if(strcmp(dstreg, "result.color") == 0) {
5506                 dstreg = "ret";
5507                 mul_final_dest = TRUE;
5508             }
5509             shader_addline(buffer, "SUB arg1, %s, const.w;\n", arg1);
5510             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
5511             shader_addline(buffer, "DP3_SAT %s%s, arg1, arg2;\n", dstreg, dstmask);
5512             break;
5513
5514         case WINED3DTOP_MULTIPLYADD:
5515             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg0);
5516             break;
5517
5518         case WINED3DTOP_LERP:
5519             /* The msdn is not quite right here */
5520             shader_addline(buffer, "LRP %s%s, %s, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5521             break;
5522
5523         case WINED3DTOP_BUMPENVMAP:
5524         case WINED3DTOP_BUMPENVMAPLUMINANCE:
5525             /* Those are handled in the first pass of the shader(generation pass 1 and 2) already */
5526             break;
5527
5528         default:
5529             FIXME("Unhandled texture op %08x\n", op);
5530     }
5531
5532     if(mul == 2) {
5533         shader_addline(buffer, "MUL_SAT %s%s, %s, const.y;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
5534     } else if(mul == 4) {
5535         shader_addline(buffer, "MUL_SAT %s%s, %s, const.z;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
5536     }
5537 }
5538
5539 /* The stateblock is passed for GLINFO_LOCATION */
5540 static GLuint gen_arbfp_ffp_shader(const struct ffp_frag_settings *settings, IWineD3DStateBlockImpl *stateblock)
5541 {
5542     unsigned int stage;
5543     struct wined3d_shader_buffer buffer;
5544     BOOL tex_read[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5545     BOOL bump_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5546     BOOL luminance_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5547     const char *textype;
5548     const char *instr, *sat;
5549     char colorcor_dst[8];
5550     GLuint ret;
5551     DWORD arg0, arg1, arg2;
5552     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
5553     BOOL op_equal;
5554     const char *final_combiner_src = "ret";
5555     GLint pos;
5556
5557     /* Find out which textures are read */
5558     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5559         if(settings->op[stage].cop == WINED3DTOP_DISABLE) break;
5560         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
5561         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
5562         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
5563         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5564         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5565         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5566
5567         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHA) tex_read[stage] = TRUE;
5568         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHAPM) tex_read[stage] = TRUE;
5569         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP) {
5570             bump_used[stage] = TRUE;
5571             tex_read[stage] = TRUE;
5572         }
5573         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5574             bump_used[stage] = TRUE;
5575             tex_read[stage] = TRUE;
5576             luminance_used[stage] = TRUE;
5577         } else if(settings->op[stage].cop == WINED3DTOP_BLENDFACTORALPHA) {
5578             tfactor_used = TRUE;
5579         }
5580
5581         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
5582             tfactor_used = TRUE;
5583         }
5584
5585         if(settings->op[stage].dst == tempreg) tempreg_used = TRUE;
5586         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
5587             tempreg_used = TRUE;
5588         }
5589
5590         if(settings->op[stage].aop == WINED3DTOP_DISABLE) continue;
5591         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
5592         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
5593         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
5594         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5595         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5596         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5597
5598         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
5599             tempreg_used = TRUE;
5600         }
5601         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
5602             tfactor_used = TRUE;
5603         }
5604     }
5605
5606     /* Shader header */
5607     if (!shader_buffer_init(&buffer))
5608     {
5609         ERR("Failed to initialize shader buffer.\n");
5610         return 0;
5611     }
5612
5613     shader_addline(&buffer, "!!ARBfp1.0\n");
5614
5615     switch(settings->fog) {
5616         case FOG_OFF:                                                         break;
5617         case FOG_LINEAR: shader_addline(&buffer, "OPTION ARB_fog_linear;\n"); break;
5618         case FOG_EXP:    shader_addline(&buffer, "OPTION ARB_fog_exp;\n");    break;
5619         case FOG_EXP2:   shader_addline(&buffer, "OPTION ARB_fog_exp2;\n");   break;
5620         default: FIXME("Unexpected fog setting %d\n", settings->fog);
5621     }
5622
5623     shader_addline(&buffer, "PARAM const = {1, 2, 4, 0.5};\n");
5624     shader_addline(&buffer, "TEMP TMP;\n");
5625     shader_addline(&buffer, "TEMP ret;\n");
5626     if(tempreg_used || settings->sRGB_write) shader_addline(&buffer, "TEMP tempreg;\n");
5627     shader_addline(&buffer, "TEMP arg0;\n");
5628     shader_addline(&buffer, "TEMP arg1;\n");
5629     shader_addline(&buffer, "TEMP arg2;\n");
5630     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5631         if(!tex_read[stage]) continue;
5632         shader_addline(&buffer, "TEMP tex%u;\n", stage);
5633         if(!bump_used[stage]) continue;
5634         shader_addline(&buffer, "PARAM bumpmat%u = program.env[%u];\n", stage, ARB_FFP_CONST_BUMPMAT(stage));
5635         if(!luminance_used[stage]) continue;
5636         shader_addline(&buffer, "PARAM luminance%u = program.env[%u];\n", stage, ARB_FFP_CONST_LUMINANCE(stage));
5637     }
5638     if(tfactor_used) {
5639         shader_addline(&buffer, "PARAM tfactor = program.env[%u];\n", ARB_FFP_CONST_TFACTOR);
5640     }
5641         shader_addline(&buffer, "PARAM specular_enable = program.env[%u];\n", ARB_FFP_CONST_SPECULAR_ENABLE);
5642
5643     if(settings->sRGB_write) {
5644         shader_addline(&buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
5645                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
5646         shader_addline(&buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
5647                        srgb_sub_high, 0.0, 0.0, 0.0);
5648     }
5649
5650     if(ffp_clip_emul(stateblock) && settings->emul_clipplanes) shader_addline(&buffer, "KIL fragment.texcoord[7];\n");
5651
5652     /* Generate texture sampling instructions) */
5653     for(stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3DTOP_DISABLE; stage++) {
5654         if(!tex_read[stage]) continue;
5655
5656         switch(settings->op[stage].tex_type) {
5657             case tex_1d:                    textype = "1D";     break;
5658             case tex_2d:                    textype = "2D";     break;
5659             case tex_3d:                    textype = "3D";     break;
5660             case tex_cube:                  textype = "CUBE";   break;
5661             case tex_rect:                  textype = "RECT";   break;
5662             default: textype = "unexpected_textype";   break;
5663         }
5664
5665         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP ||
5666            settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5667             sat = "";
5668         } else {
5669             sat = "_SAT";
5670         }
5671
5672         if(settings->op[stage].projected == proj_none) {
5673             instr = "TEX";
5674         } else if(settings->op[stage].projected == proj_count4 ||
5675                   settings->op[stage].projected == proj_count3) {
5676             instr = "TXP";
5677         } else {
5678             FIXME("Unexpected projection mode %d\n", settings->op[stage].projected);
5679             instr = "TXP";
5680         }
5681
5682         if(stage > 0 &&
5683            (settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAP ||
5684             settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE)) {
5685             shader_addline(&buffer, "SWZ arg1, bumpmat%u, x, z, 0, 0;\n", stage - 1);
5686             shader_addline(&buffer, "DP3 ret.x, arg1, tex%u;\n", stage - 1);
5687             shader_addline(&buffer, "SWZ arg1, bumpmat%u, y, w, 0, 0;\n", stage - 1);
5688             shader_addline(&buffer, "DP3 ret.y, arg1, tex%u;\n", stage - 1);
5689
5690             /* with projective textures, texbem only divides the static texture coord, not the displacement,
5691              * so multiply the displacement with the dividing parameter before passing it to TXP
5692              */
5693             if (settings->op[stage].projected != proj_none) {
5694                 if(settings->op[stage].projected == proj_count4) {
5695                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].w;\n", stage);
5696                     shader_addline(&buffer, "MUL ret.xyz, ret, fragment.texcoord[%u].w, fragment.texcoord[%u];\n", stage, stage);
5697                 } else {
5698                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].z;\n", stage);
5699                     shader_addline(&buffer, "MAD ret.xyz, ret, fragment.texcoord[%u].z, fragment.texcoord[%u];\n", stage, stage);
5700                 }
5701             } else {
5702                 shader_addline(&buffer, "ADD ret, ret, fragment.texcoord[%u];\n", stage);
5703             }
5704
5705             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
5706                            instr, sat, stage, stage, textype);
5707             if(settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5708                 shader_addline(&buffer, "MAD_SAT ret.x, tex%u.z, luminance%u.x, luminance%u.y;\n",
5709                                stage - 1, stage - 1, stage - 1);
5710                 shader_addline(&buffer, "MUL tex%u, tex%u, ret.x;\n", stage, stage);
5711             }
5712         } else if(settings->op[stage].projected == proj_count3) {
5713             shader_addline(&buffer, "MOV ret, fragment.texcoord[%u];\n", stage);
5714             shader_addline(&buffer, "MOV ret.w, ret.z;\n");
5715             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
5716                             instr, sat, stage, stage, textype);
5717         } else {
5718             shader_addline(&buffer, "%s%s tex%u, fragment.texcoord[%u], texture[%u], %s;\n",
5719                             instr, sat, stage, stage, stage, textype);
5720         }
5721
5722         sprintf(colorcor_dst, "tex%u", stage);
5723         gen_color_correction(&buffer, colorcor_dst, WINED3DSP_WRITEMASK_ALL, "const.x", "const.y",
5724                 settings->op[stage].color_fixup);
5725     }
5726
5727     /* Generate the main shader */
5728     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5729         if(settings->op[stage].cop == WINED3DTOP_DISABLE) {
5730             if(stage == 0) {
5731                 final_combiner_src = "fragment.color.primary";
5732             }
5733             break;
5734         }
5735
5736         if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
5737            settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
5738             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg1;
5739         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
5740                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
5741             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg2;
5742         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
5743                   settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
5744             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg1;
5745         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
5746                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
5747             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg2;
5748         } else {
5749             op_equal = settings->op[stage].aop   == settings->op[stage].cop &&
5750                        settings->op[stage].carg0 == settings->op[stage].aarg0 &&
5751                        settings->op[stage].carg1 == settings->op[stage].aarg1 &&
5752                        settings->op[stage].carg2 == settings->op[stage].aarg2;
5753         }
5754
5755         if(settings->op[stage].aop == WINED3DTOP_DISABLE) {
5756             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5757                           settings->op[stage].cop, settings->op[stage].carg0,
5758                           settings->op[stage].carg1, settings->op[stage].carg2);
5759             if(stage == 0) {
5760                 shader_addline(&buffer, "MOV ret.w, fragment.color.primary.w;\n");
5761             }
5762         } else if(op_equal) {
5763             gen_ffp_instr(&buffer, stage, TRUE, TRUE, settings->op[stage].dst,
5764                           settings->op[stage].cop, settings->op[stage].carg0,
5765                           settings->op[stage].carg1, settings->op[stage].carg2);
5766         } else {
5767             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5768                           settings->op[stage].cop, settings->op[stage].carg0,
5769                           settings->op[stage].carg1, settings->op[stage].carg2);
5770             gen_ffp_instr(&buffer, stage, FALSE, TRUE, settings->op[stage].dst,
5771                           settings->op[stage].aop, settings->op[stage].aarg0,
5772                           settings->op[stage].aarg1, settings->op[stage].aarg2);
5773         }
5774     }
5775
5776     if(settings->sRGB_write) {
5777         shader_addline(&buffer, "MAD ret, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
5778         arbfp_add_sRGB_correction(&buffer, "ret", "arg0", "arg1", "arg2", "tempreg", FALSE);
5779     } else {
5780         shader_addline(&buffer, "MAD result.color, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
5781     }
5782
5783     /* Footer */
5784     shader_addline(&buffer, "END\n");
5785
5786     /* Generate the shader */
5787     GL_EXTCALL(glGenProgramsARB(1, &ret));
5788     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret));
5789     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
5790             strlen(buffer.buffer), buffer.buffer));
5791     checkGLcall("glProgramStringARB()");
5792
5793     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
5794     if (pos != -1)
5795     {
5796         FIXME("Fragment program error at position %d: %s\n", pos,
5797               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
5798     }
5799     else
5800     {
5801         GLint native;
5802
5803         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
5804         checkGLcall("glGetProgramivARB()");
5805         if (!native) WARN("Program exceeds native resource limits.\n");
5806     }
5807
5808     shader_buffer_free(&buffer);
5809     return ret;
5810 }
5811
5812 static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5813 {
5814     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
5815     struct shader_arb_priv *priv = device->fragment_priv;
5816     BOOL use_pshader = use_ps(stateblock);
5817     BOOL use_vshader = use_vs(stateblock);
5818     struct ffp_frag_settings settings;
5819     const struct arbfp_ffp_desc *desc;
5820     unsigned int i;
5821
5822     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
5823
5824     if(isStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE))) {
5825         if(!use_pshader && device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
5826             /* Reload fixed function constants since they collide with the pixel shader constants */
5827             for(i = 0; i < MAX_TEXTURES; i++) {
5828                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
5829             }
5830             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
5831             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
5832         } else if(use_pshader && !isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
5833             device->shader_backend->shader_select(context, use_pshader, use_vshader);
5834         }
5835         return;
5836     }
5837
5838     if(!use_pshader) {
5839         /* Find or create a shader implementing the fixed function pipeline settings, then activate it */
5840         gen_ffp_frag_op(stateblock, &settings, FALSE);
5841         desc = (const struct arbfp_ffp_desc *)find_ffp_frag_shader(&priv->fragment_shaders, &settings);
5842         if(!desc) {
5843             struct arbfp_ffp_desc *new_desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_desc));
5844             if (!new_desc)
5845             {
5846                 ERR("Out of memory\n");
5847                 return;
5848             }
5849             new_desc->num_textures_used = 0;
5850             for(i = 0; i < GL_LIMITS(texture_stages); i++) {
5851                 if(settings.op[i].cop == WINED3DTOP_DISABLE) break;
5852                 new_desc->num_textures_used = i;
5853             }
5854
5855             memcpy(&new_desc->parent.settings, &settings, sizeof(settings));
5856             new_desc->shader = gen_arbfp_ffp_shader(&settings, stateblock);
5857             add_ffp_frag_shader(&priv->fragment_shaders, &new_desc->parent);
5858             TRACE("Allocated fixed function replacement shader descriptor %p\n", new_desc);
5859             desc = new_desc;
5860         }
5861
5862         /* Now activate the replacement program. GL_FRAGMENT_PROGRAM_ARB is already active(however, note the
5863          * comment above the shader_select call below). If e.g. GLSL is active, the shader_select call will
5864          * deactivate it.
5865          */
5866         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader));
5867         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader)");
5868         priv->current_fprogram_id = desc->shader;
5869
5870         if(device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
5871             /* Reload fixed function constants since they collide with the pixel shader constants */
5872             for(i = 0; i < MAX_TEXTURES; i++) {
5873                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
5874             }
5875             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
5876             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
5877         }
5878         context->last_was_pshader = FALSE;
5879     } else {
5880         context->last_was_pshader = TRUE;
5881     }
5882
5883     /* Finally, select the shader. If a pixel shader is used, it will be set and enabled by the shader backend.
5884      * If this shader backend is arbfp(most likely), then it will simply overwrite the last fixed function replace-
5885      * ment shader. If the shader backend is not ARB, it currently is important that the opengl implementation
5886      * type overwrites GL_ARB_fragment_program. This is currently the case with GLSL. If we really want to use
5887      * atifs or nvrc pixel shaders with arb fragment programs we'd have to disable GL_FRAGMENT_PROGRAM_ARB here
5888      *
5889      * Don't call shader_select if the vertex shader is dirty, because it will be called later on by the vertex
5890      * shader handler
5891      */
5892     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
5893         device->shader_backend->shader_select(context, use_pshader, use_vshader);
5894
5895         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
5896             device->StateTable[STATE_VERTEXSHADERCONSTANT].apply(STATE_VERTEXSHADERCONSTANT, stateblock, context);
5897         }
5898     }
5899     if(use_pshader) {
5900         device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
5901     }
5902 }
5903
5904 /* We can't link the fog states to the fragment state directly since the vertex pipeline links them
5905  * to FOGENABLE. A different linking in different pipeline parts can't be expressed in the combined
5906  * state table, so we need to handle that with a forwarding function. The other invisible side effect
5907  * is that changing the fog start and fog end(which links to FOGENABLE in vertex) results in the
5908  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
5909  */
5910 static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5911 {
5912     enum fogsource new_source;
5913
5914     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
5915
5916     if(!isStateDirty(context, STATE_PIXELSHADER)) {
5917         fragment_prog_arbfp(state, stateblock, context);
5918     }
5919
5920     if(!stateblock->renderState[WINED3DRS_FOGENABLE]) return;
5921
5922     if(stateblock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
5923         if(use_vs(stateblock)) {
5924             new_source = FOGSOURCE_VS;
5925         } else {
5926             if(stateblock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || context->last_was_rhw) {
5927                 new_source = FOGSOURCE_COORD;
5928             } else {
5929                 new_source = FOGSOURCE_FFP;
5930             }
5931         }
5932     } else {
5933         new_source = FOGSOURCE_FFP;
5934     }
5935     if(new_source != context->fog_source) {
5936         context->fog_source = new_source;
5937         state_fogstartend(STATE_RENDER(WINED3DRS_FOGSTART), stateblock, context);
5938     }
5939 }
5940
5941 static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5942 {
5943     if(!isStateDirty(context, STATE_PIXELSHADER)) {
5944         fragment_prog_arbfp(state, stateblock, context);
5945     }
5946 }
5947
5948 #undef GLINFO_LOCATION
5949
5950 static const struct StateEntryTemplate arbfp_fragmentstate_template[] = {
5951     {STATE_RENDER(WINED3DRS_TEXTUREFACTOR),               { STATE_RENDER(WINED3DRS_TEXTUREFACTOR),              state_texfactor_arbfp   }, WINED3D_GL_EXT_NONE             },
5952     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5953     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5954     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5955     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5956     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5957     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5958     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5959     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5960     {STATE_TEXTURESTAGE(0, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5961     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5962     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5963     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5964     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5965     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5966     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5967     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5968     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5969     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5970     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5971     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5972     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5973     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5974     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5975     {STATE_TEXTURESTAGE(1, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5976     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5977     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5978     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5979     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5980     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5981     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5982     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5983     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5984     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5985     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5986     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5987     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5988     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5989     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5990     {STATE_TEXTURESTAGE(2, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5991     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5992     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5993     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5994     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
5995     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5996     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
5997     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5998     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
5999     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6000     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6001     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6002     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6003     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6004     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6005     {STATE_TEXTURESTAGE(3, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6006     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6007     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6008     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6009     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6010     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6011     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6012     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6013     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6014     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6015     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6016     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6017     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6018     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6019     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6020     {STATE_TEXTURESTAGE(4, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6021     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6022     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6023     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6024     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6025     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6026     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6027     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6028     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6029     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6030     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6031     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6032     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6033     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6034     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6035     {STATE_TEXTURESTAGE(5, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6036     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6037     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6038     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6039     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6040     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6041     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6042     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6043     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6044     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6045     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6046     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6047     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6048     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6049     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6050     {STATE_TEXTURESTAGE(6, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6051     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6052     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6053     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6054     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6055     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6056     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6057     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6058     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6059     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6060     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6061     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6062     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6063     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6064     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6065     {STATE_TEXTURESTAGE(7, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6066     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6067     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6068     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6069     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6070     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6071     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6072     {STATE_SAMPLER(0),                                    { STATE_SAMPLER(0),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6073     {STATE_SAMPLER(1),                                    { STATE_SAMPLER(1),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6074     {STATE_SAMPLER(2),                                    { STATE_SAMPLER(2),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6075     {STATE_SAMPLER(3),                                    { STATE_SAMPLER(3),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6076     {STATE_SAMPLER(4),                                    { STATE_SAMPLER(4),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6077     {STATE_SAMPLER(5),                                    { STATE_SAMPLER(5),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6078     {STATE_SAMPLER(6),                                    { STATE_SAMPLER(6),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6079     {STATE_SAMPLER(7),                                    { STATE_SAMPLER(7),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6080     {STATE_PIXELSHADER,                                   { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6081     {STATE_RENDER(WINED3DRS_FOGENABLE),                   { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
6082     {STATE_RENDER(WINED3DRS_FOGTABLEMODE),                { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
6083     {STATE_RENDER(WINED3DRS_FOGVERTEXMODE),               { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
6084     {STATE_RENDER(WINED3DRS_FOGSTART),                    { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, WINED3D_GL_EXT_NONE             },
6085     {STATE_RENDER(WINED3DRS_FOGEND),                      { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, WINED3D_GL_EXT_NONE             },
6086     {STATE_RENDER(WINED3DRS_SRGBWRITEENABLE),             { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6087     {STATE_RENDER(WINED3DRS_FOGCOLOR),                    { STATE_RENDER(WINED3DRS_FOGCOLOR),                   state_fogcolor          }, WINED3D_GL_EXT_NONE             },
6088     {STATE_RENDER(WINED3DRS_FOGDENSITY),                  { STATE_RENDER(WINED3DRS_FOGDENSITY),                 state_fogdensity        }, WINED3D_GL_EXT_NONE             },
6089     {STATE_TEXTURESTAGE(0,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(0, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6090     {STATE_TEXTURESTAGE(1,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(1, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6091     {STATE_TEXTURESTAGE(2,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(2, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6092     {STATE_TEXTURESTAGE(3,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(3, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6093     {STATE_TEXTURESTAGE(4,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(4, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6094     {STATE_TEXTURESTAGE(5,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(5, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6095     {STATE_TEXTURESTAGE(6,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(6, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6096     {STATE_TEXTURESTAGE(7,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(7, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6097     {STATE_RENDER(WINED3DRS_SPECULARENABLE),              { STATE_RENDER(WINED3DRS_SPECULARENABLE),             state_arb_specularenable}, WINED3D_GL_EXT_NONE             },
6098     {0 /* Terminate */,                                   { 0,                                                  0                       }, WINED3D_GL_EXT_NONE             },
6099 };
6100
6101 const struct fragment_pipeline arbfp_fragment_pipeline = {
6102     arbfp_enable,
6103     arbfp_get_caps,
6104     arbfp_alloc,
6105     arbfp_free,
6106     shader_arb_color_fixup_supported,
6107     arbfp_fragmentstate_template,
6108     TRUE /* We can disable projected textures */
6109 };
6110
6111 #define GLINFO_LOCATION device->adapter->gl_info
6112
6113 struct arbfp_blit_priv {
6114     GLenum yuy2_rect_shader, yuy2_2d_shader;
6115     GLenum uyvy_rect_shader, uyvy_2d_shader;
6116     GLenum yv12_rect_shader, yv12_2d_shader;
6117 };
6118
6119 static HRESULT arbfp_blit_alloc(IWineD3DDevice *iface) {
6120     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6121     device->blit_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct arbfp_blit_priv));
6122     if(!device->blit_priv) {
6123         ERR("Out of memory\n");
6124         return E_OUTOFMEMORY;
6125     }
6126     return WINED3D_OK;
6127 }
6128
6129 /* Context activation is done by the caller. */
6130 static void arbfp_blit_free(IWineD3DDevice *iface) {
6131     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6132     struct arbfp_blit_priv *priv = device->blit_priv;
6133
6134     ENTER_GL();
6135     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_rect_shader));
6136     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_2d_shader));
6137     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_rect_shader));
6138     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_2d_shader));
6139     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_rect_shader));
6140     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_2d_shader));
6141     checkGLcall("Delete yuv programs");
6142     LEAVE_GL();
6143 }
6144
6145 static BOOL gen_planar_yuv_read(struct wined3d_shader_buffer *buffer, enum yuv_fixup yuv_fixup,
6146         GLenum textype, char *luminance)
6147 {
6148     char chroma;
6149     const char *tex, *texinstr;
6150
6151     if (yuv_fixup == YUV_FIXUP_UYVY) {
6152         chroma = 'x';
6153         *luminance = 'w';
6154     } else {
6155         chroma = 'w';
6156         *luminance = 'x';
6157     }
6158     switch(textype) {
6159         case GL_TEXTURE_2D:             tex = "2D";     texinstr = "TXP"; break;
6160         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   texinstr = "TEX"; break;
6161         default:
6162             /* This is more tricky than just replacing the texture type - we have to navigate
6163              * properly in the texture to find the correct chroma values
6164              */
6165             FIXME("Implement yuv correction for non-2d, non-rect textures\n");
6166             return FALSE;
6167     }
6168
6169     /* First we have to read the chroma values. This means we need at least two pixels(no filtering),
6170      * or 4 pixels(with filtering). To get the unmodified chromas, we have to rid ourselves of the
6171      * filtering when we sample the texture.
6172      *
6173      * These are the rules for reading the chroma:
6174      *
6175      * Even pixel: Cr
6176      * Even pixel: U
6177      * Odd pixel: V
6178      *
6179      * So we have to get the sampling x position in non-normalized coordinates in integers
6180      */
6181     if(textype != GL_TEXTURE_RECTANGLE_ARB) {
6182         shader_addline(buffer, "MUL texcrd.xy, fragment.texcoord[0], size.x;\n");
6183         shader_addline(buffer, "MOV texcrd.w, size.x;\n");
6184     } else {
6185         shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6186     }
6187     /* We must not allow filtering between pixel x and x+1, this would mix U and V
6188      * Vertical filtering is ok. However, bear in mind that the pixel center is at
6189      * 0.5, so add 0.5.
6190      */
6191     shader_addline(buffer, "FLR texcrd.x, texcrd.x;\n");
6192     shader_addline(buffer, "ADD texcrd.x, texcrd.x, coef.y;\n");
6193
6194     /* Divide the x coordinate by 0.5 and get the fraction. This gives 0.25 and 0.75 for the
6195      * even and odd pixels respectively
6196      */
6197     shader_addline(buffer, "MUL texcrd2, texcrd, coef.y;\n");
6198     shader_addline(buffer, "FRC texcrd2, texcrd2;\n");
6199
6200     /* Sample Pixel 1 */
6201     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
6202
6203     /* Put the value into either of the chroma values */
6204     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
6205     shader_addline(buffer, "MUL chroma.x, luminance.%c, temp.x;\n", chroma);
6206     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
6207     shader_addline(buffer, "MUL chroma.y, luminance.%c, temp.x;\n", chroma);
6208
6209     /* Sample pixel 2. If we read an even pixel(SLT above returned 1), sample
6210      * the pixel right to the current one. Otherwise, sample the left pixel.
6211      * Bias and scale the SLT result to -1;1 and add it to the texcrd.x.
6212      */
6213     shader_addline(buffer, "MAD temp.x, temp.x, coef.z, -coef.x;\n");
6214     shader_addline(buffer, "ADD texcrd.x, texcrd, temp.x;\n");
6215     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
6216
6217     /* Put the value into the other chroma */
6218     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
6219     shader_addline(buffer, "MAD chroma.y, luminance.%c, temp.x, chroma.y;\n", chroma);
6220     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
6221     shader_addline(buffer, "MAD chroma.x, luminance.%c, temp.x, chroma.x;\n", chroma);
6222
6223     /* TODO: If filtering is enabled, sample a 2nd pair of pixels left or right of
6224      * the current one and lerp the two U and V values
6225      */
6226
6227     /* This gives the correctly filtered luminance value */
6228     shader_addline(buffer, "TEX luminance, fragment.texcoord[0], texture[0], %s;\n", tex);
6229
6230     return TRUE;
6231 }
6232
6233 static BOOL gen_yv12_read(struct wined3d_shader_buffer *buffer, GLenum textype, char *luminance)
6234 {
6235     const char *tex;
6236
6237     switch(textype) {
6238         case GL_TEXTURE_2D:             tex = "2D";     break;
6239         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   break;
6240         default:
6241             FIXME("Implement yv12 correction for non-2d, non-rect textures\n");
6242             return FALSE;
6243     }
6244
6245     /* YV12 surfaces contain a WxH sized luminance plane, followed by a (W/2)x(H/2)
6246      * V and a (W/2)x(H/2) U plane, each with 8 bit per pixel. So the effective
6247      * bitdepth is 12 bits per pixel. Since the U and V planes have only half the
6248      * pitch of the luminance plane, the packing into the gl texture is a bit
6249      * unfortunate. If the whole texture is interpreted as luminance data it looks
6250      * approximately like this:
6251      *
6252      *        +----------------------------------+----
6253      *        |                                  |
6254      *        |                                  |
6255      *        |                                  |
6256      *        |                                  |
6257      *        |                                  |   2
6258      *        |            LUMINANCE             |   -
6259      *        |                                  |   3
6260      *        |                                  |
6261      *        |                                  |
6262      *        |                                  |
6263      *        |                                  |
6264      *        +----------------+-----------------+----
6265      *        |                |                 |
6266      *        |  U even rows   |  U odd rows     |
6267      *        |                |                 |   1
6268      *        +----------------+------------------   -
6269      *        |                |                 |   3
6270      *        |  V even rows   |  V odd rows     |
6271      *        |                |                 |
6272      *        +----------------+-----------------+----
6273      *        |                |                 |
6274      *        |     0.5        |       0.5       |
6275      *
6276      * So it appears as if there are 4 chroma images, but in fact the odd rows
6277      * in the chroma images are in the same row as the even ones. So its is
6278      * kinda tricky to read
6279      *
6280      * When reading from rectangle textures, keep in mind that the input y coordinates
6281      * go from 0 to d3d_height, whereas the opengl texture height is 1.5 * d3d_height
6282      */
6283     shader_addline(buffer, "PARAM yv12_coef = {%f, %f, %f, %f};\n",
6284             2.0f / 3.0f, 1.0f / 6.0f, (2.0f / 3.0f) + (1.0f / 6.0f), 1.0f / 3.0f);
6285
6286     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6287     /* the chroma planes have only half the width */
6288     shader_addline(buffer, "MUL texcrd.x, texcrd.x, coef.y;\n");
6289
6290     /* The first value is between 2/3 and 5/6th of the texture's height, so scale+bias
6291      * the coordinate. Also read the right side of the image when reading odd lines
6292      *
6293      * Don't forget to clamp the y values in into the range, otherwise we'll get filtering
6294      * bleeding
6295      */
6296     if(textype == GL_TEXTURE_2D) {
6297
6298         shader_addline(buffer, "RCP chroma.w, size.y;\n");
6299
6300         shader_addline(buffer, "MUL texcrd2.y, texcrd.y, size.y;\n");
6301
6302         shader_addline(buffer, "FLR texcrd2.y, texcrd2.y;\n");
6303         shader_addline(buffer, "MAD texcrd.y, texcrd.y, yv12_coef.y, yv12_coef.x;\n");
6304
6305         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
6306         shader_addline(buffer, "ADD texcrd2.x, texcrd2.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
6307         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
6308         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
6309         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
6310
6311         /* clamp, keep the half pixel origin in mind */
6312         shader_addline(buffer, "MAD temp.y, coef.y, chroma.w, yv12_coef.x;\n");
6313         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
6314         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.z;\n");
6315         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6316     } else {
6317         /* Read from [size - size+size/4] */
6318         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
6319         shader_addline(buffer, "MAD texcrd.y, texcrd.y, coef.w, size.y;\n");
6320
6321         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
6322         shader_addline(buffer, "ADD texcrd2.x, texcrd.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
6323         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
6324         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
6325         shader_addline(buffer, "MUL texcrd2.x, texcrd2.x, size.x;\n");
6326         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
6327
6328         /* Make sure to read exactly from the pixel center */
6329         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
6330         shader_addline(buffer, "ADD texcrd.y, texcrd.y, coef.y;\n");
6331
6332         /* Clamp */
6333         shader_addline(buffer, "MAD temp.y, size.y, coef.w, size.y;\n");
6334         shader_addline(buffer, "ADD temp.y, temp.y, -coef.y;\n");
6335         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6336         shader_addline(buffer, "ADD temp.y, size.y, -coef.y;\n");
6337         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
6338     }
6339     /* Read the texture, put the result into the output register */
6340     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
6341     shader_addline(buffer, "MOV chroma.x, temp.w;\n");
6342
6343     /* The other chroma value is 1/6th of the texture lower, from 5/6th to 6/6th
6344      * No need to clamp because we're just reusing the already clamped value from above
6345      */
6346     if(textype == GL_TEXTURE_2D) {
6347         shader_addline(buffer, "ADD texcrd.y, texcrd.y, yv12_coef.y;\n");
6348     } else {
6349         shader_addline(buffer, "MAD texcrd.y, size.y, coef.w, texcrd.y;\n");
6350     }
6351     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
6352     shader_addline(buffer, "MOV chroma.y, temp.w;\n");
6353
6354     /* Sample the luminance value. It is in the top 2/3rd of the texture, so scale the y coordinate.
6355      * Clamp the y coordinate to prevent the chroma values from bleeding into the sampled luminance
6356      * values due to filtering
6357      */
6358     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6359     if(textype == GL_TEXTURE_2D) {
6360         /* Multiply the y coordinate by 2/3 and clamp it */
6361         shader_addline(buffer, "MUL texcrd.y, texcrd.y, yv12_coef.x;\n");
6362         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.x;\n");
6363         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6364         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
6365     } else {
6366         /* Reading from texture_rectangles is pretty straightforward, just use the unmodified
6367          * texture coordinate. It is still a good idea to clamp it though, since the opengl texture
6368          * is bigger
6369          */
6370         shader_addline(buffer, "ADD temp.x, size.y, -coef.y;\n");
6371         shader_addline(buffer, "MIN texcrd.y, texcrd.y, size.x;\n");
6372         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
6373     }
6374     *luminance = 'a';
6375
6376     return TRUE;
6377 }
6378
6379 /* Context activation is done by the caller. */
6380 static GLuint gen_yuv_shader(IWineD3DDeviceImpl *device, enum yuv_fixup yuv_fixup, GLenum textype)
6381 {
6382     GLenum shader;
6383     struct wined3d_shader_buffer buffer;
6384     char luminance_component;
6385     struct arbfp_blit_priv *priv = device->blit_priv;
6386     GLint pos;
6387
6388     /* Shader header */
6389     if (!shader_buffer_init(&buffer))
6390     {
6391         ERR("Failed to initialize shader buffer.\n");
6392         return 0;
6393     }
6394
6395     ENTER_GL();
6396     GL_EXTCALL(glGenProgramsARB(1, &shader));
6397     checkGLcall("GL_EXTCALL(glGenProgramsARB(1, &shader))");
6398     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
6399     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
6400     LEAVE_GL();
6401     if(!shader) {
6402         shader_buffer_free(&buffer);
6403         return 0;
6404     }
6405
6406     /* The YUY2 and UYVY formats contain two pixels packed into a 32 bit macropixel,
6407      * giving effectively 16 bit per pixel. The color consists of a luminance(Y) and
6408      * two chroma(U and V) values. Each macropixel has two luminance values, one for
6409      * each single pixel it contains, and one U and one V value shared between both
6410      * pixels.
6411      *
6412      * The data is loaded into an A8L8 texture. With YUY2, the luminance component
6413      * contains the luminance and alpha the chroma. With UYVY it is vice versa. Thus
6414      * take the format into account when generating the read swizzles
6415      *
6416      * Reading the Y value is straightforward - just sample the texture. The hardware
6417      * takes care of filtering in the horizontal and vertical direction.
6418      *
6419      * Reading the U and V values is harder. We have to avoid filtering horizontally,
6420      * because that would mix the U and V values of one pixel or two adjacent pixels.
6421      * Thus floor the texture coordinate and add 0.5 to get an unfiltered read,
6422      * regardless of the filtering setting. Vertical filtering works automatically
6423      * though - the U and V values of two rows are mixed nicely.
6424      *
6425      * Appart of avoiding filtering issues, the code has to know which value it just
6426      * read, and where it can find the other one. To determine this, it checks if
6427      * it sampled an even or odd pixel, and shifts the 2nd read accordingly.
6428      *
6429      * Handling horizontal filtering of U and V values requires reading a 2nd pair
6430      * of pixels, extracting U and V and mixing them. This is not implemented yet.
6431      *
6432      * An alternative implementation idea is to load the texture as A8R8G8B8 texture,
6433      * with width / 2. This way one read gives all 3 values, finding U and V is easy
6434      * in an unfiltered situation. Finding the luminance on the other hand requires
6435      * finding out if it is an odd or even pixel. The real drawback of this approach
6436      * is filtering. This would have to be emulated completely in the shader, reading
6437      * up two 2 packed pixels in up to 2 rows and interpolating both horizontally and
6438      * vertically. Beyond that it would require adjustments to the texture handling
6439      * code to deal with the width scaling
6440      */
6441     shader_addline(&buffer, "!!ARBfp1.0\n");
6442     shader_addline(&buffer, "TEMP luminance;\n");
6443     shader_addline(&buffer, "TEMP temp;\n");
6444     shader_addline(&buffer, "TEMP chroma;\n");
6445     shader_addline(&buffer, "TEMP texcrd;\n");
6446     shader_addline(&buffer, "TEMP texcrd2;\n");
6447     shader_addline(&buffer, "PARAM coef = {1.0, 0.5, 2.0, 0.25};\n");
6448     shader_addline(&buffer, "PARAM yuv_coef = {1.403, 0.344, 0.714, 1.770};\n");
6449     shader_addline(&buffer, "PARAM size = program.local[0];\n");
6450
6451     switch (yuv_fixup)
6452     {
6453         case YUV_FIXUP_UYVY:
6454         case YUV_FIXUP_YUY2:
6455             if (!gen_planar_yuv_read(&buffer, yuv_fixup, textype, &luminance_component))
6456             {
6457                 shader_buffer_free(&buffer);
6458                 return 0;
6459             }
6460             break;
6461
6462         case YUV_FIXUP_YV12:
6463             if (!gen_yv12_read(&buffer, textype, &luminance_component))
6464             {
6465                 shader_buffer_free(&buffer);
6466                 return 0;
6467             }
6468             break;
6469
6470         default:
6471             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
6472             shader_buffer_free(&buffer);
6473             return 0;
6474     }
6475
6476     /* Calculate the final result. Formula is taken from
6477      * http://www.fourcc.org/fccyvrgb.php. Note that the chroma
6478      * ranges from -0.5 to 0.5
6479      */
6480     shader_addline(&buffer, "SUB chroma.xy, chroma, coef.y;\n");
6481
6482     shader_addline(&buffer, "MAD result.color.x, chroma.x, yuv_coef.x, luminance.%c;\n", luminance_component);
6483     shader_addline(&buffer, "MAD temp.x, -chroma.y, yuv_coef.y, luminance.%c;\n", luminance_component);
6484     shader_addline(&buffer, "MAD result.color.y, -chroma.x, yuv_coef.z, temp.x;\n");
6485     shader_addline(&buffer, "MAD result.color.z, chroma.y, yuv_coef.w, luminance.%c;\n", luminance_component);
6486     shader_addline(&buffer, "END\n");
6487
6488     ENTER_GL();
6489     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
6490             strlen(buffer.buffer), buffer.buffer));
6491     checkGLcall("glProgramStringARB()");
6492
6493     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
6494     if (pos != -1)
6495     {
6496         FIXME("Fragment program error at position %d: %s\n", pos,
6497               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
6498     }
6499     else
6500     {
6501         GLint native;
6502
6503         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
6504         checkGLcall("glGetProgramivARB()");
6505         if (!native) WARN("Program exceeds native resource limits.\n");
6506     }
6507
6508     shader_buffer_free(&buffer);
6509     LEAVE_GL();
6510
6511     switch (yuv_fixup)
6512     {
6513         case YUV_FIXUP_YUY2:
6514             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yuy2_rect_shader = shader;
6515             else priv->yuy2_2d_shader = shader;
6516             break;
6517
6518         case YUV_FIXUP_UYVY:
6519             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->uyvy_rect_shader = shader;
6520             else priv->uyvy_2d_shader = shader;
6521             break;
6522
6523         case YUV_FIXUP_YV12:
6524             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yv12_rect_shader = shader;
6525             else priv->yv12_2d_shader = shader;
6526             break;
6527     }
6528
6529     return shader;
6530 }
6531
6532 /* Context activation is done by the caller. */
6533 static HRESULT arbfp_blit_set(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
6534         GLenum textype, UINT width, UINT height)
6535 {
6536     GLenum shader;
6537     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6538     float size[4] = {width, height, 1, 1};
6539     struct arbfp_blit_priv *priv = device->blit_priv;
6540     enum yuv_fixup yuv_fixup;
6541
6542     if (!is_yuv_fixup(format_desc->color_fixup))
6543     {
6544         TRACE("Fixup:\n");
6545         dump_color_fixup_desc(format_desc->color_fixup);
6546         /* Don't bother setting up a shader for unconverted formats */
6547         ENTER_GL();
6548         glEnable(textype);
6549         checkGLcall("glEnable(textype)");
6550         LEAVE_GL();
6551         return WINED3D_OK;
6552     }
6553
6554     yuv_fixup = get_yuv_fixup(format_desc->color_fixup);
6555
6556     switch(yuv_fixup)
6557     {
6558         case YUV_FIXUP_YUY2:
6559             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yuy2_rect_shader : priv->yuy2_2d_shader;
6560             break;
6561
6562         case YUV_FIXUP_UYVY:
6563             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->uyvy_rect_shader : priv->uyvy_2d_shader;
6564             break;
6565
6566         case YUV_FIXUP_YV12:
6567             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yv12_rect_shader : priv->yv12_2d_shader;
6568             break;
6569
6570         default:
6571             FIXME("Unsupported YUV fixup %#x, not setting a shader\n", yuv_fixup);
6572             ENTER_GL();
6573             glEnable(textype);
6574             checkGLcall("glEnable(textype)");
6575             LEAVE_GL();
6576             return E_NOTIMPL;
6577     }
6578
6579     if (!shader) shader = gen_yuv_shader(device, yuv_fixup, textype);
6580
6581     ENTER_GL();
6582     glEnable(GL_FRAGMENT_PROGRAM_ARB);
6583     checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
6584     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
6585     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
6586     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, size));
6587     checkGLcall("glProgramLocalParameter4fvARB");
6588     LEAVE_GL();
6589
6590     return WINED3D_OK;
6591 }
6592
6593 /* Context activation is done by the caller. */
6594 static void arbfp_blit_unset(IWineD3DDevice *iface) {
6595     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6596
6597     ENTER_GL();
6598     glDisable(GL_FRAGMENT_PROGRAM_ARB);
6599     checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
6600     glDisable(GL_TEXTURE_2D);
6601     checkGLcall("glDisable(GL_TEXTURE_2D)");
6602     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
6603         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
6604         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
6605     }
6606     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
6607         glDisable(GL_TEXTURE_RECTANGLE_ARB);
6608         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
6609     }
6610     LEAVE_GL();
6611 }
6612
6613 static BOOL arbfp_blit_color_fixup_supported(struct color_fixup_desc fixup)
6614 {
6615     enum yuv_fixup yuv_fixup;
6616
6617     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
6618     {
6619         TRACE("Checking support for fixup:\n");
6620         dump_color_fixup_desc(fixup);
6621     }
6622
6623     if (is_identity_fixup(fixup))
6624     {
6625         TRACE("[OK]\n");
6626         return TRUE;
6627     }
6628
6629     /* We only support YUV conversions. */
6630     if (!is_yuv_fixup(fixup))
6631     {
6632         TRACE("[FAILED]\n");
6633         return FALSE;
6634     }
6635
6636     yuv_fixup = get_yuv_fixup(fixup);
6637     switch(yuv_fixup)
6638     {
6639         case YUV_FIXUP_YUY2:
6640         case YUV_FIXUP_UYVY:
6641         case YUV_FIXUP_YV12:
6642             TRACE("[OK]\n");
6643             return TRUE;
6644
6645         default:
6646             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
6647             TRACE("[FAILED]\n");
6648             return FALSE;
6649     }
6650 }
6651
6652 const struct blit_shader arbfp_blit = {
6653     arbfp_blit_alloc,
6654     arbfp_blit_free,
6655     arbfp_blit_set,
6656     arbfp_blit_unset,
6657     arbfp_blit_color_fixup_supported,
6658 };
6659
6660 #undef GLINFO_LOCATION