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