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