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