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