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