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