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