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