wined3d: Destroy depth_blt resources in the backend's destructor.
[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  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30
31 #include <math.h>
32 #include <stdio.h>
33
34 #include "wined3d_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
39
40 #define GLINFO_LOCATION      (*gl_info)
41
42 /********************************************************
43  * ARB_[vertex/fragment]_program helper functions follow
44  ********************************************************/
45
46 /** 
47  * Loads floating point constants into the currently set ARB_vertex/fragment_program.
48  * When constant_list == NULL, it will load all the constants.
49  *  
50  * @target_type should be either GL_VERTEX_PROGRAM_ARB (for vertex shaders)
51  *  or GL_FRAGMENT_PROGRAM_ARB (for pixel shaders)
52  */
53 static unsigned int shader_arb_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info, GLuint target_type,
54         unsigned int max_constants, float* constants, char *dirty_consts) {
55     local_constant* lconst;
56     DWORD i, j;
57     unsigned int ret;
58
59     if (TRACE_ON(d3d_shader)) {
60         for(i = 0; i < max_constants; i++) {
61             if(!dirty_consts[i]) continue;
62             TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
63                         constants[i * 4 + 0], constants[i * 4 + 1],
64                         constants[i * 4 + 2], constants[i * 4 + 3]);
65         }
66     }
67     /* In 1.X pixel shaders constants are implicitly clamped in the range [-1;1] */
68     if(target_type == GL_FRAGMENT_PROGRAM_ARB &&
69        WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1) {
70         float lcl_const[4];
71         for(i = 0; i < max_constants; i++) {
72             if(!dirty_consts[i]) continue;
73             dirty_consts[i] = 0;
74
75             j = 4 * i;
76             if(constants[j + 0] > 1.0) lcl_const[0] = 1.0;
77             else if(constants[j + 0] < -1.0) lcl_const[0] = -1.0;
78             else lcl_const[0] = constants[j + 0];
79
80             if(constants[j + 1] > 1.0) lcl_const[1] = 1.0;
81             else if(constants[j + 1] < -1.0) lcl_const[1] = -1.0;
82             else lcl_const[1] = constants[j + 1];
83
84             if(constants[j + 2] > 1.0) lcl_const[2] = 1.0;
85             else if(constants[j + 2] < -1.0) lcl_const[2] = -1.0;
86             else lcl_const[2] = constants[j + 2];
87
88             if(constants[j + 3] > 1.0) lcl_const[3] = 1.0;
89             else if(constants[j + 3] < -1.0) lcl_const[3] = -1.0;
90             else lcl_const[3] = constants[j + 3];
91
92             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
93         }
94     } else {
95         if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
96             /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
97              * or just reloading *all* constants at once
98              *
99             GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, 0, max_constants, constants));
100              */
101             for(i = 0; i < max_constants; i++) {
102                 if(!dirty_consts[i]) continue;
103
104                 /* Find the next block of dirty constants */
105                 dirty_consts[i] = 0;
106                 j = i;
107                 for(i++; (i < max_constants) && dirty_consts[i]; i++) {
108                     dirty_consts[i] = 0;
109                 }
110
111                 GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
112             }
113         } else {
114             for(i = 0; i < max_constants; i++) {
115                 if(dirty_consts[i]) {
116                     dirty_consts[i] = 0;
117                     GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
118                 }
119             }
120         }
121     }
122     checkGLcall("glProgramEnvParameter4fvARB()");
123
124     /* Load immediate constants */
125     if(This->baseShader.load_local_constsF) {
126         if (TRACE_ON(d3d_shader)) {
127             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
128                 GLfloat* values = (GLfloat*)lconst->value;
129                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
130                         values[0], values[1], values[2], values[3]);
131             }
132         }
133         /* Immediate constants are clamped for 1.X shaders at loading times */
134         ret = 0;
135         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
136             dirty_consts[lconst->idx] = 1; /* Dirtify so the non-immediate constant overwrites it next time */
137             ret = max(ret, lconst->idx + 1);
138             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, lconst->idx, (GLfloat*)lconst->value));
139         }
140         checkGLcall("glProgramEnvParameter4fvARB()");
141         return ret; /* The loaded immediate constants need reloading for the next shader */
142     } else {
143         return 0; /* No constants are dirty now */
144     }
145 }
146
147 /**
148  * Loads the app-supplied constants into the currently set ARB_[vertex/fragment]_programs.
149  * 
150  * We only support float constants in ARB at the moment, so don't 
151  * worry about the Integers or Booleans
152  */
153 void shader_arb_load_constants(
154     IWineD3DDevice* device,
155     char usePixelShader,
156     char useVertexShader) {
157    
158     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device; 
159     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
160     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
161     unsigned char i;
162
163     if (useVertexShader) {
164         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
165
166         /* Load DirectX 9 float constants for vertex shader */
167         deviceImpl->highest_dirty_vs_const = shader_arb_load_constantsF(
168                 vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
169                 deviceImpl->highest_dirty_vs_const,
170                 stateBlock->vertexShaderConstantF,
171                 deviceImpl->activeContext->vshader_const_dirty);
172
173         /* Upload the position fixup */
174         GL_EXTCALL(glProgramEnvParameter4fvARB(GL_VERTEX_PROGRAM_ARB, ARB_SHADER_PRIVCONST_POS, deviceImpl->posFixup));
175     }
176
177     if (usePixelShader) {
178
179         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
180         IWineD3DPixelShaderImpl *psi = (IWineD3DPixelShaderImpl *) pshader;
181
182         /* Load DirectX 9 float constants for pixel shader */
183         deviceImpl->highest_dirty_ps_const = shader_arb_load_constantsF(
184                 pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
185                 deviceImpl->highest_dirty_ps_const,
186                 stateBlock->pixelShaderConstantF,
187                 deviceImpl->activeContext->pshader_const_dirty);
188
189         for(i = 0; i < psi->numbumpenvmatconsts; i++) {
190             /* The state manager takes care that this function is always called if the bump env matrix changes
191              */
192             float *data = (float *) &stateBlock->textureState[(int) psi->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
193             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->bumpenvmatconst[i].const_num, data));
194             deviceImpl->activeContext->pshader_const_dirty[psi->bumpenvmatconst[i].const_num] = 1;
195
196             if(psi->luminanceconst[i].const_num != -1) {
197                 /* WINED3DTSS_BUMPENVLSCALE and WINED3DTSS_BUMPENVLOFFSET are next to each other.
198                  * point gl to the scale, and load 4 floats. x = scale, y = offset, z and w are junk, we
199                  * don't care about them. The pointers are valid for sure because the stateblock is bigger.
200                  * (they're WINED3DTSS_TEXTURETRANSFORMFLAGS and WINED3DTSS_ADDRESSW, so most likely 0 or NaN
201                  */
202                 float *scale = (float *) &stateBlock->textureState[(int) psi->luminanceconst[i].texunit][WINED3DTSS_BUMPENVLSCALE];
203                 GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->luminanceconst[i].const_num, scale));
204                 deviceImpl->activeContext->pshader_const_dirty[psi->luminanceconst[i].const_num] = 1;
205             }
206         }
207
208         if(((IWineD3DPixelShaderImpl *) pshader)->srgb_enabled &&
209            !((IWineD3DPixelShaderImpl *) pshader)->srgb_mode_hardcoded) {
210             float comparison[4];
211             float mul_low[4];
212
213             if(stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
214                 comparison[0] = srgb_cmp; comparison[1] = srgb_cmp;
215                 comparison[2] = srgb_cmp; comparison[3] = srgb_cmp;
216
217                 mul_low[0] = srgb_mul_low; mul_low[1] = srgb_mul_low;
218                 mul_low[2] = srgb_mul_low; mul_low[3] = srgb_mul_low;
219             } else {
220                 comparison[0] = 1.0 / 0.0; comparison[1] = 1.0 / 0.0;
221                 comparison[2] = 1.0 / 0.0; comparison[3] = 1.0 / 0.0;
222
223                 mul_low[0] = 1.0; mul_low[1] = 1.0;
224                 mul_low[2] = 1.0; mul_low[3] = 1.0;
225             }
226             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->srgb_cmp_const, comparison));
227             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->srgb_low_const, mul_low));
228             checkGLcall("Load sRGB correction constants\n");
229             deviceImpl->activeContext->pshader_const_dirty[psi->srgb_low_const] = 1;
230             deviceImpl->activeContext->pshader_const_dirty[psi->srgb_cmp_const] = 1;
231
232         }
233     }
234 }
235
236 /* Generate the variable & register declarations for the ARB_vertex_program output target */
237 void shader_generate_arb_declarations(
238     IWineD3DBaseShader *iface,
239     shader_reg_maps* reg_maps,
240     SHADER_BUFFER* buffer,
241     WineD3D_GL_Info* gl_info) {
242
243     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
244     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
245     DWORD i, cur;
246     char pshader = shader_is_pshader_version(This->baseShader.hex_version);
247     unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
248             (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
249     UINT extra_constants_needed = 0;
250     local_constant* lconst;
251
252     /* Temporary Output register */
253     shader_addline(buffer, "TEMP TMP_OUT;\n");
254
255     for(i = 0; i < This->baseShader.limits.temporary; i++) {
256         if (reg_maps->temporary[i])
257             shader_addline(buffer, "TEMP R%u;\n", i);
258     }
259
260     for (i = 0; i < This->baseShader.limits.address; i++) {
261         if (reg_maps->address[i])
262             shader_addline(buffer, "ADDRESS A%d;\n", i);
263     }
264
265     for(i = 0; i < This->baseShader.limits.texcoord; i++) {
266         if (reg_maps->texcoord[i])
267             shader_addline(buffer,"TEMP T%u;\n", i);
268     }
269
270     /* Texture coordinate registers must be pre-loaded */
271     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
272         if (reg_maps->texcoord[i])
273             shader_addline(buffer, "MOV T%u, fragment.texcoord[%u];\n", i, i);
274     }
275
276     for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
277         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) This;
278         if(!reg_maps->bumpmat[i]) continue;
279
280         cur = ps->numbumpenvmatconsts;
281         ps->bumpenvmatconst[cur].const_num = -1;
282         ps->bumpenvmatconst[cur].texunit = i;
283         ps->luminanceconst[cur].const_num = -1;
284         ps->luminanceconst[cur].texunit = i;
285
286         /* If the shader does not use all available constants, use the next free constant to load the bump mapping environment matrix from
287          * the stateblock into the shader. If no constant is available don't load, texbem will then just sample the texture without applying
288          * bump mapping.
289          */
290         if(max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
291             ps->bumpenvmatconst[cur].const_num = max_constantsF + extra_constants_needed;
292             shader_addline(buffer, "PARAM bumpenvmat%d = program.env[%d];\n",
293                            i, ps->bumpenvmatconst[cur].const_num);
294             extra_constants_needed++;
295
296             if(reg_maps->luminanceparams && max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
297                 ((IWineD3DPixelShaderImpl *)This)->luminanceconst[cur].const_num = max_constantsF + extra_constants_needed;
298                 shader_addline(buffer, "PARAM luminance%d = program.env[%d];\n",
299                                i, ps->luminanceconst[cur].const_num);
300                 extra_constants_needed++;
301             } else if(reg_maps->luminanceparams) {
302                 FIXME("No free constant to load the luminance parameters\n");
303             }
304         } else {
305             FIXME("No free constant found to load environemnt bump mapping matrix into the shader. texbem instruction will not apply bump mapping\n");
306         }
307
308         ps->numbumpenvmatconsts = cur + 1;
309     }
310
311     if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE] && pshader) {
312         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
313         /* If there are 2 constants left to use, use them to pass the sRGB correction values in. This way
314          * srgb write correction can be turned on and off dynamically without recompilation. Otherwise
315          * hardcode them. The drawback of hardcoding is that the shader needs recompilation to turn sRGB
316          * off again
317          */
318         if(max_constantsF + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF) && FALSE) {
319             /* The idea is that if srgb is enabled, then disabled, the constant loading code
320              * can effectively disable sRGB correction by passing 1.0 and INF as the multiplication
321              * and comparison constants. If it disables it that way, the shader won't be recompiled
322              * and the code will stay in, so sRGB writing can be turned on again by setting the
323              * constants from the spec
324              */
325             ps_impl->srgb_mode_hardcoded = 0;
326             ps_impl->srgb_low_const = GL_LIMITS(pshader_constantsF) - extra_constants_needed;
327             ps_impl->srgb_cmp_const = GL_LIMITS(pshader_constantsF) - extra_constants_needed - 1;
328             shader_addline(buffer, "PARAM srgb_mul_low = program.env[%d];\n", ps_impl->srgb_low_const);
329             shader_addline(buffer, "PARAM srgb_comparison = program.env[%d];\n", ps_impl->srgb_cmp_const);
330         } else {
331             shader_addline(buffer, "PARAM srgb_mul_low = {%f, %f, %f, 1.0};\n",
332                            srgb_mul_low, srgb_mul_low, srgb_mul_low);
333             shader_addline(buffer, "PARAM srgb_comparison =  {%f, %f, %f, %f};\n",
334                            srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
335             ps_impl->srgb_mode_hardcoded = 1;
336         }
337         /* These can be hardcoded, they do not cause any harm because no fragment will enter the high
338          * path if the comparison value is set to INF
339          */
340         shader_addline(buffer, "PARAM srgb_pow =  {%f, %f, %f, 1.0};\n",
341                        srgb_pow, srgb_pow, srgb_pow);
342         shader_addline(buffer, "PARAM srgb_mul_hi =  {%f, %f, %f, 1.0};\n",
343                        srgb_mul_high, srgb_mul_high, srgb_mul_high);
344         shader_addline(buffer, "PARAM srgb_sub_hi =  {%f, %f, %f, 0.0};\n",
345                        srgb_sub_high, srgb_sub_high, srgb_sub_high);
346         ps_impl->srgb_enabled = 1;
347     } else if(pshader) {
348         IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
349
350         /* Do not write any srgb fixup into the shader to save shader size and processing time.
351          * As a consequence, we can't toggle srgb write on without recompilation
352          */
353         ps_impl->srgb_enabled = 0;
354         ps_impl->srgb_mode_hardcoded = 1;
355     }
356
357     /* Load local constants using the program-local space,
358      * this avoids reloading them each time the shader is used
359      */
360     if(!This->baseShader.load_local_constsF) {
361         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
362             shader_addline(buffer, "PARAM C%u = program.local[%u];\n", lconst->idx,
363                            lconst->idx);
364         }
365     }
366
367     /* we use the array-based constants array if the local constants are marked for loading,
368      * because then we use indirect addressing, or when the local constant list is empty,
369      * because then we don't know if we're using indirect addressing or not. If we're hardcoding
370      * local constants do not declare the loaded constants as an array because ARB compilers usually
371      * do not optimize unused constants away
372      */
373     if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
374         /* Need to PARAM the environment parameters (constants) so we can use relative addressing */
375         shader_addline(buffer, "PARAM C[%d] = { program.env[0..%d] };\n",
376                     max_constantsF, max_constantsF - 1);
377     } else {
378         for(i = 0; i < max_constantsF; i++) {
379             if(!shader_constant_is_local(This, i)) {
380                 shader_addline(buffer, "PARAM C%d = program.env[%d];\n",i, i);
381             }
382         }
383     }
384 }
385
386 static const char * const shift_tab[] = {
387     "dummy",     /*  0 (none) */
388     "coefmul.x", /*  1 (x2)   */
389     "coefmul.y", /*  2 (x4)   */
390     "coefmul.z", /*  3 (x8)   */
391     "coefmul.w", /*  4 (x16)  */
392     "dummy",     /*  5 (x32)  */
393     "dummy",     /*  6 (x64)  */
394     "dummy",     /*  7 (x128) */
395     "dummy",     /*  8 (d256) */
396     "dummy",     /*  9 (d128) */
397     "dummy",     /* 10 (d64)  */
398     "dummy",     /* 11 (d32)  */
399     "coefdiv.w", /* 12 (d16)  */
400     "coefdiv.z", /* 13 (d8)   */
401     "coefdiv.y", /* 14 (d4)   */
402     "coefdiv.x"  /* 15 (d2)   */
403 };
404
405 static void shader_arb_get_write_mask(SHADER_OPCODE_ARG* arg, const DWORD param, char *write_mask) {
406     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) arg->shader;
407     char *ptr = write_mask;
408     char vshader = shader_is_vshader_version(This->baseShader.hex_version);
409
410     if(vshader && shader_get_regtype(param) == WINED3DSPR_ADDR) {
411         *ptr++ = '.';
412         *ptr++ = 'x';
413     } else if ((param & WINED3DSP_WRITEMASK_ALL) != WINED3DSP_WRITEMASK_ALL) {
414         *ptr++ = '.';
415         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
416         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
417         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
418         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
419     }
420
421     *ptr = '\0';
422 }
423
424 static void shader_arb_get_swizzle(const DWORD param, BOOL fixup, char *swizzle_str) {
425     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
426      * but addressed as "rgba". To fix this we need to swap the register's x
427      * and z components. */
428     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
429     char *ptr = swizzle_str;
430
431     /* swizzle bits fields: wwzzyyxx */
432     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
433     DWORD swizzle_x = swizzle & 0x03;
434     DWORD swizzle_y = (swizzle >> 2) & 0x03;
435     DWORD swizzle_z = (swizzle >> 4) & 0x03;
436     DWORD swizzle_w = (swizzle >> 6) & 0x03;
437
438     /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
439      * generate a swizzle string. Unless we need to our own swizzling. */
440     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) != swizzle || fixup) {
441         *ptr++ = '.';
442         if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
443             *ptr++ = swizzle_chars[swizzle_x];
444         } else {
445             *ptr++ = swizzle_chars[swizzle_x];
446             *ptr++ = swizzle_chars[swizzle_y];
447             *ptr++ = swizzle_chars[swizzle_z];
448             *ptr++ = swizzle_chars[swizzle_w];
449         }
450     }
451
452     *ptr = '\0';
453 }
454
455 static void pshader_get_register_name(IWineD3DBaseShader* iface,
456     const DWORD param, char* regstr) {
457
458     DWORD reg = param & WINED3DSP_REGNUM_MASK;
459     DWORD regtype = shader_get_regtype(param);
460     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
461
462     switch (regtype) {
463     case WINED3DSPR_TEMP:
464         sprintf(regstr, "R%u", reg);
465     break;
466     case WINED3DSPR_INPUT:
467         if (reg==0) {
468             strcpy(regstr, "fragment.color.primary");
469         } else {
470             strcpy(regstr, "fragment.color.secondary");
471         }
472     break;
473     case WINED3DSPR_CONST:
474         if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
475             sprintf(regstr, "C[%u]", reg);
476         } else {
477             sprintf(regstr, "C%u", reg);
478         }
479     break;
480     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
481         sprintf(regstr,"T%u", reg);
482     break;
483     case WINED3DSPR_COLOROUT:
484         if (reg == 0)
485             sprintf(regstr, "TMP_COLOR");
486         else {
487             /* TODO: See GL_ARB_draw_buffers */
488             FIXME("Unsupported write to render target %u\n", reg);
489             sprintf(regstr, "unsupported_register");
490         }
491     break;
492     case WINED3DSPR_DEPTHOUT:
493         sprintf(regstr, "result.depth");
494     break;
495     case WINED3DSPR_ATTROUT:
496         sprintf(regstr, "oD[%u]", reg);
497     break;
498     case WINED3DSPR_TEXCRDOUT:
499         sprintf(regstr, "oT[%u]", reg);
500     break;
501     default:
502         FIXME("Unhandled register name Type(%d)\n", regtype);
503         sprintf(regstr, "unrecognized_register");
504     break;
505     }
506 }
507
508 /* TODO: merge with pixel shader */
509 static void vshader_program_add_param(SHADER_OPCODE_ARG *arg, const DWORD param, BOOL is_input, char *hwLine) {
510
511   IWineD3DVertexShaderImpl* This = (IWineD3DVertexShaderImpl*) arg->shader;
512
513   /* oPos, oFog and oPts in D3D */
514   static const char * const hwrastout_reg_names[] = { "TMP_OUT", "result.fogcoord", "result.pointsize" };
515
516   DWORD reg = param & WINED3DSP_REGNUM_MASK;
517   DWORD regtype = shader_get_regtype(param);
518   char  tmpReg[255];
519   BOOL is_color = FALSE;
520
521   if ((param & WINED3DSP_SRCMOD_MASK) == WINED3DSPSM_NEG) {
522       strcat(hwLine, " -");
523   } else {
524       strcat(hwLine, " ");
525   }
526
527   switch (regtype) {
528   case WINED3DSPR_TEMP:
529     sprintf(tmpReg, "R%u", reg);
530     strcat(hwLine, tmpReg);
531     break;
532   case WINED3DSPR_INPUT:
533
534     if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
535         is_color = TRUE;
536
537     sprintf(tmpReg, "vertex.attrib[%u]", reg);
538     strcat(hwLine, tmpReg);
539     break;
540   case WINED3DSPR_CONST:
541       if(param & WINED3DSHADER_ADDRMODE_RELATIVE) {
542           if(reg >= This->rel_offset) {
543               sprintf(tmpReg, "C[A0.x + %u]", reg - This->rel_offset);
544           } else {
545               sprintf(tmpReg, "C[A0.x - %u]", -reg + This->rel_offset);
546           }
547       } else {
548           if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
549               sprintf(tmpReg, "C[%u]", reg);
550           } else {
551               sprintf(tmpReg, "C%u", reg);
552           }
553       }
554     strcat(hwLine, tmpReg);
555     break;
556   case WINED3DSPR_ADDR: /*case D3DSPR_TEXTURE:*/
557     sprintf(tmpReg, "A%u", reg);
558     strcat(hwLine, tmpReg);
559     break;
560   case WINED3DSPR_RASTOUT:
561     sprintf(tmpReg, "%s", hwrastout_reg_names[reg]);
562     strcat(hwLine, tmpReg);
563     break;
564   case WINED3DSPR_ATTROUT:
565     if (reg==0) {
566        strcat(hwLine, "result.color.primary");
567     } else {
568        strcat(hwLine, "result.color.secondary");
569     }
570     break;
571   case WINED3DSPR_TEXCRDOUT:
572     sprintf(tmpReg, "result.texcoord[%u]", reg);
573     strcat(hwLine, tmpReg);
574     break;
575   default:
576     FIXME("Unknown reg type %d %d\n", regtype, reg);
577     strcat(hwLine, "unrecognized_register");
578     break;
579   }
580
581   if (!is_input) {
582     char write_mask[6];
583     shader_arb_get_write_mask(arg, param, write_mask);
584     strcat(hwLine, write_mask);
585   } else {
586     char swizzle[6];
587     shader_arb_get_swizzle(param, is_color, swizzle);
588     strcat(hwLine, swizzle);
589   }
590 }
591
592 static void shader_hw_sample(SHADER_OPCODE_ARG* arg, DWORD sampler_idx, const char *dst_str, const char *coord_reg, BOOL projected, BOOL bias) {
593     SHADER_BUFFER* buffer = arg->buffer;
594     DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
595     const char *tex_type;
596
597     switch(sampler_type) {
598         case WINED3DSTT_1D:
599             tex_type = "1D";
600             break;
601
602         case WINED3DSTT_2D:
603         {
604             IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) arg->shader;
605             IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
606             if(device->stateBlock->textures[sampler_idx] &&
607                IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
608                 tex_type = "RECT";
609             } else {
610                 tex_type = "2D";
611             }
612             break;
613         }
614
615         case WINED3DSTT_VOLUME:
616             tex_type = "3D";
617             break;
618
619         case WINED3DSTT_CUBE:
620             tex_type = "CUBE";
621             break;
622
623         default:
624             ERR("Unexpected texture type %d\n", sampler_type);
625             tex_type = "";
626     }
627
628     if (bias) {
629         /* Shouldn't be possible, but let's check for it */
630         if(projected) FIXME("Biased and Projected texture sampling\n");
631         /* TXB takes the 4th component of the source vector automatically, as d3d. Nothing more to do */
632         shader_addline(buffer, "TXB %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
633     } else if (projected) {
634         shader_addline(buffer, "TXP %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
635     } else {
636         shader_addline(buffer, "TEX %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
637     }
638 }
639
640 static void shader_arb_color_correction(SHADER_OPCODE_ARG* arg) {
641     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
642     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) shader->baseShader.device;
643     WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
644     WINED3DFORMAT fmt;
645     WINED3DFORMAT conversion_group;
646     IWineD3DBaseTextureImpl *texture;
647     UINT i;
648     BOOL recorded = FALSE;
649     DWORD sampler_idx;
650     DWORD hex_version = shader->baseShader.hex_version;
651     char reg[256];
652     char writemask[6];
653
654     switch(arg->opcode->opcode) {
655         case WINED3DSIO_TEX:
656             if (hex_version < WINED3DPS_VERSION(2,0)) {
657                 sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
658             } else {
659                 sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
660             }
661             break;
662
663         case WINED3DSIO_TEXLDL:
664             FIXME("Add color fixup for vertex texture WINED3DSIO_TEXLDL\n");
665             return;
666
667         case WINED3DSIO_TEXDP3TEX:
668         case WINED3DSIO_TEXM3x3TEX:
669         case WINED3DSIO_TEXM3x3SPEC:
670         case WINED3DSIO_TEXM3x3VSPEC:
671         case WINED3DSIO_TEXBEM:
672         case WINED3DSIO_TEXREG2AR:
673         case WINED3DSIO_TEXREG2GB:
674         case WINED3DSIO_TEXREG2RGB:
675             sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
676             break;
677
678         default:
679             /* Not a texture sampling instruction, nothing to do */
680             return;
681     };
682
683     texture = (IWineD3DBaseTextureImpl *) deviceImpl->stateBlock->textures[sampler_idx];
684     if(texture) {
685         fmt = texture->resource.format;
686         conversion_group = texture->baseTexture.shader_conversion_group;
687     } else {
688         fmt = WINED3DFMT_UNKNOWN;
689         conversion_group = WINED3DFMT_UNKNOWN;
690     }
691
692     /* before doing anything, record the sampler with the format in the format conversion list,
693      * but check if it's not there already
694      */
695     for(i = 0; i < shader->baseShader.num_sampled_samplers; i++) {
696         if(shader->baseShader.sampled_samplers[i] == sampler_idx) {
697             recorded = TRUE;
698         }
699     }
700     if(!recorded) {
701         shader->baseShader.sampled_samplers[shader->baseShader.num_sampled_samplers] = sampler_idx;
702         shader->baseShader.num_sampled_samplers++;
703         shader->baseShader.sampled_format[sampler_idx] = conversion_group;
704     }
705
706     pshader_get_register_name(arg->shader, arg->dst, reg);
707     shader_arb_get_write_mask(arg, arg->dst, writemask);
708     if(strlen(writemask) == 0) strcpy(writemask, ".xyzw");
709
710     switch(fmt) {
711         case WINED3DFMT_V8U8:
712         case WINED3DFMT_V16U16:
713             if(GL_SUPPORT(NV_TEXTURE_SHADER) ||
714                (GL_SUPPORT(ATI_ENVMAP_BUMPMAP) && fmt == WINED3DFMT_V8U8)) {
715 #if 0
716                 /* The 3rd channel returns 1.0 in d3d, but 0.0 in gl. Fix this while we're at it :-)
717                  * disabled until an application that needs it is found because it causes unneeded
718                  * shader recompilation in some game
719                  */
720                 if(strlen(writemask) >= 4) {
721                     shader_addline(arg->buffer, "MOV %s.%c, one.z;\n", reg, writemask[3]);
722                 }
723 #endif
724             } else {
725                 /* Correct the sign, but leave the blue as it is - it was loaded correctly already
726                  * ARB shaders are a bit picky wrt writemasks and swizzles. If we're free to scale
727                  * all registers, do so, this saves an instruction.
728                  */
729                 if(strlen(writemask) >= 5) {
730                     shader_addline(arg->buffer, "MAD %s, %s, coefmul.x, -one;\n", reg, reg);
731                 } else if(strlen(writemask) >= 3) {
732                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
733                                    reg, writemask[1],
734                                    reg, writemask[1]);
735                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
736                                    reg, writemask[2],
737                                    reg, writemask[2]);
738                 } else if(strlen(writemask) == 2) {
739                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n", reg, writemask[1],
740                                    reg, writemask[1]);
741                 }
742             }
743             break;
744
745         case WINED3DFMT_X8L8V8U8:
746             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
747                 /* Red and blue are the signed channels, fix them up; Blue(=L) is correct already,
748                  * and a(X) is always 1.0. Cannot do a full conversion due to L(blue)
749                  */
750                 if(strlen(writemask) >= 3) {
751                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
752                                    reg, writemask[1],
753                                    reg, writemask[1]);
754                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
755                                    reg, writemask[2],
756                                    reg, writemask[2]);
757                 } else if(strlen(writemask) == 2) {
758                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
759                                    reg, writemask[1],
760                                    reg, writemask[1]);
761                 }
762             }
763             break;
764
765         case WINED3DFMT_L6V5U5:
766             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
767                 if(strlen(writemask) >= 4) {
768                     /* Swap y and z (U and L), and do a sign conversion on x and the new y(V and U) */
769                     shader_addline(arg->buffer, "MOV TMP.g, %s.%c;\n",
770                                    reg, writemask[2]);
771                     shader_addline(arg->buffer, "MAD %s.%c%c, %s.%c%c, coefmul.x, -one;\n",
772                                    reg, writemask[1], writemask[1],
773                                    reg, writemask[1], writemask[3]);
774                     shader_addline(arg->buffer, "MOV %s.%c, TMP.g;\n", reg,
775                                    writemask[3]);
776                 } else if(strlen(writemask) == 3) {
777                     /* This is bad: We have VL, but we need VU */
778                     FIXME("2 components sampled from a converted L6V5U5 texture\n");
779                 } else {
780                     shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
781                                    reg, writemask[1],
782                                    reg, writemask[1]);
783                 }
784             }
785             break;
786
787         case WINED3DFMT_Q8W8V8U8:
788             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
789                 /* Correct the sign in all channels */
790                 switch(strlen(writemask)) {
791                     case 4:
792                         shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
793                                        reg, writemask[3],
794                                        reg, writemask[3]);
795                         /* drop through */
796                     case 3:
797                         shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
798                                        reg, writemask[2],
799                                        reg, writemask[2]);
800                         /* drop through */
801                     case 2:
802                         shader_addline(arg->buffer, "MAD %s.%c, %s.%c, coefmul.x, -one;\n",
803                                        reg, writemask[1],
804                                        reg, writemask[1]);
805                         break;
806
807                         /* Should not occur, since it's at minimum '.' and a letter */
808                     case 1:
809                         ERR("Unexpected writemask: \"%s\"\n", writemask);
810                         break;
811
812                     case 5:
813                     default:
814                         shader_addline(arg->buffer, "MAD %s, %s, coefmul.x, -one;\n", reg, reg);
815                 }
816             }
817             break;
818
819             /* stupid compiler */
820         default:
821             break;
822     }
823 }
824
825
826 static void pshader_gen_input_modifier_line (
827     IWineD3DBaseShader *iface,
828     SHADER_BUFFER* buffer,
829     const DWORD instr,
830     int tmpreg,
831     char *outregstr) {
832
833     /* Generate a line that does the input modifier computation and return the input register to use */
834     char regstr[256];
835     char swzstr[20];
836     int insert_line;
837
838     /* Assume a new line will be added */
839     insert_line = 1;
840
841     /* Get register name */
842     pshader_get_register_name(iface, instr, regstr);
843     shader_arb_get_swizzle(instr, FALSE, swzstr);
844
845     switch (instr & WINED3DSP_SRCMOD_MASK) {
846     case WINED3DSPSM_NONE:
847         sprintf(outregstr, "%s%s", regstr, swzstr);
848         insert_line = 0;
849         break;
850     case WINED3DSPSM_NEG:
851         sprintf(outregstr, "-%s%s", regstr, swzstr);
852         insert_line = 0;
853         break;
854     case WINED3DSPSM_BIAS:
855         shader_addline(buffer, "ADD T%c, %s, -coefdiv.x;\n", 'A' + tmpreg, regstr);
856         break;
857     case WINED3DSPSM_BIASNEG:
858         shader_addline(buffer, "ADD T%c, -%s, coefdiv.x;\n", 'A' + tmpreg, regstr);
859         break;
860     case WINED3DSPSM_SIGN:
861         shader_addline(buffer, "MAD T%c, %s, coefmul.x, -one.x;\n", 'A' + tmpreg, regstr);
862         break;
863     case WINED3DSPSM_SIGNNEG:
864         shader_addline(buffer, "MAD T%c, %s, -coefmul.x, one.x;\n", 'A' + tmpreg, regstr);
865         break;
866     case WINED3DSPSM_COMP:
867         shader_addline(buffer, "SUB T%c, one.x, %s;\n", 'A' + tmpreg, regstr);
868         break;
869     case WINED3DSPSM_X2:
870         shader_addline(buffer, "ADD T%c, %s, %s;\n", 'A' + tmpreg, regstr, regstr);
871         break;
872     case WINED3DSPSM_X2NEG:
873         shader_addline(buffer, "ADD T%c, -%s, -%s;\n", 'A' + tmpreg, regstr, regstr);
874         break;
875     case WINED3DSPSM_DZ:
876         shader_addline(buffer, "RCP T%c, %s.z;\n", 'A' + tmpreg, regstr);
877         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
878         break;
879     case WINED3DSPSM_DW:
880         shader_addline(buffer, "RCP T%c, %s.w;\n", 'A' + tmpreg, regstr);
881         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
882         break;
883     default:
884         sprintf(outregstr, "%s%s", regstr, swzstr);
885         insert_line = 0;
886     }
887
888     /* Return modified or original register, with swizzle */
889     if (insert_line)
890         sprintf(outregstr, "T%c%s", 'A' + tmpreg, swzstr);
891 }
892
893 static inline void pshader_gen_output_modifier_line(
894     SHADER_BUFFER* buffer,
895     int saturate,
896     char *write_mask,
897     int shift,
898     char *regstr) {
899
900     /* Generate a line that does the output modifier computation */
901     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", saturate ? "_SAT" : "",
902         regstr, write_mask, regstr, shift_tab[shift]);
903 }
904
905 void pshader_hw_bem(SHADER_OPCODE_ARG* arg) {
906     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
907
908     SHADER_BUFFER* buffer = arg->buffer;
909     char dst_name[50];
910     char src_name[2][50];
911     char dst_wmask[20];
912     DWORD sampler_code = arg->dst & WINED3DSP_REGNUM_MASK;
913     BOOL has_bumpmat = FALSE;
914     int i;
915
916     for(i = 0; i < This->numbumpenvmatconsts; i++) {
917         if(This->bumpenvmatconst[i].const_num != -1 && This->bumpenvmatconst[i].texunit == sampler_code) {
918             has_bumpmat = TRUE;
919             break;
920         }
921     }
922
923     pshader_get_register_name(arg->shader, arg->dst, dst_name);
924     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
925     strcat(dst_name, dst_wmask);
926
927     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
928     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
929
930     if(has_bumpmat) {
931         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
932         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", sampler_code);
933         shader_addline(buffer, "DP3 TMP.r, TMP2, %s;\n", src_name[1]);
934         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", sampler_code);
935         shader_addline(buffer, "DP3 TMP.g, TMP2, %s;\n", src_name[1]);
936
937         shader_addline(buffer, "ADD %s, %s, TMP;\n", dst_name, src_name[0]);
938     } else {
939         shader_addline(buffer, "MOV %s, %s;\n", dst_name, src_name[0]);
940     }
941 }
942
943 void pshader_hw_cnd(SHADER_OPCODE_ARG* arg) {
944
945     IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
946     SHADER_BUFFER* buffer = arg->buffer;
947     char dst_wmask[20];
948     char dst_name[50];
949     char src_name[3][50];
950     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
951     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
952
953     /* FIXME: support output modifiers */
954
955     /* Handle output register */
956     pshader_get_register_name(arg->shader, arg->dst, dst_name);
957     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
958
959     /* Generate input register names (with modifiers) */
960     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
961     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
962     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
963
964     /* The coissue flag changes the semantic of the cnd instruction in <= 1.3 shaders */
965     if (shader->baseShader.hex_version <= WINED3DPS_VERSION(1, 3) &&
966         arg->opcode_token & WINED3DSI_COISSUE) {
967         shader_addline(buffer, "MOV%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1]);
968     } else {
969         shader_addline(buffer, "ADD TMP, -%s, coefdiv.x;\n", src_name[0]);
970         shader_addline(buffer, "CMP%s %s%s, TMP, %s, %s;\n",
971                                 sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1], src_name[2]);
972     }
973     if (shift != 0)
974         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
975 }
976
977 void pshader_hw_cmp(SHADER_OPCODE_ARG* arg) {
978
979     SHADER_BUFFER* buffer = arg->buffer;
980     char dst_wmask[20];
981     char dst_name[50];
982     char src_name[3][50];
983     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
984     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
985
986     /* FIXME: support output modifiers */
987
988     /* Handle output register */
989     pshader_get_register_name(arg->shader, arg->dst, dst_name);
990     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
991
992     /* Generate input register names (with modifiers) */
993     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
994     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
995     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
996
997     shader_addline(buffer, "CMP%s %s%s, %s, %s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
998                    src_name[0], src_name[2], src_name[1]);
999
1000     if (shift != 0)
1001         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1002 }
1003
1004 /** Process the WINED3DSIO_DP2ADD instruction in ARB.
1005  * dst = dot2(src0, src1) + src2 */
1006 void pshader_hw_dp2add(SHADER_OPCODE_ARG* arg) {
1007     SHADER_BUFFER* buffer = arg->buffer;
1008     char dst_wmask[20];
1009     char dst_name[50];
1010     char src_name[3][50];
1011     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1012     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1013
1014     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1015     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1016
1017     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name[0]);
1018     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[1], 1, src_name[1]);
1019     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[2], 2, src_name[2]);
1020
1021     /* Emulate a DP2 with a DP3 and 0.0 */
1022     shader_addline(buffer, "MOV TMP, %s;\n", src_name[0]);
1023     shader_addline(buffer, "MOV TMP.z, 0.0;\n");
1024     shader_addline(buffer, "DP3 TMP2, TMP, %s;\n", src_name[1]);
1025     shader_addline(buffer, "ADD%s %s%s, TMP2, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[2]);
1026
1027     if (shift != 0)
1028         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1029 }
1030
1031 /* Map the opcode 1-to-1 to the GL code */
1032 void pshader_hw_map2gl(SHADER_OPCODE_ARG* arg) {
1033
1034      CONST SHADER_OPCODE* curOpcode = arg->opcode;
1035      SHADER_BUFFER* buffer = arg->buffer;
1036      DWORD dst = arg->dst;
1037      DWORD* src = arg->src;
1038
1039      unsigned int i;
1040      char tmpLine[256];
1041
1042      /* Output token related */
1043      char output_rname[256];
1044      char output_wmask[20];
1045      BOOL saturate = FALSE;
1046      BOOL centroid = FALSE;
1047      BOOL partialprecision = FALSE;
1048      DWORD shift;
1049
1050      strcpy(tmpLine, curOpcode->glname);
1051
1052      /* Process modifiers */
1053      if (0 != (dst & WINED3DSP_DSTMOD_MASK)) {
1054          DWORD mask = dst & WINED3DSP_DSTMOD_MASK;
1055
1056          saturate = mask & WINED3DSPDM_SATURATE;
1057          centroid = mask & WINED3DSPDM_MSAMPCENTROID;
1058          partialprecision = mask & WINED3DSPDM_PARTIALPRECISION;
1059          mask &= ~(WINED3DSPDM_MSAMPCENTROID | WINED3DSPDM_PARTIALPRECISION | WINED3DSPDM_SATURATE);
1060          if (mask)
1061             FIXME("Unrecognized modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
1062
1063          if (centroid)
1064              FIXME("Unhandled modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
1065      }
1066      shift = (dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1067
1068       /* Generate input and output registers */
1069       if (curOpcode->num_params > 0) {
1070           char operands[4][100];
1071
1072           /* Generate input register names (with modifiers) */
1073           for (i = 1; i < curOpcode->num_params; ++i)
1074               pshader_gen_input_modifier_line(arg->shader, buffer, src[i-1], i-1, operands[i]);
1075
1076           /* Handle output register */
1077           pshader_get_register_name(arg->shader, dst, output_rname);
1078           strcpy(operands[0], output_rname);
1079           shader_arb_get_write_mask(arg, dst, output_wmask);
1080           strcat(operands[0], output_wmask);
1081
1082           if (saturate && (shift == 0))
1083              strcat(tmpLine, "_SAT");
1084           strcat(tmpLine, " ");
1085           strcat(tmpLine, operands[0]);
1086           for (i = 1; i < curOpcode->num_params; i++) {
1087               strcat(tmpLine, ", ");
1088               strcat(tmpLine, operands[i]);
1089           }
1090           strcat(tmpLine,";\n");
1091           shader_addline(buffer, tmpLine);
1092
1093           /* A shift requires another line. */
1094           if (shift != 0)
1095               pshader_gen_output_modifier_line(buffer, saturate, output_wmask, shift, output_rname);
1096       }
1097 }
1098
1099 void pshader_hw_texkill(SHADER_OPCODE_ARG* arg) {
1100     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1101     DWORD hex_version = This->baseShader.hex_version;
1102     SHADER_BUFFER* buffer = arg->buffer;
1103     char reg_dest[40];
1104
1105     /* No swizzles are allowed in d3d's texkill. PS 1.x ignores the 4th component as documented,
1106      * but >= 2.0 honors it(undocumented, but tested by the d3d9 testsuit)
1107      */
1108     pshader_get_register_name(arg->shader, arg->dst, reg_dest);
1109
1110     if(hex_version >= WINED3DPS_VERSION(2,0)) {
1111         /* The arb backend doesn't claim ps 2.0 support, but try to eat what the app feeds to us */
1112         shader_addline(buffer, "KIL %s;\n", reg_dest);
1113     } else {
1114         /* ARB fp doesn't like swizzles on the parameter of the KIL instruction. To mask the 4th component,
1115          * copy the register into our general purpose TMP variable, overwrite .w and pass TMP to KIL
1116          */
1117         shader_addline(buffer, "MOV TMP, %s;\n", reg_dest);
1118         shader_addline(buffer, "MOV TMP.w, one.w;\n");
1119         shader_addline(buffer, "KIL TMP;\n");
1120     }
1121 }
1122
1123 void pshader_hw_tex(SHADER_OPCODE_ARG* arg) {
1124     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1125     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1126
1127     DWORD dst = arg->dst;
1128     DWORD* src = arg->src;
1129     SHADER_BUFFER* buffer = arg->buffer;
1130     DWORD hex_version = This->baseShader.hex_version;
1131     BOOL projected = FALSE, bias = FALSE;
1132
1133     char reg_dest[40];
1134     char reg_coord[40];
1135     DWORD reg_dest_code;
1136     DWORD reg_sampler_code;
1137
1138     /* All versions have a destination register */
1139     reg_dest_code = dst & WINED3DSP_REGNUM_MASK;
1140     pshader_get_register_name(arg->shader, dst, reg_dest);
1141
1142     /* 1.0-1.3: Use destination register as coordinate source.
1143        1.4+: Use provided coordinate source register. */
1144    if (hex_version < WINED3DPS_VERSION(1,4))
1145       strcpy(reg_coord, reg_dest);
1146    else
1147       pshader_gen_input_modifier_line(arg->shader, buffer, src[0], 0, reg_coord);
1148
1149   /* 1.0-1.4: Use destination register number as texture code.
1150      2.0+: Use provided sampler number as texure code. */
1151   if (hex_version < WINED3DPS_VERSION(2,0))
1152      reg_sampler_code = reg_dest_code;
1153   else
1154      reg_sampler_code = src[1] & WINED3DSP_REGNUM_MASK;
1155
1156   /* projection flag:
1157    * 1.1, 1.2, 1.3: Use WINED3DTSS_TEXTURETRANSFORMFLAGS
1158    * 1.4: Use WINED3DSPSM_DZ or WINED3DSPSM_DW on src[0]
1159    * 2.0+: Use WINED3DSI_TEXLD_PROJECT on the opcode
1160    */
1161   if(hex_version < WINED3DPS_VERSION(1,4)) {
1162       DWORD flags = 0;
1163       if(reg_sampler_code < MAX_TEXTURES) {
1164         flags = deviceImpl->stateBlock->textureState[reg_sampler_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1165       }
1166       if (flags & WINED3DTTFF_PROJECTED) {
1167           projected = TRUE;
1168       }
1169   } else if(hex_version < WINED3DPS_VERSION(2,0)) {
1170       DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
1171       if (src_mod == WINED3DSPSM_DZ) {
1172           projected = TRUE;
1173       } else if(src_mod == WINED3DSPSM_DW) {
1174           projected = TRUE;
1175       }
1176   } else {
1177       if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
1178           projected = TRUE;
1179       }
1180       if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
1181           bias = TRUE;
1182       }
1183   }
1184   shader_hw_sample(arg, reg_sampler_code, reg_dest, reg_coord, projected, bias);
1185 }
1186
1187 void pshader_hw_texcoord(SHADER_OPCODE_ARG* arg) {
1188
1189     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1190     DWORD dst = arg->dst;
1191     SHADER_BUFFER* buffer = arg->buffer;
1192     DWORD hex_version = This->baseShader.hex_version;
1193
1194     char tmp[20];
1195     shader_arb_get_write_mask(arg, dst, tmp);
1196     if (hex_version != WINED3DPS_VERSION(1,4)) {
1197         DWORD reg = dst & WINED3DSP_REGNUM_MASK;
1198         shader_addline(buffer, "MOV_SAT T%u%s, fragment.texcoord[%u];\n", reg, tmp, reg);
1199     } else {
1200         DWORD reg1 = dst & WINED3DSP_REGNUM_MASK;
1201         char reg_src[40];
1202
1203         pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, reg_src);
1204         shader_addline(buffer, "MOV R%u%s, %s;\n", reg1, tmp, reg_src);
1205    }
1206 }
1207
1208 void pshader_hw_texreg2ar(SHADER_OPCODE_ARG* arg) {
1209
1210      SHADER_BUFFER* buffer = arg->buffer;
1211      IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1212      IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1213      DWORD flags;
1214
1215      DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1216      char dst_str[8];
1217      char src_str[50];
1218
1219      sprintf(dst_str, "T%u", reg1);
1220      pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1221      shader_addline(buffer, "MOV TMP.r, %s.a;\n", src_str);
1222      shader_addline(buffer, "MOV TMP.g, %s.r;\n", src_str);
1223      flags = reg1 < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg1][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1224      shader_hw_sample(arg, reg1, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1225 }
1226
1227 void pshader_hw_texreg2gb(SHADER_OPCODE_ARG* arg) {
1228
1229      SHADER_BUFFER* buffer = arg->buffer;
1230
1231      DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1232      char dst_str[8];
1233      char src_str[50];
1234
1235      sprintf(dst_str, "T%u", reg1);
1236      pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1237      shader_addline(buffer, "MOV TMP.r, %s.g;\n", src_str);
1238      shader_addline(buffer, "MOV TMP.g, %s.b;\n", src_str);
1239      shader_hw_sample(arg, reg1, dst_str, "TMP", FALSE, FALSE);
1240 }
1241
1242 void pshader_hw_texreg2rgb(SHADER_OPCODE_ARG* arg) {
1243
1244     SHADER_BUFFER* buffer = arg->buffer;
1245     DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
1246     char dst_str[8];
1247     char src_str[50];
1248
1249     sprintf(dst_str, "T%u", reg1);
1250     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_str);
1251     shader_hw_sample(arg, reg1, dst_str, src_str, FALSE, FALSE);
1252 }
1253
1254 void pshader_hw_texbem(SHADER_OPCODE_ARG* arg) {
1255     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1256     BOOL has_bumpmat = FALSE;
1257     BOOL has_luminance = FALSE;
1258     int i;
1259
1260     DWORD dst = arg->dst;
1261     DWORD src = arg->src[0] & WINED3DSP_REGNUM_MASK;
1262     SHADER_BUFFER* buffer = arg->buffer;
1263
1264     char reg_coord[40];
1265     DWORD reg_dest_code;
1266
1267     /* All versions have a destination register */
1268     reg_dest_code = dst & WINED3DSP_REGNUM_MASK;
1269     /* Can directly use the name because texbem is only valid for <= 1.3 shaders */
1270     pshader_get_register_name(arg->shader, dst, reg_coord);
1271
1272     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1273         if(This->bumpenvmatconst[i].const_num != -1 && reg_dest_code == This->bumpenvmatconst[i].texunit) {
1274             has_bumpmat = TRUE;
1275             break;
1276         }
1277     }
1278     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1279         if(This->luminanceconst[i].const_num != -1 && reg_dest_code == This->luminanceconst[i].texunit) {
1280             has_luminance = TRUE;
1281             break;
1282         }
1283     }
1284
1285     if(has_bumpmat) {
1286         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
1287
1288         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", reg_dest_code);
1289         shader_addline(buffer, "DP3 TMP.r, TMP2, T%u;\n", src);
1290         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", reg_dest_code);
1291         shader_addline(buffer, "DP3 TMP.g, TMP2, T%u;\n", src);
1292
1293         /* with projective textures, texbem only divides the static texture coord, not the displacement,
1294          * so we can't let the GL handle this.
1295          */
1296         if (((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS]
1297               & WINED3DTTFF_PROJECTED) {
1298             shader_addline(buffer, "RCP TMP2.a, %s.a;\n", reg_coord);
1299             shader_addline(buffer, "MUL TMP2.rg, %s, TMP2.a;\n", reg_coord);
1300             shader_addline(buffer, "ADD TMP.rg, TMP, TMP2;\n");
1301         } else {
1302             shader_addline(buffer, "ADD TMP.rg, TMP, %s;\n", reg_coord);
1303         }
1304
1305         shader_hw_sample(arg, reg_dest_code, reg_coord, "TMP", FALSE, FALSE);
1306
1307         if(arg->opcode->opcode == WINED3DSIO_TEXBEML && has_luminance) {
1308             shader_addline(buffer, "MAD TMP, T%u.z, luminance%d.x, luminance%d.y;\n",
1309                            src, reg_dest_code, reg_dest_code);
1310             shader_addline(buffer, "MUL %s, %s, TMP;\n", reg_coord, reg_coord);
1311         }
1312
1313     } else {
1314         DWORD tf;
1315         if(reg_dest_code < MAX_TEXTURES) {
1316             tf = ((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1317         } else {
1318             tf = 0;
1319         }
1320         /* Without a bump matrix loaded, just sample with the unmodified coordinates */
1321         shader_hw_sample(arg, reg_dest_code, reg_coord, reg_coord, tf & WINED3DTTFF_PROJECTED, FALSE);
1322     }
1323 }
1324
1325 void pshader_hw_texm3x2pad(SHADER_OPCODE_ARG* arg) {
1326
1327     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1328     SHADER_BUFFER* buffer = arg->buffer;
1329     char src0_name[50];
1330
1331     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1332     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", reg, src0_name);
1333 }
1334
1335 void pshader_hw_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1336
1337     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1338     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1339     DWORD flags;
1340     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1341     SHADER_BUFFER* buffer = arg->buffer;
1342     char dst_str[8];
1343     char src0_name[50];
1344
1345     sprintf(dst_str, "T%u", reg);
1346     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1347     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", reg, src0_name);
1348     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1349     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1350 }
1351
1352 void pshader_hw_texm3x3pad(SHADER_OPCODE_ARG* arg) {
1353
1354     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1355     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1356     SHADER_BUFFER* buffer = arg->buffer;
1357     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1358     char src0_name[50];
1359
1360     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1361     shader_addline(buffer, "DP3 TMP.%c, T%u, %s;\n", 'x' + current_state->current_row, reg, src0_name);
1362     current_state->texcoord_w[current_state->current_row++] = reg;
1363 }
1364
1365 void pshader_hw_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1366
1367     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1368     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1369     DWORD flags;
1370     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1371     SHADER_BUFFER* buffer = arg->buffer;
1372     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1373     char dst_str[8];
1374     char src0_name[50];
1375
1376     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1377     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1378
1379     /* Sample the texture using the calculated coordinates */
1380     sprintf(dst_str, "T%u", reg);
1381     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1382     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1383     current_state->current_row = 0;
1384 }
1385
1386 void pshader_hw_texm3x3vspec(SHADER_OPCODE_ARG* arg) {
1387
1388     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1389     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1390     DWORD flags;
1391     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1392     SHADER_BUFFER* buffer = arg->buffer;
1393     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1394     char dst_str[8];
1395     char src0_name[50];
1396
1397     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1398     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1399
1400     /* Construct the eye-ray vector from w coordinates */
1401     shader_addline(buffer, "MOV TMP2.x, fragment.texcoord[%u].w;\n", current_state->texcoord_w[0]);
1402     shader_addline(buffer, "MOV TMP2.y, fragment.texcoord[%u].w;\n", current_state->texcoord_w[1]);
1403     shader_addline(buffer, "MOV TMP2.z, fragment.texcoord[%u].w;\n", reg);
1404
1405     /* Calculate reflection vector
1406      */
1407     shader_addline(buffer, "DP3 TMP.w, TMP, TMP2;\n");
1408     /* The .w is ignored when sampling, so I can use TMP2.w to calculate dot(N, N) */
1409     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1410     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1411     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1412     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1413     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -TMP2;\n");
1414
1415     /* Sample the texture using the calculated coordinates */
1416     sprintf(dst_str, "T%u", reg);
1417     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1418     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1419     current_state->current_row = 0;
1420 }
1421
1422 void pshader_hw_texm3x3spec(SHADER_OPCODE_ARG* arg) {
1423
1424     IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1425     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1426     DWORD flags;
1427     DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1428     DWORD reg3 = arg->src[1] & WINED3DSP_REGNUM_MASK;
1429     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1430     SHADER_BUFFER* buffer = arg->buffer;
1431     char dst_str[8];
1432     char src0_name[50];
1433
1434     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0_name);
1435     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1436
1437     /* Calculate reflection vector.
1438      *
1439      *               dot(N, E)
1440      * TMP.xyz = 2 * --------- * N - E
1441      *               dot(N, N)
1442      *
1443      * Which normalizes the normal vector
1444      */
1445     shader_addline(buffer, "DP3 TMP.w, TMP, C[%u];\n", reg3);
1446     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1447     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1448     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1449     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1450     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -C[%u];\n", reg3);
1451
1452     /* Sample the texture using the calculated coordinates */
1453     sprintf(dst_str, "T%u", reg);
1454     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1455     shader_hw_sample(arg, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1456     current_state->current_row = 0;
1457 }
1458
1459 void pshader_hw_texdepth(SHADER_OPCODE_ARG* arg) {
1460     SHADER_BUFFER* buffer = arg->buffer;
1461     char dst_name[50];
1462
1463     /* texdepth has an implicit destination, the fragment depth value. It's only parameter,
1464      * which is essentially an input, is the destination register because it is the first
1465      * parameter. According to the msdn, this must be register r5, but let's keep it more flexible
1466      * here
1467      */
1468     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1469
1470     /* According to the msdn, the source register(must be r5) is unusable after
1471      * the texdepth instruction, so we're free to modify it
1472      */
1473     shader_addline(buffer, "MIN %s.g, %s.g, one.g;\n", dst_name, dst_name);
1474
1475     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1476      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1477      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1478      */
1479     shader_addline(buffer, "RCP %s.g, %s.g;\n", dst_name, dst_name);
1480     shader_addline(buffer, "MUL TMP.x, %s.r, %s.g;\n", dst_name, dst_name);
1481     shader_addline(buffer, "MIN TMP.x, TMP.x, one.r;\n");
1482     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1483 }
1484
1485 /** Process the WINED3DSIO_TEXDP3TEX instruction in ARB:
1486  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1487  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1488 void pshader_hw_texdp3tex(SHADER_OPCODE_ARG* arg) {
1489     SHADER_BUFFER* buffer = arg->buffer;
1490     DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
1491     char src0[50];
1492     char dst_str[8];
1493
1494     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1495     shader_addline(buffer, "MOV TMP, 0.0;\n");
1496     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", sampler_idx, src0);
1497
1498     sprintf(dst_str, "T%u", sampler_idx);
1499     shader_hw_sample(arg, sampler_idx, dst_str, "TMP", FALSE /* Only one coord, can't be projected */, FALSE);
1500 }
1501
1502 /** Process the WINED3DSIO_TEXDP3 instruction in ARB:
1503  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1504 void pshader_hw_texdp3(SHADER_OPCODE_ARG* arg) {
1505     char src0[50];
1506     char dst_str[50];
1507     char dst_mask[6];
1508     DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1509     SHADER_BUFFER* buffer = arg->buffer;
1510
1511     /* Handle output register */
1512     pshader_get_register_name(arg->shader, arg->dst, dst_str);
1513     shader_arb_get_write_mask(arg, arg->dst, dst_mask);
1514
1515     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1516     shader_addline(buffer, "DP3 %s%s, T%u, %s;\n", dst_str, dst_mask, dstreg, src0);
1517
1518     /* TODO: Handle output modifiers */
1519 }
1520
1521 /** Process the WINED3DSIO_TEXM3X3 instruction in ARB
1522  * Perform the 3rd row of a 3x3 matrix multiply */
1523 void pshader_hw_texm3x3(SHADER_OPCODE_ARG* arg) {
1524     SHADER_BUFFER* buffer = arg->buffer;
1525     char dst_str[50];
1526     char dst_mask[6];
1527     char src0[50];
1528     DWORD dst_reg = arg->dst & WINED3DSP_REGNUM_MASK;
1529
1530     pshader_get_register_name(arg->shader, arg->dst, dst_str);
1531     shader_arb_get_write_mask(arg, arg->dst, dst_mask);
1532
1533     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1534     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", dst_reg, src0);
1535     shader_addline(buffer, "MOV %s%s, TMP;\n", dst_str, dst_mask);
1536
1537     /* TODO: Handle output modifiers */
1538 }
1539
1540 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in ARB:
1541  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1542  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1543  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1544  */
1545 void pshader_hw_texm3x2depth(SHADER_OPCODE_ARG* arg) {
1546     SHADER_BUFFER* buffer = arg->buffer;
1547     DWORD dst_reg = arg->dst & WINED3DSP_REGNUM_MASK;
1548     char src0[50];
1549
1550     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src0);
1551     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", dst_reg, src0);
1552
1553     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1554      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1555      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1556      */
1557     shader_addline(buffer, "RCP TMP.y, TMP.y;\n");
1558     shader_addline(buffer, "MUL TMP.x, TMP.x, TMP.y;\n");
1559     shader_addline(buffer, "MIN TMP.x, TMP.x, one.r;\n");
1560     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1561 }
1562
1563 /** Handles transforming all WINED3DSIO_M?x? opcodes for
1564     Vertex/Pixel shaders to ARB_vertex_program codes */
1565 void shader_hw_mnxn(SHADER_OPCODE_ARG* arg) {
1566
1567     int i;
1568     int nComponents = 0;
1569     SHADER_OPCODE_ARG tmpArg;
1570
1571     memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));
1572
1573     /* Set constants for the temporary argument */
1574     tmpArg.shader      = arg->shader;
1575     tmpArg.buffer      = arg->buffer;
1576     tmpArg.src[0]      = arg->src[0];
1577     tmpArg.src_addr[0] = arg->src_addr[0];
1578     tmpArg.src_addr[1] = arg->src_addr[1];
1579     tmpArg.reg_maps = arg->reg_maps;
1580
1581     switch(arg->opcode->opcode) {
1582     case WINED3DSIO_M4x4:
1583         nComponents = 4;
1584         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1585         break;
1586     case WINED3DSIO_M4x3:
1587         nComponents = 3;
1588         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1589         break;
1590     case WINED3DSIO_M3x4:
1591         nComponents = 4;
1592         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1593         break;
1594     case WINED3DSIO_M3x3:
1595         nComponents = 3;
1596         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1597         break;
1598     case WINED3DSIO_M3x2:
1599         nComponents = 2;
1600         tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1601         break;
1602     default:
1603         break;
1604     }
1605
1606     for (i = 0; i < nComponents; i++) {
1607         tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1608         tmpArg.src[1] = arg->src[1]+i;
1609         vshader_hw_map2gl(&tmpArg);
1610     }
1611 }
1612
1613 void vshader_hw_rsq_rcp(SHADER_OPCODE_ARG* arg) {
1614     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1615     SHADER_BUFFER* buffer = arg->buffer;
1616     DWORD dst = arg->dst;
1617     DWORD src = arg->src[0];
1618     DWORD swizzle = (src & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
1619
1620     char tmpLine[256];
1621
1622     strcpy(tmpLine, curOpcode->glname); /* Opcode */
1623     vshader_program_add_param(arg, dst, FALSE, tmpLine); /* Destination */
1624     strcat(tmpLine, ",");
1625     vshader_program_add_param(arg, src, TRUE, tmpLine);
1626     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) == swizzle) {
1627         /* Dx sdk says .x is used if no swizzle is given, but our test shows that
1628          * .w is used
1629          */
1630         strcat(tmpLine, ".w");
1631     }
1632
1633     shader_addline(buffer, "%s;\n", tmpLine);
1634 }
1635
1636 void shader_hw_nrm(SHADER_OPCODE_ARG* arg) {
1637     SHADER_BUFFER* buffer = arg->buffer;
1638     char dst_name[50];
1639     char src_name[50];
1640     char dst_wmask[20];
1641     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1642     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1643
1644     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1645     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1646
1647     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name);
1648     shader_addline(buffer, "DP3 TMP, %s, %s;\n", src_name, src_name);
1649     shader_addline(buffer, "RSQ TMP, TMP.x;\n");
1650     /* dst.w = src[0].w * 1 / (src.x^2 + src.y^2 + src.z^2)^(1/2) according to msdn*/
1651     shader_addline(buffer, "MUL%s %s%s, %s, TMP;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1652                    src_name);
1653
1654     if (shift != 0)
1655         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1656 }
1657
1658 void shader_hw_sincos(SHADER_OPCODE_ARG* arg) {
1659     /* This instruction exists in ARB, but the d3d instruction takes two extra parameters which
1660      * must contain fixed constants. So we need a separate function to filter those constants and
1661      * can't use map2gl
1662      */
1663     SHADER_BUFFER* buffer = arg->buffer;
1664     char dst_name[50];
1665     char src_name[50];
1666     char dst_wmask[20];
1667     DWORD shift = (arg->dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1668     BOOL sat = (arg->dst & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1669
1670     pshader_get_register_name(arg->shader, arg->dst, dst_name);
1671     shader_arb_get_write_mask(arg, arg->dst, dst_wmask);
1672
1673     pshader_gen_input_modifier_line(arg->shader, buffer, arg->src[0], 0, src_name);
1674     shader_addline(buffer, "SCS%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1675                    src_name);
1676
1677     if (shift != 0)
1678         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1679
1680 }
1681
1682 /* TODO: merge with pixel shader */
1683 /* Map the opcode 1-to-1 to the GL code */
1684 void vshader_hw_map2gl(SHADER_OPCODE_ARG* arg) {
1685
1686     IWineD3DVertexShaderImpl *shader = (IWineD3DVertexShaderImpl*) arg->shader;
1687     CONST SHADER_OPCODE* curOpcode = arg->opcode;
1688     SHADER_BUFFER* buffer = arg->buffer;
1689     DWORD dst = arg->dst;
1690     DWORD* src = arg->src;
1691
1692     DWORD dst_regtype = shader_get_regtype(dst);
1693     char tmpLine[256];
1694     unsigned int i;
1695
1696     if ((curOpcode->opcode == WINED3DSIO_MOV && dst_regtype == WINED3DSPR_ADDR) || curOpcode->opcode == WINED3DSIO_MOVA) {
1697         if(shader->rel_offset) {
1698             memset(tmpLine, 0, sizeof(tmpLine));
1699             vshader_program_add_param(arg, src[0], TRUE, tmpLine);
1700             shader_addline(buffer, "ADD TMP.x, %s, helper_const.z;\n", tmpLine);
1701             shader_addline(buffer, "ARL A0.x, TMP.x;\n");
1702             return;
1703         } else {
1704             strcpy(tmpLine, "ARL");
1705         }
1706     } else
1707         strcpy(tmpLine, curOpcode->glname);
1708
1709     if (curOpcode->num_params > 0) {
1710         vshader_program_add_param(arg, dst, FALSE, tmpLine);
1711         for (i = 1; i < curOpcode->num_params; ++i) {
1712            strcat(tmpLine, ",");
1713            vshader_program_add_param(arg, src[i-1], TRUE, tmpLine);
1714         }
1715     }
1716    shader_addline(buffer, "%s;\n", tmpLine);
1717 }
1718
1719 static GLuint create_arb_blt_vertex_program(WineD3D_GL_Info *gl_info) {
1720     GLuint program_id = 0;
1721     const char *blt_vprogram =
1722         "!!ARBvp1.0\n"
1723         "PARAM c[1] = { { 1, 0.5 } };\n"
1724         "MOV result.position, vertex.position;\n"
1725         "MOV result.color, c[0].x;\n"
1726         "MAD result.texcoord[0].y, -vertex.position, c[0], c[0];\n"
1727         "MAD result.texcoord[0].x, vertex.position, c[0].y, c[0].y;\n"
1728         "END\n";
1729
1730     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1731     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, program_id));
1732     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_vprogram), blt_vprogram));
1733
1734     if (glGetError() == GL_INVALID_OPERATION) {
1735         GLint pos;
1736         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1737         FIXME("Vertex program error at position %d: %s\n", pos,
1738             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1739     }
1740
1741     return program_id;
1742 }
1743
1744 static GLuint create_arb_blt_fragment_program(WineD3D_GL_Info *gl_info) {
1745     GLuint program_id = 0;
1746     const char *blt_fprogram =
1747         "!!ARBfp1.0\n"
1748         "TEMP R0;\n"
1749         "TEX R0.x, fragment.texcoord[0], texture[0], 2D;\n"
1750         "MOV result.depth.z, R0.x;\n"
1751         "END\n";
1752
1753     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1754     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
1755     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_fprogram), blt_fprogram));
1756
1757     if (glGetError() == GL_INVALID_OPERATION) {
1758         GLint pos;
1759         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1760         FIXME("Fragment program error at position %d: %s\n", pos,
1761             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1762     }
1763
1764     return program_id;
1765 }
1766
1767 static void shader_arb_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
1768     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1769     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1770
1771     if (useVS) {
1772         TRACE("Using vertex shader\n");
1773
1774         /* Bind the vertex program */
1775         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB,
1776             ((IWineD3DVertexShaderImpl *)This->stateBlock->vertexShader)->baseShader.prgId));
1777         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
1778
1779         /* Enable OpenGL vertex programs */
1780         glEnable(GL_VERTEX_PROGRAM_ARB);
1781         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
1782         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n",
1783             This, ((IWineD3DVertexShaderImpl *)This->stateBlock->vertexShader)->baseShader.prgId);
1784     } else if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
1785         glDisable(GL_VERTEX_PROGRAM_ARB);
1786         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
1787     }
1788
1789     if (usePS) {
1790         TRACE("Using pixel shader\n");
1791
1792         /* Bind the fragment program */
1793         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB,
1794             ((IWineD3DPixelShaderImpl *)This->stateBlock->pixelShader)->baseShader.prgId));
1795         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
1796
1797         /* Enable OpenGL fragment programs */
1798         glEnable(GL_FRAGMENT_PROGRAM_ARB);
1799         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
1800         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n",
1801             This, ((IWineD3DPixelShaderImpl *)This->stateBlock->pixelShader)->baseShader.prgId);
1802     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1803         glDisable(GL_FRAGMENT_PROGRAM_ARB);
1804         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
1805     }
1806 }
1807
1808 static void shader_arb_select_depth_blt(IWineD3DDevice *iface) {
1809     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1810     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1811     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1812
1813     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
1814     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
1815     glEnable(GL_VERTEX_PROGRAM_ARB);
1816
1817     if (!priv->depth_blt_fprogram_id) priv->depth_blt_fprogram_id = create_arb_blt_fragment_program(gl_info);
1818     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->depth_blt_fprogram_id));
1819     glEnable(GL_FRAGMENT_PROGRAM_ARB);
1820 }
1821
1822 static void shader_arb_cleanup(IWineD3DDevice *iface) {
1823     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1824     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1825     if (GL_SUPPORT(ARB_VERTEX_PROGRAM)) glDisable(GL_VERTEX_PROGRAM_ARB);
1826     if (GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) glDisable(GL_FRAGMENT_PROGRAM_ARB);
1827 }
1828
1829 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
1830     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
1831     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *) This->baseShader.device)->adapter->gl_info;
1832
1833     ENTER_GL();
1834     GL_EXTCALL(glDeleteProgramsARB(1, &This->baseShader.prgId));
1835     checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &This->baseShader.prgId))");
1836     LEAVE_GL();
1837     This->baseShader.prgId = 0;
1838     This->baseShader.is_compiled = FALSE;
1839 }
1840
1841 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
1842     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1843     This->shader_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
1844     return WINED3D_OK;
1845 }
1846
1847 static void shader_arb_free(IWineD3DDevice *iface) {
1848     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1849     WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1850     struct shader_arb_priv *priv = (struct shader_arb_priv *) This->shader_priv;
1851
1852     if(priv->depth_blt_vprogram_id) {
1853         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
1854     }
1855     if(priv->depth_blt_fprogram_id) {
1856         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id));
1857     }
1858
1859     HeapFree(GetProcessHeap(), 0, This->shader_priv);
1860 }
1861
1862 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
1863     return TRUE;
1864 }
1865
1866 static void shader_arb_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer) {
1867     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
1868     shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
1869     CONST DWORD *function = This->baseShader.function;
1870     const char *fragcolor;
1871     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
1872     local_constant* lconst;
1873
1874     /*  Create the hw ARB shader */
1875     shader_addline(buffer, "!!ARBfp1.0\n");
1876
1877     shader_addline(buffer, "TEMP TMP;\n");     /* Used in matrix ops */
1878     shader_addline(buffer, "TEMP TMP2;\n");    /* Used in matrix ops */
1879     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
1880     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
1881     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
1882     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
1883     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
1884     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
1885
1886     /* Base Declarations */
1887     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
1888
1889     /* We need two variables for fog blending */
1890     shader_addline(buffer, "TEMP TMP_FOG;\n");
1891     if (This->baseShader.hex_version >= WINED3DPS_VERSION(2,0)) {
1892         shader_addline(buffer, "TEMP TMP_COLOR;\n");
1893     }
1894
1895     /* Base Shader Body */
1896     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
1897
1898     /* calculate fog and blend it
1899      * NOTE: state.fog.params.y and state.fog.params.z don't hold fog start s and end e but
1900      * -1/(e-s) and e/(e-s) respectively.
1901      */
1902     shader_addline(buffer, "MAD_SAT TMP_FOG, fragment.fogcoord, state.fog.params.y, state.fog.params.z;\n");
1903
1904     if (This->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
1905         fragcolor = "R0";
1906     } else {
1907         fragcolor = "TMP_COLOR";
1908     }
1909     if(This->srgb_enabled) {
1910         /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
1911
1912         /* Calculate the > 0.0031308 case */
1913         shader_addline(buffer, "POW TMP.x, %s.x, srgb_pow.x;\n", fragcolor);
1914         shader_addline(buffer, "POW TMP.y, %s.y, srgb_pow.y;\n", fragcolor);
1915         shader_addline(buffer, "POW TMP.z, %s.z, srgb_pow.z;\n", fragcolor);
1916         shader_addline(buffer, "MUL TMP, TMP, srgb_mul_hi;\n");
1917         shader_addline(buffer, "SUB TMP, TMP, srgb_sub_hi;\n");
1918         /* Calculate the < case */
1919         shader_addline(buffer, "MUL TMP2, srgb_mul_low, %s;\n", fragcolor);
1920         /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
1921         shader_addline(buffer, "SLT TA, srgb_comparison, %s;\n", fragcolor);
1922         shader_addline(buffer, "SGE TB, srgb_comparison, %s;\n", fragcolor);
1923         /* Store the components > 0.0031308 in the destination */
1924         shader_addline(buffer, "MUL %s, TMP, TA;\n", fragcolor);
1925         /* Add the components that are < 0.0031308 */
1926         shader_addline(buffer, "MAD result.color.xyz, TMP2, TB, %s;\n", fragcolor);
1927         /* [0.0;1.0] clamping. Not needed, this is done implicitly */
1928     }
1929     if (This->baseShader.hex_version < WINED3DPS_VERSION(3,0)) {
1930         shader_addline(buffer, "LRP result.color.rgb, TMP_FOG.x, %s, state.fog.color;\n", fragcolor);
1931         shader_addline(buffer, "MOV result.color.a, %s.a;\n", fragcolor);
1932     }
1933
1934     shader_addline(buffer, "END\n");
1935
1936     /* TODO: change to resource.glObjectHandle or something like that */
1937     GL_EXTCALL(glGenProgramsARB(1, &This->baseShader.prgId));
1938
1939     TRACE("Creating a hw pixel shader, prg=%d\n", This->baseShader.prgId);
1940     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, This->baseShader.prgId));
1941
1942     TRACE("Created hw pixel shader, prg=%d\n", This->baseShader.prgId);
1943     /* Create the program and check for errors */
1944     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
1945                buffer->bsize, buffer->buffer));
1946
1947     if (glGetError() == GL_INVALID_OPERATION) {
1948         GLint errPos;
1949         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
1950         FIXME("HW PixelShader Error at position %d: %s\n",
1951               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1952         This->baseShader.prgId = -1;
1953     }
1954
1955     /* Load immediate constants */
1956     if(!This->baseShader.load_local_constsF) {
1957         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1958             float *value = (float *) lconst->value;
1959             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst->idx, value));
1960             checkGLcall("glProgramLocalParameter4fvARB");
1961         }
1962     }
1963 }
1964
1965 static void shader_arb_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer) {
1966     IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
1967     shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
1968     CONST DWORD *function = This->baseShader.function;
1969     WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
1970     local_constant* lconst;
1971
1972     /*  Create the hw ARB shader */
1973     shader_addline(buffer, "!!ARBvp1.0\n");
1974     shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
1975
1976     /* Mesa supports only 95 constants */
1977     if (GL_VEND(MESA) || GL_VEND(WINE))
1978         This->baseShader.limits.constant_float =
1979                 min(95, This->baseShader.limits.constant_float);
1980
1981     shader_addline(buffer, "TEMP TMP;\n");
1982
1983     /* Base Declarations */
1984     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
1985
1986     /* We need a constant to fixup the final position */
1987     shader_addline(buffer, "PARAM posFixup = program.env[%d];\n", ARB_SHADER_PRIVCONST_POS);
1988
1989     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
1990      * for output parameters. D3D in theory does not do that either, but some applications depend on a
1991      * proper initialization of the secondary color, and programs using the fixed function pipeline without
1992      * a replacement shader depend on the texcoord.w being set properly.
1993      *
1994      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
1995      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
1996      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
1997      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
1998      * this can eat a number of instructions, so skip it unless this cap is set as well
1999      */
2000     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)) {
2001         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
2002
2003         if((GLINFO_LOCATION).set_texcoord_w) {
2004             int i;
2005             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
2006                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
2007                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
2008                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
2009                 }
2010             }
2011         }
2012     }
2013
2014     /* Base Shader Body */
2015     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
2016
2017     /* If this shader doesn't use fog copy the z coord to the fog coord so that we can use table fog */
2018     if (!reg_maps->fog)
2019         shader_addline(buffer, "MOV result.fogcoord, TMP_OUT.z;\n");
2020
2021     /* Write the final position.
2022      *
2023      * OpenGL coordinates specify the center of the pixel while d3d coords specify
2024      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
2025      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
2026      * contains 1.0 to allow a mad, but arb vs swizzles are too restricted for that.
2027      */
2028     shader_addline(buffer, "MUL TMP, posFixup, TMP_OUT.w;\n");
2029     shader_addline(buffer, "ADD TMP_OUT.x, TMP_OUT.x, TMP.z;\n");
2030     shader_addline(buffer, "MAD TMP_OUT.y, TMP_OUT.y, posFixup.y, TMP.w;\n");
2031
2032     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
2033      * and the glsl equivalent
2034      */
2035     shader_addline(buffer, "MAD TMP_OUT.z, TMP_OUT.z, helper_const.x, -TMP_OUT.w;\n");
2036
2037     shader_addline(buffer, "MOV result.position, TMP_OUT;\n");
2038
2039     shader_addline(buffer, "END\n");
2040
2041     /* TODO: change to resource.glObjectHandle or something like that */
2042     GL_EXTCALL(glGenProgramsARB(1, &This->baseShader.prgId));
2043
2044     TRACE("Creating a hw vertex shader, prg=%d\n", This->baseShader.prgId);
2045     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, This->baseShader.prgId));
2046
2047     TRACE("Created hw vertex shader, prg=%d\n", This->baseShader.prgId);
2048     /* Create the program and check for errors */
2049     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2050                buffer->bsize, buffer->buffer));
2051
2052     if (glGetError() == GL_INVALID_OPERATION) {
2053         GLint errPos;
2054         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2055         FIXME("HW VertexShader Error at position %d: %s\n",
2056               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2057         This->baseShader.prgId = -1;
2058     }
2059
2060     /* Load immediate constants */
2061     if(!This->baseShader.load_local_constsF) {
2062         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2063             float *value = (float *) lconst->value;
2064             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst->idx, value));
2065         }
2066     }
2067 }
2068
2069 static void shader_arb_get_caps(WINED3DDEVTYPE devtype, WineD3D_GL_Info *gl_info, struct shader_caps *pCaps) {
2070     /* We don't have an ARB fixed function pipeline yet, so let the none backend set its caps,
2071      * then overwrite the shader specific ones
2072      */
2073     none_shader_backend.shader_get_caps(devtype, gl_info, pCaps);
2074
2075     if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
2076         pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
2077         TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
2078         pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
2079     }
2080
2081     if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
2082         pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
2083         pCaps->PixelShader1xMaxValue = 8.0;
2084         TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
2085     }
2086 }
2087
2088 static void shader_arb_fragment_enable(IWineD3DDevice *iface, BOOL enable) {
2089     none_shader_backend.shader_fragment_enable(iface, enable);
2090 }
2091
2092 const shader_backend_t arb_program_shader_backend = {
2093     shader_arb_select,
2094     shader_arb_select_depth_blt,
2095     shader_arb_load_constants,
2096     shader_arb_cleanup,
2097     shader_arb_color_correction,
2098     shader_arb_destroy,
2099     shader_arb_alloc,
2100     shader_arb_free,
2101     shader_arb_dirty_const,
2102     shader_arb_generate_pshader,
2103     shader_arb_generate_vshader,
2104     shader_arb_get_caps,
2105     shader_arb_fragment_enable,
2106 };