winmm: Have xyzGetDevCaps return MMSYSERR_BADDEVICEID, not INVALHANDLE.
[wine] / dlls / wined3d / shader.c
1 /*
2  * Copyright 2002-2003 Jason Edmeades
3  * Copyright 2002-2003 Raphael Junqueira
4  * Copyright 2004 Christian Costa
5  * Copyright 2005 Oliver Stieber
6  * Copyright 2006 Ivan Gyurdiev
7  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  * Copyright 2009 Henri Verbeet for CodeWeavers
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26
27 #include <math.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include "wined3d_private.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d);
35
36 static const char *shader_opcode_names[] =
37 {
38     /* WINED3DSIH_ABS           */ "abs",
39     /* WINED3DSIH_ADD           */ "add",
40     /* WINED3DSIH_BEM           */ "bem",
41     /* WINED3DSIH_BREAK         */ "break",
42     /* WINED3DSIH_BREAKC        */ "breakc",
43     /* WINED3DSIH_BREAKP        */ "breakp",
44     /* WINED3DSIH_CALL          */ "call",
45     /* WINED3DSIH_CALLNZ        */ "callnz",
46     /* WINED3DSIH_CMP           */ "cmp",
47     /* WINED3DSIH_CND           */ "cnd",
48     /* WINED3DSIH_CRS           */ "crs",
49     /* WINED3DSIH_CUT           */ "cut",
50     /* WINED3DSIH_DCL           */ "dcl",
51     /* WINED3DSIH_DEF           */ "def",
52     /* WINED3DSIH_DEFB          */ "defb",
53     /* WINED3DSIH_DEFI          */ "defi",
54     /* WINED3DSIH_DP2ADD        */ "dp2add",
55     /* WINED3DSIH_DP3           */ "dp3",
56     /* WINED3DSIH_DP4           */ "dp4",
57     /* WINED3DSIH_DST           */ "dst",
58     /* WINED3DSIH_DSX           */ "dsx",
59     /* WINED3DSIH_DSY           */ "dsy",
60     /* WINED3DSIH_ELSE          */ "else",
61     /* WINED3DSIH_EMIT          */ "emit",
62     /* WINED3DSIH_ENDIF         */ "endif",
63     /* WINED3DSIH_ENDLOOP       */ "endloop",
64     /* WINED3DSIH_ENDREP        */ "endrep",
65     /* WINED3DSIH_EXP           */ "exp",
66     /* WINED3DSIH_EXPP          */ "expp",
67     /* WINED3DSIH_FRC           */ "frc",
68     /* WINED3DSIH_IADD          */ "iadd",
69     /* WINED3DSIH_IF            */ "if",
70     /* WINED3DSIH_IFC           */ "ifc",
71     /* WINED3DSIH_IGE           */ "ige",
72     /* WINED3DSIH_LABEL         */ "label",
73     /* WINED3DSIH_LIT           */ "lit",
74     /* WINED3DSIH_LOG           */ "log",
75     /* WINED3DSIH_LOGP          */ "logp",
76     /* WINED3DSIH_LOOP          */ "loop",
77     /* WINED3DSIH_LRP           */ "lrp",
78     /* WINED3DSIH_LT            */ "lt",
79     /* WINED3DSIH_M3x2          */ "m3x2",
80     /* WINED3DSIH_M3x3          */ "m3x3",
81     /* WINED3DSIH_M3x4          */ "m3x4",
82     /* WINED3DSIH_M4x3          */ "m4x3",
83     /* WINED3DSIH_M4x4          */ "m4x4",
84     /* WINED3DSIH_MAD           */ "mad",
85     /* WINED3DSIH_MAX           */ "max",
86     /* WINED3DSIH_MIN           */ "min",
87     /* WINED3DSIH_MOV           */ "mov",
88     /* WINED3DSIH_MOVA          */ "mova",
89     /* WINED3DSIH_MUL           */ "mul",
90     /* WINED3DSIH_NOP           */ "nop",
91     /* WINED3DSIH_NRM           */ "nrm",
92     /* WINED3DSIH_PHASE         */ "phase",
93     /* WINED3DSIH_POW           */ "pow",
94     /* WINED3DSIH_RCP           */ "rcp",
95     /* WINED3DSIH_REP           */ "rep",
96     /* WINED3DSIH_RET           */ "ret",
97     /* WINED3DSIH_RSQ           */ "rsq",
98     /* WINED3DSIH_SETP          */ "setp",
99     /* WINED3DSIH_SGE           */ "sge",
100     /* WINED3DSIH_SGN           */ "sgn",
101     /* WINED3DSIH_SINCOS        */ "sincos",
102     /* WINED3DSIH_SLT           */ "slt",
103     /* WINED3DSIH_SUB           */ "sub",
104     /* WINED3DSIH_TEX           */ "texld",
105     /* WINED3DSIH_TEXBEM        */ "texbem",
106     /* WINED3DSIH_TEXBEML       */ "texbeml",
107     /* WINED3DSIH_TEXCOORD      */ "texcrd",
108     /* WINED3DSIH_TEXDEPTH      */ "texdepth",
109     /* WINED3DSIH_TEXDP3        */ "texdp3",
110     /* WINED3DSIH_TEXDP3TEX     */ "texdp3tex",
111     /* WINED3DSIH_TEXKILL       */ "texkill",
112     /* WINED3DSIH_TEXLDD        */ "texldd",
113     /* WINED3DSIH_TEXLDL        */ "texldl",
114     /* WINED3DSIH_TEXM3x2DEPTH  */ "texm3x2depth",
115     /* WINED3DSIH_TEXM3x2PAD    */ "texm3x2pad",
116     /* WINED3DSIH_TEXM3x2TEX    */ "texm3x2tex",
117     /* WINED3DSIH_TEXM3x3       */ "texm3x3",
118     /* WINED3DSIH_TEXM3x3DIFF   */ "texm3x3diff",
119     /* WINED3DSIH_TEXM3x3PAD    */ "texm3x3pad",
120     /* WINED3DSIH_TEXM3x3SPEC   */ "texm3x3spec",
121     /* WINED3DSIH_TEXM3x3TEX    */ "texm3x3tex",
122     /* WINED3DSIH_TEXM3x3VSPEC  */ "texm3x3vspec",
123     /* WINED3DSIH_TEXREG2AR     */ "texreg2ar",
124     /* WINED3DSIH_TEXREG2GB     */ "texreg2gb",
125     /* WINED3DSIH_TEXREG2RGB    */ "texreg2rgb",
126 };
127
128 static const char *semantic_names[] =
129 {
130     /* WINED3DDECLUSAGE_POSITION        */ "SV_POSITION",
131     /* WINED3DDECLUSAGE_BLENDWEIGHT     */ "BLENDWEIGHT",
132     /* WINED3DDECLUSAGE_BLENDINDICES    */ "BLENDINDICES",
133     /* WINED3DDECLUSAGE_NORMAL          */ "NORMAL",
134     /* WINED3DDECLUSAGE_PSIZE           */ "PSIZE",
135     /* WINED3DDECLUSAGE_TEXCOORD        */ "TEXCOORD",
136     /* WINED3DDECLUSAGE_TANGENT         */ "TANGENT",
137     /* WINED3DDECLUSAGE_BINORMAL        */ "BINORMAL",
138     /* WINED3DDECLUSAGE_TESSFACTOR      */ "TESSFACTOR",
139     /* WINED3DDECLUSAGE_POSITIONT       */ "POSITIONT",
140     /* WINED3DDECLUSAGE_COLOR           */ "COLOR",
141     /* WINED3DDECLUSAGE_FOG             */ "FOG",
142     /* WINED3DDECLUSAGE_DEPTH           */ "DEPTH",
143     /* WINED3DDECLUSAGE_SAMPLE          */ "SAMPLE",
144 };
145
146 static const char *shader_semantic_name_from_usage(WINED3DDECLUSAGE usage)
147 {
148     if (usage >= sizeof(semantic_names) / sizeof(*semantic_names))
149     {
150         FIXME("Unrecognized usage %#x.\n", usage);
151         return "UNRECOGNIZED";
152     }
153
154     return semantic_names[usage];
155 }
156
157 static WINED3DDECLUSAGE shader_usage_from_semantic_name(const char *name)
158 {
159     unsigned int i;
160
161     for (i = 0; i < sizeof(semantic_names) / sizeof(*semantic_names); ++i)
162     {
163         if (!strcmp(name, semantic_names[i])) return i;
164     }
165
166     return ~0U;
167 }
168
169 BOOL shader_match_semantic(const char *semantic_name, WINED3DDECLUSAGE usage)
170 {
171     return !strcmp(semantic_name, shader_semantic_name_from_usage(usage));
172 }
173
174 static void shader_signature_from_semantic(struct wined3d_shader_signature_element *e,
175         const struct wined3d_shader_semantic *s)
176 {
177     e->semantic_name = shader_semantic_name_from_usage(s->usage);
178     e->semantic_idx = s->usage_idx;
179     e->sysval_semantic = 0;
180     e->component_type = 0;
181     e->register_idx = s->reg.reg.idx;
182     e->mask = s->reg.write_mask;
183 }
184
185 static const struct wined3d_shader_frontend *shader_select_frontend(DWORD version_token)
186 {
187     switch (version_token >> 16)
188     {
189         case WINED3D_SM1_VS:
190         case WINED3D_SM1_PS:
191             return &sm1_shader_frontend;
192
193         case WINED3D_SM4_PS:
194         case WINED3D_SM4_VS:
195         case WINED3D_SM4_GS:
196             return &sm4_shader_frontend;
197
198         default:
199             FIXME("Unrecognised version token %#x\n", version_token);
200             return NULL;
201     }
202 }
203
204 void shader_buffer_clear(struct wined3d_shader_buffer *buffer)
205 {
206     buffer->buffer[0] = '\0';
207     buffer->bsize = 0;
208     buffer->lineNo = 0;
209     buffer->newline = TRUE;
210 }
211
212 BOOL shader_buffer_init(struct wined3d_shader_buffer *buffer)
213 {
214     buffer->buffer = HeapAlloc(GetProcessHeap(), 0, SHADER_PGMSIZE);
215     if (!buffer->buffer)
216     {
217         ERR("Failed to allocate shader buffer memory.\n");
218         return FALSE;
219     }
220
221     shader_buffer_clear(buffer);
222     return TRUE;
223 }
224
225 void shader_buffer_free(struct wined3d_shader_buffer *buffer)
226 {
227     HeapFree(GetProcessHeap(), 0, buffer->buffer);
228 }
229
230 int shader_vaddline(struct wined3d_shader_buffer *buffer, const char *format, va_list args)
231 {
232     char *base = buffer->buffer + buffer->bsize;
233     int rc;
234
235     rc = vsnprintf(base, SHADER_PGMSIZE - 1 - buffer->bsize, format, args);
236
237     if (rc < 0 /* C89 */ || (unsigned int)rc > SHADER_PGMSIZE - 1 - buffer->bsize /* C99 */)
238     {
239         ERR("The buffer allocated for the shader program string "
240             "is too small at %d bytes.\n", SHADER_PGMSIZE);
241         buffer->bsize = SHADER_PGMSIZE - 1;
242         return -1;
243     }
244
245     if (buffer->newline)
246     {
247         TRACE("GL HW (%u, %u) : %s", buffer->lineNo + 1, buffer->bsize, base);
248         buffer->newline = FALSE;
249     }
250     else
251     {
252         TRACE("%s", base);
253     }
254
255     buffer->bsize += rc;
256     if (buffer->buffer[buffer->bsize-1] == '\n')
257     {
258         ++buffer->lineNo;
259         buffer->newline = TRUE;
260     }
261
262     return 0;
263 }
264
265 int shader_addline(struct wined3d_shader_buffer *buffer, const char *format, ...)
266 {
267     va_list args;
268     int ret;
269
270     va_start(args, format);
271     ret = shader_vaddline(buffer, format, args);
272     va_end(args);
273
274     return ret;
275 }
276
277 static void shader_init(struct IWineD3DBaseShaderClass *shader, IWineD3DDeviceImpl *device,
278         IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
279 {
280     shader->ref = 1;
281     shader->device = (IWineD3DDevice *)device;
282     shader->parent = parent;
283     shader->parent_ops = parent_ops;
284     list_init(&shader->linked_programs);
285     list_add_head(&device->shaders, &shader->shader_list_entry);
286 }
287
288 /* Convert floating point offset relative to a register file to an absolute
289  * offset for float constants. */
290 static unsigned int shader_get_float_offset(WINED3DSHADER_PARAM_REGISTER_TYPE register_type, UINT register_idx)
291 {
292     switch (register_type)
293     {
294         case WINED3DSPR_CONST: return register_idx;
295         case WINED3DSPR_CONST2: return 2048 + register_idx;
296         case WINED3DSPR_CONST3: return 4096 + register_idx;
297         case WINED3DSPR_CONST4: return 6144 + register_idx;
298         default:
299             FIXME("Unsupported register type: %u.\n", register_type);
300             return register_idx;
301     }
302 }
303
304 static void shader_delete_constant_list(struct list *clist)
305 {
306     struct local_constant *constant;
307     struct list *ptr;
308
309     ptr = list_head(clist);
310     while (ptr)
311     {
312         constant = LIST_ENTRY(ptr, struct local_constant, entry);
313         ptr = list_next(clist, ptr);
314         HeapFree(GetProcessHeap(), 0, constant);
315     }
316     list_init(clist);
317 }
318
319 static inline void set_bitmap_bit(DWORD *bitmap, DWORD bit)
320 {
321     DWORD idx, shift;
322     idx = bit >> 5;
323     shift = bit & 0x1f;
324     bitmap[idx] |= (1 << shift);
325 }
326
327 static void shader_record_register_usage(IWineD3DBaseShaderImpl *shader, struct shader_reg_maps *reg_maps,
328         const struct wined3d_shader_register *reg, enum wined3d_shader_type shader_type)
329 {
330     switch (reg->type)
331     {
332         case WINED3DSPR_TEXTURE: /* WINED3DSPR_ADDR */
333             if (shader_type == WINED3D_SHADER_TYPE_PIXEL) reg_maps->texcoord |= 1 << reg->idx;
334             else reg_maps->address |= 1 << reg->idx;
335             break;
336
337         case WINED3DSPR_TEMP:
338             reg_maps->temporary |= 1 << reg->idx;
339             break;
340
341         case WINED3DSPR_INPUT:
342             if (shader_type == WINED3D_SHADER_TYPE_PIXEL)
343             {
344                 if (reg->rel_addr)
345                 {
346                     /* If relative addressing is used, we must assume that all registers
347                      * are used. Even if it is a construct like v3[aL], we can't assume
348                      * that v0, v1 and v2 aren't read because aL can be negative */
349                     unsigned int i;
350                     for (i = 0; i < MAX_REG_INPUT; ++i)
351                     {
352                         ((IWineD3DPixelShaderImpl *)shader)->input_reg_used[i] = TRUE;
353                     }
354                 }
355                 else
356                 {
357                     ((IWineD3DPixelShaderImpl *)shader)->input_reg_used[reg->idx] = TRUE;
358                 }
359             }
360             else reg_maps->input_registers |= 1 << reg->idx;
361             break;
362
363         case WINED3DSPR_RASTOUT:
364             if (reg->idx == 1) reg_maps->fog = 1;
365             break;
366
367         case WINED3DSPR_MISCTYPE:
368             if (shader_type == WINED3D_SHADER_TYPE_PIXEL)
369             {
370                 if (reg->idx == 0) reg_maps->vpos = 1;
371                 else if (reg->idx == 1) reg_maps->usesfacing = 1;
372             }
373             break;
374
375         case WINED3DSPR_CONST:
376             if (reg->rel_addr)
377             {
378                 if (shader_type != WINED3D_SHADER_TYPE_PIXEL)
379                 {
380                     if (reg->idx < ((IWineD3DVertexShaderImpl *)shader)->min_rel_offset)
381                     {
382                         ((IWineD3DVertexShaderImpl *)shader)->min_rel_offset = reg->idx;
383                     }
384                     if (reg->idx > ((IWineD3DVertexShaderImpl *)shader)->max_rel_offset)
385                     {
386                         ((IWineD3DVertexShaderImpl *)shader)->max_rel_offset = reg->idx;
387                     }
388                 }
389                 reg_maps->usesrelconstF = TRUE;
390             }
391             else
392             {
393                 set_bitmap_bit(reg_maps->constf, reg->idx);
394             }
395             break;
396
397         case WINED3DSPR_CONSTINT:
398             reg_maps->integer_constants |= (1 << reg->idx);
399             break;
400
401         case WINED3DSPR_CONSTBOOL:
402             reg_maps->boolean_constants |= (1 << reg->idx);
403             break;
404
405         case WINED3DSPR_COLOROUT:
406             reg_maps->highest_render_target = max(reg_maps->highest_render_target, reg->idx);
407             break;
408
409         default:
410             TRACE("Not recording register of type %#x and idx %u\n", reg->type, reg->idx);
411             break;
412     }
413 }
414
415 static unsigned int get_instr_extra_regcount(enum WINED3D_SHADER_INSTRUCTION_HANDLER instr, unsigned int param)
416 {
417     switch (instr)
418     {
419         case WINED3DSIH_M4x4:
420         case WINED3DSIH_M3x4:
421             return param == 1 ? 3 : 0;
422
423         case WINED3DSIH_M4x3:
424         case WINED3DSIH_M3x3:
425             return param == 1 ? 2 : 0;
426
427         case WINED3DSIH_M3x2:
428             return param == 1 ? 1 : 0;
429
430         default:
431             return 0;
432     }
433 }
434
435 /* Note that this does not count the loop register as an address register. */
436 static HRESULT shader_get_registers_used(IWineD3DBaseShader *iface, const struct wined3d_shader_frontend *fe,
437         struct shader_reg_maps *reg_maps, struct wined3d_shader_signature_element *input_signature,
438         struct wined3d_shader_signature_element *output_signature, const DWORD *byte_code, DWORD constf_size)
439 {
440     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)iface;
441     unsigned int cur_loop_depth = 0, max_loop_depth = 0;
442     void *fe_data = shader->baseShader.frontend_data;
443     struct wined3d_shader_version shader_version;
444     const DWORD *ptr = byte_code;
445
446     memset(reg_maps, 0, sizeof(*reg_maps));
447
448     /* get_registers_used() is called on every compile on some 1.x shaders,
449      * which can result in stacking up a collection of local constants.
450      * Delete the old constants if existing. */
451     shader_delete_constant_list(&shader->baseShader.constantsF);
452     shader_delete_constant_list(&shader->baseShader.constantsB);
453     shader_delete_constant_list(&shader->baseShader.constantsI);
454
455     fe->shader_read_header(fe_data, &ptr, &shader_version);
456     reg_maps->shader_version = shader_version;
457
458     reg_maps->constf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
459             sizeof(*reg_maps->constf) * ((constf_size + 31) / 32));
460     if (!reg_maps->constf)
461     {
462         ERR("Failed to allocate constant map memory.\n");
463         return E_OUTOFMEMORY;
464     }
465
466     while (!fe->shader_is_end(fe_data, &ptr))
467     {
468         struct wined3d_shader_instruction ins;
469         const char *comment;
470         UINT param_size;
471
472         /* Skip comments. */
473         fe->shader_read_comment(&ptr, &comment);
474         if (comment) continue;
475
476         /* Fetch opcode. */
477         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
478
479         /* Unhandled opcode, and its parameters. */
480         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
481         {
482             TRACE("Skipping unrecognized instruction.\n");
483             ptr += param_size;
484             continue;
485         }
486
487         /* Handle declarations. */
488         if (ins.handler_idx == WINED3DSIH_DCL)
489         {
490             struct wined3d_shader_semantic semantic;
491
492             fe->shader_read_semantic(&ptr, &semantic);
493
494             switch (semantic.reg.reg.type)
495             {
496                 /* Mark input registers used. */
497                 case WINED3DSPR_INPUT:
498                     reg_maps->input_registers |= 1 << semantic.reg.reg.idx;
499                     shader_signature_from_semantic(&input_signature[semantic.reg.reg.idx], &semantic);
500                     break;
501
502                 /* Vertex shader: mark 3.0 output registers used, save token. */
503                 case WINED3DSPR_OUTPUT:
504                     reg_maps->output_registers |= 1 << semantic.reg.reg.idx;
505                     shader_signature_from_semantic(&output_signature[semantic.reg.reg.idx], &semantic);
506                     if (semantic.usage == WINED3DDECLUSAGE_FOG) reg_maps->fog = 1;
507                     break;
508
509                 /* Save sampler usage token. */
510                 case WINED3DSPR_SAMPLER:
511                     reg_maps->sampler_type[semantic.reg.reg.idx] = semantic.sampler_type;
512                     break;
513
514                 default:
515                     TRACE("Not recording DCL register type %#x.\n", semantic.reg.reg.type);
516                     break;
517             }
518         }
519         else if (ins.handler_idx == WINED3DSIH_DEF)
520         {
521             struct wined3d_shader_src_param rel_addr;
522             struct wined3d_shader_dst_param dst;
523
524             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
525             if (!lconst) return E_OUTOFMEMORY;
526
527             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
528             lconst->idx = dst.reg.idx;
529
530             memcpy(lconst->value, ptr, 4 * sizeof(DWORD));
531             ptr += 4;
532
533             /* In pixel shader 1.X shaders, the constants are clamped between [-1;1] */
534             if (shader_version.major == 1 && shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
535             {
536                 float *value = (float *)lconst->value;
537                 if (value[0] < -1.0f) value[0] = -1.0f;
538                 else if (value[0] > 1.0f) value[0] = 1.0f;
539                 if (value[1] < -1.0f) value[1] = -1.0f;
540                 else if (value[1] > 1.0f) value[1] = 1.0f;
541                 if (value[2] < -1.0f) value[2] = -1.0f;
542                 else if (value[2] > 1.0f) value[2] = 1.0f;
543                 if (value[3] < -1.0f) value[3] = -1.0f;
544                 else if (value[3] > 1.0f) value[3] = 1.0f;
545             }
546
547             list_add_head(&shader->baseShader.constantsF, &lconst->entry);
548         }
549         else if (ins.handler_idx == WINED3DSIH_DEFI)
550         {
551             struct wined3d_shader_src_param rel_addr;
552             struct wined3d_shader_dst_param dst;
553
554             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
555             if (!lconst) return E_OUTOFMEMORY;
556
557             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
558             lconst->idx = dst.reg.idx;
559
560             memcpy(lconst->value, ptr, 4 * sizeof(DWORD));
561             ptr += 4;
562
563             list_add_head(&shader->baseShader.constantsI, &lconst->entry);
564             reg_maps->local_int_consts |= (1 << dst.reg.idx);
565         }
566         else if (ins.handler_idx == WINED3DSIH_DEFB)
567         {
568             struct wined3d_shader_src_param rel_addr;
569             struct wined3d_shader_dst_param dst;
570
571             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
572             if (!lconst) return E_OUTOFMEMORY;
573
574             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
575             lconst->idx = dst.reg.idx;
576
577             memcpy(lconst->value, ptr, sizeof(DWORD));
578             ++ptr;
579
580             list_add_head(&shader->baseShader.constantsB, &lconst->entry);
581             reg_maps->local_bool_consts |= (1 << dst.reg.idx);
582         }
583         /* If there's a loop in the shader. */
584         else if (ins.handler_idx == WINED3DSIH_LOOP
585                 || ins.handler_idx == WINED3DSIH_REP)
586         {
587             struct wined3d_shader_src_param src, rel_addr;
588
589             fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
590
591             /* Rep and Loop always use an integer constant for the control parameters. */
592             if (ins.handler_idx == WINED3DSIH_REP)
593             {
594                 reg_maps->integer_constants |= 1 << src.reg.idx;
595             }
596             else
597             {
598                 fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
599                 reg_maps->integer_constants |= 1 << src.reg.idx;
600             }
601
602             cur_loop_depth++;
603             if (cur_loop_depth > max_loop_depth) max_loop_depth = cur_loop_depth;
604         }
605         else if (ins.handler_idx == WINED3DSIH_ENDLOOP
606                 || ins.handler_idx == WINED3DSIH_ENDREP)
607         {
608             cur_loop_depth--;
609         }
610         /* For subroutine prototypes. */
611         else if (ins.handler_idx == WINED3DSIH_LABEL)
612         {
613             struct wined3d_shader_src_param src, rel_addr;
614
615             fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
616             reg_maps->labels |= 1 << src.reg.idx;
617         }
618         /* Set texture, address, temporary registers. */
619         else
620         {
621             BOOL color0_mov = FALSE;
622             int i, limit;
623
624             /* This will loop over all the registers and try to
625              * make a bitmask of the ones we're interested in.
626              *
627              * Relative addressing tokens are ignored, but that's
628              * okay, since we'll catch any address registers when
629              * they are initialized (required by spec). */
630             if (ins.dst_count)
631             {
632                 struct wined3d_shader_src_param dst_rel_addr;
633                 struct wined3d_shader_dst_param dst_param;
634
635                 fe->shader_read_dst_param(fe_data, &ptr, &dst_param, &dst_rel_addr);
636
637                 shader_record_register_usage(shader, reg_maps, &dst_param.reg, shader_version.type);
638
639                 /* WINED3DSPR_TEXCRDOUT is the same as WINED3DSPR_OUTPUT. _OUTPUT can be > MAX_REG_TEXCRD and
640                  * is used in >= 3.0 shaders. Filter 3.0 shaders to prevent overflows, and also filter pixel
641                  * shaders because TECRDOUT isn't used in them, but future register types might cause issues */
642                 if (shader_version.type == WINED3D_SHADER_TYPE_VERTEX && shader_version.major < 3
643                         && dst_param.reg.type == WINED3DSPR_TEXCRDOUT)
644                 {
645                     reg_maps->texcoord_mask[dst_param.reg.idx] |= dst_param.write_mask;
646                 }
647
648                 if (shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
649                 {
650                     IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *)shader;
651
652                     if (dst_param.reg.type == WINED3DSPR_COLOROUT && dst_param.reg.idx == 0)
653                     {
654                     /* Many 2.0 and 3.0 pixel shaders end with a MOV from a temp register to
655                      * COLOROUT 0. If we know this in advance, the ARB shader backend can skip
656                      * the mov and perform the sRGB write correction from the source register.
657                      *
658                      * However, if the mov is only partial, we can't do this, and if the write
659                      * comes from an instruction other than MOV it is hard to do as well. If
660                      * COLOROUT 0 is overwritten partially later, the marker is dropped again. */
661
662                         ps->color0_mov = FALSE;
663                         if (ins.handler_idx == WINED3DSIH_MOV)
664                         {
665                             /* Used later when the source register is read. */
666                             color0_mov = TRUE;
667                         }
668                     }
669                     /* Also drop the MOV marker if the source register is overwritten prior to the shader
670                      * end
671                      */
672                     else if (dst_param.reg.type == WINED3DSPR_TEMP && dst_param.reg.idx == ps->color0_reg)
673                     {
674                         ps->color0_mov = FALSE;
675                     }
676                 }
677
678                 /* Declare 1.x samplers implicitly, based on the destination reg. number. */
679                 if (shader_version.major == 1
680                         && (ins.handler_idx == WINED3DSIH_TEX
681                             || ins.handler_idx == WINED3DSIH_TEXBEM
682                             || ins.handler_idx == WINED3DSIH_TEXBEML
683                             || ins.handler_idx == WINED3DSIH_TEXDP3TEX
684                             || ins.handler_idx == WINED3DSIH_TEXM3x2TEX
685                             || ins.handler_idx == WINED3DSIH_TEXM3x3SPEC
686                             || ins.handler_idx == WINED3DSIH_TEXM3x3TEX
687                             || ins.handler_idx == WINED3DSIH_TEXM3x3VSPEC
688                             || ins.handler_idx == WINED3DSIH_TEXREG2AR
689                             || ins.handler_idx == WINED3DSIH_TEXREG2GB
690                             || ins.handler_idx == WINED3DSIH_TEXREG2RGB))
691                 {
692                     /* Fake sampler usage, only set reserved bit and type. */
693                     DWORD sampler_code = dst_param.reg.idx;
694
695                     TRACE("Setting fake 2D sampler for 1.x pixelshader.\n");
696                     reg_maps->sampler_type[sampler_code] = WINED3DSTT_2D;
697
698                     /* texbem is only valid with < 1.4 pixel shaders */
699                     if (ins.handler_idx == WINED3DSIH_TEXBEM
700                             || ins.handler_idx == WINED3DSIH_TEXBEML)
701                     {
702                         reg_maps->bumpmat |= 1 << dst_param.reg.idx;
703                         if (ins.handler_idx == WINED3DSIH_TEXBEML)
704                         {
705                             reg_maps->luminanceparams |= 1 << dst_param.reg.idx;
706                         }
707                     }
708                 }
709                 else if (ins.handler_idx == WINED3DSIH_BEM)
710                 {
711                     reg_maps->bumpmat |= 1 << dst_param.reg.idx;
712                 }
713             }
714
715             if (ins.handler_idx == WINED3DSIH_NRM) reg_maps->usesnrm = 1;
716             else if (ins.handler_idx == WINED3DSIH_DSY) reg_maps->usesdsy = 1;
717             else if (ins.handler_idx == WINED3DSIH_DSX) reg_maps->usesdsx = 1;
718             else if (ins.handler_idx == WINED3DSIH_TEXLDD) reg_maps->usestexldd = 1;
719             else if (ins.handler_idx == WINED3DSIH_TEXLDL) reg_maps->usestexldl = 1;
720             else if (ins.handler_idx == WINED3DSIH_MOVA) reg_maps->usesmova = 1;
721             else if (ins.handler_idx == WINED3DSIH_IFC) reg_maps->usesifc = 1;
722             else if (ins.handler_idx == WINED3DSIH_CALL) reg_maps->usescall = 1;
723
724             limit = ins.src_count + (ins.predicate ? 1 : 0);
725             for (i = 0; i < limit; ++i)
726             {
727                 struct wined3d_shader_src_param src_param, src_rel_addr;
728                 unsigned int count;
729
730                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
731                 count = get_instr_extra_regcount(ins.handler_idx, i);
732
733                 shader_record_register_usage(shader, reg_maps, &src_param.reg, shader_version.type);
734                 while (count)
735                 {
736                     ++src_param.reg.idx;
737                     shader_record_register_usage(shader, reg_maps, &src_param.reg, shader_version.type);
738                     --count;
739                 }
740
741                 if (color0_mov)
742                 {
743                     IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *)shader;
744                     if (src_param.reg.type == WINED3DSPR_TEMP
745                             && src_param.swizzle == WINED3DSP_NOSWIZZLE)
746                     {
747                         ps->color0_mov = TRUE;
748                         ps->color0_reg = src_param.reg.idx;
749                     }
750                 }
751             }
752         }
753     }
754     reg_maps->loop_depth = max_loop_depth;
755
756     shader->baseShader.functionLength = ((const char *)ptr - (const char *)byte_code);
757
758     return WINED3D_OK;
759 }
760
761 unsigned int shader_find_free_input_register(const struct shader_reg_maps *reg_maps, unsigned int max)
762 {
763     DWORD map = 1 << max;
764     map |= map - 1;
765     map &= reg_maps->shader_version.major < 3 ? ~reg_maps->texcoord : ~reg_maps->input_registers;
766
767     return wined3d_log2i(map);
768 }
769
770 static void shader_dump_decl_usage(const struct wined3d_shader_semantic *semantic,
771         const struct wined3d_shader_version *shader_version)
772 {
773     TRACE("dcl");
774
775     if (semantic->reg.reg.type == WINED3DSPR_SAMPLER)
776     {
777         switch (semantic->sampler_type)
778         {
779             case WINED3DSTT_2D: TRACE("_2d"); break;
780             case WINED3DSTT_CUBE: TRACE("_cube"); break;
781             case WINED3DSTT_VOLUME: TRACE("_volume"); break;
782             default: TRACE("_unknown_ttype(0x%08x)", semantic->sampler_type);
783         }
784     }
785     else
786     {
787         /* Pixel shaders 3.0 don't have usage semantics. */
788         if (shader_version->major < 3 && shader_version->type == WINED3D_SHADER_TYPE_PIXEL) return;
789         else TRACE("_");
790
791         switch (semantic->usage)
792         {
793             case WINED3DDECLUSAGE_POSITION:
794                 TRACE("position%u", semantic->usage_idx);
795                 break;
796
797             case WINED3DDECLUSAGE_BLENDINDICES:
798                 TRACE("blend");
799                 break;
800
801             case WINED3DDECLUSAGE_BLENDWEIGHT:
802                 TRACE("weight");
803                 break;
804
805             case WINED3DDECLUSAGE_NORMAL:
806                 TRACE("normal%u", semantic->usage_idx);
807                 break;
808
809             case WINED3DDECLUSAGE_PSIZE:
810                 TRACE("psize");
811                 break;
812
813             case WINED3DDECLUSAGE_COLOR:
814                 if (semantic->usage_idx == 0) TRACE("color");
815                 else TRACE("specular%u", (semantic->usage_idx - 1));
816                 break;
817
818             case WINED3DDECLUSAGE_TEXCOORD:
819                 TRACE("texture%u", semantic->usage_idx);
820                 break;
821
822             case WINED3DDECLUSAGE_TANGENT:
823                 TRACE("tangent");
824                 break;
825
826             case WINED3DDECLUSAGE_BINORMAL:
827                 TRACE("binormal");
828                 break;
829
830             case WINED3DDECLUSAGE_TESSFACTOR:
831                 TRACE("tessfactor");
832                 break;
833
834             case WINED3DDECLUSAGE_POSITIONT:
835                 TRACE("positionT%u", semantic->usage_idx);
836                 break;
837
838             case WINED3DDECLUSAGE_FOG:
839                 TRACE("fog");
840                 break;
841
842             case WINED3DDECLUSAGE_DEPTH:
843                 TRACE("depth");
844                 break;
845
846             case WINED3DDECLUSAGE_SAMPLE:
847                 TRACE("sample");
848                 break;
849
850             default:
851                 FIXME("unknown_semantics(0x%08x)", semantic->usage);
852         }
853     }
854 }
855
856 static void shader_dump_register(const struct wined3d_shader_register *reg,
857         const struct wined3d_shader_version *shader_version)
858 {
859     static const char * const rastout_reg_names[] = {"oPos", "oFog", "oPts"};
860     static const char * const misctype_reg_names[] = {"vPos", "vFace"};
861     UINT offset = reg->idx;
862
863     switch (reg->type)
864     {
865         case WINED3DSPR_TEMP:
866             TRACE("r");
867             break;
868
869         case WINED3DSPR_INPUT:
870             TRACE("v");
871             break;
872
873         case WINED3DSPR_CONST:
874         case WINED3DSPR_CONST2:
875         case WINED3DSPR_CONST3:
876         case WINED3DSPR_CONST4:
877             TRACE("c");
878             offset = shader_get_float_offset(reg->type, reg->idx);
879             break;
880
881         case WINED3DSPR_TEXTURE: /* vs: case WINED3DSPR_ADDR */
882             TRACE("%c", shader_version->type == WINED3D_SHADER_TYPE_PIXEL ? 't' : 'a');
883             break;
884
885         case WINED3DSPR_RASTOUT:
886             TRACE("%s", rastout_reg_names[reg->idx]);
887             break;
888
889         case WINED3DSPR_COLOROUT:
890             TRACE("oC");
891             break;
892
893         case WINED3DSPR_DEPTHOUT:
894             TRACE("oDepth");
895             break;
896
897         case WINED3DSPR_ATTROUT:
898             TRACE("oD");
899             break;
900
901         case WINED3DSPR_TEXCRDOUT:
902             /* Vertex shaders >= 3.0 use general purpose output registers
903              * (WINED3DSPR_OUTPUT), which can include an address token. */
904             if (shader_version->major >= 3) TRACE("o");
905             else TRACE("oT");
906             break;
907
908         case WINED3DSPR_CONSTINT:
909             TRACE("i");
910             break;
911
912         case WINED3DSPR_CONSTBOOL:
913             TRACE("b");
914             break;
915
916         case WINED3DSPR_LABEL:
917             TRACE("l");
918             break;
919
920         case WINED3DSPR_LOOP:
921             TRACE("aL");
922             break;
923
924         case WINED3DSPR_SAMPLER:
925             TRACE("s");
926             break;
927
928         case WINED3DSPR_MISCTYPE:
929             if (reg->idx > 1) FIXME("Unhandled misctype register %u.\n", reg->idx);
930             else TRACE("%s", misctype_reg_names[reg->idx]);
931             break;
932
933         case WINED3DSPR_PREDICATE:
934             TRACE("p");
935             break;
936
937         case WINED3DSPR_IMMCONST:
938             TRACE("l");
939             break;
940
941         case WINED3DSPR_CONSTBUFFER:
942             TRACE("cb");
943             break;
944
945         default:
946             TRACE("unhandled_rtype(%#x)", reg->type);
947             break;
948     }
949
950     if (reg->type == WINED3DSPR_IMMCONST)
951     {
952         TRACE("(");
953         switch (reg->immconst_type)
954         {
955             case WINED3D_IMMCONST_FLOAT:
956                 TRACE("%.8e", *(const float *)reg->immconst_data);
957                 break;
958
959             case WINED3D_IMMCONST_FLOAT4:
960                 TRACE("%.8e, %.8e, %.8e, %.8e",
961                         *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
962                         *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
963                 break;
964
965             default:
966                 TRACE("<unhandled immconst_type %#x>", reg->immconst_type);
967                 break;
968         }
969         TRACE(")");
970     }
971     else if (reg->type != WINED3DSPR_RASTOUT && reg->type != WINED3DSPR_MISCTYPE)
972     {
973         if (reg->array_idx != ~0U)
974         {
975             TRACE("%u[%u", offset, reg->array_idx);
976             if (reg->rel_addr)
977             {
978                 TRACE(" + ");
979                 shader_dump_src_param(reg->rel_addr, shader_version);
980             }
981             TRACE("]");
982         }
983         else
984         {
985             if (reg->rel_addr)
986             {
987                 TRACE("[");
988                 shader_dump_src_param(reg->rel_addr, shader_version);
989                 TRACE(" + ");
990             }
991             TRACE("%u", offset);
992             if (reg->rel_addr) TRACE("]");
993         }
994     }
995 }
996
997 void shader_dump_dst_param(const struct wined3d_shader_dst_param *param,
998         const struct wined3d_shader_version *shader_version)
999 {
1000     DWORD write_mask = param->write_mask;
1001
1002     shader_dump_register(&param->reg, shader_version);
1003
1004     if (write_mask != WINED3DSP_WRITEMASK_ALL)
1005     {
1006         static const char *write_mask_chars = "xyzw";
1007
1008         TRACE(".");
1009         if (write_mask & WINED3DSP_WRITEMASK_0) TRACE("%c", write_mask_chars[0]);
1010         if (write_mask & WINED3DSP_WRITEMASK_1) TRACE("%c", write_mask_chars[1]);
1011         if (write_mask & WINED3DSP_WRITEMASK_2) TRACE("%c", write_mask_chars[2]);
1012         if (write_mask & WINED3DSP_WRITEMASK_3) TRACE("%c", write_mask_chars[3]);
1013     }
1014 }
1015
1016 void shader_dump_src_param(const struct wined3d_shader_src_param *param,
1017         const struct wined3d_shader_version *shader_version)
1018 {
1019     DWORD src_modifier = param->modifiers;
1020     DWORD swizzle = param->swizzle;
1021
1022     if (src_modifier == WINED3DSPSM_NEG
1023             || src_modifier == WINED3DSPSM_BIASNEG
1024             || src_modifier == WINED3DSPSM_SIGNNEG
1025             || src_modifier == WINED3DSPSM_X2NEG
1026             || src_modifier == WINED3DSPSM_ABSNEG)
1027         TRACE("-");
1028     else if (src_modifier == WINED3DSPSM_COMP)
1029         TRACE("1-");
1030     else if (src_modifier == WINED3DSPSM_NOT)
1031         TRACE("!");
1032
1033     if (src_modifier == WINED3DSPSM_ABS || src_modifier == WINED3DSPSM_ABSNEG)
1034         TRACE("abs(");
1035
1036     shader_dump_register(&param->reg, shader_version);
1037
1038     if (src_modifier)
1039     {
1040         switch (src_modifier)
1041         {
1042             case WINED3DSPSM_NONE:    break;
1043             case WINED3DSPSM_NEG:     break;
1044             case WINED3DSPSM_NOT:     break;
1045             case WINED3DSPSM_BIAS:    TRACE("_bias"); break;
1046             case WINED3DSPSM_BIASNEG: TRACE("_bias"); break;
1047             case WINED3DSPSM_SIGN:    TRACE("_bx2"); break;
1048             case WINED3DSPSM_SIGNNEG: TRACE("_bx2"); break;
1049             case WINED3DSPSM_COMP:    break;
1050             case WINED3DSPSM_X2:      TRACE("_x2"); break;
1051             case WINED3DSPSM_X2NEG:   TRACE("_x2"); break;
1052             case WINED3DSPSM_DZ:      TRACE("_dz"); break;
1053             case WINED3DSPSM_DW:      TRACE("_dw"); break;
1054             case WINED3DSPSM_ABSNEG:  TRACE(")"); break;
1055             case WINED3DSPSM_ABS:     TRACE(")"); break;
1056             default:                  TRACE("_unknown_modifier(%#x)", src_modifier);
1057         }
1058     }
1059
1060     if (swizzle != WINED3DSP_NOSWIZZLE)
1061     {
1062         static const char *swizzle_chars = "xyzw";
1063         DWORD swizzle_x = swizzle & 0x03;
1064         DWORD swizzle_y = (swizzle >> 2) & 0x03;
1065         DWORD swizzle_z = (swizzle >> 4) & 0x03;
1066         DWORD swizzle_w = (swizzle >> 6) & 0x03;
1067
1068         if (swizzle_x == swizzle_y
1069                 && swizzle_x == swizzle_z
1070                 && swizzle_x == swizzle_w)
1071         {
1072             TRACE(".%c", swizzle_chars[swizzle_x]);
1073         }
1074         else
1075         {
1076             TRACE(".%c%c%c%c", swizzle_chars[swizzle_x], swizzle_chars[swizzle_y],
1077                     swizzle_chars[swizzle_z], swizzle_chars[swizzle_w]);
1078         }
1079     }
1080 }
1081
1082 /* Shared code in order to generate the bulk of the shader string.
1083  * NOTE: A description of how to parse tokens can be found on MSDN. */
1084 void shader_generate_main(IWineD3DBaseShader *iface, struct wined3d_shader_buffer *buffer,
1085         const shader_reg_maps *reg_maps, const DWORD *byte_code, void *backend_ctx)
1086 {
1087     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)iface;
1088     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)shader->baseShader.device;
1089     const struct wined3d_shader_frontend *fe = shader->baseShader.frontend;
1090     void *fe_data = shader->baseShader.frontend_data;
1091     struct wined3d_shader_src_param src_rel_addr[4];
1092     struct wined3d_shader_src_param src_param[4];
1093     struct wined3d_shader_version shader_version;
1094     struct wined3d_shader_src_param dst_rel_addr;
1095     struct wined3d_shader_dst_param dst_param;
1096     struct wined3d_shader_instruction ins;
1097     struct wined3d_shader_context ctx;
1098     const DWORD *ptr = byte_code;
1099     DWORD i;
1100
1101     /* Initialize current parsing state. */
1102     ctx.shader = iface;
1103     ctx.gl_info = &device->adapter->gl_info;
1104     ctx.reg_maps = reg_maps;
1105     ctx.buffer = buffer;
1106     ctx.backend_data = backend_ctx;
1107
1108     ins.ctx = &ctx;
1109     ins.dst = &dst_param;
1110     ins.src = src_param;
1111     shader->baseShader.parse_state.current_row = 0;
1112
1113     fe->shader_read_header(fe_data, &ptr, &shader_version);
1114
1115     while (!fe->shader_is_end(fe_data, &ptr))
1116     {
1117         const char *comment;
1118         UINT param_size;
1119
1120         /* Skip comment tokens. */
1121         fe->shader_read_comment(&ptr, &comment);
1122         if (comment) continue;
1123
1124         /* Read opcode. */
1125         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
1126
1127         /* Unknown opcode and its parameters. */
1128         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
1129         {
1130             TRACE("Skipping unrecognized instruction.\n");
1131             ptr += param_size;
1132             continue;
1133         }
1134
1135         /* Nothing to do. */
1136         if (ins.handler_idx == WINED3DSIH_DCL
1137                 || ins.handler_idx == WINED3DSIH_NOP
1138                 || ins.handler_idx == WINED3DSIH_DEF
1139                 || ins.handler_idx == WINED3DSIH_DEFI
1140                 || ins.handler_idx == WINED3DSIH_DEFB
1141                 || ins.handler_idx == WINED3DSIH_PHASE)
1142         {
1143             ptr += param_size;
1144             continue;
1145         }
1146
1147         /* Destination token */
1148         if (ins.dst_count) fe->shader_read_dst_param(fe_data, &ptr, &dst_param, &dst_rel_addr);
1149
1150         /* Predication token */
1151         if (ins.predicate) ins.predicate = *ptr++;
1152
1153         /* Other source tokens */
1154         for (i = 0; i < ins.src_count; ++i)
1155         {
1156             fe->shader_read_src_param(fe_data, &ptr, &src_param[i], &src_rel_addr[i]);
1157         }
1158
1159         /* Call appropriate function for output target */
1160         device->shader_backend->shader_handle_instruction(&ins);
1161     }
1162 }
1163
1164 static void shader_dump_ins_modifiers(const struct wined3d_shader_dst_param *dst)
1165 {
1166     DWORD mmask = dst->modifiers;
1167
1168     switch (dst->shift)
1169     {
1170         case 0: break;
1171         case 13: TRACE("_d8"); break;
1172         case 14: TRACE("_d4"); break;
1173         case 15: TRACE("_d2"); break;
1174         case 1: TRACE("_x2"); break;
1175         case 2: TRACE("_x4"); break;
1176         case 3: TRACE("_x8"); break;
1177         default: TRACE("_unhandled_shift(%d)", dst->shift); break;
1178     }
1179
1180     if (mmask & WINED3DSPDM_SATURATE)         TRACE("_sat");
1181     if (mmask & WINED3DSPDM_PARTIALPRECISION) TRACE("_pp");
1182     if (mmask & WINED3DSPDM_MSAMPCENTROID)    TRACE("_centroid");
1183
1184     mmask &= ~(WINED3DSPDM_SATURATE | WINED3DSPDM_PARTIALPRECISION | WINED3DSPDM_MSAMPCENTROID);
1185     if (mmask) FIXME("_unrecognized_modifier(%#x)", mmask);
1186 }
1187
1188 static void shader_trace_init(const struct wined3d_shader_frontend *fe, void *fe_data, const DWORD *byte_code)
1189 {
1190     struct wined3d_shader_version shader_version;
1191     const DWORD *ptr = byte_code;
1192     const char *type_prefix;
1193     DWORD i;
1194
1195     TRACE("Parsing %p.\n", byte_code);
1196
1197     fe->shader_read_header(fe_data, &ptr, &shader_version);
1198
1199     switch (shader_version.type)
1200     {
1201         case WINED3D_SHADER_TYPE_VERTEX:
1202             type_prefix = "vs";
1203             break;
1204
1205         case WINED3D_SHADER_TYPE_GEOMETRY:
1206             type_prefix = "gs";
1207             break;
1208
1209         case WINED3D_SHADER_TYPE_PIXEL:
1210             type_prefix = "ps";
1211             break;
1212
1213         default:
1214             FIXME("Unhandled shader type %#x.\n", shader_version.type);
1215             type_prefix = "unknown";
1216             break;
1217     }
1218
1219     TRACE("%s_%u_%u\n", type_prefix, shader_version.major, shader_version.minor);
1220
1221     while (!fe->shader_is_end(fe_data, &ptr))
1222     {
1223         struct wined3d_shader_instruction ins;
1224         const char *comment;
1225         UINT param_size;
1226
1227         /* comment */
1228         fe->shader_read_comment(&ptr, &comment);
1229         if (comment)
1230         {
1231             TRACE("//%s\n", comment);
1232             continue;
1233         }
1234
1235         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
1236         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
1237         {
1238             TRACE("Skipping unrecognized instruction.\n");
1239             ptr += param_size;
1240             continue;
1241         }
1242
1243         if (ins.handler_idx == WINED3DSIH_DCL)
1244         {
1245             struct wined3d_shader_semantic semantic;
1246
1247             fe->shader_read_semantic(&ptr, &semantic);
1248
1249             shader_dump_decl_usage(&semantic, &shader_version);
1250             shader_dump_ins_modifiers(&semantic.reg);
1251             TRACE(" ");
1252             shader_dump_dst_param(&semantic.reg, &shader_version);
1253         }
1254         else if (ins.handler_idx == WINED3DSIH_DEF)
1255         {
1256             struct wined3d_shader_src_param rel_addr;
1257             struct wined3d_shader_dst_param dst;
1258
1259             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1260
1261             TRACE("def c%u = %f, %f, %f, %f", shader_get_float_offset(dst.reg.type, dst.reg.idx),
1262                     *(const float *)(ptr),
1263                     *(const float *)(ptr + 1),
1264                     *(const float *)(ptr + 2),
1265                     *(const float *)(ptr + 3));
1266             ptr += 4;
1267         }
1268         else if (ins.handler_idx == WINED3DSIH_DEFI)
1269         {
1270             struct wined3d_shader_src_param rel_addr;
1271             struct wined3d_shader_dst_param dst;
1272
1273             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1274
1275             TRACE("defi i%u = %d, %d, %d, %d", dst.reg.idx,
1276                     *(ptr),
1277                     *(ptr + 1),
1278                     *(ptr + 2),
1279                     *(ptr + 3));
1280             ptr += 4;
1281         }
1282         else if (ins.handler_idx == WINED3DSIH_DEFB)
1283         {
1284             struct wined3d_shader_src_param rel_addr;
1285             struct wined3d_shader_dst_param dst;
1286
1287             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1288
1289             TRACE("defb b%u = %s", dst.reg.idx, *ptr ? "true" : "false");
1290             ++ptr;
1291         }
1292         else
1293         {
1294             struct wined3d_shader_src_param dst_rel_addr, src_rel_addr;
1295             struct wined3d_shader_dst_param dst_param;
1296             struct wined3d_shader_src_param src_param;
1297
1298             if (ins.dst_count)
1299             {
1300                 fe->shader_read_dst_param(fe_data, &ptr, &dst_param, &dst_rel_addr);
1301             }
1302
1303             /* Print out predication source token first - it follows
1304              * the destination token. */
1305             if (ins.predicate)
1306             {
1307                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
1308                 TRACE("(");
1309                 shader_dump_src_param(&src_param, &shader_version);
1310                 TRACE(") ");
1311             }
1312
1313             /* PixWin marks instructions with the coissue flag with a '+' */
1314             if (ins.coissue) TRACE("+");
1315
1316             TRACE("%s", shader_opcode_names[ins.handler_idx]);
1317
1318             if (ins.handler_idx == WINED3DSIH_IFC
1319                     || ins.handler_idx == WINED3DSIH_BREAKC)
1320             {
1321                 switch (ins.flags)
1322                 {
1323                     case COMPARISON_GT: TRACE("_gt"); break;
1324                     case COMPARISON_EQ: TRACE("_eq"); break;
1325                     case COMPARISON_GE: TRACE("_ge"); break;
1326                     case COMPARISON_LT: TRACE("_lt"); break;
1327                     case COMPARISON_NE: TRACE("_ne"); break;
1328                     case COMPARISON_LE: TRACE("_le"); break;
1329                     default: TRACE("_(%u)", ins.flags);
1330                 }
1331             }
1332             else if (ins.handler_idx == WINED3DSIH_TEX
1333                     && shader_version.major >= 2
1334                     && (ins.flags & WINED3DSI_TEXLD_PROJECT))
1335             {
1336                 TRACE("p");
1337             }
1338
1339             /* We already read the destination token, print it. */
1340             if (ins.dst_count)
1341             {
1342                 shader_dump_ins_modifiers(&dst_param);
1343                 TRACE(" ");
1344                 shader_dump_dst_param(&dst_param, &shader_version);
1345             }
1346
1347             /* Other source tokens */
1348             for (i = ins.dst_count; i < (ins.dst_count + ins.src_count); ++i)
1349             {
1350                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
1351                 TRACE(!i ? " " : ", ");
1352                 shader_dump_src_param(&src_param, &shader_version);
1353             }
1354         }
1355         TRACE("\n");
1356     }
1357 }
1358
1359 static void shader_cleanup(IWineD3DBaseShader *iface)
1360 {
1361     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)iface;
1362
1363     ((IWineD3DDeviceImpl *)shader->baseShader.device)->shader_backend->shader_destroy(iface);
1364     HeapFree(GetProcessHeap(), 0, shader->baseShader.reg_maps.constf);
1365     HeapFree(GetProcessHeap(), 0, shader->baseShader.function);
1366     shader_delete_constant_list(&shader->baseShader.constantsF);
1367     shader_delete_constant_list(&shader->baseShader.constantsB);
1368     shader_delete_constant_list(&shader->baseShader.constantsI);
1369     list_remove(&shader->baseShader.shader_list_entry);
1370
1371     if (shader->baseShader.frontend && shader->baseShader.frontend_data)
1372     {
1373         shader->baseShader.frontend->shader_free(shader->baseShader.frontend_data);
1374     }
1375 }
1376
1377 static void shader_none_handle_instruction(const struct wined3d_shader_instruction *ins) {}
1378 static void shader_none_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS) {}
1379 static void shader_none_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {}
1380 static void shader_none_deselect_depth_blt(IWineD3DDevice *iface) {}
1381 static void shader_none_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count) {}
1382 static void shader_none_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count) {}
1383 static void shader_none_load_constants(const struct wined3d_context *context, char usePS, char useVS) {}
1384 static void shader_none_load_np2fixup_constants(IWineD3DDevice *iface, char usePS, char useVS) {}
1385 static void shader_none_destroy(IWineD3DBaseShader *iface) {}
1386 static HRESULT shader_none_alloc(IWineD3DDevice *iface) {return WINED3D_OK;}
1387 static void shader_none_free(IWineD3DDevice *iface) {}
1388 static BOOL shader_none_dirty_const(IWineD3DDevice *iface) {return FALSE;}
1389
1390 static void shader_none_get_caps(WINED3DDEVTYPE devtype,
1391         const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
1392 {
1393     /* Set the shader caps to 0 for the none shader backend */
1394     caps->VertexShaderVersion = 0;
1395     caps->PixelShaderVersion = 0;
1396     caps->PixelShader1xMaxValue = 0.0f;
1397 }
1398
1399 static BOOL shader_none_color_fixup_supported(struct color_fixup_desc fixup)
1400 {
1401     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
1402     {
1403         TRACE("Checking support for fixup:\n");
1404         dump_color_fixup_desc(fixup);
1405     }
1406
1407     /* Faked to make some apps happy. */
1408     if (!is_yuv_fixup(fixup))
1409     {
1410         TRACE("[OK]\n");
1411         return TRUE;
1412     }
1413
1414     TRACE("[FAILED]\n");
1415     return FALSE;
1416 }
1417
1418 const shader_backend_t none_shader_backend = {
1419     shader_none_handle_instruction,
1420     shader_none_select,
1421     shader_none_select_depth_blt,
1422     shader_none_deselect_depth_blt,
1423     shader_none_update_float_vertex_constants,
1424     shader_none_update_float_pixel_constants,
1425     shader_none_load_constants,
1426     shader_none_load_np2fixup_constants,
1427     shader_none_destroy,
1428     shader_none_alloc,
1429     shader_none_free,
1430     shader_none_dirty_const,
1431     shader_none_get_caps,
1432     shader_none_color_fixup_supported,
1433 };
1434
1435 static void shader_get_parent(IWineD3DBaseShaderImpl *shader, IUnknown **parent)
1436 {
1437     *parent = shader->baseShader.parent;
1438     IUnknown_AddRef(*parent);
1439     TRACE("shader %p, returning %p.\n", shader, *parent);
1440 }
1441
1442 static HRESULT shader_get_function(IWineD3DBaseShaderImpl *shader, void *data, UINT *data_size)
1443 {
1444     if (!data)
1445     {
1446         *data_size = shader->baseShader.functionLength;
1447         return WINED3D_OK;
1448     }
1449
1450     if (*data_size < shader->baseShader.functionLength)
1451     {
1452         /* MSDN claims (for d3d8 at least) that if *pSizeOfData is smaller
1453          * than the required size we should write the required size and
1454          * return D3DERR_MOREDATA. That's not actually true. */
1455         return WINED3DERR_INVALIDCALL;
1456     }
1457
1458     memcpy(data, shader->baseShader.function, shader->baseShader.functionLength);
1459
1460     return WINED3D_OK;
1461 }
1462
1463 static HRESULT shader_set_function(IWineD3DBaseShaderImpl *shader, const DWORD *byte_code,
1464         const struct wined3d_shader_signature *output_signature, DWORD float_const_count)
1465 {
1466     struct shader_reg_maps *reg_maps = &shader->baseShader.reg_maps;
1467     const struct wined3d_shader_frontend *fe;
1468     HRESULT hr;
1469
1470     TRACE("shader %p, byte_code %p, output_signature %p, float_const_count %u.\n",
1471             shader, byte_code, output_signature, float_const_count);
1472
1473     fe = shader_select_frontend(*byte_code);
1474     if (!fe)
1475     {
1476         FIXME("Unable to find frontend for shader.\n");
1477         return WINED3DERR_INVALIDCALL;
1478     }
1479     shader->baseShader.frontend = fe;
1480     shader->baseShader.frontend_data = fe->shader_init(byte_code, output_signature);
1481     if (!shader->baseShader.frontend_data)
1482     {
1483         FIXME("Failed to initialize frontend.\n");
1484         return WINED3DERR_INVALIDCALL;
1485     }
1486
1487     /* First pass: trace shader. */
1488     if (TRACE_ON(d3d_shader)) shader_trace_init(fe, shader->baseShader.frontend_data, byte_code);
1489
1490     /* Initialize immediate constant lists. */
1491     list_init(&shader->baseShader.constantsF);
1492     list_init(&shader->baseShader.constantsB);
1493     list_init(&shader->baseShader.constantsI);
1494
1495     /* Second pass: figure out which registers are used, what the semantics are, etc. */
1496     hr = shader_get_registers_used((IWineD3DBaseShader *)shader, fe,
1497             reg_maps, shader->baseShader.input_signature, shader->baseShader.output_signature,
1498             byte_code, float_const_count);
1499     if (FAILED(hr)) return hr;
1500
1501     shader->baseShader.function = HeapAlloc(GetProcessHeap(), 0, shader->baseShader.functionLength);
1502     if (!shader->baseShader.function) return E_OUTOFMEMORY;
1503     memcpy(shader->baseShader.function, byte_code, shader->baseShader.functionLength);
1504
1505     return WINED3D_OK;
1506 }
1507
1508 static HRESULT STDMETHODCALLTYPE vertexshader_QueryInterface(IWineD3DVertexShader *iface, REFIID riid, void **object)
1509 {
1510     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
1511
1512     if (IsEqualGUID(riid, &IID_IWineD3DVertexShader)
1513             || IsEqualGUID(riid, &IID_IWineD3DBaseShader)
1514             || IsEqualGUID(riid, &IID_IWineD3DBase)
1515             || IsEqualGUID(riid, &IID_IUnknown))
1516     {
1517         IUnknown_AddRef(iface);
1518         *object = iface;
1519         return S_OK;
1520     }
1521
1522     WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
1523
1524     *object = NULL;
1525     return E_NOINTERFACE;
1526 }
1527
1528 static ULONG STDMETHODCALLTYPE vertexshader_AddRef(IWineD3DVertexShader *iface)
1529 {
1530     IWineD3DVertexShaderImpl *shader = (IWineD3DVertexShaderImpl *)iface;
1531     ULONG refcount = InterlockedIncrement(&shader->baseShader.ref);
1532
1533     TRACE("%p increasing refcount to %u.\n", shader, refcount);
1534
1535     return refcount;
1536 }
1537
1538 static ULONG STDMETHODCALLTYPE vertexshader_Release(IWineD3DVertexShader *iface)
1539 {
1540     IWineD3DVertexShaderImpl *shader = (IWineD3DVertexShaderImpl *)iface;
1541     ULONG refcount = InterlockedDecrement(&shader->baseShader.ref);
1542
1543     TRACE("%p decreasing refcount to %u.\n", shader, refcount);
1544
1545     if (!refcount)
1546     {
1547         shader_cleanup((IWineD3DBaseShader *)iface);
1548         shader->baseShader.parent_ops->wined3d_object_destroyed(shader->baseShader.parent);
1549         HeapFree(GetProcessHeap(), 0, shader);
1550     }
1551
1552     return refcount;
1553 }
1554
1555 static HRESULT STDMETHODCALLTYPE vertexshader_GetParent(IWineD3DVertexShader *iface, IUnknown **parent)
1556 {
1557     TRACE("iface %p, parent %p.\n", iface, parent);
1558
1559     shader_get_parent((IWineD3DBaseShaderImpl *)iface, parent);
1560
1561     return WINED3D_OK;
1562 }
1563
1564 static HRESULT STDMETHODCALLTYPE vertexshader_GetFunction(IWineD3DVertexShader *iface, void *data, UINT *data_size)
1565 {
1566     TRACE("iface %p, data %p, data_size %p.\n", iface, data, data_size);
1567
1568     return shader_get_function((IWineD3DBaseShaderImpl *)iface, data, data_size);
1569 }
1570
1571 /* Set local constants for d3d8 shaders. */
1572 static HRESULT STDMETHODCALLTYPE vertexshader_SetLocalConstantsF(IWineD3DVertexShader *iface,
1573         UINT start_idx, const float *src_data, UINT count)
1574 {
1575     IWineD3DVertexShaderImpl *shader =(IWineD3DVertexShaderImpl *)iface;
1576     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)shader->baseShader.device;
1577     UINT i, end_idx;
1578
1579     TRACE("iface %p, start_idx %u, src_data %p, count %u.\n", iface, start_idx, src_data, count);
1580
1581     end_idx = start_idx + count;
1582     if (end_idx > device->d3d_vshader_constantF)
1583     {
1584         WARN("end_idx %u > float constants limit %u.\n", end_idx, device->d3d_vshader_constantF);
1585         end_idx = device->d3d_vshader_constantF;
1586     }
1587
1588     for (i = start_idx; i < end_idx; ++i)
1589     {
1590         local_constant* lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
1591         if (!lconst) return E_OUTOFMEMORY;
1592
1593         lconst->idx = i;
1594         memcpy(lconst->value, src_data + (i - start_idx) * 4 /* 4 components */, 4 * sizeof(float));
1595         list_add_head(&shader->baseShader.constantsF, &lconst->entry);
1596     }
1597
1598     return WINED3D_OK;
1599 }
1600
1601 static const IWineD3DVertexShaderVtbl IWineD3DVertexShader_Vtbl =
1602 {
1603     /* IUnknown methods */
1604     vertexshader_QueryInterface,
1605     vertexshader_AddRef,
1606     vertexshader_Release,
1607     /* IWineD3DBase methods */
1608     vertexshader_GetParent,
1609     /* IWineD3DBaseShader methods */
1610     vertexshader_GetFunction,
1611     /* IWineD3DVertexShader methods */
1612     vertexshader_SetLocalConstantsF,
1613 };
1614
1615 void find_vs_compile_args(IWineD3DVertexShaderImpl *shader,
1616         IWineD3DStateBlockImpl *stateblock, struct vs_compile_args *args)
1617 {
1618     args->fog_src = stateblock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE ? VS_FOG_COORD : VS_FOG_Z;
1619     args->clip_enabled = stateblock->renderState[WINED3DRS_CLIPPING]
1620             && stateblock->renderState[WINED3DRS_CLIPPLANEENABLE];
1621     args->swizzle_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.swizzle_map;
1622 }
1623
1624 static BOOL match_usage(BYTE usage1, BYTE usage_idx1, BYTE usage2, BYTE usage_idx2)
1625 {
1626     if (usage_idx1 != usage_idx2) return FALSE;
1627     if (usage1 == usage2) return TRUE;
1628     if (usage1 == WINED3DDECLUSAGE_POSITION && usage2 == WINED3DDECLUSAGE_POSITIONT) return TRUE;
1629     if (usage2 == WINED3DDECLUSAGE_POSITION && usage1 == WINED3DDECLUSAGE_POSITIONT) return TRUE;
1630
1631     return FALSE;
1632 }
1633
1634 BOOL vshader_get_input(IWineD3DVertexShader *iface, BYTE usage_req, BYTE usage_idx_req, unsigned int *regnum)
1635 {
1636     IWineD3DVertexShaderImpl *shader = (IWineD3DVertexShaderImpl *)iface;
1637     WORD map = shader->baseShader.reg_maps.input_registers;
1638     unsigned int i;
1639
1640     for (i = 0; map; map >>= 1, ++i)
1641     {
1642         if (!(map & 1)) continue;
1643
1644         if (match_usage(shader->attributes[i].usage,
1645                 shader->attributes[i].usage_idx, usage_req, usage_idx_req))
1646         {
1647             *regnum = i;
1648             return TRUE;
1649         }
1650     }
1651     return FALSE;
1652 }
1653
1654 static void vertexshader_set_limits(IWineD3DVertexShaderImpl *shader)
1655 {
1656     DWORD shader_version = WINED3D_SHADER_VERSION(shader->baseShader.reg_maps.shader_version.major,
1657             shader->baseShader.reg_maps.shader_version.minor);
1658     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)shader->baseShader.device;
1659
1660     shader->baseShader.limits.texcoord = 0;
1661     shader->baseShader.limits.attributes = 16;
1662     shader->baseShader.limits.packed_input = 0;
1663
1664     switch (shader_version)
1665     {
1666         case WINED3D_SHADER_VERSION(1, 0):
1667         case WINED3D_SHADER_VERSION(1, 1):
1668             shader->baseShader.limits.temporary = 12;
1669             shader->baseShader.limits.constant_bool = 0;
1670             shader->baseShader.limits.constant_int = 0;
1671             shader->baseShader.limits.address = 1;
1672             shader->baseShader.limits.packed_output = 0;
1673             shader->baseShader.limits.sampler = 0;
1674             shader->baseShader.limits.label = 0;
1675             /* TODO: vs_1_1 has a minimum of 96 constants. What happens when
1676              * a vs_1_1 shader is used on a vs_3_0 capable card that has 256
1677              * constants? */
1678             shader->baseShader.limits.constant_float = min(256, device->d3d_vshader_constantF);
1679             break;
1680
1681         case WINED3D_SHADER_VERSION(2, 0):
1682         case WINED3D_SHADER_VERSION(2, 1):
1683             shader->baseShader.limits.temporary = 12;
1684             shader->baseShader.limits.constant_bool = 16;
1685             shader->baseShader.limits.constant_int = 16;
1686             shader->baseShader.limits.address = 1;
1687             shader->baseShader.limits.packed_output = 0;
1688             shader->baseShader.limits.sampler = 0;
1689             shader->baseShader.limits.label = 16;
1690             shader->baseShader.limits.constant_float = min(256, device->d3d_vshader_constantF);
1691             break;
1692
1693         case WINED3D_SHADER_VERSION(4, 0):
1694             FIXME("Using 3.0 limits for 4.0 shader.\n");
1695             /* Fall through. */
1696
1697         case WINED3D_SHADER_VERSION(3, 0):
1698             shader->baseShader.limits.temporary = 32;
1699             shader->baseShader.limits.constant_bool = 32;
1700             shader->baseShader.limits.constant_int = 32;
1701             shader->baseShader.limits.address = 1;
1702             shader->baseShader.limits.packed_output = 12;
1703             shader->baseShader.limits.sampler = 4;
1704             shader->baseShader.limits.label = 16; /* FIXME: 2048 */
1705             /* DX10 cards on Windows advertise a d3d9 constant limit of 256
1706              * even though they are capable of supporting much more (GL
1707              * drivers advertise 1024). d3d9.dll and d3d8.dll clamp the
1708              * wined3d-advertised maximum. Clamp the constant limit for <= 3.0
1709              * shaders to 256. */
1710             shader->baseShader.limits.constant_float = min(256, device->d3d_vshader_constantF);
1711             break;
1712
1713         default:
1714             shader->baseShader.limits.temporary = 12;
1715             shader->baseShader.limits.constant_bool = 16;
1716             shader->baseShader.limits.constant_int = 16;
1717             shader->baseShader.limits.address = 1;
1718             shader->baseShader.limits.packed_output = 0;
1719             shader->baseShader.limits.sampler = 0;
1720             shader->baseShader.limits.label = 16;
1721             shader->baseShader.limits.constant_float = min(256, device->d3d_vshader_constantF);
1722             FIXME("Unrecognized vertex shader version \"%u.%u\".\n",
1723                     shader->baseShader.reg_maps.shader_version.major,
1724                     shader->baseShader.reg_maps.shader_version.minor);
1725     }
1726 }
1727
1728 HRESULT vertexshader_init(IWineD3DVertexShaderImpl *shader, IWineD3DDeviceImpl *device,
1729         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
1730         IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
1731 {
1732     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1733     struct shader_reg_maps *reg_maps = &shader->baseShader.reg_maps;
1734     unsigned int i;
1735     HRESULT hr;
1736     WORD map;
1737
1738     if (!byte_code) return WINED3DERR_INVALIDCALL;
1739
1740     shader->lpVtbl = &IWineD3DVertexShader_Vtbl;
1741     shader_init(&shader->baseShader, device, parent, parent_ops);
1742
1743     hr = shader_set_function((IWineD3DBaseShaderImpl *)shader, byte_code,
1744             output_signature, device->d3d_vshader_constantF);
1745     if (FAILED(hr))
1746     {
1747         WARN("Failed to set function, hr %#x.\n", hr);
1748         shader_cleanup((IWineD3DBaseShader *)shader);
1749         return hr;
1750     }
1751
1752     map = shader->baseShader.reg_maps.input_registers;
1753     for (i = 0; map; map >>= 1, ++i)
1754     {
1755         if (!(map & 1) || !shader->baseShader.input_signature[i].semantic_name) continue;
1756
1757         shader->attributes[i].usage =
1758                 shader_usage_from_semantic_name(shader->baseShader.input_signature[i].semantic_name);
1759         shader->attributes[i].usage_idx = shader->baseShader.input_signature[i].semantic_idx;
1760     }
1761
1762     if (output_signature)
1763     {
1764         for (i = 0; i < output_signature->element_count; ++i)
1765         {
1766             struct wined3d_shader_signature_element *e = &output_signature->elements[i];
1767             reg_maps->output_registers |= 1 << e->register_idx;
1768             shader->baseShader.output_signature[e->register_idx] = *e;
1769         }
1770     }
1771
1772     vertexshader_set_limits(shader);
1773
1774     if (device->vs_selected_mode == SHADER_ARB
1775             && (gl_info->quirks & WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT)
1776             && shader->min_rel_offset <= shader->max_rel_offset)
1777     {
1778         if (shader->max_rel_offset - shader->min_rel_offset > 127)
1779         {
1780             FIXME("The difference between the minimum and maximum relative offset is > 127.\n");
1781             FIXME("Which this OpenGL implementation does not support. Try using GLSL.\n");
1782             FIXME("Min: %d, Max: %d.\n", shader->min_rel_offset, shader->max_rel_offset);
1783         }
1784         else if (shader->max_rel_offset - shader->min_rel_offset > 63)
1785         {
1786             shader->rel_offset = shader->min_rel_offset + 63;
1787         }
1788         else if (shader->max_rel_offset > 63)
1789         {
1790             shader->rel_offset = shader->min_rel_offset;
1791         }
1792         else
1793         {
1794             shader->rel_offset = 0;
1795         }
1796     }
1797
1798     shader->baseShader.load_local_constsF = shader->baseShader.reg_maps.usesrelconstF
1799             && !list_empty(&shader->baseShader.constantsF);
1800
1801     return WINED3D_OK;
1802 }
1803
1804 static HRESULT STDMETHODCALLTYPE geometryshader_QueryInterface(IWineD3DGeometryShader *iface,
1805         REFIID riid, void **object)
1806 {
1807     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
1808
1809     if (IsEqualGUID(riid, &IID_IWineD3DGeometryShader)
1810             || IsEqualGUID(riid, &IID_IWineD3DBaseShader)
1811             || IsEqualGUID(riid, &IID_IWineD3DBase)
1812             || IsEqualGUID(riid, &IID_IUnknown))
1813     {
1814         IUnknown_AddRef(iface);
1815         *object = iface;
1816         return S_OK;
1817     }
1818
1819     WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
1820
1821     *object = NULL;
1822     return E_NOINTERFACE;
1823 }
1824
1825 static ULONG STDMETHODCALLTYPE geometryshader_AddRef(IWineD3DGeometryShader *iface)
1826 {
1827     struct wined3d_geometryshader *shader = (struct wined3d_geometryshader *)iface;
1828     ULONG refcount = InterlockedIncrement(&shader->base_shader.ref);
1829
1830     TRACE("%p increasing refcount to %u.\n", shader, refcount);
1831
1832     return refcount;
1833 }
1834
1835 static ULONG STDMETHODCALLTYPE geometryshader_Release(IWineD3DGeometryShader *iface)
1836 {
1837     struct wined3d_geometryshader *shader = (struct wined3d_geometryshader *)iface;
1838     ULONG refcount = InterlockedDecrement(&shader->base_shader.ref);
1839
1840     TRACE("%p decreasing refcount to %u.\n", shader, refcount);
1841
1842     if (!refcount)
1843     {
1844         shader_cleanup((IWineD3DBaseShader *)iface);
1845         shader->base_shader.parent_ops->wined3d_object_destroyed(shader->base_shader.parent);
1846         HeapFree(GetProcessHeap(), 0, shader);
1847     }
1848
1849     return refcount;
1850 }
1851
1852 static HRESULT STDMETHODCALLTYPE geometryshader_GetParent(IWineD3DGeometryShader *iface, IUnknown **parent)
1853 {
1854     TRACE("iface %p, parent %p.\n", iface, parent);
1855
1856     shader_get_parent((IWineD3DBaseShaderImpl *)iface, parent);
1857
1858     return WINED3D_OK;
1859 }
1860
1861 static HRESULT STDMETHODCALLTYPE geometryshader_GetFunction(IWineD3DGeometryShader *iface, void *data, UINT *data_size)
1862 {
1863     TRACE("iface %p, data %p, data_size %p.\n", iface, data, data_size);
1864
1865     return shader_get_function((IWineD3DBaseShaderImpl *)iface, data, data_size);
1866 }
1867
1868 static const IWineD3DGeometryShaderVtbl wined3d_geometryshader_vtbl =
1869 {
1870     /* IUnknown methods */
1871     geometryshader_QueryInterface,
1872     geometryshader_AddRef,
1873     geometryshader_Release,
1874     /* IWineD3DBase methods */
1875     geometryshader_GetParent,
1876     /* IWineD3DBaseShader methods */
1877     geometryshader_GetFunction,
1878 };
1879
1880 HRESULT geometryshader_init(struct wined3d_geometryshader *shader, IWineD3DDeviceImpl *device,
1881         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
1882         IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
1883 {
1884     HRESULT hr;
1885
1886     shader->vtbl = &wined3d_geometryshader_vtbl;
1887     shader_init(&shader->base_shader, device, parent, parent_ops);
1888
1889     hr = shader_set_function((IWineD3DBaseShaderImpl *)shader, byte_code, output_signature, 0);
1890     if (FAILED(hr))
1891     {
1892         WARN("Failed to set function, hr %#x.\n", hr);
1893         shader_cleanup((IWineD3DBaseShader *)shader);
1894         return hr;
1895     }
1896
1897     shader->base_shader.load_local_constsF = FALSE;
1898
1899     return WINED3D_OK;
1900 }
1901
1902 static HRESULT STDMETHODCALLTYPE pixelshader_QueryInterface(IWineD3DPixelShader *iface, REFIID riid, void **object)
1903 {
1904     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
1905
1906     if (IsEqualGUID(riid, &IID_IWineD3DPixelShader)
1907             || IsEqualGUID(riid, &IID_IWineD3DBaseShader)
1908             || IsEqualGUID(riid, &IID_IWineD3DBase)
1909             || IsEqualGUID(riid, &IID_IUnknown))
1910     {
1911         IUnknown_AddRef(iface);
1912         *object = iface;
1913         return S_OK;
1914     }
1915
1916     WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
1917
1918     *object = NULL;
1919     return E_NOINTERFACE;
1920 }
1921
1922 static ULONG STDMETHODCALLTYPE pixelshader_AddRef(IWineD3DPixelShader *iface)
1923 {
1924     IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)iface;
1925     ULONG refcount = InterlockedIncrement(&shader->baseShader.ref);
1926
1927     TRACE("%p increasing refcount to %u.\n", shader, refcount);
1928
1929     return refcount;
1930 }
1931
1932 static ULONG STDMETHODCALLTYPE pixelshader_Release(IWineD3DPixelShader *iface)
1933 {
1934     IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)iface;
1935     ULONG refcount = InterlockedDecrement(&shader->baseShader.ref);
1936
1937     TRACE("%p decreasing refcount to %u.\n", shader, refcount);
1938
1939     if (!refcount)
1940     {
1941         shader_cleanup((IWineD3DBaseShader *)iface);
1942         shader->baseShader.parent_ops->wined3d_object_destroyed(shader->baseShader.parent);
1943         HeapFree(GetProcessHeap(), 0, shader);
1944     }
1945
1946     return refcount;
1947 }
1948
1949 static HRESULT STDMETHODCALLTYPE pixelshader_GetParent(IWineD3DPixelShader *iface, IUnknown **parent)
1950 {
1951     TRACE("iface %p, parent %p.\n", iface, parent);
1952
1953     shader_get_parent((IWineD3DBaseShaderImpl *)iface, parent);
1954
1955     return WINED3D_OK;
1956 }
1957
1958 static HRESULT STDMETHODCALLTYPE pixelshader_GetFunction(IWineD3DPixelShader *iface, void *data, UINT *data_size)
1959 {
1960     TRACE("iface %p, data %p, data_size %p.\n", iface, data, data_size);
1961
1962     return shader_get_function((IWineD3DBaseShaderImpl *)iface, data, data_size);
1963 }
1964
1965 static const IWineD3DPixelShaderVtbl IWineD3DPixelShader_Vtbl =
1966 {
1967     /* IUnknown methods */
1968     pixelshader_QueryInterface,
1969     pixelshader_AddRef,
1970     pixelshader_Release,
1971     /* IWineD3DBase methods */
1972     pixelshader_GetParent,
1973     /* IWineD3DBaseShader methods */
1974     pixelshader_GetFunction
1975 };
1976
1977 void find_ps_compile_args(IWineD3DPixelShaderImpl *shader,
1978         IWineD3DStateBlockImpl *stateblock, struct ps_compile_args *args)
1979 {
1980     IWineD3DBaseTextureImpl *texture;
1981     UINT i;
1982
1983     memset(args, 0, sizeof(*args)); /* FIXME: Make sure all bits are set. */
1984     args->srgb_correction = stateblock->renderState[WINED3DRS_SRGBWRITEENABLE] ? 1 : 0;
1985     args->np2_fixup = 0;
1986
1987     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
1988     {
1989         if (!shader->baseShader.reg_maps.sampler_type[i]) continue;
1990         texture = (IWineD3DBaseTextureImpl *)stateblock->textures[i];
1991         if (!texture)
1992         {
1993             args->color_fixup[i] = COLOR_FIXUP_IDENTITY;
1994             continue;
1995         }
1996         args->color_fixup[i] = texture->resource.format_desc->color_fixup;
1997
1998         /* Flag samplers that need NP2 texcoord fixup. */
1999         if (!texture->baseTexture.pow2Matrix_identity)
2000         {
2001             args->np2_fixup |= (1 << i);
2002         }
2003     }
2004     if (shader->baseShader.reg_maps.shader_version.major >= 3)
2005     {
2006         if (((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.position_transformed)
2007         {
2008             args->vp_mode = pretransformed;
2009         }
2010         else if (use_vs(stateblock))
2011         {
2012             args->vp_mode = vertexshader;
2013         }
2014         else
2015         {
2016             args->vp_mode = fixedfunction;
2017         }
2018         args->fog = FOG_OFF;
2019     }
2020     else
2021     {
2022         args->vp_mode = vertexshader;
2023         if (stateblock->renderState[WINED3DRS_FOGENABLE])
2024         {
2025             switch (stateblock->renderState[WINED3DRS_FOGTABLEMODE])
2026             {
2027                 case WINED3DFOG_NONE:
2028                     if (((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.position_transformed
2029                             || use_vs(stateblock))
2030                     {
2031                         args->fog = FOG_LINEAR;
2032                         break;
2033                     }
2034
2035                     switch (stateblock->renderState[WINED3DRS_FOGVERTEXMODE])
2036                     {
2037                         case WINED3DFOG_NONE: /* Fall through. */
2038                         case WINED3DFOG_LINEAR: args->fog = FOG_LINEAR; break;
2039                         case WINED3DFOG_EXP:    args->fog = FOG_EXP;    break;
2040                         case WINED3DFOG_EXP2:   args->fog = FOG_EXP2;   break;
2041                     }
2042                     break;
2043
2044                 case WINED3DFOG_LINEAR: args->fog = FOG_LINEAR; break;
2045                 case WINED3DFOG_EXP:    args->fog = FOG_EXP;    break;
2046                 case WINED3DFOG_EXP2:   args->fog = FOG_EXP2;   break;
2047             }
2048         }
2049         else
2050         {
2051             args->fog = FOG_OFF;
2052         }
2053     }
2054 }
2055
2056 static void pixelshader_set_limits(IWineD3DPixelShaderImpl *shader)
2057 {
2058     DWORD shader_version = WINED3D_SHADER_VERSION(shader->baseShader.reg_maps.shader_version.major,
2059             shader->baseShader.reg_maps.shader_version.minor);
2060
2061     shader->baseShader.limits.attributes = 0;
2062     shader->baseShader.limits.address = 0;
2063     shader->baseShader.limits.packed_output = 0;
2064
2065     switch (shader_version)
2066     {
2067         case WINED3D_SHADER_VERSION(1, 0):
2068         case WINED3D_SHADER_VERSION(1, 1):
2069         case WINED3D_SHADER_VERSION(1, 2):
2070         case WINED3D_SHADER_VERSION(1, 3):
2071             shader->baseShader.limits.temporary = 2;
2072             shader->baseShader.limits.constant_float = 8;
2073             shader->baseShader.limits.constant_int = 0;
2074             shader->baseShader.limits.constant_bool = 0;
2075             shader->baseShader.limits.texcoord = 4;
2076             shader->baseShader.limits.sampler = 4;
2077             shader->baseShader.limits.packed_input = 0;
2078             shader->baseShader.limits.label = 0;
2079             break;
2080
2081         case WINED3D_SHADER_VERSION(1, 4):
2082             shader->baseShader.limits.temporary = 6;
2083             shader->baseShader.limits.constant_float = 8;
2084             shader->baseShader.limits.constant_int = 0;
2085             shader->baseShader.limits.constant_bool = 0;
2086             shader->baseShader.limits.texcoord = 6;
2087             shader->baseShader.limits.sampler = 6;
2088             shader->baseShader.limits.packed_input = 0;
2089             shader->baseShader.limits.label = 0;
2090             break;
2091
2092         /* FIXME: Temporaries must match D3DPSHADERCAPS2_0.NumTemps. */
2093         case WINED3D_SHADER_VERSION(2, 0):
2094             shader->baseShader.limits.temporary = 32;
2095             shader->baseShader.limits.constant_float = 32;
2096             shader->baseShader.limits.constant_int = 16;
2097             shader->baseShader.limits.constant_bool = 16;
2098             shader->baseShader.limits.texcoord = 8;
2099             shader->baseShader.limits.sampler = 16;
2100             shader->baseShader.limits.packed_input = 0;
2101             break;
2102
2103         case WINED3D_SHADER_VERSION(2, 1):
2104             shader->baseShader.limits.temporary = 32;
2105             shader->baseShader.limits.constant_float = 32;
2106             shader->baseShader.limits.constant_int = 16;
2107             shader->baseShader.limits.constant_bool = 16;
2108             shader->baseShader.limits.texcoord = 8;
2109             shader->baseShader.limits.sampler = 16;
2110             shader->baseShader.limits.packed_input = 0;
2111             shader->baseShader.limits.label = 16;
2112             break;
2113
2114         case WINED3D_SHADER_VERSION(4, 0):
2115             FIXME("Using 3.0 limits for 4.0 shader.\n");
2116             /* Fall through. */
2117
2118         case WINED3D_SHADER_VERSION(3, 0):
2119             shader->baseShader.limits.temporary = 32;
2120             shader->baseShader.limits.constant_float = 224;
2121             shader->baseShader.limits.constant_int = 16;
2122             shader->baseShader.limits.constant_bool = 16;
2123             shader->baseShader.limits.texcoord = 0;
2124             shader->baseShader.limits.sampler = 16;
2125             shader->baseShader.limits.packed_input = 12;
2126             shader->baseShader.limits.label = 16; /* FIXME: 2048 */
2127             break;
2128
2129         default:
2130             shader->baseShader.limits.temporary = 32;
2131             shader->baseShader.limits.constant_float = 32;
2132             shader->baseShader.limits.constant_int = 16;
2133             shader->baseShader.limits.constant_bool = 16;
2134             shader->baseShader.limits.texcoord = 8;
2135             shader->baseShader.limits.sampler = 16;
2136             shader->baseShader.limits.packed_input = 0;
2137             shader->baseShader.limits.label = 0;
2138             FIXME("Unrecognized pixel shader version %u.%u\n",
2139                     shader->baseShader.reg_maps.shader_version.major,
2140                     shader->baseShader.reg_maps.shader_version.minor);
2141     }
2142 }
2143
2144 HRESULT pixelshader_init(IWineD3DPixelShaderImpl *shader, IWineD3DDeviceImpl *device,
2145         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
2146         IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
2147 {
2148     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2149     unsigned int i, highest_reg_used = 0, num_regs_used = 0;
2150     HRESULT hr;
2151
2152     if (!byte_code) return WINED3DERR_INVALIDCALL;
2153
2154     shader->lpVtbl = &IWineD3DPixelShader_Vtbl;
2155     shader_init(&shader->baseShader, device, parent, parent_ops);
2156
2157     hr = shader_set_function((IWineD3DBaseShaderImpl *)shader, byte_code,
2158             output_signature, device->d3d_pshader_constantF);
2159     if (FAILED(hr))
2160     {
2161         WARN("Failed to set function, hr %#x.\n", hr);
2162         shader_cleanup((IWineD3DBaseShader *)shader);
2163         return hr;
2164     }
2165
2166     pixelshader_set_limits(shader);
2167
2168     for (i = 0; i < MAX_REG_INPUT; ++i)
2169     {
2170         if (shader->input_reg_used[i])
2171         {
2172             ++num_regs_used;
2173             highest_reg_used = i;
2174         }
2175     }
2176
2177     /* Don't do any register mapping magic if it is not needed, or if we can't
2178      * achieve anything anyway */
2179     if (highest_reg_used < (gl_info->limits.glsl_varyings / 4)
2180             || num_regs_used > (gl_info->limits.glsl_varyings / 4))
2181     {
2182         if (num_regs_used > (gl_info->limits.glsl_varyings / 4))
2183         {
2184             /* This happens with relative addressing. The input mapper function
2185              * warns about this if the higher registers are declared too, so
2186              * don't write a FIXME here */
2187             WARN("More varying registers used than supported\n");
2188         }
2189
2190         for (i = 0; i < MAX_REG_INPUT; ++i)
2191         {
2192             shader->input_reg_map[i] = i;
2193         }
2194
2195         shader->declared_in_count = highest_reg_used + 1;
2196     }
2197     else
2198     {
2199         shader->declared_in_count = 0;
2200         for (i = 0; i < MAX_REG_INPUT; ++i)
2201         {
2202             if (shader->input_reg_used[i]) shader->input_reg_map[i] = shader->declared_in_count++;
2203             else shader->input_reg_map[i] = ~0U;
2204         }
2205     }
2206
2207     shader->baseShader.load_local_constsF = FALSE;
2208
2209     return WINED3D_OK;
2210 }
2211
2212 void pixelshader_update_samplers(struct shader_reg_maps *reg_maps, IWineD3DBaseTexture * const *textures)
2213 {
2214     WINED3DSAMPLER_TEXTURE_TYPE *sampler_type = reg_maps->sampler_type;
2215     unsigned int i;
2216
2217     if (reg_maps->shader_version.major != 1) return;
2218
2219     for (i = 0; i < max(MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS); ++i)
2220     {
2221         /* We don't sample from this sampler. */
2222         if (!sampler_type[i]) continue;
2223
2224         if (!textures[i])
2225         {
2226             WARN("No texture bound to sampler %u, using 2D.\n", i);
2227             sampler_type[i] = WINED3DSTT_2D;
2228             continue;
2229         }
2230
2231         switch (IWineD3DBaseTexture_GetTextureDimensions(textures[i]))
2232         {
2233             case GL_TEXTURE_RECTANGLE_ARB:
2234             case GL_TEXTURE_2D:
2235                 /* We have to select between texture rectangles and 2D
2236                  * textures later because 2.0 and 3.0 shaders only have
2237                  * WINED3DSTT_2D as well. */
2238                 sampler_type[i] = WINED3DSTT_2D;
2239                 break;
2240
2241             case GL_TEXTURE_3D:
2242                 sampler_type[i] = WINED3DSTT_VOLUME;
2243                 break;
2244
2245             case GL_TEXTURE_CUBE_MAP_ARB:
2246                 sampler_type[i] = WINED3DSTT_CUBE;
2247                 break;
2248
2249             default:
2250                 FIXME("Unrecognized texture type %#x, using 2D.\n",
2251                         IWineD3DBaseTexture_GetTextureDimensions(textures[i]));
2252                 sampler_type[i] = WINED3DSTT_2D;
2253         }
2254     }
2255 }