wined3d: Use the shader object ids as program key.
[wine.git] / dlls / wined3d / glsl_shader.c
blob75fb7e4684a95d8c7fa0f5fe04d25a2d5536a5ad
1 /*
2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * D3D shader asm has swizzles on source parameters, and write masks for
26 * destination parameters. GLSL uses swizzles for both. The result of this is
27 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29 * mask for the destination parameter into account.
32 #include "config.h"
33 #include "wine/port.h"
35 #include <limits.h>
36 #include <stdio.h>
38 #include "wined3d_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
41 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
42 WINE_DECLARE_DEBUG_CHANNEL(d3d);
43 WINE_DECLARE_DEBUG_CHANNEL(winediag);
45 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
46 #define WINED3D_GLSL_SAMPLE_RECT 0x2
47 #define WINED3D_GLSL_SAMPLE_LOD 0x4
48 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
50 struct glsl_dst_param
52 char reg_name[150];
53 char mask_str[6];
56 struct glsl_src_param
58 char reg_name[150];
59 char param_str[200];
62 struct glsl_sample_function
64 const char *name;
65 DWORD coord_mask;
68 enum heap_node_op
70 HEAP_NODE_TRAVERSE_LEFT,
71 HEAP_NODE_TRAVERSE_RIGHT,
72 HEAP_NODE_POP,
75 struct constant_entry
77 unsigned int idx;
78 unsigned int version;
81 struct constant_heap
83 struct constant_entry *entries;
84 unsigned int *positions;
85 unsigned int size;
88 /* GLSL shader private data */
89 struct shader_glsl_priv {
90 struct wined3d_shader_buffer shader_buffer;
91 struct wine_rb_tree program_lookup;
92 struct glsl_shader_prog_link *glsl_program;
93 struct constant_heap vconst_heap;
94 struct constant_heap pconst_heap;
95 unsigned char *stack;
96 GLhandleARB depth_blt_program_full[tex_type_count];
97 GLhandleARB depth_blt_program_masked[tex_type_count];
98 UINT next_constant_version;
100 const struct fragment_pipeline *fragment_pipe;
103 /* Struct to maintain data about a linked GLSL program */
104 struct glsl_shader_prog_link {
105 struct wine_rb_entry program_lookup_entry;
106 struct list vshader_entry;
107 struct list pshader_entry;
108 GLhandleARB programId;
109 GLint *vuniformF_locations;
110 GLint *puniformF_locations;
111 GLint vuniformI_locations[MAX_CONST_I];
112 GLint puniformI_locations[MAX_CONST_I];
113 GLint posFixup_location;
114 GLint np2Fixup_location;
115 GLint bumpenvmat_location[MAX_TEXTURES];
116 GLint luminancescale_location[MAX_TEXTURES];
117 GLint luminanceoffset_location[MAX_TEXTURES];
118 GLint ycorrection_location;
119 GLenum vertex_color_clamp;
120 GLhandleARB vs_id;
121 GLhandleARB ps_id;
122 UINT constant_version;
123 const struct ps_np2fixup_info *np2Fixup_info;
126 struct glsl_program_key
128 GLhandleARB vs_id;
129 GLhandleARB ps_id;
132 struct shader_glsl_ctx_priv {
133 const struct vs_compile_args *cur_vs_args;
134 const struct ps_compile_args *cur_ps_args;
135 struct ps_np2fixup_info *cur_np2fixup_info;
138 struct glsl_ps_compiled_shader
140 struct ps_compile_args args;
141 struct ps_np2fixup_info np2fixup;
142 GLhandleARB prgId;
145 struct glsl_vs_compiled_shader
147 struct vs_compile_args args;
148 GLhandleARB prgId;
151 struct glsl_shader_private
153 union
155 struct glsl_vs_compiled_shader *vs;
156 struct glsl_ps_compiled_shader *ps;
157 } gl_shaders;
158 UINT num_gl_shaders, shader_array_size;
161 static const char *debug_gl_shader_type(GLenum type)
163 switch (type)
165 #define WINED3D_TO_STR(u) case u: return #u
166 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
167 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
168 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
169 #undef WINED3D_TO_STR
170 default:
171 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
175 static const char *shader_glsl_get_prefix(enum wined3d_shader_type type)
177 switch (type)
179 case WINED3D_SHADER_TYPE_VERTEX:
180 return "vs";
182 case WINED3D_SHADER_TYPE_GEOMETRY:
183 return "gs";
185 case WINED3D_SHADER_TYPE_PIXEL:
186 return "ps";
188 default:
189 FIXME("Unhandled shader type %#x.\n", type);
190 return "unknown";
194 /* Extract a line from the info log.
195 * Note that this modifies the source string. */
196 static char *get_info_log_line(char **ptr)
198 char *p, *q;
200 p = *ptr;
201 if (!(q = strstr(p, "\n")))
203 if (!*p) return NULL;
204 *ptr += strlen(p);
205 return p;
207 *q = '\0';
208 *ptr = q + 1;
210 return p;
213 /** Prints the GLSL info log which will contain error messages if they exist */
214 /* GL locking is done by the caller */
215 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
217 int infologLength = 0;
218 char *infoLog;
220 if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
221 return;
223 GL_EXTCALL(glGetObjectParameterivARB(obj,
224 GL_OBJECT_INFO_LOG_LENGTH_ARB,
225 &infologLength));
227 /* A size of 1 is just a null-terminated string, so the log should be bigger than
228 * that if there are errors. */
229 if (infologLength > 1)
231 char *ptr, *line;
233 infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
234 /* The info log is supposed to be zero-terminated, but at least some
235 * versions of fglrx don't terminate the string properly. The reported
236 * length does include the terminator, so explicitly set it to zero
237 * here. */
238 infoLog[infologLength - 1] = 0;
239 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
241 ptr = infoLog;
242 if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
244 WARN("Info log received from GLSL shader #%u:\n", obj);
245 while ((line = get_info_log_line(&ptr))) WARN(" %s\n", line);
247 else
249 FIXME("Info log received from GLSL shader #%u:\n", obj);
250 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
252 HeapFree(GetProcessHeap(), 0, infoLog);
256 /* GL locking is done by the caller. */
257 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
259 TRACE("Compiling shader object %u.\n", shader);
260 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
261 checkGLcall("glShaderSourceARB");
262 GL_EXTCALL(glCompileShaderARB(shader));
263 checkGLcall("glCompileShaderARB");
264 print_glsl_info_log(gl_info, shader);
267 /* GL locking is done by the caller. */
268 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
270 GLint i, object_count, source_size = -1;
271 GLhandleARB *objects;
272 char *source = NULL;
274 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
275 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
276 if (!objects)
278 ERR("Failed to allocate object array memory.\n");
279 return;
282 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
283 for (i = 0; i < object_count; ++i)
285 char *ptr, *line;
286 GLint tmp;
288 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
290 if (source_size < tmp)
292 HeapFree(GetProcessHeap(), 0, source);
294 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
295 if (!source)
297 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
298 HeapFree(GetProcessHeap(), 0, objects);
299 return;
301 source_size = tmp;
304 FIXME("Object %u:\n", objects[i]);
305 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
306 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
307 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
308 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
309 FIXME("\n");
311 ptr = source;
312 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
313 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
314 FIXME("\n");
317 HeapFree(GetProcessHeap(), 0, source);
318 HeapFree(GetProcessHeap(), 0, objects);
321 /* GL locking is done by the caller. */
322 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
324 GLint tmp;
326 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
328 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
329 if (tmp == GL_PROGRAM_OBJECT_ARB)
331 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
332 if (!tmp)
334 FIXME("Program %u link status invalid.\n", program);
335 shader_glsl_dump_program_source(gl_info, program);
339 print_glsl_info_log(gl_info, program);
343 * Loads (pixel shader) samplers
345 /* GL locking is done by the caller */
346 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
347 const DWORD *tex_unit_map, GLhandleARB programId)
349 GLint name_loc;
350 char sampler_name[20];
351 unsigned int i;
353 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
355 snprintf(sampler_name, sizeof(sampler_name), "ps_sampler%u", i);
356 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
357 if (name_loc != -1) {
358 DWORD mapped_unit = tex_unit_map[i];
359 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
361 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
362 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
363 checkGLcall("glUniform1iARB");
364 } else {
365 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
371 /* GL locking is done by the caller */
372 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
373 const DWORD *tex_unit_map, GLhandleARB programId)
375 GLint name_loc;
376 char sampler_name[20];
377 unsigned int i;
379 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
381 snprintf(sampler_name, sizeof(sampler_name), "vs_sampler%u", i);
382 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
383 if (name_loc != -1) {
384 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
385 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
387 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
388 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
389 checkGLcall("glUniform1iARB");
390 } else {
391 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
397 /* GL locking is done by the caller */
398 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
399 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
401 int stack_idx = 0;
402 unsigned int heap_idx = 1;
403 unsigned int idx;
405 if (heap->entries[heap_idx].version <= version) return;
407 idx = heap->entries[heap_idx].idx;
408 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
409 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
411 while (stack_idx >= 0)
413 /* Note that we fall through to the next case statement. */
414 switch(stack[stack_idx])
416 case HEAP_NODE_TRAVERSE_LEFT:
418 unsigned int left_idx = heap_idx << 1;
419 if (left_idx < heap->size && heap->entries[left_idx].version > version)
421 heap_idx = left_idx;
422 idx = heap->entries[heap_idx].idx;
423 if (constant_locations[idx] != -1)
424 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
426 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
427 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
428 break;
432 case HEAP_NODE_TRAVERSE_RIGHT:
434 unsigned int right_idx = (heap_idx << 1) + 1;
435 if (right_idx < heap->size && heap->entries[right_idx].version > version)
437 heap_idx = right_idx;
438 idx = heap->entries[heap_idx].idx;
439 if (constant_locations[idx] != -1)
440 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
442 stack[stack_idx++] = HEAP_NODE_POP;
443 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
444 break;
448 case HEAP_NODE_POP:
449 heap_idx >>= 1;
450 --stack_idx;
451 break;
454 checkGLcall("walk_constant_heap()");
457 /* GL locking is done by the caller */
458 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
460 GLfloat clamped_constant[4];
462 if (location == -1) return;
464 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
465 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
466 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
467 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
469 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
472 /* GL locking is done by the caller */
473 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
474 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
476 int stack_idx = 0;
477 unsigned int heap_idx = 1;
478 unsigned int idx;
480 if (heap->entries[heap_idx].version <= version) return;
482 idx = heap->entries[heap_idx].idx;
483 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
484 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
486 while (stack_idx >= 0)
488 /* Note that we fall through to the next case statement. */
489 switch(stack[stack_idx])
491 case HEAP_NODE_TRAVERSE_LEFT:
493 unsigned int left_idx = heap_idx << 1;
494 if (left_idx < heap->size && heap->entries[left_idx].version > version)
496 heap_idx = left_idx;
497 idx = heap->entries[heap_idx].idx;
498 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
500 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
501 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
502 break;
506 case HEAP_NODE_TRAVERSE_RIGHT:
508 unsigned int right_idx = (heap_idx << 1) + 1;
509 if (right_idx < heap->size && heap->entries[right_idx].version > version)
511 heap_idx = right_idx;
512 idx = heap->entries[heap_idx].idx;
513 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
515 stack[stack_idx++] = HEAP_NODE_POP;
516 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
517 break;
521 case HEAP_NODE_POP:
522 heap_idx >>= 1;
523 --stack_idx;
524 break;
527 checkGLcall("walk_constant_heap_clamped()");
530 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
531 /* GL locking is done by the caller */
532 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
533 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
534 unsigned char *stack, UINT version)
536 const struct wined3d_shader_lconst *lconst;
538 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
539 if (shader->reg_maps.shader_version.major == 1
540 && shader->reg_maps.shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
541 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
542 else
543 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
545 if (!shader->load_local_constsF)
547 TRACE("No need to load local float constants for this shader\n");
548 return;
551 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
552 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
554 GLint location = constant_locations[lconst->idx];
555 /* We found this uniform name in the program - go ahead and send the data */
556 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
558 checkGLcall("glUniform4fvARB()");
561 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
562 /* GL locking is done by the caller */
563 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
564 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
566 unsigned int i;
567 struct list* ptr;
569 for (i = 0; constants_set; constants_set >>= 1, ++i)
571 if (!(constants_set & 1)) continue;
573 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
574 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
576 /* We found this uniform name in the program - go ahead and send the data */
577 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
578 checkGLcall("glUniform4ivARB");
581 /* Load immediate constants */
582 ptr = list_head(&shader->constantsI);
583 while (ptr)
585 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
586 unsigned int idx = lconst->idx;
587 const GLint *values = (const GLint *)lconst->value;
589 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
590 values[0], values[1], values[2], values[3]);
592 /* We found this uniform name in the program - go ahead and send the data */
593 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
594 checkGLcall("glUniform4ivARB");
595 ptr = list_next(&shader->constantsI, ptr);
599 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
600 /* GL locking is done by the caller */
601 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
602 GLhandleARB programId, const BOOL *constants, WORD constants_set)
604 GLint tmp_loc;
605 unsigned int i;
606 char tmp_name[10];
607 const char *prefix;
608 struct list* ptr;
610 prefix = shader_glsl_get_prefix(shader->reg_maps.shader_version.type);
612 /* TODO: Benchmark and see if it would be beneficial to store the
613 * locations of the constants to avoid looking up each time */
614 for (i = 0; constants_set; constants_set >>= 1, ++i)
616 if (!(constants_set & 1)) continue;
618 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
620 /* TODO: Benchmark and see if it would be beneficial to store the
621 * locations of the constants to avoid looking up each time */
622 snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, i);
623 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
624 if (tmp_loc != -1)
626 /* We found this uniform name in the program - go ahead and send the data */
627 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
628 checkGLcall("glUniform1ivARB");
632 /* Load immediate constants */
633 ptr = list_head(&shader->constantsB);
634 while (ptr)
636 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
637 unsigned int idx = lconst->idx;
638 const GLint *values = (const GLint *)lconst->value;
640 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
642 snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, idx);
643 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
644 if (tmp_loc != -1) {
645 /* We found this uniform name in the program - go ahead and send the data */
646 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
647 checkGLcall("glUniform1ivARB");
649 ptr = list_next(&shader->constantsB, ptr);
653 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
655 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
659 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
661 /* GL locking is done by the caller (state handler) */
662 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
663 const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
665 struct shader_glsl_priv *glsl_priv = shader_priv;
666 const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
668 /* No GLSL program set - nothing to do. */
669 if (!prog) return;
671 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
672 if (!use_ps(state)) return;
674 if (prog->np2Fixup_info && prog->np2Fixup_location != -1)
676 UINT i;
677 UINT fixup = prog->np2Fixup_info->active;
678 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
680 for (i = 0; fixup; fixup >>= 1, ++i)
682 const struct wined3d_texture *tex = state->textures[i];
683 const unsigned char idx = prog->np2Fixup_info->idx[i];
684 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
686 if (!tex)
688 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
689 continue;
692 if (idx % 2)
694 tex_dim[2] = tex->pow2_matrix[0];
695 tex_dim[3] = tex->pow2_matrix[5];
697 else
699 tex_dim[0] = tex->pow2_matrix[0];
700 tex_dim[1] = tex->pow2_matrix[5];
704 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
709 * Loads the app-supplied constants into the currently set GLSL program.
711 /* GL locking is done by the caller (state handler) */
712 static void shader_glsl_load_constants(const struct wined3d_context *context,
713 BOOL usePixelShader, BOOL useVertexShader)
715 const struct wined3d_gl_info *gl_info = context->gl_info;
716 struct wined3d_device *device = context->swapchain->device;
717 struct wined3d_stateblock *stateBlock = device->stateBlock;
718 const struct wined3d_state *state = &stateBlock->state;
719 struct shader_glsl_priv *priv = device->shader_priv;
720 float position_fixup[4];
722 GLhandleARB programId;
723 struct glsl_shader_prog_link *prog = priv->glsl_program;
724 UINT constant_version;
725 int i;
727 if (!prog) {
728 /* No GLSL program set - nothing to do. */
729 return;
731 programId = prog->programId;
732 constant_version = prog->constant_version;
734 if (useVertexShader)
736 const struct wined3d_shader *vshader = state->vertex_shader;
738 /* Load DirectX 9 float constants/uniforms for vertex shader */
739 shader_glsl_load_constantsF(vshader, gl_info, state->vs_consts_f,
740 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
742 /* Load DirectX 9 integer constants/uniforms for vertex shader */
743 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, state->vs_consts_i,
744 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
746 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
747 shader_glsl_load_constantsB(vshader, gl_info, programId, state->vs_consts_b,
748 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
750 /* Upload the position fixup params */
751 shader_get_position_fixup(context, state, position_fixup);
752 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
753 checkGLcall("glUniform4fvARB");
756 if (usePixelShader)
758 const struct wined3d_shader *pshader = state->pixel_shader;
760 /* Load DirectX 9 float constants/uniforms for pixel shader */
761 shader_glsl_load_constantsF(pshader, gl_info, state->ps_consts_f,
762 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
764 /* Load DirectX 9 integer constants/uniforms for pixel shader */
765 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, state->ps_consts_i,
766 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
768 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
769 shader_glsl_load_constantsB(pshader, gl_info, programId, state->ps_consts_b,
770 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
772 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
773 * It can't be 0 for a valid texbem instruction.
775 for(i = 0; i < MAX_TEXTURES; i++) {
776 const float *data;
778 if(prog->bumpenvmat_location[i] == -1) continue;
780 data = (const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_MAT00];
781 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
782 checkGLcall("glUniformMatrix2fvARB");
784 /* texbeml needs the luminance scale and offset too. If texbeml
785 * is used, needsbumpmat is set too, so we can check that in the
786 * needsbumpmat check. */
787 if (prog->luminancescale_location[i] != -1)
789 const GLfloat *scale = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LSCALE];
790 const GLfloat *offset = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LOFFSET];
792 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
793 checkGLcall("glUniform1fvARB");
794 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
795 checkGLcall("glUniform1fvARB");
799 if (prog->ycorrection_location != -1)
801 float correction_params[4];
803 if (context->render_offscreen)
805 correction_params[0] = 0.0f;
806 correction_params[1] = 1.0f;
807 } else {
808 /* position is window relative, not viewport relative */
809 correction_params[0] = (float) context->current_rt->resource.height;
810 correction_params[1] = -1.0f;
812 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
816 if (priv->next_constant_version == UINT_MAX)
818 TRACE("Max constant version reached, resetting to 0.\n");
819 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
820 priv->next_constant_version = 1;
822 else
824 prog->constant_version = priv->next_constant_version++;
828 static void update_heap_entry(const struct constant_heap *heap, unsigned int idx,
829 unsigned int heap_idx, DWORD new_version)
831 struct constant_entry *entries = heap->entries;
832 unsigned int *positions = heap->positions;
833 unsigned int parent_idx;
835 while (heap_idx > 1)
837 parent_idx = heap_idx >> 1;
839 if (new_version <= entries[parent_idx].version) break;
841 entries[heap_idx] = entries[parent_idx];
842 positions[entries[parent_idx].idx] = heap_idx;
843 heap_idx = parent_idx;
846 entries[heap_idx].version = new_version;
847 entries[heap_idx].idx = idx;
848 positions[idx] = heap_idx;
851 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
853 struct shader_glsl_priv *priv = device->shader_priv;
854 struct constant_heap *heap = &priv->vconst_heap;
855 UINT i;
857 for (i = start; i < count + start; ++i)
859 if (!device->stateBlock->changed.vertexShaderConstantsF[i])
860 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
861 else
862 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
866 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
868 struct shader_glsl_priv *priv = device->shader_priv;
869 struct constant_heap *heap = &priv->pconst_heap;
870 UINT i;
872 for (i = start; i < count + start; ++i)
874 if (!device->stateBlock->changed.pixelShaderConstantsF[i])
875 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
876 else
877 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
881 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
883 unsigned int ret = gl_info->limits.glsl_varyings / 4;
884 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
885 if(shader_major > 3) return ret;
887 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
888 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
889 return ret;
892 /** Generate the variable & register declarations for the GLSL output target */
893 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
894 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
895 const struct wined3d_shader_reg_maps *reg_maps, const struct shader_glsl_ctx_priv *ctx_priv)
897 const struct wined3d_shader_version *version = &reg_maps->shader_version;
898 const struct wined3d_state *state = &shader->device->stateBlock->state;
899 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
900 const struct wined3d_gl_info *gl_info = context->gl_info;
901 const struct wined3d_fb_state *fb = &shader->device->fb;
902 unsigned int i, extra_constants_needed = 0;
903 const struct wined3d_shader_lconst *lconst;
904 const char *prefix;
905 DWORD map;
907 prefix = shader_glsl_get_prefix(version->type);
909 /* Prototype the subroutines */
910 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
912 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
915 /* Declare the constants (aka uniforms) */
916 if (shader->limits.constant_float > 0)
918 unsigned max_constantsF;
920 /* Unless the shader uses indirect addressing, always declare the
921 * maximum array size and ignore that we need some uniforms privately.
922 * E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup
923 * and immediate values, still declare VC[256]. If the shader needs
924 * more uniforms than we have it won't work in any case. If it uses
925 * less, the compiler will figure out which uniforms are really used
926 * and strip them out. This allows a shader to use c255 on a dx9 card,
927 * as long as it doesn't also use all the other constants.
929 * If the shader uses indirect addressing the compiler must assume
930 * that all declared uniforms are used. In this case, declare only the
931 * amount that we're assured to have.
933 * Thus we run into problems in these two cases:
934 * 1) The shader really uses more uniforms than supported.
935 * 2) The shader uses indirect addressing, less constants than
936 * supported, but uses a constant index > #supported consts. */
937 if (version->type == WINED3D_SHADER_TYPE_PIXEL)
939 /* No indirect addressing here. */
940 max_constantsF = gl_info->limits.glsl_ps_float_constants;
942 else
944 if (reg_maps->usesrelconstF)
946 /* Subtract the other potential uniforms from the max
947 * available (bools, ints, and 1 row of projection matrix).
948 * Subtract another uniform for immediate values, which have
949 * to be loaded via uniform by the driver as well. The shader
950 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
951 * shader code, so one vec4 should be enough. (Unfortunately
952 * the Nvidia driver doesn't store 128 and -128 in one float).
954 * Writing gl_ClipVertex requires one uniform for each
955 * clipplane as well. */
956 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
957 if(ctx_priv->cur_vs_args->clip_enabled)
959 max_constantsF -= gl_info->limits.clipplanes;
961 max_constantsF -= count_bits(reg_maps->integer_constants);
962 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
963 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
964 * for now take this into account when calculating the number of available constants
966 max_constantsF -= count_bits(reg_maps->boolean_constants);
967 /* Set by driver quirks in directx.c */
968 max_constantsF -= gl_info->reserved_glsl_constants;
970 if (max_constantsF < shader->limits.constant_float)
972 static unsigned int once;
974 if (!once++)
975 ERR_(winediag)("The hardware does not support enough uniform components to run this shader,"
976 " it may not render correctly.\n");
977 else
978 WARN("The hardware does not support enough uniform components to run this shader.\n");
981 else
983 max_constantsF = gl_info->limits.glsl_vs_float_constants;
986 max_constantsF = min(shader->limits.constant_float, max_constantsF);
987 shader_addline(buffer, "uniform vec4 %s_c[%u];\n", prefix, max_constantsF);
990 /* Always declare the full set of constants, the compiler can remove the
991 * unused ones because d3d doesn't (yet) support indirect int and bool
992 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
993 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
994 shader_addline(buffer, "uniform ivec4 %s_i[%u];\n", prefix, shader->limits.constant_int);
996 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
997 shader_addline(buffer, "uniform bool %s_b[%u];\n", prefix, shader->limits.constant_bool);
999 for (i = 0; i < WINED3D_MAX_CBS; ++i)
1001 if (reg_maps->cb_sizes[i])
1002 shader_addline(buffer, "uniform vec4 %s_cb%u[%u];\n", prefix, i, reg_maps->cb_sizes[i]);
1005 /* Declare texture samplers */
1006 for (i = 0; i < shader->limits.sampler; ++i)
1008 if (reg_maps->sampler_type[i])
1010 BOOL shadow_sampler = version->type == WINED3D_SHADER_TYPE_PIXEL && (ps_args->shadow & (1 << i));
1011 const struct wined3d_texture *texture;
1013 switch (reg_maps->sampler_type[i])
1015 case WINED3DSTT_1D:
1016 if (shadow_sampler)
1017 shader_addline(buffer, "uniform sampler1DShadow %s_sampler%u;\n", prefix, i);
1018 else
1019 shader_addline(buffer, "uniform sampler1D %s_sampler%u;\n", prefix, i);
1020 break;
1021 case WINED3DSTT_2D:
1022 texture = state->textures[i];
1023 if (shadow_sampler)
1025 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1026 shader_addline(buffer, "uniform sampler2DRectShadow %s_sampler%u;\n", prefix, i);
1027 else
1028 shader_addline(buffer, "uniform sampler2DShadow %s_sampler%u;\n", prefix, i);
1030 else
1032 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1033 shader_addline(buffer, "uniform sampler2DRect %s_sampler%u;\n", prefix, i);
1034 else
1035 shader_addline(buffer, "uniform sampler2D %s_sampler%u;\n", prefix, i);
1037 break;
1038 case WINED3DSTT_CUBE:
1039 if (shadow_sampler)
1040 FIXME("Unsupported Cube shadow sampler.\n");
1041 shader_addline(buffer, "uniform samplerCube %s_sampler%u;\n", prefix, i);
1042 break;
1043 case WINED3DSTT_VOLUME:
1044 if (shadow_sampler)
1045 FIXME("Unsupported 3D shadow sampler.\n");
1046 shader_addline(buffer, "uniform sampler3D %s_sampler%u;\n", prefix, i);
1047 break;
1048 default:
1049 shader_addline(buffer, "uniform unsupported_sampler %s_sampler%u;\n", prefix, i);
1050 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1051 break;
1056 /* Declare uniforms for NP2 texcoord fixup:
1057 * This is NOT done inside the loop that declares the texture samplers
1058 * since the NP2 fixup code is currently only used for the GeforceFX
1059 * series and when forcing the ARB_npot extension off. Modern cards just
1060 * skip the code anyway, so put it inside a separate loop. */
1061 if (version->type == WINED3D_SHADER_TYPE_PIXEL && ps_args->np2_fixup)
1063 struct ps_np2fixup_info *fixup = ctx_priv->cur_np2fixup_info;
1064 UINT cur = 0;
1066 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1067 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1068 * samplerNP2Fixup stores texture dimensions and is updated through
1069 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1071 for (i = 0; i < shader->limits.sampler; ++i)
1073 if (reg_maps->sampler_type[i])
1075 if (!(ps_args->np2_fixup & (1 << i))) continue;
1077 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1078 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1079 continue;
1082 fixup->idx[i] = cur++;
1086 fixup->num_consts = (cur + 1) >> 1;
1087 fixup->active = ps_args->np2_fixup;
1088 shader_addline(buffer, "uniform vec4 %s_samplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1091 /* Declare address variables */
1092 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1094 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1097 /* Declare texture coordinate temporaries and initialize them */
1098 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1100 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1103 if (version->type == WINED3D_SHADER_TYPE_VERTEX)
1105 /* Declare attributes. */
1106 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1108 if (map & 1)
1109 shader_addline(buffer, "attribute vec4 %s_in%u;\n", prefix, i);
1112 shader_addline(buffer, "uniform vec4 posFixup;\n");
1113 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", shader->limits.packed_output);
1115 else if (version->type == WINED3D_SHADER_TYPE_PIXEL)
1117 if (version->major >= 3)
1119 UINT in_count = min(vec4_varyings(version->major, gl_info), shader->limits.packed_input);
1121 if (use_vs(state))
1122 shader_addline(buffer, "varying vec4 %s_in[%u];\n", prefix, in_count);
1123 else
1124 /* TODO: Write a replacement shader for the fixed function
1125 * vertex pipeline, so this isn't needed. For fixed function
1126 * vertex processing + 3.0 pixel shader we need a separate
1127 * function in the pixel shader that reads the fixed function
1128 * color into the packed input registers. */
1129 shader_addline(buffer, "vec4 %s_in[%u];\n", prefix, in_count);
1132 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1134 if (!(map & 1))
1135 continue;
1137 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1139 if (reg_maps->luminanceparams & (1 << i))
1141 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1142 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1143 extra_constants_needed++;
1146 extra_constants_needed++;
1149 if (ps_args->srgb_correction)
1151 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1152 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1153 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1154 srgb_cmp);
1156 if (reg_maps->vpos || reg_maps->usesdsy)
1158 if (shader->limits.constant_float + extra_constants_needed
1159 + 1 < gl_info->limits.glsl_ps_float_constants)
1161 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1162 extra_constants_needed++;
1164 else
1166 /* This happens because we do not have proper tracking of the constant registers that are
1167 * actually used, only the max limit of the shader version
1169 FIXME("Cannot find a free uniform for vpos correction params\n");
1170 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1171 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1172 context->render_offscreen ? 1.0f : -1.0f);
1174 shader_addline(buffer, "vec4 vpos;\n");
1178 /* Declare output register temporaries */
1179 if (shader->limits.packed_output)
1180 shader_addline(buffer, "vec4 %s_out[%u];\n", prefix, shader->limits.packed_output);
1182 /* Declare temporary variables */
1183 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1185 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1188 /* Declare loop registers aLx */
1189 if (version->major < 4)
1191 for (i = 0; i < reg_maps->loop_depth; ++i)
1193 shader_addline(buffer, "int aL%u;\n", i);
1194 shader_addline(buffer, "int tmpInt%u;\n", i);
1198 /* Temporary variables for matrix operations */
1199 shader_addline(buffer, "vec4 tmp0;\n");
1200 shader_addline(buffer, "vec4 tmp1;\n");
1202 /* Local constants use a different name so they can be loaded once at shader link time
1203 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1204 * float -> string conversion can cause precision loss.
1206 if (!shader->load_local_constsF)
1208 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1210 shader_addline(buffer, "uniform vec4 %s_lc%u;\n", prefix, lconst->idx);
1214 /* Start the main program. */
1215 shader_addline(buffer, "void main()\n{\n");
1217 /* Direct3D applications expect integer vPos values, while OpenGL drivers
1218 * add approximately 0.5. This causes off-by-one problems as spotted by
1219 * the vPos d3d9 visual test. Unfortunately ATI cards do not add exactly
1220 * 0.5, but rather something like 0.49999999 or 0.50000001, which still
1221 * causes precision troubles when we just subtract 0.5.
1223 * To deal with that, just floor() the position. This will eliminate the
1224 * fraction on all cards.
1226 * TODO: Test how this behaves with multisampling.
1228 * An advantage of floor is that it works even if the driver doesn't add
1229 * 0.5. It is somewhat questionable if 1.5, 2.5, ... are the proper values
1230 * to return in gl_FragCoord, even though coordinates specify the pixel
1231 * centers instead of the pixel corners. This code will behave correctly
1232 * on drivers that returns integer values. */
1233 if (version->type == WINED3D_SHADER_TYPE_PIXEL && reg_maps->vpos)
1234 shader_addline(buffer,
1235 "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1238 /*****************************************************************************
1239 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1241 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1242 ****************************************************************************/
1244 /* Prototypes */
1245 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1246 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1248 /** Used for opcode modifiers - They multiply the result by the specified amount */
1249 static const char * const shift_glsl_tab[] = {
1250 "", /* 0 (none) */
1251 "2.0 * ", /* 1 (x2) */
1252 "4.0 * ", /* 2 (x4) */
1253 "8.0 * ", /* 3 (x8) */
1254 "16.0 * ", /* 4 (x16) */
1255 "32.0 * ", /* 5 (x32) */
1256 "", /* 6 (x64) */
1257 "", /* 7 (x128) */
1258 "", /* 8 (d256) */
1259 "", /* 9 (d128) */
1260 "", /* 10 (d64) */
1261 "", /* 11 (d32) */
1262 "0.0625 * ", /* 12 (d16) */
1263 "0.125 * ", /* 13 (d8) */
1264 "0.25 * ", /* 14 (d4) */
1265 "0.5 * " /* 15 (d2) */
1268 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1269 static void shader_glsl_gen_modifier(enum wined3d_shader_src_modifier src_modifier,
1270 const char *in_reg, const char *in_regswizzle, char *out_str)
1272 out_str[0] = 0;
1274 switch (src_modifier)
1276 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1277 case WINED3DSPSM_DW:
1278 case WINED3DSPSM_NONE:
1279 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1280 break;
1281 case WINED3DSPSM_NEG:
1282 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1283 break;
1284 case WINED3DSPSM_NOT:
1285 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1286 break;
1287 case WINED3DSPSM_BIAS:
1288 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1289 break;
1290 case WINED3DSPSM_BIASNEG:
1291 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1292 break;
1293 case WINED3DSPSM_SIGN:
1294 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1295 break;
1296 case WINED3DSPSM_SIGNNEG:
1297 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1298 break;
1299 case WINED3DSPSM_COMP:
1300 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1301 break;
1302 case WINED3DSPSM_X2:
1303 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1304 break;
1305 case WINED3DSPSM_X2NEG:
1306 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1307 break;
1308 case WINED3DSPSM_ABS:
1309 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1310 break;
1311 case WINED3DSPSM_ABSNEG:
1312 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1313 break;
1314 default:
1315 FIXME("Unhandled modifier %u\n", src_modifier);
1316 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1320 /** Writes the GLSL variable name that corresponds to the register that the
1321 * DX opcode parameter is trying to access */
1322 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1323 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1325 /* oPos, oFog and oPts in D3D */
1326 static const char * const hwrastout_reg_names[] = {"vs_out[10]", "vs_out[11].x", "vs_out[11].y"};
1328 const struct wined3d_shader *shader = ins->ctx->shader;
1329 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1330 const struct wined3d_shader_version *version = &reg_maps->shader_version;
1331 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1332 const char *prefix = shader_glsl_get_prefix(version->type);
1334 *is_color = FALSE;
1336 switch (reg->type)
1338 case WINED3DSPR_TEMP:
1339 sprintf(register_name, "R%u", reg->idx[0].offset);
1340 break;
1342 case WINED3DSPR_INPUT:
1343 /* vertex shaders */
1344 if (version->type == WINED3D_SHADER_TYPE_VERTEX)
1346 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1347 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx[0].offset))
1348 *is_color = TRUE;
1349 sprintf(register_name, "%s_in%u", prefix, reg->idx[0].offset);
1350 break;
1353 /* pixel shaders >= 3.0 */
1354 if (version->major >= 3)
1356 DWORD idx = shader->u.ps.input_reg_map[reg->idx[0].offset];
1357 unsigned int in_count = vec4_varyings(version->major, gl_info);
1359 if (reg->idx[0].rel_addr)
1361 struct glsl_src_param rel_param;
1363 shader_glsl_add_src_param(ins, reg->idx[0].rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1365 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1366 * operation there */
1367 if (idx)
1369 if (shader->u.ps.declared_in_count > in_count)
1371 sprintf(register_name,
1372 "((%s + %u) > %u ? (%s + %u) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s + %u])",
1373 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1374 prefix, rel_param.param_str, idx);
1376 else
1378 sprintf(register_name, "%s_in[%s + %u]", prefix, rel_param.param_str, idx);
1381 else
1383 if (shader->u.ps.declared_in_count > in_count)
1385 sprintf(register_name, "((%s) > %u ? (%s) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s])",
1386 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1387 prefix, rel_param.param_str);
1389 else
1391 sprintf(register_name, "%s_in[%s]", prefix, rel_param.param_str);
1395 else
1397 if (idx == in_count) sprintf(register_name, "gl_Color");
1398 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1399 else sprintf(register_name, "%s_in[%u]", prefix, idx);
1402 else
1404 if (!reg->idx[0].offset)
1405 strcpy(register_name, "gl_Color");
1406 else
1407 strcpy(register_name, "gl_SecondaryColor");
1408 break;
1410 break;
1412 case WINED3DSPR_CONST:
1414 /* Relative addressing */
1415 if (reg->idx[0].rel_addr)
1417 struct glsl_src_param rel_param;
1418 shader_glsl_add_src_param(ins, reg->idx[0].rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1419 if (reg->idx[0].offset)
1420 sprintf(register_name, "%s_c[%s + %u]", prefix, rel_param.param_str, reg->idx[0].offset);
1421 else
1422 sprintf(register_name, "%s_c[%s]", prefix, rel_param.param_str);
1424 else
1426 if (shader_constant_is_local(shader, reg->idx[0].offset))
1427 sprintf(register_name, "%s_lc%u", prefix, reg->idx[0].offset);
1428 else
1429 sprintf(register_name, "%s_c[%u]", prefix, reg->idx[0].offset);
1432 break;
1434 case WINED3DSPR_CONSTINT:
1435 sprintf(register_name, "%s_i[%u]", prefix, reg->idx[0].offset);
1436 break;
1438 case WINED3DSPR_CONSTBOOL:
1439 sprintf(register_name, "%s_b[%u]", prefix, reg->idx[0].offset);
1440 break;
1442 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1443 if (version->type == WINED3D_SHADER_TYPE_PIXEL)
1444 sprintf(register_name, "T%u", reg->idx[0].offset);
1445 else
1446 sprintf(register_name, "A%u", reg->idx[0].offset);
1447 break;
1449 case WINED3DSPR_LOOP:
1450 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1451 break;
1453 case WINED3DSPR_SAMPLER:
1454 sprintf(register_name, "%s_sampler%u", prefix, reg->idx[0].offset);
1455 break;
1457 case WINED3DSPR_COLOROUT:
1458 if (reg->idx[0].offset >= gl_info->limits.buffers)
1459 WARN("Write to render target %u, only %d supported.\n",
1460 reg->idx[0].offset, gl_info->limits.buffers);
1462 sprintf(register_name, "gl_FragData[%u]", reg->idx[0].offset);
1463 break;
1465 case WINED3DSPR_RASTOUT:
1466 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx[0].offset]);
1467 break;
1469 case WINED3DSPR_DEPTHOUT:
1470 sprintf(register_name, "gl_FragDepth");
1471 break;
1473 case WINED3DSPR_ATTROUT:
1474 if (!reg->idx[0].offset)
1475 sprintf(register_name, "%s_out[8]", prefix);
1476 else
1477 sprintf(register_name, "%s_out[9]", prefix);
1478 break;
1480 case WINED3DSPR_TEXCRDOUT:
1481 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1482 sprintf(register_name, "%s_out[%u]", prefix, reg->idx[0].offset);
1483 break;
1485 case WINED3DSPR_MISCTYPE:
1486 if (!reg->idx[0].offset)
1488 /* vPos */
1489 sprintf(register_name, "vpos");
1491 else if (reg->idx[0].offset == 1)
1493 /* Note that gl_FrontFacing is a bool, while vFace is
1494 * a float for which the sign determines front/back */
1495 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1497 else
1499 FIXME("Unhandled misctype register %u.\n", reg->idx[0].offset);
1500 sprintf(register_name, "unrecognized_register");
1502 break;
1504 case WINED3DSPR_IMMCONST:
1505 switch (reg->immconst_type)
1507 case WINED3D_IMMCONST_SCALAR:
1508 switch (reg->data_type)
1510 case WINED3D_DATA_FLOAT:
1511 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1512 break;
1513 case WINED3D_DATA_INT:
1514 sprintf(register_name, "%#x", reg->immconst_data[0]);
1515 break;
1516 case WINED3D_DATA_RESOURCE:
1517 case WINED3D_DATA_SAMPLER:
1518 case WINED3D_DATA_UINT:
1519 sprintf(register_name, "%#xu", reg->immconst_data[0]);
1520 break;
1521 default:
1522 sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1523 break;
1525 break;
1527 case WINED3D_IMMCONST_VEC4:
1528 switch (reg->data_type)
1530 case WINED3D_DATA_FLOAT:
1531 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1532 *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1533 *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1534 break;
1535 case WINED3D_DATA_INT:
1536 sprintf(register_name, "ivec4(%#x, %#x, %#x, %#x)",
1537 reg->immconst_data[0], reg->immconst_data[1],
1538 reg->immconst_data[2], reg->immconst_data[3]);
1539 break;
1540 case WINED3D_DATA_RESOURCE:
1541 case WINED3D_DATA_SAMPLER:
1542 case WINED3D_DATA_UINT:
1543 sprintf(register_name, "uvec4(%#xu, %#xu, %#xu, %#xu)",
1544 reg->immconst_data[0], reg->immconst_data[1],
1545 reg->immconst_data[2], reg->immconst_data[3]);
1546 break;
1547 default:
1548 sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1549 break;
1551 break;
1553 default:
1554 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1555 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1557 break;
1559 case WINED3DSPR_CONSTBUFFER:
1560 if (reg->idx[1].rel_addr)
1562 struct glsl_src_param rel_param;
1563 shader_glsl_add_src_param(ins, reg->idx[1].rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1564 sprintf(register_name, "%s_cb%u[%s + %u]",
1565 prefix, reg->idx[0].offset, rel_param.param_str, reg->idx[1].offset);
1567 else
1569 sprintf(register_name, "%s_cb%u[%u]", prefix, reg->idx[0].offset, reg->idx[1].offset);
1571 break;
1573 case WINED3DSPR_PRIMID:
1574 sprintf(register_name, "uint(gl_PrimitiveIDIn)");
1575 break;
1577 default:
1578 FIXME("Unhandled register type %#x.\n", reg->type);
1579 sprintf(register_name, "unrecognized_register");
1580 break;
1584 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1586 *str++ = '.';
1587 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1588 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1589 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1590 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1591 *str = '\0';
1594 /* Get the GLSL write mask for the destination register */
1595 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1597 DWORD mask = param->write_mask;
1599 if (shader_is_scalar(&param->reg))
1601 mask = WINED3DSP_WRITEMASK_0;
1602 *write_mask = '\0';
1604 else
1606 shader_glsl_write_mask_to_str(mask, write_mask);
1609 return mask;
1612 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1613 unsigned int size = 0;
1615 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1616 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1617 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1618 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1620 return size;
1623 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1625 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1626 * but addressed as "rgba". To fix this we need to swap the register's x
1627 * and z components. */
1628 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1630 *str++ = '.';
1631 /* swizzle bits fields: wwzzyyxx */
1632 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1633 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1634 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1635 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1636 *str = '\0';
1639 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1640 BOOL fixup, DWORD mask, char *swizzle_str)
1642 if (shader_is_scalar(&param->reg))
1643 *swizzle_str = '\0';
1644 else
1645 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1648 /* From a given parameter token, generate the corresponding GLSL string.
1649 * Also, return the actual register name and swizzle in case the
1650 * caller needs this information as well. */
1651 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1652 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1654 BOOL is_color = FALSE;
1655 char swizzle_str[6];
1657 glsl_src->reg_name[0] = '\0';
1658 glsl_src->param_str[0] = '\0';
1659 swizzle_str[0] = '\0';
1661 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1662 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1664 if (wined3d_src->reg.type == WINED3DSPR_IMMCONST || wined3d_src->reg.type == WINED3DSPR_PRIMID)
1666 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1668 else
1670 char param_str[200];
1672 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, param_str);
1674 switch (wined3d_src->reg.data_type)
1676 case WINED3D_DATA_FLOAT:
1677 sprintf(glsl_src->param_str, "%s", param_str);
1678 break;
1679 case WINED3D_DATA_INT:
1680 sprintf(glsl_src->param_str, "floatBitsToInt(%s)", param_str);
1681 break;
1682 case WINED3D_DATA_RESOURCE:
1683 case WINED3D_DATA_SAMPLER:
1684 case WINED3D_DATA_UINT:
1685 sprintf(glsl_src->param_str, "floatBitsToUint(%s)", param_str);
1686 break;
1687 default:
1688 FIXME("Unhandled data type %#x.\n", wined3d_src->reg.data_type);
1689 sprintf(glsl_src->param_str, "%s", param_str);
1690 break;
1695 /* From a given parameter token, generate the corresponding GLSL string.
1696 * Also, return the actual register name and swizzle in case the
1697 * caller needs this information as well. */
1698 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1699 const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1701 BOOL is_color = FALSE;
1703 glsl_dst->mask_str[0] = '\0';
1704 glsl_dst->reg_name[0] = '\0';
1706 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1707 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1710 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1711 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1712 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1714 struct glsl_dst_param glsl_dst;
1715 DWORD mask;
1717 if ((mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst)))
1719 switch (dst->reg.data_type)
1721 case WINED3D_DATA_FLOAT:
1722 shader_addline(buffer, "%s%s = %s(",
1723 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1724 break;
1725 case WINED3D_DATA_INT:
1726 shader_addline(buffer, "%s%s = %sintBitsToFloat(",
1727 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1728 break;
1729 case WINED3D_DATA_RESOURCE:
1730 case WINED3D_DATA_SAMPLER:
1731 case WINED3D_DATA_UINT:
1732 shader_addline(buffer, "%s%s = %suintBitsToFloat(",
1733 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1734 break;
1735 default:
1736 FIXME("Unhandled data type %#x.\n", dst->reg.data_type);
1737 shader_addline(buffer, "%s%s = %s(",
1738 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1739 break;
1743 return mask;
1746 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1747 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1749 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1752 /** Process GLSL instruction modifiers */
1753 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1755 struct glsl_dst_param dst_param;
1756 DWORD modifiers;
1758 if (!ins->dst_count) return;
1760 modifiers = ins->dst[0].modifiers;
1761 if (!modifiers) return;
1763 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1765 if (modifiers & WINED3DSPDM_SATURATE)
1767 /* _SAT means to clamp the value of the register to between 0 and 1 */
1768 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1769 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1772 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1774 FIXME("_centroid modifier not handled\n");
1777 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1779 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1783 static const char *shader_glsl_get_rel_op(enum wined3d_shader_rel_op op)
1785 switch (op)
1787 case WINED3D_SHADER_REL_OP_GT: return ">";
1788 case WINED3D_SHADER_REL_OP_EQ: return "==";
1789 case WINED3D_SHADER_REL_OP_GE: return ">=";
1790 case WINED3D_SHADER_REL_OP_LT: return "<";
1791 case WINED3D_SHADER_REL_OP_NE: return "!=";
1792 case WINED3D_SHADER_REL_OP_LE: return "<=";
1793 default:
1794 FIXME("Unrecognized operator %#x.\n", op);
1795 return "(\?\?)";
1799 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1800 DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1802 enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1803 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1804 BOOL shadow = ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_PIXEL
1805 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1806 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1807 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1808 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1809 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1811 /* Note that there's no such thing as a projected cube texture. */
1812 switch(sampler_type) {
1813 case WINED3DSTT_1D:
1814 if (shadow)
1816 if (lod)
1818 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1820 else if (grad)
1822 if (gl_info->supported[EXT_GPU_SHADER4])
1823 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1824 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1825 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1826 else
1828 FIXME("Unsupported 1D shadow grad function.\n");
1829 sample_function->name = "unsupported1DGrad";
1832 else
1834 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1836 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1838 else
1840 if (lod)
1842 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1844 else if (grad)
1846 if (gl_info->supported[EXT_GPU_SHADER4])
1847 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1848 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1849 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1850 else
1852 FIXME("Unsupported 1D grad function.\n");
1853 sample_function->name = "unsupported1DGrad";
1856 else
1858 sample_function->name = projected ? "texture1DProj" : "texture1D";
1860 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1862 break;
1864 case WINED3DSTT_2D:
1865 if (shadow)
1867 if (texrect)
1869 if (lod)
1871 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1873 else if (grad)
1875 if (gl_info->supported[EXT_GPU_SHADER4])
1876 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1877 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1878 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1879 else
1881 FIXME("Unsupported RECT shadow grad function.\n");
1882 sample_function->name = "unsupported2DRectGrad";
1885 else
1887 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1890 else
1892 if (lod)
1894 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1896 else if (grad)
1898 if (gl_info->supported[EXT_GPU_SHADER4])
1899 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1900 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1901 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1902 else
1904 FIXME("Unsupported 2D shadow grad function.\n");
1905 sample_function->name = "unsupported2DGrad";
1908 else
1910 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1913 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1915 else
1917 if (texrect)
1919 if (lod)
1921 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1923 else if (grad)
1925 if (gl_info->supported[EXT_GPU_SHADER4])
1926 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1927 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1928 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1929 else
1931 FIXME("Unsupported RECT grad function.\n");
1932 sample_function->name = "unsupported2DRectGrad";
1935 else
1937 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1940 else
1942 if (lod)
1944 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1946 else if (grad)
1948 if (gl_info->supported[EXT_GPU_SHADER4])
1949 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1950 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1951 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1952 else
1954 FIXME("Unsupported 2D grad function.\n");
1955 sample_function->name = "unsupported2DGrad";
1958 else
1960 sample_function->name = projected ? "texture2DProj" : "texture2D";
1963 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1965 break;
1967 case WINED3DSTT_CUBE:
1968 if (shadow)
1970 FIXME("Unsupported Cube shadow function.\n");
1971 sample_function->name = "unsupportedCubeShadow";
1972 sample_function->coord_mask = 0;
1974 else
1976 if (lod)
1978 sample_function->name = "textureCubeLod";
1980 else if (grad)
1982 if (gl_info->supported[EXT_GPU_SHADER4])
1983 sample_function->name = "textureCubeGrad";
1984 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1985 sample_function->name = "textureCubeGradARB";
1986 else
1988 FIXME("Unsupported Cube grad function.\n");
1989 sample_function->name = "unsupportedCubeGrad";
1992 else
1994 sample_function->name = "textureCube";
1996 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1998 break;
2000 case WINED3DSTT_VOLUME:
2001 if (shadow)
2003 FIXME("Unsupported 3D shadow function.\n");
2004 sample_function->name = "unsupported3DShadow";
2005 sample_function->coord_mask = 0;
2007 else
2009 if (lod)
2011 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
2013 else if (grad)
2015 if (gl_info->supported[EXT_GPU_SHADER4])
2016 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
2017 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
2018 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
2019 else
2021 FIXME("Unsupported 3D grad function.\n");
2022 sample_function->name = "unsupported3DGrad";
2025 else
2027 sample_function->name = projected ? "texture3DProj" : "texture3D";
2029 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2031 break;
2033 default:
2034 sample_function->name = "";
2035 sample_function->coord_mask = 0;
2036 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
2037 break;
2041 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
2042 BOOL sign_fixup, enum fixup_channel_source channel_source)
2044 switch(channel_source)
2046 case CHANNEL_SOURCE_ZERO:
2047 strcat(arguments, "0.0");
2048 break;
2050 case CHANNEL_SOURCE_ONE:
2051 strcat(arguments, "1.0");
2052 break;
2054 case CHANNEL_SOURCE_X:
2055 strcat(arguments, reg_name);
2056 strcat(arguments, ".x");
2057 break;
2059 case CHANNEL_SOURCE_Y:
2060 strcat(arguments, reg_name);
2061 strcat(arguments, ".y");
2062 break;
2064 case CHANNEL_SOURCE_Z:
2065 strcat(arguments, reg_name);
2066 strcat(arguments, ".z");
2067 break;
2069 case CHANNEL_SOURCE_W:
2070 strcat(arguments, reg_name);
2071 strcat(arguments, ".w");
2072 break;
2074 default:
2075 FIXME("Unhandled channel source %#x\n", channel_source);
2076 strcat(arguments, "undefined");
2077 break;
2080 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
2083 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
2085 struct wined3d_shader_dst_param dst;
2086 unsigned int mask_size, remaining;
2087 struct glsl_dst_param dst_param;
2088 char arguments[256];
2089 DWORD mask;
2091 mask = 0;
2092 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
2093 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
2094 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
2095 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
2096 mask &= ins->dst[0].write_mask;
2098 if (!mask) return; /* Nothing to do */
2100 if (is_complex_fixup(fixup))
2102 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
2103 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
2104 return;
2107 mask_size = shader_glsl_get_write_mask_size(mask);
2109 dst = ins->dst[0];
2110 dst.write_mask = mask;
2111 shader_glsl_add_dst_param(ins, &dst, &dst_param);
2113 arguments[0] = '\0';
2114 remaining = mask_size;
2115 if (mask & WINED3DSP_WRITEMASK_0)
2117 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
2118 if (--remaining) strcat(arguments, ", ");
2120 if (mask & WINED3DSP_WRITEMASK_1)
2122 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
2123 if (--remaining) strcat(arguments, ", ");
2125 if (mask & WINED3DSP_WRITEMASK_2)
2127 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
2128 if (--remaining) strcat(arguments, ", ");
2130 if (mask & WINED3DSP_WRITEMASK_3)
2132 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2133 if (--remaining) strcat(arguments, ", ");
2136 if (mask_size > 1)
2138 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2139 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2141 else
2143 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2147 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2148 DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2149 const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2151 const struct wined3d_shader_version *version = &ins->ctx->reg_maps->shader_version;
2152 char dst_swizzle[6];
2153 struct color_fixup_desc fixup;
2154 BOOL np2_fixup = FALSE;
2155 va_list args;
2157 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2159 if (version->type == WINED3D_SHADER_TYPE_PIXEL)
2161 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2162 fixup = priv->cur_ps_args->color_fixup[sampler];
2164 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2165 if(bias) {
2166 FIXME("Biased sampling from NP2 textures is unsupported\n");
2167 } else {
2168 np2_fixup = TRUE;
2172 else
2174 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2177 shader_glsl_append_dst(ins->ctx->buffer, ins);
2179 shader_addline(ins->ctx->buffer, "%s(%s_sampler%u, ",
2180 sample_function->name, shader_glsl_get_prefix(version->type), sampler);
2182 va_start(args, coord_reg_fmt);
2183 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2184 va_end(args);
2186 if(bias) {
2187 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2188 } else {
2189 if (np2_fixup) {
2190 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2191 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2193 shader_addline(ins->ctx->buffer, " * ps_samplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2194 (idx % 2) ? "zw" : "xy", dst_swizzle);
2195 } else if(dx && dy) {
2196 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2197 } else {
2198 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2202 if(!is_identity_fixup(fixup)) {
2203 shader_glsl_color_correction(ins, fixup);
2207 /*****************************************************************************
2208 * Begin processing individual instruction opcodes
2209 ****************************************************************************/
2211 static void shader_glsl_binop(const struct wined3d_shader_instruction *ins)
2213 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2214 struct glsl_src_param src0_param;
2215 struct glsl_src_param src1_param;
2216 DWORD write_mask;
2217 const char *op;
2219 /* Determine the GLSL operator to use based on the opcode */
2220 switch (ins->handler_idx)
2222 case WINED3DSIH_ADD: op = "+"; break;
2223 case WINED3DSIH_AND: op = "&"; break;
2224 case WINED3DSIH_DIV: op = "/"; break;
2225 case WINED3DSIH_IADD: op = "+"; break;
2226 case WINED3DSIH_MUL: op = "*"; break;
2227 case WINED3DSIH_SUB: op = "-"; break;
2228 case WINED3DSIH_USHR: op = ">>"; break;
2229 case WINED3DSIH_XOR: op = "^"; break;
2230 default:
2231 op = "<unhandled operator>";
2232 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2233 break;
2236 write_mask = shader_glsl_append_dst(buffer, ins);
2237 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2238 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2239 shader_addline(buffer, "%s %s %s);\n", src0_param.param_str, op, src1_param.param_str);
2242 static void shader_glsl_relop(const struct wined3d_shader_instruction *ins)
2244 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2245 struct glsl_src_param src0_param;
2246 struct glsl_src_param src1_param;
2247 unsigned int mask_size;
2248 DWORD write_mask;
2249 const char *op;
2251 write_mask = shader_glsl_append_dst(buffer, ins);
2252 mask_size = shader_glsl_get_write_mask_size(write_mask);
2253 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2254 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2256 if (mask_size > 1)
2258 switch (ins->handler_idx)
2260 case WINED3DSIH_EQ: op = "equal"; break;
2261 case WINED3DSIH_GE: op = "greaterThanEqual"; break;
2262 case WINED3DSIH_IGE: op = "greaterThanEqual"; break;
2263 case WINED3DSIH_LT: op = "lessThan"; break;
2264 default:
2265 op = "<unhandled operator>";
2266 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2267 break;
2270 shader_addline(buffer, "uvec%u(%s(%s, %s)) * 0xffffffffu);\n",
2271 mask_size, op, src0_param.param_str, src1_param.param_str);
2273 else
2275 switch (ins->handler_idx)
2277 case WINED3DSIH_EQ: op = "=="; break;
2278 case WINED3DSIH_GE: op = ">="; break;
2279 case WINED3DSIH_IGE: op = ">="; break;
2280 case WINED3DSIH_LT: op = "<"; break;
2281 default:
2282 op = "<unhandled operator>";
2283 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2284 break;
2287 shader_addline(buffer, "%s %s %s ? 0xffffffffu : 0u);\n",
2288 src0_param.param_str, op, src1_param.param_str);
2292 static void shader_glsl_imul(const struct wined3d_shader_instruction *ins)
2294 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2295 struct glsl_src_param src0_param;
2296 struct glsl_src_param src1_param;
2297 DWORD write_mask;
2299 /* If we have ARB_gpu_shader5 or GLSL 4.0, we can use imulExtended(). If
2300 * not, we can emulate it. */
2301 if (ins->dst[0].reg.type != WINED3DSPR_NULL)
2302 FIXME("64-bit integer multiplies not implemented.\n");
2304 if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2306 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2307 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2308 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2310 shader_addline(ins->ctx->buffer, "%s * %s);\n",
2311 src0_param.param_str, src1_param.param_str);
2315 static void shader_glsl_udiv(const struct wined3d_shader_instruction *ins)
2317 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2318 struct glsl_src_param src0_param, src1_param;
2319 DWORD write_mask;
2321 if (ins->dst[0].reg.type != WINED3DSPR_NULL)
2324 if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2326 char dst_mask[6];
2328 write_mask = shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2329 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2330 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2331 shader_addline(buffer, "tmp0%s = %s / %s;\n",
2332 dst_mask, src0_param.param_str, src1_param.param_str);
2334 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2335 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2336 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2337 shader_addline(buffer, "%s %% %s));\n", src0_param.param_str, src1_param.param_str);
2339 shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
2340 shader_addline(buffer, "tmp0%s);\n", dst_mask);
2342 else
2344 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
2345 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2346 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2347 shader_addline(buffer, "%s / %s);\n", src0_param.param_str, src1_param.param_str);
2350 else if (ins->dst[1].reg.type != WINED3DSPR_NULL)
2352 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
2353 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2354 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2355 shader_addline(buffer, "%s %% %s);\n", src0_param.param_str, src1_param.param_str);
2359 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2360 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2362 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2363 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2364 struct glsl_src_param src0_param;
2365 DWORD write_mask;
2367 write_mask = shader_glsl_append_dst(buffer, ins);
2368 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2370 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2371 * shader versions WINED3DSIO_MOVA is used for this. */
2372 if (ins->ctx->reg_maps->shader_version.major == 1
2373 && ins->ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX
2374 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2376 /* This is a simple floor() */
2377 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2378 if (mask_size > 1) {
2379 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2380 } else {
2381 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2384 else if(ins->handler_idx == WINED3DSIH_MOVA)
2386 /* We need to *round* to the nearest int here. */
2387 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2389 if (gl_info->supported[EXT_GPU_SHADER4])
2391 if (mask_size > 1)
2392 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2393 else
2394 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2396 else
2398 if (mask_size > 1)
2399 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2400 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2401 else
2402 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2403 src0_param.param_str, src0_param.param_str);
2406 else
2408 shader_addline(buffer, "%s);\n", src0_param.param_str);
2412 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2413 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2415 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2416 struct glsl_src_param src0_param;
2417 struct glsl_src_param src1_param;
2418 DWORD dst_write_mask, src_write_mask;
2419 unsigned int dst_size = 0;
2421 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2422 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2424 /* dp3 works on vec3, dp4 on vec4 */
2425 if (ins->handler_idx == WINED3DSIH_DP4)
2427 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2428 } else {
2429 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2432 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2433 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2435 if (dst_size > 1) {
2436 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2437 } else {
2438 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2442 /* Note that this instruction has some restrictions. The destination write mask
2443 * can't contain the w component, and the source swizzles have to be .xyzw */
2444 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2446 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2447 struct glsl_src_param src0_param;
2448 struct glsl_src_param src1_param;
2449 char dst_mask[6];
2451 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2452 shader_glsl_append_dst(ins->ctx->buffer, ins);
2453 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2454 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2455 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2458 static void shader_glsl_cut(const struct wined3d_shader_instruction *ins)
2460 shader_addline(ins->ctx->buffer, "EndPrimitive();\n");
2463 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2464 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2465 * GLSL uses the value as-is. */
2466 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2468 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2469 struct glsl_src_param src0_param;
2470 struct glsl_src_param src1_param;
2471 DWORD dst_write_mask;
2472 unsigned int dst_size;
2474 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2475 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2477 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2478 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2480 if (dst_size > 1)
2482 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2483 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2485 else
2487 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2488 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2492 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2493 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2494 * GLSL uses the value as-is. */
2495 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2497 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2498 struct glsl_src_param src0_param;
2499 DWORD dst_write_mask;
2500 unsigned int dst_size;
2502 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2503 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2505 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2507 if (dst_size > 1)
2509 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2510 dst_size, src0_param.param_str);
2512 else
2514 shader_addline(buffer, "log2(abs(%s)));\n",
2515 src0_param.param_str);
2519 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2520 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2522 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2523 struct glsl_src_param src_param;
2524 const char *instruction;
2525 DWORD write_mask;
2526 unsigned i;
2528 /* Determine the GLSL function to use based on the opcode */
2529 /* TODO: Possibly make this a table for faster lookups */
2530 switch (ins->handler_idx)
2532 case WINED3DSIH_MIN: instruction = "min"; break;
2533 case WINED3DSIH_MAX: instruction = "max"; break;
2534 case WINED3DSIH_ABS: instruction = "abs"; break;
2535 case WINED3DSIH_FRC: instruction = "fract"; break;
2536 case WINED3DSIH_EXP: instruction = "exp2"; break;
2537 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2538 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2539 case WINED3DSIH_ROUND_NI: instruction = "floor"; break;
2540 default: instruction = "";
2541 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2542 break;
2545 write_mask = shader_glsl_append_dst(buffer, ins);
2547 shader_addline(buffer, "%s(", instruction);
2549 if (ins->src_count)
2551 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2552 shader_addline(buffer, "%s", src_param.param_str);
2553 for (i = 1; i < ins->src_count; ++i)
2555 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2556 shader_addline(buffer, ", %s", src_param.param_str);
2560 shader_addline(buffer, "));\n");
2563 static void shader_glsl_nop(const struct wined3d_shader_instruction *ins) {}
2565 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2567 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2568 struct glsl_src_param src_param;
2569 unsigned int mask_size;
2570 DWORD write_mask;
2571 char dst_mask[6];
2573 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2574 mask_size = shader_glsl_get_write_mask_size(write_mask);
2575 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2577 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2578 src_param.param_str, src_param.param_str);
2579 shader_glsl_append_dst(buffer, ins);
2581 if (mask_size > 1)
2583 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2584 mask_size, src_param.param_str);
2586 else
2588 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2589 src_param.param_str);
2593 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2594 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2595 * dst.x = 2^(floor(src))
2596 * dst.y = src - floor(src)
2597 * dst.z = 2^src (partial precision is allowed, but optional)
2598 * dst.w = 1.0;
2599 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2600 * dst = 2^src; (partial precision is allowed, but optional)
2602 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2604 struct glsl_src_param src_param;
2606 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2608 if (ins->ctx->reg_maps->shader_version.major < 2)
2610 char dst_mask[6];
2612 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2613 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2614 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2615 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2617 shader_glsl_append_dst(ins->ctx->buffer, ins);
2618 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2619 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2620 } else {
2621 DWORD write_mask;
2622 unsigned int mask_size;
2624 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2625 mask_size = shader_glsl_get_write_mask_size(write_mask);
2627 if (mask_size > 1) {
2628 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2629 } else {
2630 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2635 static void shader_glsl_to_int(const struct wined3d_shader_instruction *ins)
2637 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2638 struct glsl_src_param src_param;
2639 unsigned int mask_size;
2640 DWORD write_mask;
2642 write_mask = shader_glsl_append_dst(buffer, ins);
2643 mask_size = shader_glsl_get_write_mask_size(write_mask);
2644 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2646 if (mask_size > 1)
2647 shader_addline(buffer, "ivec%u(%s));\n", mask_size, src_param.param_str);
2648 else
2649 shader_addline(buffer, "int(%s));\n", src_param.param_str);
2652 static void shader_glsl_to_float(const struct wined3d_shader_instruction *ins)
2654 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2655 struct glsl_src_param src_param;
2656 unsigned int mask_size;
2657 DWORD write_mask;
2659 write_mask = shader_glsl_append_dst(buffer, ins);
2660 mask_size = shader_glsl_get_write_mask_size(write_mask);
2661 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2663 if (mask_size > 1)
2664 shader_addline(buffer, "vec%u(%s));\n", mask_size, src_param.param_str);
2665 else
2666 shader_addline(buffer, "float(%s));\n", src_param.param_str);
2669 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2670 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2672 struct glsl_src_param src_param;
2673 DWORD write_mask;
2674 unsigned int mask_size;
2676 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2677 mask_size = shader_glsl_get_write_mask_size(write_mask);
2678 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2680 if (mask_size > 1)
2682 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2683 mask_size, src_param.param_str);
2685 else
2687 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2688 src_param.param_str);
2692 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2694 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2695 struct glsl_src_param src_param;
2696 DWORD write_mask;
2697 unsigned int mask_size;
2699 write_mask = shader_glsl_append_dst(buffer, ins);
2700 mask_size = shader_glsl_get_write_mask_size(write_mask);
2702 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2704 if (mask_size > 1)
2706 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2707 mask_size, src_param.param_str);
2709 else
2711 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2712 src_param.param_str);
2716 /** Process signed comparison opcodes in GLSL. */
2717 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2719 struct glsl_src_param src0_param;
2720 struct glsl_src_param src1_param;
2721 DWORD write_mask;
2722 unsigned int mask_size;
2724 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2725 mask_size = shader_glsl_get_write_mask_size(write_mask);
2726 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2727 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2729 if (mask_size > 1) {
2730 const char *compare;
2732 switch(ins->handler_idx)
2734 case WINED3DSIH_SLT: compare = "lessThan"; break;
2735 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2736 default: compare = "";
2737 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2740 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2741 src0_param.param_str, src1_param.param_str);
2742 } else {
2743 switch(ins->handler_idx)
2745 case WINED3DSIH_SLT:
2746 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2747 * to return 0.0 but step returns 1.0 because step is not < x
2748 * An alternative is a bvec compare padded with an unused second component.
2749 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2750 * issue. Playing with not() is not possible either because not() does not accept
2751 * a scalar.
2753 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2754 src0_param.param_str, src1_param.param_str);
2755 break;
2756 case WINED3DSIH_SGE:
2757 /* Here we can use the step() function and safe a conditional */
2758 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2759 break;
2760 default:
2761 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2767 static void shader_glsl_conditional_move(const struct wined3d_shader_instruction *ins)
2769 const char *condition_prefix, *condition_suffix;
2770 struct wined3d_shader_dst_param dst;
2771 struct glsl_src_param src0_param;
2772 struct glsl_src_param src1_param;
2773 struct glsl_src_param src2_param;
2774 BOOL temp_destination = FALSE;
2775 DWORD cmp_channel = 0;
2776 unsigned int i, j;
2777 char mask_char[6];
2778 DWORD write_mask;
2780 switch (ins->handler_idx)
2782 case WINED3DSIH_CMP:
2783 condition_prefix = "";
2784 condition_suffix = " >= 0.0";
2785 break;
2787 case WINED3DSIH_CND:
2788 condition_prefix = "";
2789 condition_suffix = " > 0.5";
2790 break;
2792 case WINED3DSIH_MOVC:
2793 condition_prefix = "bool(";
2794 condition_suffix = ")";
2795 break;
2797 default:
2798 FIXME("Unhandled instruction %#x.\n", ins->handler_idx);
2799 condition_prefix = "<unhandled prefix>";
2800 condition_suffix = "<unhandled suffix>";
2801 break;
2804 if (shader_is_scalar(&ins->src[0].reg))
2806 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2807 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2808 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2809 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2811 shader_addline(ins->ctx->buffer, "%s%s%s ? %s : %s);\n",
2812 condition_prefix, src0_param.param_str, condition_suffix,
2813 src1_param.param_str, src2_param.param_str);
2814 return;
2817 dst = ins->dst[0];
2819 /* Splitting the instruction up in multiple lines imposes a problem:
2820 * The first lines may overwrite source parameters of the following lines.
2821 * Deal with that by using a temporary destination register if needed. */
2822 if ((ins->src[0].reg.idx[0].offset == dst.reg.idx[0].offset
2823 && ins->src[0].reg.type == dst.reg.type)
2824 || (ins->src[1].reg.idx[0].offset == dst.reg.idx[0].offset
2825 && ins->src[1].reg.type == dst.reg.type)
2826 || (ins->src[2].reg.idx[0].offset == dst.reg.idx[0].offset
2827 && ins->src[2].reg.type == dst.reg.type))
2828 temp_destination = TRUE;
2830 /* Cycle through all source0 channels. */
2831 for (i = 0; i < 4; ++i)
2833 write_mask = 0;
2834 /* Find the destination channels which use the current source0 channel. */
2835 for (j = 0; j < 4; ++j)
2837 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2839 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2840 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2843 dst.write_mask = ins->dst[0].write_mask & write_mask;
2845 if (temp_destination)
2847 if (!(write_mask = shader_glsl_get_write_mask(&dst, mask_char)))
2848 continue;
2849 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2851 else if (!(write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst)))
2852 continue;
2854 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2855 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2856 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2858 shader_addline(ins->ctx->buffer, "%s%s%s ? %s : %s);\n",
2859 condition_prefix, src0_param.param_str, condition_suffix,
2860 src1_param.param_str, src2_param.param_str);
2863 if (temp_destination)
2865 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2866 shader_glsl_append_dst(ins->ctx->buffer, ins);
2867 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2871 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2872 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2873 * the compare is done per component of src0. */
2874 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2876 struct glsl_src_param src0_param;
2877 struct glsl_src_param src1_param;
2878 struct glsl_src_param src2_param;
2879 DWORD write_mask;
2880 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2881 ins->ctx->reg_maps->shader_version.minor);
2883 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2885 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2886 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2887 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2888 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2890 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2891 if (ins->coissue)
2893 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2894 } else {
2895 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2896 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2898 return;
2901 shader_glsl_conditional_move(ins);
2904 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2905 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2907 struct glsl_src_param src0_param;
2908 struct glsl_src_param src1_param;
2909 struct glsl_src_param src2_param;
2910 DWORD write_mask;
2912 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2913 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2914 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2915 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2916 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2917 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2920 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2921 Vertex shaders to GLSL codes */
2922 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2924 int i;
2925 int nComponents = 0;
2926 struct wined3d_shader_dst_param tmp_dst = {{0}};
2927 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2928 struct wined3d_shader_instruction tmp_ins;
2930 memset(&tmp_ins, 0, sizeof(tmp_ins));
2932 /* Set constants for the temporary argument */
2933 tmp_ins.ctx = ins->ctx;
2934 tmp_ins.dst_count = 1;
2935 tmp_ins.dst = &tmp_dst;
2936 tmp_ins.src_count = 2;
2937 tmp_ins.src = tmp_src;
2939 switch(ins->handler_idx)
2941 case WINED3DSIH_M4x4:
2942 nComponents = 4;
2943 tmp_ins.handler_idx = WINED3DSIH_DP4;
2944 break;
2945 case WINED3DSIH_M4x3:
2946 nComponents = 3;
2947 tmp_ins.handler_idx = WINED3DSIH_DP4;
2948 break;
2949 case WINED3DSIH_M3x4:
2950 nComponents = 4;
2951 tmp_ins.handler_idx = WINED3DSIH_DP3;
2952 break;
2953 case WINED3DSIH_M3x3:
2954 nComponents = 3;
2955 tmp_ins.handler_idx = WINED3DSIH_DP3;
2956 break;
2957 case WINED3DSIH_M3x2:
2958 nComponents = 2;
2959 tmp_ins.handler_idx = WINED3DSIH_DP3;
2960 break;
2961 default:
2962 break;
2965 tmp_dst = ins->dst[0];
2966 tmp_src[0] = ins->src[0];
2967 tmp_src[1] = ins->src[1];
2968 for (i = 0; i < nComponents; ++i)
2970 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2971 shader_glsl_dot(&tmp_ins);
2972 ++tmp_src[1].reg.idx[0].offset;
2977 The LRP instruction performs a component-wise linear interpolation
2978 between the second and third operands using the first operand as the
2979 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2980 This is equivalent to mix(src2, src1, src0);
2982 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2984 struct glsl_src_param src0_param;
2985 struct glsl_src_param src1_param;
2986 struct glsl_src_param src2_param;
2987 DWORD write_mask;
2989 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2991 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2992 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2993 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2995 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2996 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2999 /** Process the WINED3DSIO_LIT instruction in GLSL:
3000 * dst.x = dst.w = 1.0
3001 * dst.y = (src0.x > 0) ? src0.x
3002 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
3003 * where src.w is clamped at +- 128
3005 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
3007 struct glsl_src_param src0_param;
3008 struct glsl_src_param src1_param;
3009 struct glsl_src_param src3_param;
3010 char dst_mask[6];
3012 shader_glsl_append_dst(ins->ctx->buffer, ins);
3013 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3015 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3016 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
3017 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
3019 /* The sdk specifies the instruction like this
3020 * dst.x = 1.0;
3021 * if(src.x > 0.0) dst.y = src.x
3022 * else dst.y = 0.0.
3023 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
3024 * else dst.z = 0.0;
3025 * dst.w = 1.0;
3026 * (where power = src.w clamped between -128 and 128)
3028 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
3029 * dst.x = 1.0 ... No further explanation needed
3030 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
3031 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
3032 * dst.w = 1.0. ... Nothing fancy.
3034 * So we still have one conditional in there. So do this:
3035 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
3037 * step(0.0, x) will return 1 if src.x > 0.0, and 0 otherwise. So if y is 0 we get pow(0.0 * 1.0, power),
3038 * which sets dst.z to 0. If y > 0, but x = 0.0, we get pow(y * 0.0, power), which results in 0 too.
3039 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
3041 * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
3042 * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
3043 * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
3045 shader_addline(ins->ctx->buffer,
3046 "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
3047 "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
3048 src0_param.param_str, src3_param.param_str, src1_param.param_str,
3049 src0_param.param_str, src3_param.param_str, dst_mask);
3052 /** Process the WINED3DSIO_DST instruction in GLSL:
3053 * dst.x = 1.0
3054 * dst.y = src0.x * src0.y
3055 * dst.z = src0.z
3056 * dst.w = src1.w
3058 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
3060 struct glsl_src_param src0y_param;
3061 struct glsl_src_param src0z_param;
3062 struct glsl_src_param src1y_param;
3063 struct glsl_src_param src1w_param;
3064 char dst_mask[6];
3066 shader_glsl_append_dst(ins->ctx->buffer, ins);
3067 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3069 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
3070 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
3071 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
3072 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
3074 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
3075 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
3078 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
3079 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
3080 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
3082 * dst.x = cos(src0.?)
3083 * dst.y = sin(src0.?)
3084 * dst.z = dst.z
3085 * dst.w = dst.w
3087 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
3089 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3090 struct glsl_src_param src0_param;
3091 DWORD write_mask;
3093 if (ins->ctx->reg_maps->shader_version.major < 4)
3095 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3097 write_mask = shader_glsl_append_dst(buffer, ins);
3098 switch (write_mask)
3100 case WINED3DSP_WRITEMASK_0:
3101 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3102 break;
3104 case WINED3DSP_WRITEMASK_1:
3105 shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
3106 break;
3108 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
3109 shader_addline(buffer, "vec2(cos(%s), sin(%s)));\n",
3110 src0_param.param_str, src0_param.param_str);
3111 break;
3113 default:
3114 ERR("Write mask should be .x, .y or .xy\n");
3115 break;
3118 return;
3121 if (ins->dst[0].reg.type != WINED3DSPR_NULL)
3124 if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3126 char dst_mask[6];
3128 write_mask = shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3129 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3130 shader_addline(buffer, "tmp0%s = sin(%s);\n", dst_mask, src0_param.param_str);
3132 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3133 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3134 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3136 shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3137 shader_addline(buffer, "tmp0%s);\n", dst_mask);
3139 else
3141 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3142 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3143 shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
3146 else if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3148 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3149 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3150 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3154 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
3155 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
3156 * generate invalid code
3158 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
3160 struct glsl_src_param src0_param;
3161 DWORD write_mask;
3163 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3164 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3166 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
3169 /** Process the WINED3DSIO_LOOP instruction in GLSL:
3170 * Start a for() loop where src1.y is the initial value of aL,
3171 * increment aL by src1.z for a total of src1.x iterations.
3172 * Need to use a temporary variable for this operation.
3174 /* FIXME: I don't think nested loops will work correctly this way. */
3175 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
3177 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3178 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3179 const struct wined3d_shader *shader = ins->ctx->shader;
3180 const struct wined3d_shader_lconst *constant;
3181 struct glsl_src_param src1_param;
3182 const DWORD *control_values = NULL;
3184 if (ins->ctx->reg_maps->shader_version.major < 4)
3186 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
3188 /* Try to hardcode the loop control parameters if possible. Direct3D 9
3189 * class hardware doesn't support real varying indexing, but Microsoft
3190 * designed this feature for Shader model 2.x+. If the loop control is
3191 * known at compile time, the GLSL compiler can unroll the loop, and
3192 * replace indirect addressing with direct addressing. */
3193 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
3195 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3197 if (constant->idx == ins->src[1].reg.idx[0].offset)
3199 control_values = constant->value;
3200 break;
3205 if (control_values)
3207 struct wined3d_shader_loop_control loop_control;
3208 loop_control.count = control_values[0];
3209 loop_control.start = control_values[1];
3210 loop_control.step = (int)control_values[2];
3212 if (loop_control.step > 0)
3214 shader_addline(buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d)\n{\n",
3215 loop_state->current_depth, loop_control.start,
3216 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3217 loop_state->current_depth, loop_control.step);
3219 else if (loop_control.step < 0)
3221 shader_addline(buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d)\n{\n",
3222 loop_state->current_depth, loop_control.start,
3223 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3224 loop_state->current_depth, loop_control.step);
3226 else
3228 shader_addline(buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++)\n{\n",
3229 loop_state->current_depth, loop_control.start, loop_state->current_depth,
3230 loop_state->current_depth, loop_control.count,
3231 loop_state->current_depth);
3234 else
3236 shader_addline(buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z)\n{\n",
3237 loop_state->current_depth, loop_state->current_reg,
3238 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
3239 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
3242 ++loop_state->current_reg;
3244 else
3246 shader_addline(buffer, "for (;;)\n{\n");
3249 ++loop_state->current_depth;
3252 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
3254 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3256 shader_addline(ins->ctx->buffer, "}\n");
3258 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
3260 --loop_state->current_depth;
3261 --loop_state->current_reg;
3264 if (ins->handler_idx == WINED3DSIH_ENDREP)
3266 --loop_state->current_depth;
3270 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
3272 const struct wined3d_shader *shader = ins->ctx->shader;
3273 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3274 const struct wined3d_shader_lconst *constant;
3275 struct glsl_src_param src0_param;
3276 const DWORD *control_values = NULL;
3278 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
3279 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
3281 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3283 if (constant->idx == ins->src[0].reg.idx[0].offset)
3285 control_values = constant->value;
3286 break;
3291 if (control_values)
3293 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
3294 loop_state->current_depth, loop_state->current_depth,
3295 control_values[0], loop_state->current_depth);
3297 else
3299 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3300 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
3301 loop_state->current_depth, loop_state->current_depth,
3302 src0_param.param_str, loop_state->current_depth);
3305 ++loop_state->current_depth;
3308 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
3310 struct glsl_src_param src0_param;
3312 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3313 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
3316 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
3318 struct glsl_src_param src0_param;
3319 struct glsl_src_param src1_param;
3321 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3322 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3324 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
3325 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3328 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
3330 shader_addline(ins->ctx->buffer, "} else {\n");
3333 static void shader_glsl_emit(const struct wined3d_shader_instruction *ins)
3335 shader_addline(ins->ctx->buffer, "EmitVertex();\n");
3338 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
3340 shader_addline(ins->ctx->buffer, "break;\n");
3343 /* FIXME: According to MSDN the compare is done per component. */
3344 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
3346 struct glsl_src_param src0_param;
3347 struct glsl_src_param src1_param;
3349 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3350 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3352 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3353 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3356 static void shader_glsl_breakp(const struct wined3d_shader_instruction *ins)
3358 struct glsl_src_param src_param;
3360 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
3361 shader_addline(ins->ctx->buffer, "if (bool(%s)) break;\n", src_param.param_str);
3364 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3366 shader_addline(ins->ctx->buffer, "}\n");
3367 shader_addline(ins->ctx->buffer, "void subroutine%u()\n{\n", ins->src[0].reg.idx[0].offset);
3370 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3372 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx[0].offset);
3375 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3377 struct glsl_src_param src1_param;
3379 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3380 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n",
3381 src1_param.param_str, ins->src[0].reg.idx[0].offset);
3384 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3386 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3387 * function only suppresses the unhandled instruction warning
3391 /*********************************************
3392 * Pixel Shader Specific Code begins here
3393 ********************************************/
3394 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3396 const struct wined3d_shader *shader = ins->ctx->shader;
3397 struct wined3d_device *device = shader->device;
3398 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3399 ins->ctx->reg_maps->shader_version.minor);
3400 struct glsl_sample_function sample_function;
3401 const struct wined3d_texture *texture;
3402 DWORD sample_flags = 0;
3403 DWORD sampler_idx;
3404 DWORD mask = 0, swizzle;
3406 /* 1.0-1.4: Use destination register as sampler source.
3407 * 2.0+: Use provided sampler source. */
3408 if (shader_version < WINED3D_SHADER_VERSION(2,0))
3409 sampler_idx = ins->dst[0].reg.idx[0].offset;
3410 else
3411 sampler_idx = ins->src[1].reg.idx[0].offset;
3412 texture = device->stateBlock->state.textures[sampler_idx];
3414 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3416 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3417 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3418 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3419 enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3421 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3422 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE)
3424 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3425 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3427 case WINED3D_TTFF_COUNT1:
3428 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3429 break;
3430 case WINED3D_TTFF_COUNT2:
3431 mask = WINED3DSP_WRITEMASK_1;
3432 break;
3433 case WINED3D_TTFF_COUNT3:
3434 mask = WINED3DSP_WRITEMASK_2;
3435 break;
3436 case WINED3D_TTFF_COUNT4:
3437 case WINED3D_TTFF_DISABLE:
3438 mask = WINED3DSP_WRITEMASK_3;
3439 break;
3443 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3445 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3447 if (src_mod == WINED3DSPSM_DZ) {
3448 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3449 mask = WINED3DSP_WRITEMASK_2;
3450 } else if (src_mod == WINED3DSPSM_DW) {
3451 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3452 mask = WINED3DSP_WRITEMASK_3;
3454 } else {
3455 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3457 /* ps 2.0 texldp instruction always divides by the fourth component. */
3458 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3459 mask = WINED3DSP_WRITEMASK_3;
3463 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3464 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3466 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3467 mask |= sample_function.coord_mask;
3469 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3470 else swizzle = ins->src[1].swizzle;
3472 /* 1.0-1.3: Use destination register as coordinate source.
3473 1.4+: Use provided coordinate source register. */
3474 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3476 char coord_mask[6];
3477 shader_glsl_write_mask_to_str(mask, coord_mask);
3478 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3479 "T%u%s", sampler_idx, coord_mask);
3481 else
3483 struct glsl_src_param coord_param;
3484 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3485 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3487 struct glsl_src_param bias;
3488 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3489 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3490 "%s", coord_param.param_str);
3491 } else {
3492 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3493 "%s", coord_param.param_str);
3498 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3500 const struct wined3d_shader *shader = ins->ctx->shader;
3501 struct wined3d_device *device = shader->device;
3502 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3503 struct glsl_src_param coord_param, dx_param, dy_param;
3504 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3505 struct glsl_sample_function sample_function;
3506 DWORD sampler_idx;
3507 DWORD swizzle = ins->src[1].swizzle;
3508 const struct wined3d_texture *texture;
3510 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3512 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3513 shader_glsl_tex(ins);
3514 return;
3517 sampler_idx = ins->src[1].reg.idx[0].offset;
3518 texture = device->stateBlock->state.textures[sampler_idx];
3519 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3520 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3522 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3523 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3524 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3525 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3527 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3528 "%s", coord_param.param_str);
3531 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3533 const struct wined3d_shader *shader = ins->ctx->shader;
3534 struct wined3d_device *device = shader->device;
3535 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3536 struct glsl_src_param coord_param, lod_param;
3537 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3538 struct glsl_sample_function sample_function;
3539 DWORD sampler_idx;
3540 DWORD swizzle = ins->src[1].swizzle;
3541 const struct wined3d_texture *texture;
3543 sampler_idx = ins->src[1].reg.idx[0].offset;
3544 texture = device->stateBlock->state.textures[sampler_idx];
3545 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3546 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3548 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3549 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3551 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3553 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3554 && ins->ctx->reg_maps->shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
3556 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3557 * However, the NVIDIA drivers allow them in fragment shaders as well,
3558 * even without the appropriate extension. */
3559 WARN("Using %s in fragment shader.\n", sample_function.name);
3561 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3562 "%s", coord_param.param_str);
3565 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3567 /* FIXME: Make this work for more than just 2D textures */
3568 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3569 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3571 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3573 char dst_mask[6];
3575 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3576 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3577 ins->dst[0].reg.idx[0].offset, dst_mask);
3579 else
3581 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3582 DWORD reg = ins->src[0].reg.idx[0].offset;
3583 char dst_swizzle[6];
3585 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3587 if (src_mod == WINED3DSPSM_DZ)
3589 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3590 struct glsl_src_param div_param;
3592 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3594 if (mask_size > 1) {
3595 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3596 } else {
3597 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3600 else if (src_mod == WINED3DSPSM_DW)
3602 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3603 struct glsl_src_param div_param;
3605 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3607 if (mask_size > 1) {
3608 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3609 } else {
3610 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3612 } else {
3613 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3618 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3619 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3620 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3621 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3623 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3624 DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3625 struct glsl_sample_function sample_function;
3626 struct glsl_src_param src0_param;
3627 UINT mask_size;
3629 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3631 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3632 * scalar, and projected sampling would require 4.
3634 * It is a dependent read - not valid with conditional NP2 textures
3636 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3637 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3639 switch(mask_size)
3641 case 1:
3642 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3643 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3644 break;
3646 case 2:
3647 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3648 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3649 break;
3651 case 3:
3652 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3653 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3654 break;
3656 default:
3657 FIXME("Unexpected mask size %u\n", mask_size);
3658 break;
3662 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3663 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3664 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3666 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3667 DWORD dstreg = ins->dst[0].reg.idx[0].offset;
3668 struct glsl_src_param src0_param;
3669 DWORD dst_mask;
3670 unsigned int mask_size;
3672 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3673 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3674 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3676 if (mask_size > 1) {
3677 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3678 } else {
3679 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3683 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3684 * Calculate the depth as dst.x / dst.y */
3685 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3687 struct glsl_dst_param dst_param;
3689 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3691 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3692 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3693 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3694 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3695 * >= 1.0 or < 0.0
3697 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3698 dst_param.reg_name, dst_param.reg_name);
3701 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3702 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3703 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3704 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3706 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3708 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3709 DWORD dstreg = ins->dst[0].reg.idx[0].offset;
3710 struct glsl_src_param src0_param;
3712 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3714 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3715 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3718 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3719 * Calculate the 1st of a 2-row matrix multiplication. */
3720 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3722 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3723 DWORD reg = ins->dst[0].reg.idx[0].offset;
3724 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3725 struct glsl_src_param src0_param;
3727 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3728 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3731 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3732 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3733 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3735 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3736 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3737 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3738 DWORD reg = ins->dst[0].reg.idx[0].offset;
3739 struct glsl_src_param src0_param;
3741 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3742 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3743 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3746 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3748 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3749 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3750 struct glsl_sample_function sample_function;
3751 DWORD reg = ins->dst[0].reg.idx[0].offset;
3752 struct glsl_src_param src0_param;
3754 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3755 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3757 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3759 /* Sample the texture using the calculated coordinates */
3760 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3763 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3764 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3765 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3767 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3768 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3769 struct glsl_sample_function sample_function;
3770 DWORD reg = ins->dst[0].reg.idx[0].offset;
3771 struct glsl_src_param src0_param;
3773 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3774 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3776 /* Dependent read, not valid with conditional NP2 */
3777 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3779 /* Sample the texture using the calculated coordinates */
3780 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3782 tex_mx->current_row = 0;
3785 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3786 * Perform the 3rd row of a 3x3 matrix multiply */
3787 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3789 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3790 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3791 DWORD reg = ins->dst[0].reg.idx[0].offset;
3792 struct glsl_src_param src0_param;
3793 char dst_mask[6];
3795 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3797 shader_glsl_append_dst(ins->ctx->buffer, ins);
3798 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3799 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3801 tex_mx->current_row = 0;
3804 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3805 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3806 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3808 struct glsl_src_param src0_param;
3809 struct glsl_src_param src1_param;
3810 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3811 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3812 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3813 struct glsl_sample_function sample_function;
3814 DWORD reg = ins->dst[0].reg.idx[0].offset;
3815 char coord_mask[6];
3817 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3818 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3820 /* Perform the last matrix multiply operation */
3821 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3822 /* Reflection calculation */
3823 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3825 /* Dependent read, not valid with conditional NP2 */
3826 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3827 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3829 /* Sample the texture */
3830 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3831 NULL, NULL, NULL, "tmp0%s", coord_mask);
3833 tex_mx->current_row = 0;
3836 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3837 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3838 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3840 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3841 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3842 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3843 struct glsl_sample_function sample_function;
3844 DWORD reg = ins->dst[0].reg.idx[0].offset;
3845 struct glsl_src_param src0_param;
3846 char coord_mask[6];
3848 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3850 /* Perform the last matrix multiply operation */
3851 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3853 /* Construct the eye-ray vector from w coordinates */
3854 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3855 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3856 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3858 /* Dependent read, not valid with conditional NP2 */
3859 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3860 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3862 /* Sample the texture using the calculated coordinates */
3863 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3864 NULL, NULL, NULL, "tmp0%s", coord_mask);
3866 tex_mx->current_row = 0;
3869 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3870 * Apply a fake bump map transform.
3871 * texbem is pshader <= 1.3 only, this saves a few version checks
3873 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3875 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3876 struct glsl_sample_function sample_function;
3877 struct glsl_src_param coord_param;
3878 DWORD sampler_idx;
3879 DWORD mask;
3880 DWORD flags;
3881 char coord_mask[6];
3883 sampler_idx = ins->dst[0].reg.idx[0].offset;
3884 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3885 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3887 /* Dependent read, not valid with conditional NP2 */
3888 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3889 mask = sample_function.coord_mask;
3891 shader_glsl_write_mask_to_str(mask, coord_mask);
3893 /* With projected textures, texbem only divides the static texture coord,
3894 * not the displacement, so we can't let GL handle this. */
3895 if (flags & WINED3D_PSARGS_PROJECTED)
3897 DWORD div_mask=0;
3898 char coord_div_mask[3];
3899 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3901 case WINED3D_TTFF_COUNT1:
3902 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3903 break;
3904 case WINED3D_TTFF_COUNT2:
3905 div_mask = WINED3DSP_WRITEMASK_1;
3906 break;
3907 case WINED3D_TTFF_COUNT3:
3908 div_mask = WINED3DSP_WRITEMASK_2;
3909 break;
3910 case WINED3D_TTFF_COUNT4:
3911 case WINED3D_TTFF_DISABLE:
3912 div_mask = WINED3DSP_WRITEMASK_3;
3913 break;
3915 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3916 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3919 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3921 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3922 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3923 coord_param.param_str, coord_mask);
3925 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3927 struct glsl_src_param luminance_param;
3928 struct glsl_dst_param dst_param;
3930 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3931 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3933 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3934 dst_param.reg_name, dst_param.mask_str,
3935 luminance_param.param_str, sampler_idx, sampler_idx);
3939 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3941 DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3942 struct glsl_src_param src0_param, src1_param;
3944 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3945 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3947 shader_glsl_append_dst(ins->ctx->buffer, ins);
3948 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3949 src0_param.param_str, sampler_idx, src1_param.param_str);
3952 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3953 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3954 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3956 DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3957 struct glsl_sample_function sample_function;
3958 struct glsl_src_param src0_param;
3960 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3962 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3963 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3964 "%s.wx", src0_param.reg_name);
3967 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3968 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3969 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3971 DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3972 struct glsl_sample_function sample_function;
3973 struct glsl_src_param src0_param;
3975 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3977 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3978 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3979 "%s.yz", src0_param.reg_name);
3982 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3983 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3984 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3986 DWORD sampler_idx = ins->dst[0].reg.idx[0].offset;
3987 struct glsl_sample_function sample_function;
3988 struct glsl_src_param src0_param;
3990 /* Dependent read, not valid with conditional NP2 */
3991 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3992 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3994 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3995 "%s", src0_param.param_str);
3998 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3999 * If any of the first 3 components are < 0, discard this pixel */
4000 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
4002 struct glsl_dst_param dst_param;
4004 /* The argument is a destination parameter, and no writemasks are allowed */
4005 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
4006 if (ins->ctx->reg_maps->shader_version.major >= 2)
4008 /* 2.0 shaders compare all 4 components in texkill */
4009 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
4010 } else {
4011 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
4012 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
4013 * 4 components are defined, only the first 3 are used
4015 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
4019 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
4020 * dst = dot2(src0, src1) + src2 */
4021 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
4023 struct glsl_src_param src0_param;
4024 struct glsl_src_param src1_param;
4025 struct glsl_src_param src2_param;
4026 DWORD write_mask;
4027 unsigned int mask_size;
4029 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
4030 mask_size = shader_glsl_get_write_mask_size(write_mask);
4032 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
4033 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
4034 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
4036 if (mask_size > 1) {
4037 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
4038 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
4039 } else {
4040 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
4041 src0_param.param_str, src1_param.param_str, src2_param.param_str);
4045 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
4046 const struct wined3d_shader_signature_element *input_signature,
4047 const struct wined3d_shader_reg_maps *reg_maps,
4048 enum vertexprocessing_mode vertexprocessing)
4050 WORD map = reg_maps->input_registers;
4051 unsigned int i;
4053 for (i = 0; map; map >>= 1, ++i)
4055 const char *semantic_name;
4056 UINT semantic_idx;
4057 char reg_mask[6];
4059 /* Unused */
4060 if (!(map & 1)) continue;
4062 semantic_name = input_signature[i].semantic_name;
4063 semantic_idx = input_signature[i].semantic_idx;
4064 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
4066 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
4068 if (semantic_idx < 8 && vertexprocessing == pretransformed)
4069 shader_addline(buffer, "ps_in[%u]%s = gl_TexCoord[%u]%s;\n",
4070 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
4071 else
4072 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4073 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4075 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
4077 if (!semantic_idx)
4078 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_Color)%s;\n",
4079 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4080 else if (semantic_idx == 1)
4081 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_SecondaryColor)%s;\n",
4082 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4083 else
4084 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4085 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4087 else
4089 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4090 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
4095 /*********************************************
4096 * Vertex Shader Specific Code begins here
4097 ********************************************/
4099 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
4101 struct glsl_program_key key;
4103 key.vs_id = entry->vs_id;
4104 key.ps_id = entry->ps_id;
4106 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
4108 ERR("Failed to insert program entry.\n");
4112 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
4113 GLhandleARB vs_id, GLhandleARB ps_id)
4115 struct wine_rb_entry *entry;
4116 struct glsl_program_key key;
4118 key.vs_id = vs_id;
4119 key.ps_id = ps_id;
4121 entry = wine_rb_get(&priv->program_lookup, &key);
4122 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
4125 /* GL locking is done by the caller */
4126 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
4127 struct glsl_shader_prog_link *entry)
4129 struct glsl_program_key key;
4131 key.vs_id = entry->vs_id;
4132 key.ps_id = entry->ps_id;
4133 wine_rb_remove(&priv->program_lookup, &key);
4135 GL_EXTCALL(glDeleteObjectARB(entry->programId));
4136 if (entry->vs_id)
4137 list_remove(&entry->vshader_entry);
4138 if (entry->ps_id)
4139 list_remove(&entry->pshader_entry);
4140 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
4141 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
4142 HeapFree(GetProcessHeap(), 0, entry);
4145 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
4146 const struct wined3d_gl_info *gl_info, const DWORD *map,
4147 const struct wined3d_shader_signature_element *input_signature,
4148 const struct wined3d_shader_reg_maps *reg_maps_in,
4149 const struct wined3d_shader_signature_element *output_signature,
4150 const struct wined3d_shader_reg_maps *reg_maps_out)
4152 unsigned int i, j;
4153 const char *semantic_name_in;
4154 UINT semantic_idx_in;
4155 DWORD *set;
4156 DWORD in_idx;
4157 unsigned int in_count = vec4_varyings(3, gl_info);
4158 char reg_mask[6];
4159 char destination[50];
4160 WORD input_map, output_map;
4162 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
4164 input_map = reg_maps_in->input_registers;
4165 for (i = 0; input_map; input_map >>= 1, ++i)
4167 if (!(input_map & 1)) continue;
4169 in_idx = map[i];
4170 /* Declared, but not read register */
4171 if (in_idx == ~0U) continue;
4172 if (in_idx >= (in_count + 2))
4174 FIXME("More input varyings declared than supported, expect issues.\n");
4175 continue;
4178 if (in_idx == in_count)
4179 sprintf(destination, "gl_FrontColor");
4180 else if (in_idx == in_count + 1)
4181 sprintf(destination, "gl_FrontSecondaryColor");
4182 else
4183 sprintf(destination, "ps_in[%u]", in_idx);
4185 semantic_name_in = input_signature[i].semantic_name;
4186 semantic_idx_in = input_signature[i].semantic_idx;
4187 set[in_idx] = ~0U;
4189 output_map = reg_maps_out->output_registers;
4190 for (j = 0; output_map; output_map >>= 1, ++j)
4192 DWORD mask;
4194 if (!(output_map & 1)
4195 || semantic_idx_in != output_signature[j].semantic_idx
4196 || strcmp(semantic_name_in, output_signature[j].semantic_name)
4197 || !(mask = input_signature[i].mask & output_signature[j].mask))
4198 continue;
4200 set[in_idx] = mask;
4201 shader_glsl_write_mask_to_str(mask, reg_mask);
4203 shader_addline(buffer, "%s%s = vs_out[%u]%s;\n",
4204 destination, reg_mask, j, reg_mask);
4208 for (i = 0; i < in_count + 2; ++i)
4210 unsigned int size;
4212 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
4213 continue;
4215 if (set[i] == ~0U) set[i] = 0;
4217 size = 0;
4218 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
4219 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
4220 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
4221 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
4222 reg_mask[size] = '\0';
4224 if (i == in_count)
4225 sprintf(destination, "gl_FrontColor");
4226 else if (i == in_count + 1)
4227 sprintf(destination, "gl_FrontSecondaryColor");
4228 else
4229 sprintf(destination, "ps_in[%u]", i);
4231 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
4232 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
4235 HeapFree(GetProcessHeap(), 0, set);
4238 /* GL locking is done by the caller */
4239 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
4240 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
4241 const struct wined3d_gl_info *gl_info)
4243 GLhandleARB ret = 0;
4244 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
4245 unsigned int i;
4246 const char *semantic_name;
4247 UINT semantic_idx;
4248 char reg_mask[6];
4249 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
4250 WORD map = vs->reg_maps.output_registers;
4252 shader_buffer_clear(buffer);
4254 shader_addline(buffer, "#version 120\n");
4256 if (ps_major < 3)
4258 shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4260 for (i = 0; map; map >>= 1, ++i)
4262 DWORD write_mask;
4264 if (!(map & 1)) continue;
4266 semantic_name = output_signature[i].semantic_name;
4267 semantic_idx = output_signature[i].semantic_idx;
4268 write_mask = output_signature[i].mask;
4269 shader_glsl_write_mask_to_str(write_mask, reg_mask);
4271 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
4273 if (!semantic_idx)
4274 shader_addline(buffer, "gl_FrontColor%s = vs_out[%u]%s;\n",
4275 reg_mask, i, reg_mask);
4276 else if (semantic_idx == 1)
4277 shader_addline(buffer, "gl_FrontSecondaryColor%s = vs_out[%u]%s;\n",
4278 reg_mask, i, reg_mask);
4280 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4282 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4283 reg_mask, i, reg_mask);
4285 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
4287 if (semantic_idx < 8)
4289 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
4290 write_mask |= WINED3DSP_WRITEMASK_3;
4292 shader_addline(buffer, "gl_TexCoord[%u]%s = vs_out[%u]%s;\n",
4293 semantic_idx, reg_mask, i, reg_mask);
4294 if (!(write_mask & WINED3DSP_WRITEMASK_3))
4295 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
4298 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4300 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4302 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_FOG))
4304 shader_addline(buffer, "gl_FogFragCoord = clamp(vs_out[%u].%c, 0.0, 1.0);\n", i, reg_mask[1]);
4307 shader_addline(buffer, "}\n");
4309 else
4311 UINT in_count = min(vec4_varyings(ps_major, gl_info), ps->limits.packed_input);
4312 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
4313 shader_addline(buffer, "varying vec4 ps_in[%u];\n", in_count);
4314 shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4316 /* First, sort out position and point size. Those are not passed to the pixel shader */
4317 for (i = 0; map; map >>= 1, ++i)
4319 if (!(map & 1)) continue;
4321 semantic_name = output_signature[i].semantic_name;
4322 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
4324 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4326 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4327 reg_mask, i, reg_mask);
4329 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4331 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4335 /* Then, fix the pixel shader input */
4336 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
4337 &ps->reg_maps, output_signature, &vs->reg_maps);
4339 shader_addline(buffer, "}\n");
4342 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4343 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4344 shader_glsl_compile(gl_info, ret, buffer->buffer);
4346 return ret;
4349 /* GL locking is done by the caller */
4350 static void hardcode_local_constants(const struct wined3d_shader *shader,
4351 const struct wined3d_gl_info *gl_info, GLhandleARB programId, const char *prefix)
4353 const struct wined3d_shader_lconst *lconst;
4354 GLint tmp_loc;
4355 const float *value;
4356 char glsl_name[10];
4358 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
4360 value = (const float *)lconst->value;
4361 snprintf(glsl_name, sizeof(glsl_name), "%s_lc%u", prefix, lconst->idx);
4362 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4363 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4365 checkGLcall("Hardcoding local constants");
4368 /* GL locking is done by the caller */
4369 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4370 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4371 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4373 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4374 const struct wined3d_gl_info *gl_info = context->gl_info;
4375 const DWORD *function = shader->function;
4376 struct shader_glsl_ctx_priv priv_ctx;
4378 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4379 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4381 memset(&priv_ctx, 0, sizeof(priv_ctx));
4382 priv_ctx.cur_ps_args = args;
4383 priv_ctx.cur_np2fixup_info = np2fixup_info;
4385 shader_addline(buffer, "#version 120\n");
4387 if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4388 shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4389 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
4390 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4391 /* The spec says that it doesn't have to be explicitly enabled, but the
4392 * nvidia drivers write a warning if we don't do so. */
4393 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4394 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4395 if (gl_info->supported[EXT_GPU_SHADER4])
4396 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4398 /* Base Declarations */
4399 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4401 /* Pack 3.0 inputs */
4402 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4403 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4405 /* Base Shader Body */
4406 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4408 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4409 if (reg_maps->shader_version.major < 2)
4411 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4412 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4415 if (args->srgb_correction)
4417 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4418 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4419 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4420 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4421 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4422 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4424 /* Pixel shader < 3.0 do not replace the fog stage.
4425 * This implements linear fog computation and blending.
4426 * TODO: non linear fog
4427 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4428 * -1/(e-s) and e/(e-s) respectively.
4430 if (reg_maps->shader_version.major < 3)
4432 switch(args->fog) {
4433 case FOG_OFF: break;
4434 case FOG_LINEAR:
4435 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4436 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4437 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4438 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4439 break;
4440 case FOG_EXP:
4441 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4442 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4443 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4444 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4445 break;
4446 case FOG_EXP2:
4447 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4448 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4449 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4450 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4451 break;
4455 shader_addline(buffer, "}\n");
4457 TRACE("Compiling shader object %u\n", shader_obj);
4458 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4460 /* Store the shader object */
4461 return shader_obj;
4464 /* GL locking is done by the caller */
4465 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4466 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4467 const struct vs_compile_args *args)
4469 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4470 const struct wined3d_gl_info *gl_info = context->gl_info;
4471 const DWORD *function = shader->function;
4472 struct shader_glsl_ctx_priv priv_ctx;
4474 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4475 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4477 shader_addline(buffer, "#version 120\n");
4479 if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4480 shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4481 if (gl_info->supported[EXT_GPU_SHADER4])
4482 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4484 memset(&priv_ctx, 0, sizeof(priv_ctx));
4485 priv_ctx.cur_vs_args = args;
4487 /* Base Declarations */
4488 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4490 /* Base Shader Body */
4491 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4493 /* Unpack outputs */
4494 shader_addline(buffer, "order_ps_input(vs_out);\n");
4496 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4497 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4498 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4499 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4501 if (args->fog_src == VS_FOG_Z)
4502 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4503 else if (!reg_maps->fog)
4504 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4506 /* We always store the clipplanes without y inversion */
4507 if (args->clip_enabled)
4508 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4510 /* Write the final position.
4512 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4513 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4514 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4515 * contains 1.0 to allow a mad.
4517 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4518 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4520 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4522 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4523 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4524 * which is the same as z = z * 2 - w.
4526 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4528 shader_addline(buffer, "}\n");
4530 TRACE("Compiling shader object %u\n", shader_obj);
4531 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4533 return shader_obj;
4536 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4537 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4538 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4540 struct wined3d_state *state = &shader->device->stateBlock->state;
4541 struct glsl_ps_compiled_shader *gl_shaders, *new_array;
4542 struct glsl_shader_private *shader_data;
4543 struct ps_np2fixup_info *np2fixup;
4544 UINT i;
4545 DWORD new_size;
4546 GLhandleARB ret;
4548 if (!shader->backend_data)
4550 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4551 if (!shader->backend_data)
4553 ERR("Failed to allocate backend data.\n");
4554 return 0;
4557 shader_data = shader->backend_data;
4558 gl_shaders = shader_data->gl_shaders.ps;
4560 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4561 * so a linear search is more performant than a hashmap or a binary search
4562 * (cache coherency etc)
4564 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4566 if (!memcmp(&gl_shaders[i].args, args, sizeof(*args)))
4568 if (args->np2_fixup)
4569 *np2fixup_info = &gl_shaders[i].np2fixup;
4570 return gl_shaders[i].prgId;
4574 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4575 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4576 if (shader_data->num_gl_shaders)
4578 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4579 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.ps,
4580 new_size * sizeof(*gl_shaders));
4582 else
4584 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4585 new_size = 1;
4588 if(!new_array) {
4589 ERR("Out of memory\n");
4590 return 0;
4592 shader_data->gl_shaders.ps = new_array;
4593 shader_data->shader_array_size = new_size;
4594 gl_shaders = new_array;
4597 gl_shaders[shader_data->num_gl_shaders].args = *args;
4599 np2fixup = &gl_shaders[shader_data->num_gl_shaders].np2fixup;
4600 memset(np2fixup, 0, sizeof(*np2fixup));
4601 *np2fixup_info = args->np2_fixup ? np2fixup : NULL;
4603 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4605 shader_buffer_clear(buffer);
4606 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4607 gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4609 return ret;
4612 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4613 const DWORD use_map) {
4614 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4615 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4616 return stored->fog_src == new->fog_src;
4619 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4620 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4621 const struct vs_compile_args *args)
4623 UINT i;
4624 DWORD new_size;
4625 DWORD use_map = shader->device->strided_streams.use_map;
4626 struct glsl_vs_compiled_shader *gl_shaders, *new_array;
4627 struct glsl_shader_private *shader_data;
4628 GLhandleARB ret;
4630 if (!shader->backend_data)
4632 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4633 if (!shader->backend_data)
4635 ERR("Failed to allocate backend data.\n");
4636 return 0;
4639 shader_data = shader->backend_data;
4640 gl_shaders = shader_data->gl_shaders.vs;
4642 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4643 * so a linear search is more performant than a hashmap or a binary search
4644 * (cache coherency etc)
4646 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4648 if (vs_args_equal(&gl_shaders[i].args, args, use_map))
4649 return gl_shaders[i].prgId;
4652 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4654 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4655 if (shader_data->num_gl_shaders)
4657 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4658 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.vs,
4659 new_size * sizeof(*gl_shaders));
4661 else
4663 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4664 new_size = 1;
4667 if(!new_array) {
4668 ERR("Out of memory\n");
4669 return 0;
4671 shader_data->gl_shaders.vs = new_array;
4672 shader_data->shader_array_size = new_size;
4673 gl_shaders = new_array;
4676 gl_shaders[shader_data->num_gl_shaders].args = *args;
4678 shader_buffer_clear(buffer);
4679 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4680 gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4682 return ret;
4685 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4686 * It sets the programId on the current StateBlock (because it should be called
4687 * inside of the DrawPrimitive() part of the render loop).
4689 * If a program for the given combination does not exist, create one, and store
4690 * the program in the hash table. If it creates a program, it will link the
4691 * given objects, too.
4694 /* GL locking is done by the caller */
4695 static void set_glsl_shader_program(const struct wined3d_context *context,
4696 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4698 const struct wined3d_state *state = &device->stateBlock->state;
4699 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4700 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4701 const struct wined3d_gl_info *gl_info = context->gl_info;
4702 const struct ps_np2fixup_info *np2fixup_info = NULL;
4703 struct shader_glsl_priv *priv = device->shader_priv;
4704 struct glsl_shader_prog_link *entry = NULL;
4705 GLhandleARB programId = 0;
4706 GLhandleARB reorder_shader_id = 0;
4707 unsigned int i;
4708 char glsl_name[10];
4709 struct ps_compile_args ps_compile_args;
4710 struct vs_compile_args vs_compile_args;
4711 GLhandleARB vs_id, ps_id;
4713 if (vshader)
4715 find_vs_compile_args(state, vshader, &vs_compile_args);
4716 vs_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4718 else
4720 vs_id = 0;
4723 if (pshader)
4725 find_ps_compile_args(state, pshader, &ps_compile_args);
4726 ps_id = find_glsl_pshader(context, &priv->shader_buffer,
4727 pshader, &ps_compile_args, &np2fixup_info);
4729 else
4731 ps_id = 0;
4734 if ((entry = get_glsl_program_entry(priv, vs_id, ps_id)))
4736 priv->glsl_program = entry;
4737 return;
4740 /* If we get to this point, then no matching program exists, so we create one */
4741 programId = GL_EXTCALL(glCreateProgramObjectARB());
4742 TRACE("Created new GLSL shader program %u\n", programId);
4744 /* Create the entry */
4745 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4746 entry->programId = programId;
4747 entry->vs_id = vs_id;
4748 entry->ps_id = ps_id;
4749 entry->constant_version = 0;
4750 entry->np2Fixup_info = np2fixup_info;
4751 /* Add the hash table entry */
4752 add_glsl_program_entry(priv, entry);
4754 /* Set the current program */
4755 priv->glsl_program = entry;
4757 /* Attach GLSL vshader */
4758 if (vshader)
4760 WORD map = vshader->reg_maps.input_registers;
4761 char tmp_name[10];
4763 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4764 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4765 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4766 checkGLcall("glAttachObjectARB");
4767 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4768 * is destroyed
4770 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4772 TRACE("Attaching GLSL shader object %u to program %u.\n", vs_id, programId);
4773 GL_EXTCALL(glAttachObjectARB(programId, vs_id));
4774 checkGLcall("glAttachObjectARB");
4776 /* Bind vertex attributes to a corresponding index number to match
4777 * the same index numbers as ARB_vertex_programs (makes loading
4778 * vertex attributes simpler). With this method, we can use the
4779 * exact same code to load the attributes later for both ARB and
4780 * GLSL shaders.
4782 * We have to do this here because we need to know the Program ID
4783 * in order to make the bindings work, and it has to be done prior
4784 * to linking the GLSL program. */
4785 for (i = 0; map; map >>= 1, ++i)
4787 if (!(map & 1)) continue;
4789 snprintf(tmp_name, sizeof(tmp_name), "vs_in%u", i);
4790 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4792 checkGLcall("glBindAttribLocationARB");
4794 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4797 /* Attach GLSL pshader */
4798 if (pshader)
4800 TRACE("Attaching GLSL shader object %u to program %u.\n", ps_id, programId);
4801 GL_EXTCALL(glAttachObjectARB(programId, ps_id));
4802 checkGLcall("glAttachObjectARB");
4804 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4807 /* Link the program */
4808 TRACE("Linking GLSL shader program %u\n", programId);
4809 GL_EXTCALL(glLinkProgramARB(programId));
4810 shader_glsl_validate_link(gl_info, programId);
4812 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4813 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4814 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4816 snprintf(glsl_name, sizeof(glsl_name), "vs_c[%u]", i);
4817 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4819 for (i = 0; i < MAX_CONST_I; ++i)
4821 snprintf(glsl_name, sizeof(glsl_name), "vs_i[%u]", i);
4822 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4824 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4825 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4826 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4828 snprintf(glsl_name, sizeof(glsl_name), "ps_c[%u]", i);
4829 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4831 for (i = 0; i < MAX_CONST_I; ++i)
4833 snprintf(glsl_name, sizeof(glsl_name), "ps_i[%u]", i);
4834 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4837 if(pshader) {
4838 char name[32];
4840 for(i = 0; i < MAX_TEXTURES; i++) {
4841 sprintf(name, "bumpenvmat%u", i);
4842 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4843 sprintf(name, "luminancescale%u", i);
4844 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4845 sprintf(name, "luminanceoffset%u", i);
4846 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4849 if (ps_compile_args.np2_fixup)
4851 if (entry->np2Fixup_info)
4852 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ps_samplerNP2Fixup"));
4853 else
4854 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4858 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4859 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4860 checkGLcall("Find glsl program uniform locations");
4862 if (pshader && pshader->reg_maps.shader_version.major >= 3
4863 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4865 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4866 entry->vertex_color_clamp = GL_FALSE;
4867 } else {
4868 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4871 /* Set the shader to allow uniform loading on it */
4872 GL_EXTCALL(glUseProgramObjectARB(programId));
4873 checkGLcall("glUseProgramObjectARB(programId)");
4875 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4876 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4877 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4878 * vertex shader with fixed function pixel processing is used we make sure that the card
4879 * supports enough samplers to allow the max number of vertex samplers with all possible
4880 * fixed function fragment processing setups. So once the program is linked these samplers
4881 * won't change.
4883 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4884 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4886 /* If the local constants do not have to be loaded with the environment constants,
4887 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4888 * later
4890 if (pshader && !pshader->load_local_constsF)
4891 hardcode_local_constants(pshader, gl_info, programId, "ps");
4892 if (vshader && !vshader->load_local_constsF)
4893 hardcode_local_constants(vshader, gl_info, programId, "vs");
4896 /* GL locking is done by the caller */
4897 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4899 GLhandleARB program_id;
4900 GLhandleARB vshader_id, pshader_id;
4901 const char *blt_pshader;
4903 static const char *blt_vshader =
4904 "#version 120\n"
4905 "void main(void)\n"
4906 "{\n"
4907 " gl_Position = gl_Vertex;\n"
4908 " gl_FrontColor = vec4(1.0);\n"
4909 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4910 "}\n";
4912 static const char * const blt_pshaders_full[tex_type_count] =
4914 /* tex_1d */
4915 NULL,
4916 /* tex_2d */
4917 "#version 120\n"
4918 "uniform sampler2D sampler;\n"
4919 "void main(void)\n"
4920 "{\n"
4921 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4922 "}\n",
4923 /* tex_3d */
4924 NULL,
4925 /* tex_cube */
4926 "#version 120\n"
4927 "uniform samplerCube sampler;\n"
4928 "void main(void)\n"
4929 "{\n"
4930 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4931 "}\n",
4932 /* tex_rect */
4933 "#version 120\n"
4934 "#extension GL_ARB_texture_rectangle : enable\n"
4935 "uniform sampler2DRect sampler;\n"
4936 "void main(void)\n"
4937 "{\n"
4938 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4939 "}\n",
4942 static const char * const blt_pshaders_masked[tex_type_count] =
4944 /* tex_1d */
4945 NULL,
4946 /* tex_2d */
4947 "#version 120\n"
4948 "uniform sampler2D sampler;\n"
4949 "uniform vec4 mask;\n"
4950 "void main(void)\n"
4951 "{\n"
4952 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4953 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4954 "}\n",
4955 /* tex_3d */
4956 NULL,
4957 /* tex_cube */
4958 "#version 120\n"
4959 "uniform samplerCube sampler;\n"
4960 "uniform vec4 mask;\n"
4961 "void main(void)\n"
4962 "{\n"
4963 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4964 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4965 "}\n",
4966 /* tex_rect */
4967 "#version 120\n"
4968 "#extension GL_ARB_texture_rectangle : enable\n"
4969 "uniform sampler2DRect sampler;\n"
4970 "uniform vec4 mask;\n"
4971 "void main(void)\n"
4972 "{\n"
4973 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4974 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4975 "}\n",
4978 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4979 if (!blt_pshader)
4981 FIXME("tex_type %#x not supported\n", tex_type);
4982 return 0;
4985 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4986 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4988 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4989 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4991 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4992 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4993 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4994 GL_EXTCALL(glLinkProgramARB(program_id));
4996 shader_glsl_validate_link(gl_info, program_id);
4998 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4999 * is destroyed
5001 GL_EXTCALL(glDeleteObjectARB(vshader_id));
5002 GL_EXTCALL(glDeleteObjectARB(pshader_id));
5003 return program_id;
5006 /* GL locking is done by the caller */
5007 static void shader_glsl_select(const struct wined3d_context *context, enum wined3d_shader_mode vertex_mode,
5008 enum wined3d_shader_mode fragment_mode)
5010 const struct wined3d_gl_info *gl_info = context->gl_info;
5011 struct wined3d_device *device = context->swapchain->device;
5012 struct shader_glsl_priv *priv = device->shader_priv;
5013 GLhandleARB program_id = 0;
5014 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
5015 BOOL useVS = vertex_mode == WINED3D_SHADER_MODE_SHADER;
5016 BOOL usePS = fragment_mode == WINED3D_SHADER_MODE_SHADER;
5018 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
5020 priv->fragment_pipe->enable_extension(gl_info, fragment_mode == WINED3D_SHADER_MODE_FFP);
5021 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
5022 else priv->glsl_program = NULL;
5024 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
5026 if (old_vertex_color_clamp != current_vertex_color_clamp)
5028 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
5030 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
5031 checkGLcall("glClampColorARB");
5033 else
5035 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
5039 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5040 if (program_id) TRACE("Using GLSL program %u\n", program_id);
5041 GL_EXTCALL(glUseProgramObjectARB(program_id));
5042 checkGLcall("glUseProgramObjectARB");
5044 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
5045 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
5046 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
5047 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
5049 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
5053 /* GL locking is done by the caller */
5054 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
5055 enum tex_types tex_type, const SIZE *ds_mask_size)
5057 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
5058 struct shader_glsl_priv *priv = shader_priv;
5059 GLhandleARB *blt_program;
5060 GLint loc;
5062 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
5063 if (!*blt_program)
5065 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
5066 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
5067 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5068 GL_EXTCALL(glUniform1iARB(loc, 0));
5070 else
5072 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5075 if (masked)
5077 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
5078 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
5082 /* GL locking is done by the caller */
5083 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
5085 struct shader_glsl_priv *priv = shader_priv;
5086 GLhandleARB program_id;
5088 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5089 if (program_id) TRACE("Using GLSL program %u\n", program_id);
5091 GL_EXTCALL(glUseProgramObjectARB(program_id));
5092 checkGLcall("glUseProgramObjectARB");
5095 static void shader_glsl_destroy(struct wined3d_shader *shader)
5097 struct glsl_shader_private *shader_data = shader->backend_data;
5098 struct wined3d_device *device = shader->device;
5099 struct shader_glsl_priv *priv = device->shader_priv;
5100 const struct wined3d_gl_info *gl_info;
5101 const struct list *linked_programs;
5102 struct wined3d_context *context;
5104 if (!shader_data || !shader_data->num_gl_shaders)
5106 HeapFree(GetProcessHeap(), 0, shader_data);
5107 shader->backend_data = NULL;
5108 return;
5111 context = context_acquire(device, NULL);
5112 gl_info = context->gl_info;
5114 TRACE("Deleting linked programs.\n");
5115 linked_programs = &shader->linked_programs;
5116 if (linked_programs->next)
5118 struct glsl_shader_prog_link *entry, *entry2;
5119 UINT i;
5121 ENTER_GL();
5123 switch (shader->reg_maps.shader_version.type)
5125 case WINED3D_SHADER_TYPE_PIXEL:
5127 struct glsl_ps_compiled_shader *gl_shaders = shader_data->gl_shaders.ps;
5129 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
5130 struct glsl_shader_prog_link, pshader_entry)
5132 delete_glsl_program_entry(priv, gl_info, entry);
5135 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5137 TRACE("Deleting pixel shader %u.\n", gl_shaders[i].prgId);
5138 if (priv->glsl_program && priv->glsl_program->ps_id == gl_shaders[i].prgId)
5139 shader_glsl_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
5140 GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5141 checkGLcall("glDeleteObjectARB");
5143 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.ps);
5145 break;
5148 case WINED3D_SHADER_TYPE_VERTEX:
5150 struct glsl_vs_compiled_shader *gl_shaders = shader_data->gl_shaders.vs;
5152 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
5153 struct glsl_shader_prog_link, vshader_entry)
5155 delete_glsl_program_entry(priv, gl_info, entry);
5158 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5160 TRACE("Deleting vertex shader %u.\n", gl_shaders[i].prgId);
5161 if (priv->glsl_program && priv->glsl_program->vs_id == gl_shaders[i].prgId)
5162 shader_glsl_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
5163 GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5164 checkGLcall("glDeleteObjectARB");
5166 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.vs);
5168 break;
5171 default:
5172 ERR("Unhandled shader type %#x.\n", shader->reg_maps.shader_version.type);
5173 break;
5176 LEAVE_GL();
5179 HeapFree(GetProcessHeap(), 0, shader->backend_data);
5180 shader->backend_data = NULL;
5182 context_release(context);
5185 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
5187 const struct glsl_program_key *k = key;
5188 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
5189 const struct glsl_shader_prog_link, program_lookup_entry);
5191 if (k->vs_id > prog->vs_id) return 1;
5192 else if (k->vs_id < prog->vs_id) return -1;
5194 if (k->ps_id > prog->ps_id) return 1;
5195 else if (k->ps_id < prog->ps_id) return -1;
5197 return 0;
5200 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
5202 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5203 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
5205 if (!mem)
5207 ERR("Failed to allocate memory\n");
5208 return FALSE;
5211 heap->entries = mem;
5212 heap->entries[1].version = 0;
5213 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
5214 heap->size = 1;
5216 return TRUE;
5219 static void constant_heap_free(struct constant_heap *heap)
5221 HeapFree(GetProcessHeap(), 0, heap->entries);
5224 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
5226 wined3d_rb_alloc,
5227 wined3d_rb_realloc,
5228 wined3d_rb_free,
5229 glsl_program_key_compare,
5232 static HRESULT shader_glsl_alloc(struct wined3d_device *device, const struct fragment_pipeline *fragment_pipe)
5234 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5235 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
5236 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
5237 gl_info->limits.glsl_ps_float_constants)) + 1;
5238 void *fragment_priv;
5240 if (!(fragment_priv = fragment_pipe->alloc_private(&glsl_shader_backend, priv)))
5242 ERR("Failed to initialize fragment pipe.\n");
5243 HeapFree(GetProcessHeap(), 0, priv);
5244 return E_FAIL;
5247 if (!shader_buffer_init(&priv->shader_buffer))
5249 ERR("Failed to initialize shader buffer.\n");
5250 goto fail;
5253 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
5254 if (!priv->stack)
5256 ERR("Failed to allocate memory.\n");
5257 goto fail;
5260 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
5262 ERR("Failed to initialize vertex shader constant heap\n");
5263 goto fail;
5266 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
5268 ERR("Failed to initialize pixel shader constant heap\n");
5269 goto fail;
5272 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
5274 ERR("Failed to initialize rbtree.\n");
5275 goto fail;
5278 priv->next_constant_version = 1;
5279 device->fragment_priv = fragment_priv;
5280 priv->fragment_pipe = fragment_pipe;
5282 device->shader_priv = priv;
5283 return WINED3D_OK;
5285 fail:
5286 constant_heap_free(&priv->pconst_heap);
5287 constant_heap_free(&priv->vconst_heap);
5288 HeapFree(GetProcessHeap(), 0, priv->stack);
5289 shader_buffer_free(&priv->shader_buffer);
5290 fragment_pipe->free_private(device);
5291 HeapFree(GetProcessHeap(), 0, priv);
5292 return E_OUTOFMEMORY;
5295 /* Context activation is done by the caller. */
5296 static void shader_glsl_free(struct wined3d_device *device)
5298 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5299 struct shader_glsl_priv *priv = device->shader_priv;
5300 int i;
5302 ENTER_GL();
5303 for (i = 0; i < tex_type_count; ++i)
5305 if (priv->depth_blt_program_full[i])
5307 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
5309 if (priv->depth_blt_program_masked[i])
5311 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
5314 LEAVE_GL();
5316 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
5317 constant_heap_free(&priv->pconst_heap);
5318 constant_heap_free(&priv->vconst_heap);
5319 HeapFree(GetProcessHeap(), 0, priv->stack);
5320 shader_buffer_free(&priv->shader_buffer);
5321 priv->fragment_pipe->free_private(device);
5323 HeapFree(GetProcessHeap(), 0, device->shader_priv);
5324 device->shader_priv = NULL;
5327 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
5329 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
5331 UINT shader_model;
5333 if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_SHADER_BIT_ENCODING]
5334 && gl_info->supported[ARB_GEOMETRY_SHADER4] && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
5335 shader_model = 4;
5336 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
5337 * texldd and texldl instructions. */
5338 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
5339 shader_model = 3;
5340 else
5341 shader_model = 2;
5342 TRACE("Shader model %u.\n", shader_model);
5344 caps->vs_version = shader_model;
5345 caps->gs_version = shader_model;
5346 caps->ps_version = shader_model;
5348 caps->vs_uniform_count = gl_info->limits.glsl_vs_float_constants;
5349 caps->ps_uniform_count = gl_info->limits.glsl_ps_float_constants;
5351 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
5352 * Direct3D minimum requirement.
5354 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
5355 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
5357 * The problem is that the refrast clamps temporary results in the shader to
5358 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
5359 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
5360 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
5361 * offer a way to query this.
5363 caps->ps_1x_max_value = 8.0;
5365 caps->vs_clipping = TRUE;
5368 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5370 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5372 TRACE("Checking support for fixup:\n");
5373 dump_color_fixup_desc(fixup);
5376 /* We support everything except YUV conversions. */
5377 if (!is_complex_fixup(fixup))
5379 TRACE("[OK]\n");
5380 return TRUE;
5383 TRACE("[FAILED]\n");
5384 return FALSE;
5387 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5389 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5390 /* WINED3DSIH_ADD */ shader_glsl_binop,
5391 /* WINED3DSIH_AND */ shader_glsl_binop,
5392 /* WINED3DSIH_BEM */ shader_glsl_bem,
5393 /* WINED3DSIH_BREAK */ shader_glsl_break,
5394 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5395 /* WINED3DSIH_BREAKP */ shader_glsl_breakp,
5396 /* WINED3DSIH_CALL */ shader_glsl_call,
5397 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5398 /* WINED3DSIH_CMP */ shader_glsl_conditional_move,
5399 /* WINED3DSIH_CND */ shader_glsl_cnd,
5400 /* WINED3DSIH_CRS */ shader_glsl_cross,
5401 /* WINED3DSIH_CUT */ shader_glsl_cut,
5402 /* WINED3DSIH_DCL */ shader_glsl_nop,
5403 /* WINED3DSIH_DCL_CONSTANT_BUFFER */ shader_glsl_nop,
5404 /* WINED3DSIH_DCL_INPUT_PRIMITIVE */ shader_glsl_nop,
5405 /* WINED3DSIH_DCL_OUTPUT_TOPOLOGY */ shader_glsl_nop,
5406 /* WINED3DSIH_DCL_VERTICES_OUT */ shader_glsl_nop,
5407 /* WINED3DSIH_DEF */ shader_glsl_nop,
5408 /* WINED3DSIH_DEFB */ shader_glsl_nop,
5409 /* WINED3DSIH_DEFI */ shader_glsl_nop,
5410 /* WINED3DSIH_DIV */ shader_glsl_binop,
5411 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5412 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5413 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5414 /* WINED3DSIH_DST */ shader_glsl_dst,
5415 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5416 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5417 /* WINED3DSIH_ELSE */ shader_glsl_else,
5418 /* WINED3DSIH_EMIT */ shader_glsl_emit,
5419 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5420 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5421 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5422 /* WINED3DSIH_EQ */ shader_glsl_relop,
5423 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5424 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5425 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5426 /* WINED3DSIH_FTOI */ shader_glsl_to_int,
5427 /* WINED3DSIH_GE */ shader_glsl_relop,
5428 /* WINED3DSIH_IADD */ shader_glsl_binop,
5429 /* WINED3DSIH_IEQ */ NULL,
5430 /* WINED3DSIH_IF */ shader_glsl_if,
5431 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5432 /* WINED3DSIH_IGE */ shader_glsl_relop,
5433 /* WINED3DSIH_IMUL */ shader_glsl_imul,
5434 /* WINED3DSIH_ITOF */ shader_glsl_to_float,
5435 /* WINED3DSIH_LABEL */ shader_glsl_label,
5436 /* WINED3DSIH_LD */ NULL,
5437 /* WINED3DSIH_LIT */ shader_glsl_lit,
5438 /* WINED3DSIH_LOG */ shader_glsl_log,
5439 /* WINED3DSIH_LOGP */ shader_glsl_log,
5440 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5441 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5442 /* WINED3DSIH_LT */ shader_glsl_relop,
5443 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5444 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5445 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5446 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5447 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5448 /* WINED3DSIH_MAD */ shader_glsl_mad,
5449 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5450 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5451 /* WINED3DSIH_MOV */ shader_glsl_mov,
5452 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5453 /* WINED3DSIH_MOVC */ shader_glsl_conditional_move,
5454 /* WINED3DSIH_MUL */ shader_glsl_binop,
5455 /* WINED3DSIH_NOP */ shader_glsl_nop,
5456 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5457 /* WINED3DSIH_PHASE */ shader_glsl_nop,
5458 /* WINED3DSIH_POW */ shader_glsl_pow,
5459 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5460 /* WINED3DSIH_REP */ shader_glsl_rep,
5461 /* WINED3DSIH_RET */ shader_glsl_ret,
5462 /* WINED3DSIH_ROUND_NI */ shader_glsl_map2gl,
5463 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5464 /* WINED3DSIH_SAMPLE */ NULL,
5465 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5466 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5467 /* WINED3DSIH_SETP */ NULL,
5468 /* WINED3DSIH_SGE */ shader_glsl_compare,
5469 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5470 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5471 /* WINED3DSIH_SLT */ shader_glsl_compare,
5472 /* WINED3DSIH_SQRT */ NULL,
5473 /* WINED3DSIH_SUB */ shader_glsl_binop,
5474 /* WINED3DSIH_TEX */ shader_glsl_tex,
5475 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5476 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5477 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5478 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5479 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5480 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5481 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5482 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5483 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5484 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5485 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5486 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5487 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5488 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5489 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5490 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5491 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5492 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5493 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5494 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5495 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5496 /* WINED3DSIH_UDIV */ shader_glsl_udiv,
5497 /* WINED3DSIH_USHR */ shader_glsl_binop,
5498 /* WINED3DSIH_UTOF */ shader_glsl_to_float,
5499 /* WINED3DSIH_XOR */ shader_glsl_binop,
5502 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5503 SHADER_HANDLER hw_fct;
5505 /* Select handler */
5506 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5508 /* Unhandled opcode */
5509 if (!hw_fct)
5511 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5512 return;
5514 hw_fct(ins);
5516 shader_glsl_add_instruction_modifiers(ins);
5519 static BOOL shader_glsl_has_ffp_proj_control(void *shader_priv)
5521 struct shader_glsl_priv *priv = shader_priv;
5523 return priv->fragment_pipe->ffp_proj_control;
5526 const struct wined3d_shader_backend_ops glsl_shader_backend =
5528 shader_glsl_handle_instruction,
5529 shader_glsl_select,
5530 shader_glsl_select_depth_blt,
5531 shader_glsl_deselect_depth_blt,
5532 shader_glsl_update_float_vertex_constants,
5533 shader_glsl_update_float_pixel_constants,
5534 shader_glsl_load_constants,
5535 shader_glsl_load_np2fixup_constants,
5536 shader_glsl_destroy,
5537 shader_glsl_alloc,
5538 shader_glsl_free,
5539 shader_glsl_context_destroyed,
5540 shader_glsl_get_caps,
5541 shader_glsl_color_fixup_supported,
5542 shader_glsl_has_ffp_proj_control,