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.
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
42 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
43 #define WINED3D_GLSL_SAMPLE_RECT 0x2
44 #define WINED3D_GLSL_SAMPLE_LOD 0x4
45 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
60 } glsl_sample_function_t;
64 HEAP_NODE_TRAVERSE_LEFT,
65 HEAP_NODE_TRAVERSE_RIGHT,
77 struct constant_entry *entries;
78 unsigned int *positions;
82 /* GLSL shader private data */
83 struct shader_glsl_priv {
84 struct wined3d_shader_buffer shader_buffer;
85 struct wine_rb_tree program_lookup;
86 struct glsl_shader_prog_link *glsl_program;
87 struct constant_heap vconst_heap;
88 struct constant_heap pconst_heap;
90 GLhandleARB depth_blt_program_full[tex_type_count];
91 GLhandleARB depth_blt_program_masked[tex_type_count];
92 UINT next_constant_version;
95 /* Struct to maintain data about a linked GLSL program */
96 struct glsl_shader_prog_link {
97 struct wine_rb_entry program_lookup_entry;
98 struct list vshader_entry;
99 struct list pshader_entry;
100 GLhandleARB programId;
101 GLint *vuniformF_locations;
102 GLint *puniformF_locations;
103 GLint vuniformI_locations[MAX_CONST_I];
104 GLint puniformI_locations[MAX_CONST_I];
105 GLint posFixup_location;
106 GLint np2Fixup_location;
107 GLint bumpenvmat_location[MAX_TEXTURES];
108 GLint luminancescale_location[MAX_TEXTURES];
109 GLint luminanceoffset_location[MAX_TEXTURES];
110 GLint ycorrection_location;
111 GLenum vertex_color_clamp;
112 const struct wined3d_shader *vshader;
113 const struct wined3d_shader *pshader;
114 struct vs_compile_args vs_args;
115 struct ps_compile_args ps_args;
116 UINT constant_version;
117 const struct ps_np2fixup_info *np2Fixup_info;
120 struct glsl_program_key
122 const struct wined3d_shader *vshader;
123 const struct wined3d_shader *pshader;
124 struct ps_compile_args ps_args;
125 struct vs_compile_args vs_args;
128 struct shader_glsl_ctx_priv {
129 const struct vs_compile_args *cur_vs_args;
130 const struct ps_compile_args *cur_ps_args;
131 struct ps_np2fixup_info *cur_np2fixup_info;
134 struct glsl_ps_compiled_shader
136 struct ps_compile_args args;
137 struct ps_np2fixup_info np2fixup;
141 struct glsl_pshader_private
143 struct glsl_ps_compiled_shader *gl_shaders;
144 UINT num_gl_shaders, shader_array_size;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
153 struct glsl_vshader_private
155 struct glsl_vs_compiled_shader *gl_shaders;
156 UINT num_gl_shaders, shader_array_size;
159 static const char *debug_gl_shader_type(GLenum type)
163 #define WINED3D_TO_STR(u) case u: return #u
164 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
165 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
166 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
167 #undef WINED3D_TO_STR
169 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
173 /* Extract a line from the info log.
174 * Note that this modifies the source string. */
175 static char *get_info_log_line(char **ptr)
180 if (!(q = strstr(p, "\n")))
182 if (!*p) return NULL;
192 /** Prints the GLSL info log which will contain error messages if they exist */
193 /* GL locking is done by the caller */
194 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
196 int infologLength = 0;
201 static const char * const spam[] =
203 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
204 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
205 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
206 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
207 "Fragment shader(s) linked, vertex shader(s) linked. \n", /* fglrx, with \n */
208 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
209 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
210 "Vertex shader(s) linked, no fragment shader(s) defined. \n", /* fglrx, with \n */
211 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
212 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
213 "Fragment shader(s) linked, no vertex shader(s) defined. \n", /* fglrx, with \n */
214 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
217 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
219 GL_EXTCALL(glGetObjectParameterivARB(obj,
220 GL_OBJECT_INFO_LOG_LENGTH_ARB,
223 /* A size of 1 is just a null-terminated string, so the log should be bigger than
224 * that if there are errors. */
225 if (infologLength > 1)
229 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
230 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
232 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
233 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
236 for (i = 0; i < sizeof(spam) / sizeof(*spam); ++i)
238 if (!strcmp(infoLog, spam[i]))
248 TRACE("Spam received from GLSL shader #%u:\n", obj);
249 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
253 FIXME("Error received from GLSL shader #%u:\n", obj);
254 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
256 HeapFree(GetProcessHeap(), 0, infoLog);
260 /* GL locking is done by the caller. */
261 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
263 TRACE("Compiling shader object %u.\n", shader);
264 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
265 checkGLcall("glShaderSourceARB");
266 GL_EXTCALL(glCompileShaderARB(shader));
267 checkGLcall("glCompileShaderARB");
268 print_glsl_info_log(gl_info, shader);
271 /* GL locking is done by the caller. */
272 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
274 GLint i, object_count, source_size = -1;
275 GLhandleARB *objects;
278 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
279 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
282 ERR("Failed to allocate object array memory.\n");
286 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
287 for (i = 0; i < object_count; ++i)
292 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
294 if (source_size < tmp)
296 HeapFree(GetProcessHeap(), 0, source);
298 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
301 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
302 HeapFree(GetProcessHeap(), 0, objects);
308 FIXME("Object %u:\n", objects[i]);
309 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
310 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
311 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
312 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
316 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
317 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
321 HeapFree(GetProcessHeap(), 0, source);
322 HeapFree(GetProcessHeap(), 0, objects);
325 /* GL locking is done by the caller. */
326 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
330 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
332 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
333 if (tmp == GL_PROGRAM_OBJECT_ARB)
335 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
338 FIXME("Program %u link status invalid.\n", program);
339 shader_glsl_dump_program_source(gl_info, program);
343 print_glsl_info_log(gl_info, program);
347 * Loads (pixel shader) samplers
349 /* GL locking is done by the caller */
350 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
351 DWORD *tex_unit_map, GLhandleARB programId)
355 char sampler_name[20];
357 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
358 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
359 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
360 if (name_loc != -1) {
361 DWORD mapped_unit = tex_unit_map[i];
362 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
364 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
365 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
366 checkGLcall("glUniform1iARB");
368 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
374 /* GL locking is done by the caller */
375 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
376 DWORD *tex_unit_map, GLhandleARB programId)
379 char sampler_name[20];
382 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
383 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
384 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
385 if (name_loc != -1) {
386 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
387 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
389 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
390 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
391 checkGLcall("glUniform1iARB");
393 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
399 /* GL locking is done by the caller */
400 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
401 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
404 unsigned int heap_idx = 1;
407 if (heap->entries[heap_idx].version <= version) return;
409 idx = heap->entries[heap_idx].idx;
410 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
411 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
413 while (stack_idx >= 0)
415 /* Note that we fall through to the next case statement. */
416 switch(stack[stack_idx])
418 case HEAP_NODE_TRAVERSE_LEFT:
420 unsigned int left_idx = heap_idx << 1;
421 if (left_idx < heap->size && heap->entries[left_idx].version > version)
424 idx = heap->entries[heap_idx].idx;
425 if (constant_locations[idx] != -1)
426 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
428 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
429 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
434 case HEAP_NODE_TRAVERSE_RIGHT:
436 unsigned int right_idx = (heap_idx << 1) + 1;
437 if (right_idx < heap->size && heap->entries[right_idx].version > version)
439 heap_idx = right_idx;
440 idx = heap->entries[heap_idx].idx;
441 if (constant_locations[idx] != -1)
442 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
444 stack[stack_idx++] = HEAP_NODE_POP;
445 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
458 checkGLcall("walk_constant_heap()");
461 /* GL locking is done by the caller */
462 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
464 GLfloat clamped_constant[4];
466 if (location == -1) return;
468 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
469 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
470 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
471 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
473 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
476 /* GL locking is done by the caller */
477 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
478 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
481 unsigned int heap_idx = 1;
484 if (heap->entries[heap_idx].version <= version) return;
486 idx = heap->entries[heap_idx].idx;
487 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
488 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
490 while (stack_idx >= 0)
492 /* Note that we fall through to the next case statement. */
493 switch(stack[stack_idx])
495 case HEAP_NODE_TRAVERSE_LEFT:
497 unsigned int left_idx = heap_idx << 1;
498 if (left_idx < heap->size && heap->entries[left_idx].version > version)
501 idx = heap->entries[heap_idx].idx;
502 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
504 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
505 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
510 case HEAP_NODE_TRAVERSE_RIGHT:
512 unsigned int right_idx = (heap_idx << 1) + 1;
513 if (right_idx < heap->size && heap->entries[right_idx].version > version)
515 heap_idx = right_idx;
516 idx = heap->entries[heap_idx].idx;
517 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
519 stack[stack_idx++] = HEAP_NODE_POP;
520 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
533 checkGLcall("walk_constant_heap_clamped()");
536 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
537 /* GL locking is done by the caller */
538 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
539 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
540 unsigned char *stack, UINT version)
542 const local_constant *lconst;
544 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
545 if (shader->reg_maps.shader_version.major == 1
546 && shader_is_pshader_version(shader->reg_maps.shader_version.type))
547 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
549 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
551 if (!shader->load_local_constsF)
553 TRACE("No need to load local float constants for this shader\n");
557 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
558 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
560 GLint location = constant_locations[lconst->idx];
561 /* We found this uniform name in the program - go ahead and send the data */
562 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
564 checkGLcall("glUniform4fvARB()");
567 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
568 /* GL locking is done by the caller */
569 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
570 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
575 for (i = 0; constants_set; constants_set >>= 1, ++i)
577 if (!(constants_set & 1)) continue;
579 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
580 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
582 /* We found this uniform name in the program - go ahead and send the data */
583 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
584 checkGLcall("glUniform4ivARB");
587 /* Load immediate constants */
588 ptr = list_head(&shader->constantsI);
591 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
592 unsigned int idx = lconst->idx;
593 const GLint *values = (const GLint *)lconst->value;
595 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
596 values[0], values[1], values[2], values[3]);
598 /* We found this uniform name in the program - go ahead and send the data */
599 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
600 checkGLcall("glUniform4ivARB");
601 ptr = list_next(&shader->constantsI, ptr);
605 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
606 /* GL locking is done by the caller */
607 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
608 GLhandleARB programId, const BOOL *constants, WORD constants_set)
616 switch (shader->reg_maps.shader_version.type)
618 case WINED3D_SHADER_TYPE_VERTEX:
622 case WINED3D_SHADER_TYPE_GEOMETRY:
626 case WINED3D_SHADER_TYPE_PIXEL:
631 FIXME("Unknown shader type %#x.\n",
632 shader->reg_maps.shader_version.type);
637 /* TODO: Benchmark and see if it would be beneficial to store the
638 * locations of the constants to avoid looking up each time */
639 for (i = 0; constants_set; constants_set >>= 1, ++i)
641 if (!(constants_set & 1)) continue;
643 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
645 /* TODO: Benchmark and see if it would be beneficial to store the
646 * locations of the constants to avoid looking up each time */
647 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
648 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
651 /* We found this uniform name in the program - go ahead and send the data */
652 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
653 checkGLcall("glUniform1ivARB");
657 /* Load immediate constants */
658 ptr = list_head(&shader->constantsB);
661 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
662 unsigned int idx = lconst->idx;
663 const GLint *values = (const GLint *)lconst->value;
665 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
667 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
668 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
670 /* We found this uniform name in the program - go ahead and send the data */
671 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
672 checkGLcall("glUniform1ivARB");
674 ptr = list_next(&shader->constantsB, ptr);
678 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
680 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
684 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
686 /* GL locking is done by the caller (state handler) */
687 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
688 const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
690 struct shader_glsl_priv *glsl_priv = shader_priv;
691 const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
693 /* No GLSL program set - nothing to do. */
696 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
697 if (!use_ps(state)) return;
699 if (prog->ps_args.np2_fixup && prog->np2Fixup_location != -1)
702 UINT fixup = prog->ps_args.np2_fixup;
703 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
705 for (i = 0; fixup; fixup >>= 1, ++i)
707 const struct wined3d_texture *tex = state->textures[i];
708 const unsigned char idx = prog->np2Fixup_info->idx[i];
709 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
713 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
719 tex_dim[2] = tex->pow2_matrix[0];
720 tex_dim[3] = tex->pow2_matrix[5];
724 tex_dim[0] = tex->pow2_matrix[0];
725 tex_dim[1] = tex->pow2_matrix[5];
729 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
734 * Loads the app-supplied constants into the currently set GLSL program.
736 /* GL locking is done by the caller (state handler) */
737 static void shader_glsl_load_constants(const struct wined3d_context *context,
738 char usePixelShader, char useVertexShader)
740 const struct wined3d_gl_info *gl_info = context->gl_info;
741 struct wined3d_device *device = context->swapchain->device;
742 struct wined3d_stateblock *stateBlock = device->stateBlock;
743 struct shader_glsl_priv *priv = device->shader_priv;
744 float position_fixup[4];
746 GLhandleARB programId;
747 struct glsl_shader_prog_link *prog = priv->glsl_program;
748 UINT constant_version;
752 /* No GLSL program set - nothing to do. */
755 programId = prog->programId;
756 constant_version = prog->constant_version;
760 const struct wined3d_shader *vshader = stateBlock->state.vertex_shader;
762 /* Load DirectX 9 float constants/uniforms for vertex shader */
763 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->state.vs_consts_f,
764 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
766 /* Load DirectX 9 integer constants/uniforms for vertex shader */
767 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->state.vs_consts_i,
768 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
770 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
771 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->state.vs_consts_b,
772 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
774 /* Upload the position fixup params */
775 shader_get_position_fixup(context, &stateBlock->state, position_fixup);
776 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
777 checkGLcall("glUniform4fvARB");
782 const struct wined3d_shader *pshader = stateBlock->state.pixel_shader;
784 /* Load DirectX 9 float constants/uniforms for pixel shader */
785 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->state.ps_consts_f,
786 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
788 /* Load DirectX 9 integer constants/uniforms for pixel shader */
789 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->state.ps_consts_i,
790 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
792 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
793 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->state.ps_consts_b,
794 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
796 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
797 * It can't be 0 for a valid texbem instruction.
799 for(i = 0; i < MAX_TEXTURES; i++) {
802 if(prog->bumpenvmat_location[i] == -1) continue;
804 data = (const float *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVMAT00];
805 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
806 checkGLcall("glUniformMatrix2fvARB");
808 /* texbeml needs the luminance scale and offset too. If texbeml
809 * is used, needsbumpmat is set too, so we can check that in the
810 * needsbumpmat check. */
811 if (prog->luminancescale_location[i] != -1)
813 const GLfloat *scale = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLSCALE];
814 const GLfloat *offset = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLOFFSET];
816 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
817 checkGLcall("glUniform1fvARB");
818 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
819 checkGLcall("glUniform1fvARB");
823 if (pshader->u.ps.vpos_uniform)
825 float correction_params[4];
827 if (context->render_offscreen)
829 correction_params[0] = 0.0f;
830 correction_params[1] = 1.0f;
832 /* position is window relative, not viewport relative */
833 correction_params[0] = (float) context->current_rt->resource.height;
834 correction_params[1] = -1.0f;
836 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
840 if (priv->next_constant_version == UINT_MAX)
842 TRACE("Max constant version reached, resetting to 0.\n");
843 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
844 priv->next_constant_version = 1;
848 prog->constant_version = priv->next_constant_version++;
852 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
853 unsigned int heap_idx, DWORD new_version)
855 struct constant_entry *entries = heap->entries;
856 unsigned int *positions = heap->positions;
857 unsigned int parent_idx;
861 parent_idx = heap_idx >> 1;
863 if (new_version <= entries[parent_idx].version) break;
865 entries[heap_idx] = entries[parent_idx];
866 positions[entries[parent_idx].idx] = heap_idx;
867 heap_idx = parent_idx;
870 entries[heap_idx].version = new_version;
871 entries[heap_idx].idx = idx;
872 positions[idx] = heap_idx;
875 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
877 struct shader_glsl_priv *priv = device->shader_priv;
878 struct constant_heap *heap = &priv->vconst_heap;
881 for (i = start; i < count + start; ++i)
883 if (!device->stateBlock->changed.vertexShaderConstantsF[i])
884 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
886 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
890 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
892 struct shader_glsl_priv *priv = device->shader_priv;
893 struct constant_heap *heap = &priv->pconst_heap;
896 for (i = start; i < count + start; ++i)
898 if (!device->stateBlock->changed.pixelShaderConstantsF[i])
899 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
901 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
905 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
907 unsigned int ret = gl_info->limits.glsl_varyings / 4;
908 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
909 if(shader_major > 3) return ret;
911 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
912 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
916 /** Generate the variable & register declarations for the GLSL output target */
917 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
918 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
919 const struct wined3d_shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
921 const struct wined3d_state *state = &shader->device->stateBlock->state;
922 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
923 const struct wined3d_gl_info *gl_info = context->gl_info;
924 const struct wined3d_fb_state *fb = &shader->device->fb;
925 unsigned int i, extra_constants_needed = 0;
926 const local_constant *lconst;
929 /* There are some minor differences between pixel and vertex shaders */
930 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
931 char prefix = pshader ? 'P' : 'V';
933 /* Prototype the subroutines */
934 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
936 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
939 /* Declare the constants (aka uniforms) */
940 if (shader->limits.constant_float > 0)
942 unsigned max_constantsF;
943 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
944 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
945 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
946 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
947 * a dx9 card, as long as it doesn't also use all the other constants.
949 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
950 * declare only the amount that we're assured to have.
952 * Thus we run into problems in these two cases:
953 * 1) The shader really uses more uniforms than supported
954 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
958 /* No indirect addressing here. */
959 max_constantsF = gl_info->limits.glsl_ps_float_constants;
963 if (reg_maps->usesrelconstF)
965 /* Subtract the other potential uniforms from the max
966 * available (bools, ints, and 1 row of projection matrix).
967 * Subtract another uniform for immediate values, which have
968 * to be loaded via uniform by the driver as well. The shader
969 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
970 * shader code, so one vec4 should be enough. (Unfortunately
971 * the Nvidia driver doesn't store 128 and -128 in one float).
973 * Writing gl_ClipVertex requires one uniform for each
974 * clipplane as well. */
975 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
976 if(ctx_priv->cur_vs_args->clip_enabled)
978 max_constantsF -= gl_info->limits.clipplanes;
980 max_constantsF -= count_bits(reg_maps->integer_constants);
981 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
982 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
983 * for now take this into account when calculating the number of available constants
985 max_constantsF -= count_bits(reg_maps->boolean_constants);
986 /* Set by driver quirks in directx.c */
987 max_constantsF -= gl_info->reserved_glsl_constants;
991 max_constantsF = gl_info->limits.glsl_vs_float_constants;
994 max_constantsF = min(shader->limits.constant_float, max_constantsF);
995 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
998 /* Always declare the full set of constants, the compiler can remove the
999 * unused ones because d3d doesn't (yet) support indirect int and bool
1000 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
1001 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
1002 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, shader->limits.constant_int);
1004 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
1005 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, shader->limits.constant_bool);
1009 shader_addline(buffer, "uniform vec4 posFixup;\n");
1010 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1014 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1016 if (!(map & 1)) continue;
1018 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1020 if (reg_maps->luminanceparams & (1 << i))
1022 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1023 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1024 extra_constants_needed++;
1027 extra_constants_needed++;
1030 if (ps_args->srgb_correction)
1032 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1033 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1034 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1037 if (reg_maps->vpos || reg_maps->usesdsy)
1039 if (shader->limits.constant_float + extra_constants_needed
1040 + 1 < gl_info->limits.glsl_ps_float_constants)
1042 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1043 shader->u.ps.vpos_uniform = 1;
1044 extra_constants_needed++;
1048 /* This happens because we do not have proper tracking of the constant registers that are
1049 * actually used, only the max limit of the shader version
1051 FIXME("Cannot find a free uniform for vpos correction params\n");
1052 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1053 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1054 context->render_offscreen ? 1.0f : -1.0f);
1056 shader_addline(buffer, "vec4 vpos;\n");
1060 /* Declare texture samplers */
1061 for (i = 0; i < shader->limits.sampler; ++i)
1063 if (reg_maps->sampler_type[i])
1065 const struct wined3d_texture *texture;
1067 switch (reg_maps->sampler_type[i])
1070 if (pshader && ps_args->shadow & (1 << i))
1071 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1073 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1076 texture = state->textures[i];
1077 if (pshader && ps_args->shadow & (1 << i))
1079 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1080 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1082 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1086 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1087 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1089 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1092 case WINED3DSTT_CUBE:
1093 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1094 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1096 case WINED3DSTT_VOLUME:
1097 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1098 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1101 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1102 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1108 /* Declare uniforms for NP2 texcoord fixup:
1109 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1110 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1111 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1112 if (pshader && ps_args->np2_fixup) {
1114 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1117 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1118 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1119 * samplerNP2Fixup stores texture dimensions and is updated through
1120 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1122 for (i = 0; i < shader->limits.sampler; ++i)
1124 if (reg_maps->sampler_type[i])
1126 if (!(ps_args->np2_fixup & (1 << i))) continue;
1128 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1129 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1133 fixup->idx[i] = cur++;
1137 fixup->num_consts = (cur + 1) >> 1;
1138 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1141 /* Declare address variables */
1142 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1144 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1147 /* Declare texture coordinate temporaries and initialize them */
1148 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1150 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1153 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1154 * helper function shader that is linked in at link time
1156 if (pshader && reg_maps->shader_version.major >= 3)
1160 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1162 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1163 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1164 * pixel shader that reads the fixed function color into the packed input registers.
1166 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1170 /* Declare output register temporaries */
1171 if (shader->limits.packed_output)
1172 shader_addline(buffer, "vec4 OUT[%u];\n", shader->limits.packed_output);
1174 /* Declare temporary variables */
1175 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1177 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1180 /* Declare attributes */
1181 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1183 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1185 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1189 /* Declare loop registers aLx */
1190 for (i = 0; i < reg_maps->loop_depth; i++) {
1191 shader_addline(buffer, "int aL%u;\n", i);
1192 shader_addline(buffer, "int tmpInt%u;\n", i);
1195 /* Temporary variables for matrix operations */
1196 shader_addline(buffer, "vec4 tmp0;\n");
1197 shader_addline(buffer, "vec4 tmp1;\n");
1199 /* Local constants use a different name so they can be loaded once at shader link time
1200 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1201 * float -> string conversion can cause precision loss.
1203 if (!shader->load_local_constsF)
1205 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
1207 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1211 /* Start the main program */
1212 shader_addline(buffer, "void main() {\n");
1213 if(pshader && reg_maps->vpos) {
1214 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1215 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1216 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1217 * precision troubles when we just subtract 0.5.
1219 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1221 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1223 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1224 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1225 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1226 * correctly on drivers that returns integer values.
1228 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1232 /*****************************************************************************
1233 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1235 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1236 ****************************************************************************/
1239 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1240 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1242 /** Used for opcode modifiers - They multiply the result by the specified amount */
1243 static const char * const shift_glsl_tab[] = {
1245 "2.0 * ", /* 1 (x2) */
1246 "4.0 * ", /* 2 (x4) */
1247 "8.0 * ", /* 3 (x8) */
1248 "16.0 * ", /* 4 (x16) */
1249 "32.0 * ", /* 5 (x32) */
1256 "0.0625 * ", /* 12 (d16) */
1257 "0.125 * ", /* 13 (d8) */
1258 "0.25 * ", /* 14 (d4) */
1259 "0.5 * " /* 15 (d2) */
1262 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1263 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1267 switch (src_modifier)
1269 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1270 case WINED3DSPSM_DW:
1271 case WINED3DSPSM_NONE:
1272 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1274 case WINED3DSPSM_NEG:
1275 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1277 case WINED3DSPSM_NOT:
1278 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1280 case WINED3DSPSM_BIAS:
1281 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1283 case WINED3DSPSM_BIASNEG:
1284 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1286 case WINED3DSPSM_SIGN:
1287 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1289 case WINED3DSPSM_SIGNNEG:
1290 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1292 case WINED3DSPSM_COMP:
1293 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1295 case WINED3DSPSM_X2:
1296 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1298 case WINED3DSPSM_X2NEG:
1299 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1301 case WINED3DSPSM_ABS:
1302 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1304 case WINED3DSPSM_ABSNEG:
1305 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1308 FIXME("Unhandled modifier %u\n", src_modifier);
1309 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1313 /** Writes the GLSL variable name that corresponds to the register that the
1314 * DX opcode parameter is trying to access */
1315 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1316 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1318 /* oPos, oFog and oPts in D3D */
1319 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1321 const struct wined3d_shader *shader = ins->ctx->shader;
1322 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1323 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1324 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1330 case WINED3DSPR_TEMP:
1331 sprintf(register_name, "R%u", reg->idx);
1334 case WINED3DSPR_INPUT:
1335 /* vertex shaders */
1338 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1339 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1340 sprintf(register_name, "attrib%u", reg->idx);
1344 /* pixel shaders >= 3.0 */
1345 if (reg_maps->shader_version.major >= 3)
1347 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1348 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1352 glsl_src_param_t rel_param;
1354 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1356 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1357 * operation there */
1360 if (shader->u.ps.declared_in_count > in_count)
1362 sprintf(register_name,
1363 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1364 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1365 rel_param.param_str, idx);
1369 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1374 if (shader->u.ps.declared_in_count > in_count)
1376 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1377 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1378 rel_param.param_str);
1382 sprintf(register_name, "IN[%s]", rel_param.param_str);
1388 if (idx == in_count) sprintf(register_name, "gl_Color");
1389 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1390 else sprintf(register_name, "IN[%u]", idx);
1395 if (!reg->idx) strcpy(register_name, "gl_Color");
1396 else strcpy(register_name, "gl_SecondaryColor");
1401 case WINED3DSPR_CONST:
1403 const char prefix = pshader ? 'P' : 'V';
1405 /* Relative addressing */
1408 glsl_src_param_t rel_param;
1409 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1410 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1411 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1415 if (shader_constant_is_local(shader, reg->idx))
1416 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1418 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1423 case WINED3DSPR_CONSTINT:
1424 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1425 else sprintf(register_name, "VI[%u]", reg->idx);
1428 case WINED3DSPR_CONSTBOOL:
1429 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1430 else sprintf(register_name, "VB[%u]", reg->idx);
1433 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1434 if (pshader) sprintf(register_name, "T%u", reg->idx);
1435 else sprintf(register_name, "A%u", reg->idx);
1438 case WINED3DSPR_LOOP:
1439 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1442 case WINED3DSPR_SAMPLER:
1443 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1444 else sprintf(register_name, "Vsampler%u", reg->idx);
1447 case WINED3DSPR_COLOROUT:
1448 if (reg->idx >= gl_info->limits.buffers)
1449 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1451 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1454 case WINED3DSPR_RASTOUT:
1455 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1458 case WINED3DSPR_DEPTHOUT:
1459 sprintf(register_name, "gl_FragDepth");
1462 case WINED3DSPR_ATTROUT:
1463 if (!reg->idx) sprintf(register_name, "OUT[8]");
1464 else sprintf(register_name, "OUT[9]");
1467 case WINED3DSPR_TEXCRDOUT:
1468 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1469 sprintf(register_name, "OUT[%u]", reg->idx);
1472 case WINED3DSPR_MISCTYPE:
1476 sprintf(register_name, "vpos");
1478 else if (reg->idx == 1)
1480 /* Note that gl_FrontFacing is a bool, while vFace is
1481 * a float for which the sign determines front/back */
1482 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1486 FIXME("Unhandled misctype register %d\n", reg->idx);
1487 sprintf(register_name, "unrecognized_register");
1491 case WINED3DSPR_IMMCONST:
1492 switch (reg->immconst_type)
1494 case WINED3D_IMMCONST_SCALAR:
1495 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1498 case WINED3D_IMMCONST_VEC4:
1499 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1500 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1501 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1505 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1506 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1511 FIXME("Unhandled register name Type(%d)\n", reg->type);
1512 sprintf(register_name, "unrecognized_register");
1517 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1520 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1521 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1522 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1523 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1527 /* Get the GLSL write mask for the destination register */
1528 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1530 DWORD mask = param->write_mask;
1532 if (shader_is_scalar(¶m->reg))
1534 mask = WINED3DSP_WRITEMASK_0;
1539 shader_glsl_write_mask_to_str(mask, write_mask);
1545 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1546 unsigned int size = 0;
1548 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1549 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1550 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1551 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1556 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1558 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1559 * but addressed as "rgba". To fix this we need to swap the register's x
1560 * and z components. */
1561 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1564 /* swizzle bits fields: wwzzyyxx */
1565 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1566 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1567 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1568 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1572 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1573 BOOL fixup, DWORD mask, char *swizzle_str)
1575 if (shader_is_scalar(¶m->reg))
1576 *swizzle_str = '\0';
1578 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1581 /* From a given parameter token, generate the corresponding GLSL string.
1582 * Also, return the actual register name and swizzle in case the
1583 * caller needs this information as well. */
1584 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1585 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1587 BOOL is_color = FALSE;
1588 char swizzle_str[6];
1590 glsl_src->reg_name[0] = '\0';
1591 glsl_src->param_str[0] = '\0';
1592 swizzle_str[0] = '\0';
1594 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1595 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1596 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1599 /* From a given parameter token, generate the corresponding GLSL string.
1600 * Also, return the actual register name and swizzle in case the
1601 * caller needs this information as well. */
1602 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1603 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1605 BOOL is_color = FALSE;
1607 glsl_dst->mask_str[0] = '\0';
1608 glsl_dst->reg_name[0] = '\0';
1610 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1611 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1614 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1615 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1616 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1618 glsl_dst_param_t glsl_dst;
1621 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1622 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1627 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1628 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1630 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1633 /** Process GLSL instruction modifiers */
1634 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1636 glsl_dst_param_t dst_param;
1639 if (!ins->dst_count) return;
1641 modifiers = ins->dst[0].modifiers;
1642 if (!modifiers) return;
1644 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1646 if (modifiers & WINED3DSPDM_SATURATE)
1648 /* _SAT means to clamp the value of the register to between 0 and 1 */
1649 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1650 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1653 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1655 FIXME("_centroid modifier not handled\n");
1658 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1660 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1664 static inline const char *shader_get_comp_op(DWORD op)
1667 case COMPARISON_GT: return ">";
1668 case COMPARISON_EQ: return "==";
1669 case COMPARISON_GE: return ">=";
1670 case COMPARISON_LT: return "<";
1671 case COMPARISON_NE: return "!=";
1672 case COMPARISON_LE: return "<=";
1674 FIXME("Unrecognized comparison value: %u\n", op);
1679 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1680 DWORD sampler_idx, DWORD flags, glsl_sample_function_t *sample_function)
1682 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1683 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1684 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1685 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1686 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1687 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1688 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1689 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1691 /* Note that there's no such thing as a projected cube texture. */
1692 switch(sampler_type) {
1698 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1702 if (gl_info->supported[EXT_GPU_SHADER4])
1703 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1704 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1705 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1708 FIXME("Unsupported 1D shadow grad function.\n");
1709 sample_function->name = "unsupported1DGrad";
1714 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1716 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1722 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1726 if (gl_info->supported[EXT_GPU_SHADER4])
1727 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1728 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1729 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1732 FIXME("Unsupported 1D grad function.\n");
1733 sample_function->name = "unsupported1DGrad";
1738 sample_function->name = projected ? "texture1DProj" : "texture1D";
1740 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1751 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1755 if (gl_info->supported[EXT_GPU_SHADER4])
1756 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1757 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1758 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1761 FIXME("Unsupported RECT shadow grad function.\n");
1762 sample_function->name = "unsupported2DRectGrad";
1767 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1774 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1778 if (gl_info->supported[EXT_GPU_SHADER4])
1779 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1780 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1781 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1784 FIXME("Unsupported 2D shadow grad function.\n");
1785 sample_function->name = "unsupported2DGrad";
1790 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1793 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1801 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1805 if (gl_info->supported[EXT_GPU_SHADER4])
1806 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1807 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1808 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1811 FIXME("Unsupported RECT grad function.\n");
1812 sample_function->name = "unsupported2DRectGrad";
1817 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1824 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1828 if (gl_info->supported[EXT_GPU_SHADER4])
1829 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1830 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1831 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1834 FIXME("Unsupported 2D grad function.\n");
1835 sample_function->name = "unsupported2DGrad";
1840 sample_function->name = projected ? "texture2DProj" : "texture2D";
1843 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1847 case WINED3DSTT_CUBE:
1850 FIXME("Unsupported Cube shadow function.\n");
1851 sample_function->name = "unsupportedCubeShadow";
1852 sample_function->coord_mask = 0;
1858 sample_function->name = "textureCubeLod";
1862 if (gl_info->supported[EXT_GPU_SHADER4])
1863 sample_function->name = "textureCubeGrad";
1864 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1865 sample_function->name = "textureCubeGradARB";
1868 FIXME("Unsupported Cube grad function.\n");
1869 sample_function->name = "unsupportedCubeGrad";
1874 sample_function->name = "textureCube";
1876 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1880 case WINED3DSTT_VOLUME:
1883 FIXME("Unsupported 3D shadow function.\n");
1884 sample_function->name = "unsupported3DShadow";
1885 sample_function->coord_mask = 0;
1891 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1895 if (gl_info->supported[EXT_GPU_SHADER4])
1896 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1897 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1898 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1901 FIXME("Unsupported 3D grad function.\n");
1902 sample_function->name = "unsupported3DGrad";
1907 sample_function->name = projected ? "texture3DProj" : "texture3D";
1909 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1914 sample_function->name = "";
1915 sample_function->coord_mask = 0;
1916 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1921 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1922 BOOL sign_fixup, enum fixup_channel_source channel_source)
1924 switch(channel_source)
1926 case CHANNEL_SOURCE_ZERO:
1927 strcat(arguments, "0.0");
1930 case CHANNEL_SOURCE_ONE:
1931 strcat(arguments, "1.0");
1934 case CHANNEL_SOURCE_X:
1935 strcat(arguments, reg_name);
1936 strcat(arguments, ".x");
1939 case CHANNEL_SOURCE_Y:
1940 strcat(arguments, reg_name);
1941 strcat(arguments, ".y");
1944 case CHANNEL_SOURCE_Z:
1945 strcat(arguments, reg_name);
1946 strcat(arguments, ".z");
1949 case CHANNEL_SOURCE_W:
1950 strcat(arguments, reg_name);
1951 strcat(arguments, ".w");
1955 FIXME("Unhandled channel source %#x\n", channel_source);
1956 strcat(arguments, "undefined");
1960 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1963 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1965 struct wined3d_shader_dst_param dst;
1966 unsigned int mask_size, remaining;
1967 glsl_dst_param_t dst_param;
1968 char arguments[256];
1972 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1973 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1974 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1975 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1976 mask &= ins->dst[0].write_mask;
1978 if (!mask) return; /* Nothing to do */
1980 if (is_complex_fixup(fixup))
1982 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1983 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1987 mask_size = shader_glsl_get_write_mask_size(mask);
1990 dst.write_mask = mask;
1991 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1993 arguments[0] = '\0';
1994 remaining = mask_size;
1995 if (mask & WINED3DSP_WRITEMASK_0)
1997 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1998 if (--remaining) strcat(arguments, ", ");
2000 if (mask & WINED3DSP_WRITEMASK_1)
2002 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
2003 if (--remaining) strcat(arguments, ", ");
2005 if (mask & WINED3DSP_WRITEMASK_2)
2007 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
2008 if (--remaining) strcat(arguments, ", ");
2010 if (mask & WINED3DSP_WRITEMASK_3)
2012 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2013 if (--remaining) strcat(arguments, ", ");
2018 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2019 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2023 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2027 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2028 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
2029 const char *dx, const char *dy,
2030 const char *bias, const char *coord_reg_fmt, ...)
2032 const char *sampler_base;
2033 char dst_swizzle[6];
2034 struct color_fixup_desc fixup;
2035 BOOL np2_fixup = FALSE;
2038 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2040 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2042 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2043 fixup = priv->cur_ps_args->color_fixup[sampler];
2044 sampler_base = "Psampler";
2046 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2048 FIXME("Biased sampling from NP2 textures is unsupported\n");
2054 sampler_base = "Vsampler";
2055 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2058 shader_glsl_append_dst(ins->ctx->buffer, ins);
2060 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2062 va_start(args, coord_reg_fmt);
2063 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2067 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2070 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2071 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2073 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2074 (idx % 2) ? "zw" : "xy", dst_swizzle);
2075 } else if(dx && dy) {
2076 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2078 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2082 if(!is_identity_fixup(fixup)) {
2083 shader_glsl_color_correction(ins, fixup);
2087 /*****************************************************************************
2088 * Begin processing individual instruction opcodes
2089 ****************************************************************************/
2091 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2092 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2094 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2095 glsl_src_param_t src0_param;
2096 glsl_src_param_t src1_param;
2100 /* Determine the GLSL operator to use based on the opcode */
2101 switch (ins->handler_idx)
2103 case WINED3DSIH_MUL: op = '*'; break;
2104 case WINED3DSIH_ADD: op = '+'; break;
2105 case WINED3DSIH_SUB: op = '-'; break;
2108 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2112 write_mask = shader_glsl_append_dst(buffer, ins);
2113 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2114 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2115 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2118 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2119 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2121 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2122 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2123 glsl_src_param_t src0_param;
2126 write_mask = shader_glsl_append_dst(buffer, ins);
2127 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2129 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2130 * shader versions WINED3DSIO_MOVA is used for this. */
2131 if (ins->ctx->reg_maps->shader_version.major == 1
2132 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2133 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2135 /* This is a simple floor() */
2136 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2137 if (mask_size > 1) {
2138 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2140 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2143 else if(ins->handler_idx == WINED3DSIH_MOVA)
2145 /* We need to *round* to the nearest int here. */
2146 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2148 if (gl_info->supported[EXT_GPU_SHADER4])
2151 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2153 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2158 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2159 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2161 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2162 src0_param.param_str, src0_param.param_str);
2167 shader_addline(buffer, "%s);\n", src0_param.param_str);
2171 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2172 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2174 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2175 glsl_src_param_t src0_param;
2176 glsl_src_param_t src1_param;
2177 DWORD dst_write_mask, src_write_mask;
2178 unsigned int dst_size = 0;
2180 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2181 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2183 /* dp3 works on vec3, dp4 on vec4 */
2184 if (ins->handler_idx == WINED3DSIH_DP4)
2186 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2188 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2191 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2192 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2195 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2197 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2201 /* Note that this instruction has some restrictions. The destination write mask
2202 * can't contain the w component, and the source swizzles have to be .xyzw */
2203 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2205 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2206 glsl_src_param_t src0_param;
2207 glsl_src_param_t src1_param;
2210 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2211 shader_glsl_append_dst(ins->ctx->buffer, ins);
2212 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2213 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2214 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2217 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2218 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2219 * GLSL uses the value as-is. */
2220 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2222 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2223 glsl_src_param_t src0_param;
2224 glsl_src_param_t src1_param;
2225 DWORD dst_write_mask;
2226 unsigned int dst_size;
2228 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2229 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2231 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2232 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2236 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2237 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2241 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2242 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2246 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2247 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2248 * GLSL uses the value as-is. */
2249 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2251 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2252 glsl_src_param_t src0_param;
2253 DWORD dst_write_mask;
2254 unsigned int dst_size;
2256 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2257 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2259 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2263 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2264 dst_size, src0_param.param_str);
2268 shader_addline(buffer, "log2(abs(%s)));\n",
2269 src0_param.param_str);
2273 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2274 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2276 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2277 glsl_src_param_t src_param;
2278 const char *instruction;
2282 /* Determine the GLSL function to use based on the opcode */
2283 /* TODO: Possibly make this a table for faster lookups */
2284 switch (ins->handler_idx)
2286 case WINED3DSIH_MIN: instruction = "min"; break;
2287 case WINED3DSIH_MAX: instruction = "max"; break;
2288 case WINED3DSIH_ABS: instruction = "abs"; break;
2289 case WINED3DSIH_FRC: instruction = "fract"; break;
2290 case WINED3DSIH_EXP: instruction = "exp2"; break;
2291 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2292 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2293 default: instruction = "";
2294 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2298 write_mask = shader_glsl_append_dst(buffer, ins);
2300 shader_addline(buffer, "%s(", instruction);
2304 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2305 shader_addline(buffer, "%s", src_param.param_str);
2306 for (i = 1; i < ins->src_count; ++i)
2308 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2309 shader_addline(buffer, ", %s", src_param.param_str);
2313 shader_addline(buffer, "));\n");
2316 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2318 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2319 glsl_src_param_t src_param;
2320 unsigned int mask_size;
2324 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2325 mask_size = shader_glsl_get_write_mask_size(write_mask);
2326 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2328 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2329 src_param.param_str, src_param.param_str);
2330 shader_glsl_append_dst(buffer, ins);
2334 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2335 mask_size, src_param.param_str);
2339 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2340 src_param.param_str);
2344 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2345 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2346 * dst.x = 2^(floor(src))
2347 * dst.y = src - floor(src)
2348 * dst.z = 2^src (partial precision is allowed, but optional)
2350 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2351 * dst = 2^src; (partial precision is allowed, but optional)
2353 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2355 glsl_src_param_t src_param;
2357 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2359 if (ins->ctx->reg_maps->shader_version.major < 2)
2363 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2364 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2365 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2366 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2368 shader_glsl_append_dst(ins->ctx->buffer, ins);
2369 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2370 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2373 unsigned int mask_size;
2375 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2376 mask_size = shader_glsl_get_write_mask_size(write_mask);
2378 if (mask_size > 1) {
2379 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2381 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2386 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2387 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2389 glsl_src_param_t src_param;
2391 unsigned int mask_size;
2393 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2394 mask_size = shader_glsl_get_write_mask_size(write_mask);
2395 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2399 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2400 mask_size, src_param.param_str);
2404 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2405 src_param.param_str);
2409 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2411 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2412 glsl_src_param_t src_param;
2414 unsigned int mask_size;
2416 write_mask = shader_glsl_append_dst(buffer, ins);
2417 mask_size = shader_glsl_get_write_mask_size(write_mask);
2419 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2423 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2424 mask_size, src_param.param_str);
2428 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2429 src_param.param_str);
2433 /** Process signed comparison opcodes in GLSL. */
2434 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2436 glsl_src_param_t src0_param;
2437 glsl_src_param_t src1_param;
2439 unsigned int mask_size;
2441 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2442 mask_size = shader_glsl_get_write_mask_size(write_mask);
2443 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2444 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2446 if (mask_size > 1) {
2447 const char *compare;
2449 switch(ins->handler_idx)
2451 case WINED3DSIH_SLT: compare = "lessThan"; break;
2452 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2453 default: compare = "";
2454 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2457 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2458 src0_param.param_str, src1_param.param_str);
2460 switch(ins->handler_idx)
2462 case WINED3DSIH_SLT:
2463 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2464 * to return 0.0 but step returns 1.0 because step is not < x
2465 * An alternative is a bvec compare padded with an unused second component.
2466 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2467 * issue. Playing with not() is not possible either because not() does not accept
2470 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2471 src0_param.param_str, src1_param.param_str);
2473 case WINED3DSIH_SGE:
2474 /* Here we can use the step() function and safe a conditional */
2475 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2478 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2484 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2485 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2487 glsl_src_param_t src0_param;
2488 glsl_src_param_t src1_param;
2489 glsl_src_param_t src2_param;
2490 DWORD write_mask, cmp_channel = 0;
2493 BOOL temp_destination = FALSE;
2495 if (shader_is_scalar(&ins->src[0].reg))
2497 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2499 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2500 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2501 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2503 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2504 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2506 DWORD dst_mask = ins->dst[0].write_mask;
2507 struct wined3d_shader_dst_param dst = ins->dst[0];
2509 /* Cycle through all source0 channels */
2510 for (i=0; i<4; i++) {
2512 /* Find the destination channels which use the current source0 channel */
2513 for (j=0; j<4; j++) {
2514 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2516 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2517 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2520 dst.write_mask = dst_mask & write_mask;
2522 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2523 * The first lines may overwrite source parameters of the following lines.
2524 * Deal with that by using a temporary destination register if needed
2526 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2527 && ins->src[0].reg.type == ins->dst[0].reg.type)
2528 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2529 && ins->src[1].reg.type == ins->dst[0].reg.type)
2530 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2531 && ins->src[2].reg.type == ins->dst[0].reg.type))
2533 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2534 if (!write_mask) continue;
2535 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2536 temp_destination = TRUE;
2538 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2539 if (!write_mask) continue;
2542 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2543 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2544 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2546 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2547 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2550 if(temp_destination) {
2551 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2552 shader_glsl_append_dst(ins->ctx->buffer, ins);
2553 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2559 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2560 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2561 * the compare is done per component of src0. */
2562 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2564 struct wined3d_shader_dst_param dst;
2565 glsl_src_param_t src0_param;
2566 glsl_src_param_t src1_param;
2567 glsl_src_param_t src2_param;
2568 DWORD write_mask, cmp_channel = 0;
2571 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2572 ins->ctx->reg_maps->shader_version.minor);
2574 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2576 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2577 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2578 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2579 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2581 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2584 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2586 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2587 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2591 /* Cycle through all source0 channels */
2592 dst_mask = ins->dst[0].write_mask;
2594 for (i=0; i<4; i++) {
2596 /* Find the destination channels which use the current source0 channel */
2597 for (j=0; j<4; j++) {
2598 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2600 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2601 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2605 dst.write_mask = dst_mask & write_mask;
2606 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2607 if (!write_mask) continue;
2609 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2610 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2611 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2613 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2614 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2618 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2619 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2621 glsl_src_param_t src0_param;
2622 glsl_src_param_t src1_param;
2623 glsl_src_param_t src2_param;
2626 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2627 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2628 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2629 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2630 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2631 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2634 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2635 Vertex shaders to GLSL codes */
2636 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2639 int nComponents = 0;
2640 struct wined3d_shader_dst_param tmp_dst = {{0}};
2641 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2642 struct wined3d_shader_instruction tmp_ins;
2644 memset(&tmp_ins, 0, sizeof(tmp_ins));
2646 /* Set constants for the temporary argument */
2647 tmp_ins.ctx = ins->ctx;
2648 tmp_ins.dst_count = 1;
2649 tmp_ins.dst = &tmp_dst;
2650 tmp_ins.src_count = 2;
2651 tmp_ins.src = tmp_src;
2653 switch(ins->handler_idx)
2655 case WINED3DSIH_M4x4:
2657 tmp_ins.handler_idx = WINED3DSIH_DP4;
2659 case WINED3DSIH_M4x3:
2661 tmp_ins.handler_idx = WINED3DSIH_DP4;
2663 case WINED3DSIH_M3x4:
2665 tmp_ins.handler_idx = WINED3DSIH_DP3;
2667 case WINED3DSIH_M3x3:
2669 tmp_ins.handler_idx = WINED3DSIH_DP3;
2671 case WINED3DSIH_M3x2:
2673 tmp_ins.handler_idx = WINED3DSIH_DP3;
2679 tmp_dst = ins->dst[0];
2680 tmp_src[0] = ins->src[0];
2681 tmp_src[1] = ins->src[1];
2682 for (i = 0; i < nComponents; ++i)
2684 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2685 shader_glsl_dot(&tmp_ins);
2686 ++tmp_src[1].reg.idx;
2691 The LRP instruction performs a component-wise linear interpolation
2692 between the second and third operands using the first operand as the
2693 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2694 This is equivalent to mix(src2, src1, src0);
2696 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2698 glsl_src_param_t src0_param;
2699 glsl_src_param_t src1_param;
2700 glsl_src_param_t src2_param;
2703 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2705 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2706 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2707 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2709 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2710 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2713 /** Process the WINED3DSIO_LIT instruction in GLSL:
2714 * dst.x = dst.w = 1.0
2715 * dst.y = (src0.x > 0) ? src0.x
2716 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2717 * where src.w is clamped at +- 128
2719 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2721 glsl_src_param_t src0_param;
2722 glsl_src_param_t src1_param;
2723 glsl_src_param_t src3_param;
2726 shader_glsl_append_dst(ins->ctx->buffer, ins);
2727 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2729 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2730 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2731 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2733 /* The sdk specifies the instruction like this
2735 * if(src.x > 0.0) dst.y = src.x
2737 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2741 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2742 * dst.x = 1.0 ... No further explanation needed
2743 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2744 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2745 * dst.w = 1.0. ... Nothing fancy.
2747 * So we still have one conditional in there. So do this:
2748 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2750 * 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),
2751 * 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.
2752 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2754 shader_addline(ins->ctx->buffer,
2755 "vec4(1.0, max(%s, 0.0), pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2756 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2759 /** Process the WINED3DSIO_DST instruction in GLSL:
2761 * dst.y = src0.x * src0.y
2765 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2767 glsl_src_param_t src0y_param;
2768 glsl_src_param_t src0z_param;
2769 glsl_src_param_t src1y_param;
2770 glsl_src_param_t src1w_param;
2773 shader_glsl_append_dst(ins->ctx->buffer, ins);
2774 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2776 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2777 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2778 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2779 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2781 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2782 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2785 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2786 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2787 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2789 * dst.x = cos(src0.?)
2790 * dst.y = sin(src0.?)
2794 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2796 glsl_src_param_t src0_param;
2799 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2800 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2802 switch (write_mask) {
2803 case WINED3DSP_WRITEMASK_0:
2804 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2807 case WINED3DSP_WRITEMASK_1:
2808 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2811 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2812 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2816 ERR("Write mask should be .x, .y or .xy\n");
2821 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2822 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2823 * generate invalid code
2825 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2827 glsl_src_param_t src0_param;
2830 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2831 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2833 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2836 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2837 * Start a for() loop where src1.y is the initial value of aL,
2838 * increment aL by src1.z for a total of src1.x iterations.
2839 * Need to use a temporary variable for this operation.
2841 /* FIXME: I don't think nested loops will work correctly this way. */
2842 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2844 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2845 const struct wined3d_shader *shader = ins->ctx->shader;
2846 glsl_src_param_t src1_param;
2847 const DWORD *control_values = NULL;
2848 const local_constant *constant;
2850 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2852 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2853 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2854 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2857 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2859 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, local_constant, entry)
2861 if (constant->idx == ins->src[1].reg.idx)
2863 control_values = constant->value;
2871 struct wined3d_shader_loop_control loop_control;
2872 loop_control.count = control_values[0];
2873 loop_control.start = control_values[1];
2874 loop_control.step = (int)control_values[2];
2876 if (loop_control.step > 0)
2878 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2879 loop_state->current_depth, loop_control.start,
2880 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2881 loop_state->current_depth, loop_control.step);
2883 else if (loop_control.step < 0)
2885 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2886 loop_state->current_depth, loop_control.start,
2887 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2888 loop_state->current_depth, loop_control.step);
2892 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2893 loop_state->current_depth, loop_control.start, loop_state->current_depth,
2894 loop_state->current_depth, loop_control.count,
2895 loop_state->current_depth);
2898 shader_addline(ins->ctx->buffer,
2899 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2900 loop_state->current_depth, loop_state->current_reg,
2901 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
2902 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
2905 ++loop_state->current_depth;
2906 ++loop_state->current_reg;
2909 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2911 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2913 shader_addline(ins->ctx->buffer, "}\n");
2915 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2917 --loop_state->current_depth;
2918 --loop_state->current_reg;
2921 if (ins->handler_idx == WINED3DSIH_ENDREP)
2923 --loop_state->current_depth;
2927 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2929 const struct wined3d_shader *shader = ins->ctx->shader;
2930 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2931 glsl_src_param_t src0_param;
2932 const DWORD *control_values = NULL;
2933 const local_constant *constant;
2935 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2936 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2938 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, local_constant, entry)
2940 if (constant->idx == ins->src[0].reg.idx)
2942 control_values = constant->value;
2950 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2951 loop_state->current_depth, loop_state->current_depth,
2952 control_values[0], loop_state->current_depth);
2956 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2957 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2958 loop_state->current_depth, loop_state->current_depth,
2959 src0_param.param_str, loop_state->current_depth);
2962 ++loop_state->current_depth;
2965 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2967 glsl_src_param_t src0_param;
2969 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2970 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2973 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2975 glsl_src_param_t src0_param;
2976 glsl_src_param_t src1_param;
2978 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2979 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2981 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2982 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2985 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2987 shader_addline(ins->ctx->buffer, "} else {\n");
2990 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2992 shader_addline(ins->ctx->buffer, "break;\n");
2995 /* FIXME: According to MSDN the compare is done per component. */
2996 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2998 glsl_src_param_t src0_param;
2999 glsl_src_param_t src1_param;
3001 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3002 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3004 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3005 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
3008 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3010 shader_addline(ins->ctx->buffer, "}\n");
3011 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3014 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3016 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3019 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3021 glsl_src_param_t src1_param;
3023 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3024 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3027 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3029 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3030 * function only suppresses the unhandled instruction warning
3034 /*********************************************
3035 * Pixel Shader Specific Code begins here
3036 ********************************************/
3037 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3039 const struct wined3d_shader *shader = ins->ctx->shader;
3040 struct wined3d_device *device = shader->device;
3041 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3042 ins->ctx->reg_maps->shader_version.minor);
3043 glsl_sample_function_t sample_function;
3044 const struct wined3d_texture *texture;
3045 DWORD sample_flags = 0;
3047 DWORD mask = 0, swizzle;
3049 /* 1.0-1.4: Use destination register as sampler source.
3050 * 2.0+: Use provided sampler source. */
3051 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3052 else sampler_idx = ins->src[1].reg.idx;
3053 texture = device->stateBlock->state.textures[sampler_idx];
3055 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3057 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3058 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3059 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3060 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3062 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3063 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3064 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3065 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3066 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3067 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3068 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3069 case WINED3DTTFF_COUNT4:
3070 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3074 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3076 DWORD src_mod = ins->src[0].modifiers;
3078 if (src_mod == WINED3DSPSM_DZ) {
3079 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3080 mask = WINED3DSP_WRITEMASK_2;
3081 } else if (src_mod == WINED3DSPSM_DW) {
3082 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3083 mask = WINED3DSP_WRITEMASK_3;
3086 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3088 /* ps 2.0 texldp instruction always divides by the fourth component. */
3089 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3090 mask = WINED3DSP_WRITEMASK_3;
3094 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3095 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3097 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3098 mask |= sample_function.coord_mask;
3100 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3101 else swizzle = ins->src[1].swizzle;
3103 /* 1.0-1.3: Use destination register as coordinate source.
3104 1.4+: Use provided coordinate source register. */
3105 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3108 shader_glsl_write_mask_to_str(mask, coord_mask);
3109 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3110 "T%u%s", sampler_idx, coord_mask);
3112 glsl_src_param_t coord_param;
3113 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3114 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3116 glsl_src_param_t bias;
3117 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3118 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3119 "%s", coord_param.param_str);
3121 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3122 "%s", coord_param.param_str);
3127 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3129 const struct wined3d_shader *shader = ins->ctx->shader;
3130 struct wined3d_device *device = shader->device;
3131 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3132 glsl_sample_function_t sample_function;
3133 glsl_src_param_t coord_param, dx_param, dy_param;
3134 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3136 DWORD swizzle = ins->src[1].swizzle;
3137 const struct wined3d_texture *texture;
3139 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3141 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3142 shader_glsl_tex(ins);
3146 sampler_idx = ins->src[1].reg.idx;
3147 texture = device->stateBlock->state.textures[sampler_idx];
3148 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3149 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3151 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3152 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3153 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3154 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3156 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3157 "%s", coord_param.param_str);
3160 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3162 const struct wined3d_shader *shader = ins->ctx->shader;
3163 struct wined3d_device *device = shader->device;
3164 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3165 glsl_sample_function_t sample_function;
3166 glsl_src_param_t coord_param, lod_param;
3167 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3169 DWORD swizzle = ins->src[1].swizzle;
3170 const struct wined3d_texture *texture;
3172 sampler_idx = ins->src[1].reg.idx;
3173 texture = device->stateBlock->state.textures[sampler_idx];
3174 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3175 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3177 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3178 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3180 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3182 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3183 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3185 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3186 * However, the NVIDIA drivers allow them in fragment shaders as well,
3187 * even without the appropriate extension. */
3188 WARN("Using %s in fragment shader.\n", sample_function.name);
3190 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3191 "%s", coord_param.param_str);
3194 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3196 /* FIXME: Make this work for more than just 2D textures */
3197 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3198 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3200 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3204 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3205 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3206 ins->dst[0].reg.idx, dst_mask);
3208 DWORD reg = ins->src[0].reg.idx;
3209 DWORD src_mod = ins->src[0].modifiers;
3210 char dst_swizzle[6];
3212 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3214 if (src_mod == WINED3DSPSM_DZ) {
3215 glsl_src_param_t div_param;
3216 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3217 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3219 if (mask_size > 1) {
3220 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3222 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3224 } else if (src_mod == WINED3DSPSM_DW) {
3225 glsl_src_param_t div_param;
3226 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3227 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3229 if (mask_size > 1) {
3230 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3232 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3235 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3240 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3241 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3242 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3243 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3245 glsl_src_param_t src0_param;
3246 glsl_sample_function_t sample_function;
3247 DWORD sampler_idx = ins->dst[0].reg.idx;
3248 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3251 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3253 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3254 * scalar, and projected sampling would require 4.
3256 * It is a dependent read - not valid with conditional NP2 textures
3258 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3259 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3264 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3265 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3269 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3270 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3274 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3275 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3279 FIXME("Unexpected mask size %u\n", mask_size);
3284 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3285 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3286 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3288 glsl_src_param_t src0_param;
3289 DWORD dstreg = ins->dst[0].reg.idx;
3290 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3292 unsigned int mask_size;
3294 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3295 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3296 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3298 if (mask_size > 1) {
3299 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3301 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3305 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3306 * Calculate the depth as dst.x / dst.y */
3307 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3309 glsl_dst_param_t dst_param;
3311 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3313 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3314 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3315 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3316 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3319 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3320 dst_param.reg_name, dst_param.reg_name);
3323 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3324 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3325 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3326 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3328 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3330 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3331 DWORD dstreg = ins->dst[0].reg.idx;
3332 glsl_src_param_t src0_param;
3334 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3336 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3337 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3340 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3341 * Calculate the 1st of a 2-row matrix multiplication. */
3342 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3344 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3345 DWORD reg = ins->dst[0].reg.idx;
3346 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3347 glsl_src_param_t src0_param;
3349 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3350 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3353 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3354 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3355 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3357 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3358 DWORD reg = ins->dst[0].reg.idx;
3359 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3360 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3361 glsl_src_param_t src0_param;
3363 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3364 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3365 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3368 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3370 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3371 DWORD reg = ins->dst[0].reg.idx;
3372 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3373 glsl_src_param_t src0_param;
3374 glsl_sample_function_t sample_function;
3376 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3377 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3379 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3381 /* Sample the texture using the calculated coordinates */
3382 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3385 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3386 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3387 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3389 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3390 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3391 glsl_src_param_t src0_param;
3392 DWORD reg = ins->dst[0].reg.idx;
3393 glsl_sample_function_t sample_function;
3395 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3396 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3398 /* Dependent read, not valid with conditional NP2 */
3399 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3401 /* Sample the texture using the calculated coordinates */
3402 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3404 tex_mx->current_row = 0;
3407 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3408 * Perform the 3rd row of a 3x3 matrix multiply */
3409 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3411 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3412 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3413 glsl_src_param_t src0_param;
3415 DWORD reg = ins->dst[0].reg.idx;
3417 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3419 shader_glsl_append_dst(ins->ctx->buffer, ins);
3420 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3421 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3423 tex_mx->current_row = 0;
3426 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3427 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3428 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3430 DWORD reg = ins->dst[0].reg.idx;
3431 glsl_src_param_t src0_param;
3432 glsl_src_param_t src1_param;
3433 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3434 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3435 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3436 glsl_sample_function_t sample_function;
3438 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3439 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3441 /* Perform the last matrix multiply operation */
3442 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3443 /* Reflection calculation */
3444 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3446 /* Dependent read, not valid with conditional NP2 */
3447 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3449 /* Sample the texture */
3450 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3452 tex_mx->current_row = 0;
3455 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3456 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3457 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3459 DWORD reg = ins->dst[0].reg.idx;
3460 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3461 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3462 glsl_src_param_t src0_param;
3463 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3464 glsl_sample_function_t sample_function;
3466 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3468 /* Perform the last matrix multiply operation */
3469 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3471 /* Construct the eye-ray vector from w coordinates */
3472 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3473 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3474 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3476 /* Dependent read, not valid with conditional NP2 */
3477 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3479 /* Sample the texture using the calculated coordinates */
3480 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3482 tex_mx->current_row = 0;
3485 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3486 * Apply a fake bump map transform.
3487 * texbem is pshader <= 1.3 only, this saves a few version checks
3489 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3491 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3492 glsl_sample_function_t sample_function;
3493 glsl_src_param_t coord_param;
3499 sampler_idx = ins->dst[0].reg.idx;
3500 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3501 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3503 /* Dependent read, not valid with conditional NP2 */
3504 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3505 mask = sample_function.coord_mask;
3507 shader_glsl_write_mask_to_str(mask, coord_mask);
3509 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3510 * so we can't let the GL handle this.
3512 if (flags & WINED3D_PSARGS_PROJECTED) {
3514 char coord_div_mask[3];
3515 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3516 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3517 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3518 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3519 case WINED3DTTFF_COUNT4:
3520 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3522 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3523 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3526 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3528 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3529 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3530 coord_param.param_str, coord_mask);
3532 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3534 glsl_src_param_t luminance_param;
3535 glsl_dst_param_t dst_param;
3537 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3538 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3540 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3541 dst_param.reg_name, dst_param.mask_str,
3542 luminance_param.param_str, sampler_idx, sampler_idx);
3546 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3548 glsl_src_param_t src0_param, src1_param;
3549 DWORD sampler_idx = ins->dst[0].reg.idx;
3551 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3552 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3554 shader_glsl_append_dst(ins->ctx->buffer, ins);
3555 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3556 src0_param.param_str, sampler_idx, src1_param.param_str);
3559 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3560 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3561 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3563 glsl_src_param_t src0_param;
3564 DWORD sampler_idx = ins->dst[0].reg.idx;
3565 glsl_sample_function_t sample_function;
3567 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3569 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3570 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3571 "%s.wx", src0_param.reg_name);
3574 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3575 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3576 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3578 glsl_src_param_t src0_param;
3579 DWORD sampler_idx = ins->dst[0].reg.idx;
3580 glsl_sample_function_t sample_function;
3582 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3584 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3585 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3586 "%s.yz", src0_param.reg_name);
3589 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3590 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3591 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3593 glsl_src_param_t src0_param;
3594 DWORD sampler_idx = ins->dst[0].reg.idx;
3595 glsl_sample_function_t sample_function;
3597 /* Dependent read, not valid with conditional NP2 */
3598 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3599 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3601 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3602 "%s", src0_param.param_str);
3605 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3606 * If any of the first 3 components are < 0, discard this pixel */
3607 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3609 glsl_dst_param_t dst_param;
3611 /* The argument is a destination parameter, and no writemasks are allowed */
3612 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3613 if (ins->ctx->reg_maps->shader_version.major >= 2)
3615 /* 2.0 shaders compare all 4 components in texkill */
3616 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3618 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3619 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3620 * 4 components are defined, only the first 3 are used
3622 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3626 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3627 * dst = dot2(src0, src1) + src2 */
3628 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3630 glsl_src_param_t src0_param;
3631 glsl_src_param_t src1_param;
3632 glsl_src_param_t src2_param;
3634 unsigned int mask_size;
3636 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3637 mask_size = shader_glsl_get_write_mask_size(write_mask);
3639 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3640 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3641 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3643 if (mask_size > 1) {
3644 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3645 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3647 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3648 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3652 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3653 const struct wined3d_shader_signature_element *input_signature,
3654 const struct wined3d_shader_reg_maps *reg_maps,
3655 enum vertexprocessing_mode vertexprocessing)
3657 WORD map = reg_maps->input_registers;
3660 for (i = 0; map; map >>= 1, ++i)
3662 const char *semantic_name;
3667 if (!(map & 1)) continue;
3669 semantic_name = input_signature[i].semantic_name;
3670 semantic_idx = input_signature[i].semantic_idx;
3671 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3673 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3675 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3676 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3677 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3679 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3680 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3682 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3685 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3686 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3687 else if (semantic_idx == 1)
3688 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3689 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3691 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3692 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3696 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3697 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3702 /*********************************************
3703 * Vertex Shader Specific Code begins here
3704 ********************************************/
3706 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3708 struct glsl_program_key key;
3710 key.vshader = entry->vshader;
3711 key.pshader = entry->pshader;
3712 key.vs_args = entry->vs_args;
3713 key.ps_args = entry->ps_args;
3715 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3717 ERR("Failed to insert program entry.\n");
3721 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3722 const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3723 struct vs_compile_args *vs_args, struct ps_compile_args *ps_args)
3725 struct wine_rb_entry *entry;
3726 struct glsl_program_key key;
3728 key.vshader = vshader;
3729 key.pshader = pshader;
3730 key.vs_args = *vs_args;
3731 key.ps_args = *ps_args;
3733 entry = wine_rb_get(&priv->program_lookup, &key);
3734 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3737 /* GL locking is done by the caller */
3738 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3739 struct glsl_shader_prog_link *entry)
3741 struct glsl_program_key key;
3743 key.vshader = entry->vshader;
3744 key.pshader = entry->pshader;
3745 key.vs_args = entry->vs_args;
3746 key.ps_args = entry->ps_args;
3747 wine_rb_remove(&priv->program_lookup, &key);
3749 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3750 if (entry->vshader) list_remove(&entry->vshader_entry);
3751 if (entry->pshader) list_remove(&entry->pshader_entry);
3752 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3753 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3754 HeapFree(GetProcessHeap(), 0, entry);
3757 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
3758 const struct wined3d_gl_info *gl_info, const DWORD *map,
3759 const struct wined3d_shader_signature_element *input_signature,
3760 const struct wined3d_shader_reg_maps *reg_maps_in,
3761 const struct wined3d_shader_signature_element *output_signature,
3762 const struct wined3d_shader_reg_maps *reg_maps_out)
3765 const char *semantic_name_in;
3766 UINT semantic_idx_in;
3769 unsigned int in_count = vec4_varyings(3, gl_info);
3771 char destination[50];
3772 WORD input_map, output_map;
3774 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3776 input_map = reg_maps_in->input_registers;
3777 for (i = 0; input_map; input_map >>= 1, ++i)
3779 if (!(input_map & 1)) continue;
3782 /* Declared, but not read register */
3783 if (in_idx == ~0U) continue;
3784 if (in_idx >= (in_count + 2))
3786 FIXME("More input varyings declared than supported, expect issues.\n");
3790 if (in_idx == in_count) {
3791 sprintf(destination, "gl_FrontColor");
3792 } else if (in_idx == in_count + 1) {
3793 sprintf(destination, "gl_FrontSecondaryColor");
3795 sprintf(destination, "IN[%u]", in_idx);
3798 semantic_name_in = input_signature[i].semantic_name;
3799 semantic_idx_in = input_signature[i].semantic_idx;
3802 output_map = reg_maps_out->output_registers;
3803 for (j = 0; output_map; output_map >>= 1, ++j)
3807 if (!(output_map & 1)
3808 || semantic_idx_in != output_signature[j].semantic_idx
3809 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3810 || !(mask = input_signature[i].mask & output_signature[j].mask))
3814 shader_glsl_write_mask_to_str(mask, reg_mask);
3816 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3817 destination, reg_mask, j, reg_mask);
3821 for (i = 0; i < in_count + 2; ++i)
3825 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3828 if (set[i] == ~0U) set[i] = 0;
3831 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3832 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3833 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3834 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3835 reg_mask[size] = '\0';
3837 if (i == in_count) sprintf(destination, "gl_FrontColor");
3838 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3839 else sprintf(destination, "IN[%u]", i);
3841 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3842 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3845 HeapFree(GetProcessHeap(), 0, set);
3848 /* GL locking is done by the caller */
3849 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3850 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
3851 const struct wined3d_gl_info *gl_info)
3853 GLhandleARB ret = 0;
3854 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
3856 const char *semantic_name;
3859 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
3860 WORD map = vs->reg_maps.output_registers;
3862 shader_buffer_clear(buffer);
3864 shader_addline(buffer, "#version 120\n");
3868 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3870 for (i = 0; map; map >>= 1, ++i)
3874 if (!(map & 1)) continue;
3876 semantic_name = output_signature[i].semantic_name;
3877 semantic_idx = output_signature[i].semantic_idx;
3878 write_mask = output_signature[i].mask;
3879 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3881 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3884 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n",
3885 reg_mask, i, reg_mask);
3886 else if (semantic_idx == 1)
3887 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n",
3888 reg_mask, i, reg_mask);
3890 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3892 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3893 reg_mask, i, reg_mask);
3895 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3897 if (semantic_idx < 8)
3899 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3900 write_mask |= WINED3DSP_WRITEMASK_3;
3902 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3903 semantic_idx, reg_mask, i, reg_mask);
3904 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3905 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3908 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3910 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3912 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3914 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3917 shader_addline(buffer, "}\n");
3922 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3923 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3924 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3926 /* First, sort out position and point size. Those are not passed to the pixel shader */
3927 for (i = 0; map; map >>= 1, ++i)
3929 if (!(map & 1)) continue;
3931 semantic_name = output_signature[i].semantic_name;
3932 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3934 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3936 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3937 reg_mask, i, reg_mask);
3939 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3941 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3945 /* Then, fix the pixel shader input */
3946 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
3947 &ps->reg_maps, output_signature, &vs->reg_maps);
3949 shader_addline(buffer, "}\n");
3952 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3953 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3954 shader_glsl_compile(gl_info, ret, buffer->buffer);
3959 /* GL locking is done by the caller */
3960 static void hardcode_local_constants(const struct wined3d_shader *shader,
3961 const struct wined3d_gl_info *gl_info, GLhandleARB programId, char prefix)
3963 const local_constant *lconst;
3968 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
3970 value = (const float *)lconst->value;
3971 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3972 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3973 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3975 checkGLcall("Hardcoding local constants");
3978 /* GL locking is done by the caller */
3979 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3980 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
3981 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3983 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
3984 const struct wined3d_gl_info *gl_info = context->gl_info;
3985 const DWORD *function = shader->function;
3986 struct shader_glsl_ctx_priv priv_ctx;
3988 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3989 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3991 memset(&priv_ctx, 0, sizeof(priv_ctx));
3992 priv_ctx.cur_ps_args = args;
3993 priv_ctx.cur_np2fixup_info = np2fixup_info;
3995 shader_addline(buffer, "#version 120\n");
3997 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
3999 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4001 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4003 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4004 * drivers write a warning if we don't do so
4006 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4008 if (gl_info->supported[EXT_GPU_SHADER4])
4010 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4013 /* Base Declarations */
4014 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4016 /* Pack 3.0 inputs */
4017 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4018 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4020 /* Base Shader Body */
4021 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4023 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4024 if (reg_maps->shader_version.major < 2)
4026 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4027 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4030 if (args->srgb_correction)
4032 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4033 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4034 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4035 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4036 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4037 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4039 /* Pixel shader < 3.0 do not replace the fog stage.
4040 * This implements linear fog computation and blending.
4041 * TODO: non linear fog
4042 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4043 * -1/(e-s) and e/(e-s) respectively.
4045 if (reg_maps->shader_version.major < 3)
4048 case FOG_OFF: break;
4050 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4051 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4052 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4053 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4056 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4057 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4058 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4059 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4062 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4063 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4064 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4065 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4070 shader_addline(buffer, "}\n");
4072 TRACE("Compiling shader object %u\n", shader_obj);
4073 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4075 /* Store the shader object */
4079 /* GL locking is done by the caller */
4080 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4081 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4082 const struct vs_compile_args *args)
4084 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4085 const struct wined3d_gl_info *gl_info = context->gl_info;
4086 const DWORD *function = shader->function;
4087 struct shader_glsl_ctx_priv priv_ctx;
4089 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4090 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4092 shader_addline(buffer, "#version 120\n");
4094 if (gl_info->supported[EXT_GPU_SHADER4])
4095 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4097 memset(&priv_ctx, 0, sizeof(priv_ctx));
4098 priv_ctx.cur_vs_args = args;
4100 /* Base Declarations */
4101 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4103 /* Base Shader Body */
4104 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4106 /* Unpack outputs */
4107 shader_addline(buffer, "order_ps_input(OUT);\n");
4109 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4110 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4111 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4112 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4114 if (args->fog_src == VS_FOG_Z)
4115 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4116 else if (!reg_maps->fog)
4117 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4119 /* We always store the clipplanes without y inversion */
4120 if (args->clip_enabled)
4121 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4123 /* Write the final position.
4125 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4126 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4127 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4128 * contains 1.0 to allow a mad.
4130 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4131 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4133 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4135 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4136 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4137 * which is the same as z = z * 2 - w.
4139 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4141 shader_addline(buffer, "}\n");
4143 TRACE("Compiling shader object %u\n", shader_obj);
4144 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4149 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4150 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4151 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4153 struct wined3d_state *state = &shader->device->stateBlock->state;
4156 struct glsl_ps_compiled_shader *new_array;
4157 struct glsl_pshader_private *shader_data;
4158 struct ps_np2fixup_info *np2fixup = NULL;
4161 if (!shader->backend_data)
4163 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4164 if (!shader->backend_data)
4166 ERR("Failed to allocate backend data.\n");
4170 shader_data = shader->backend_data;
4172 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4173 * so a linear search is more performant than a hashmap or a binary search
4174 * (cache coherency etc)
4176 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4178 if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4180 if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4181 return shader_data->gl_shaders[i].prgId;
4185 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4186 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4187 if (shader_data->num_gl_shaders)
4189 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4190 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4191 new_size * sizeof(*shader_data->gl_shaders));
4193 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4198 ERR("Out of memory\n");
4201 shader_data->gl_shaders = new_array;
4202 shader_data->shader_array_size = new_size;
4205 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4207 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4208 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4210 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4212 shader_buffer_clear(buffer);
4213 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4214 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4215 *np2fixup_info = np2fixup;
4220 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4221 const DWORD use_map) {
4222 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4223 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4224 return stored->fog_src == new->fog_src;
4227 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4228 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4229 const struct vs_compile_args *args)
4233 struct glsl_vs_compiled_shader *new_array;
4234 DWORD use_map = shader->device->strided_streams.use_map;
4235 struct glsl_vshader_private *shader_data;
4238 if (!shader->backend_data)
4240 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4241 if (!shader->backend_data)
4243 ERR("Failed to allocate backend data.\n");
4247 shader_data = shader->backend_data;
4249 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4250 * so a linear search is more performant than a hashmap or a binary search
4251 * (cache coherency etc)
4253 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4254 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4255 return shader_data->gl_shaders[i].prgId;
4259 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4261 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4262 if (shader_data->num_gl_shaders)
4264 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4265 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4266 new_size * sizeof(*shader_data->gl_shaders));
4268 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4273 ERR("Out of memory\n");
4276 shader_data->gl_shaders = new_array;
4277 shader_data->shader_array_size = new_size;
4280 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4282 shader_buffer_clear(buffer);
4283 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4284 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4289 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4290 * It sets the programId on the current StateBlock (because it should be called
4291 * inside of the DrawPrimitive() part of the render loop).
4293 * If a program for the given combination does not exist, create one, and store
4294 * the program in the hash table. If it creates a program, it will link the
4295 * given objects, too.
4298 /* GL locking is done by the caller */
4299 static void set_glsl_shader_program(const struct wined3d_context *context,
4300 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4302 const struct wined3d_state *state = &device->stateBlock->state;
4303 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4304 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4305 const struct wined3d_gl_info *gl_info = context->gl_info;
4306 struct shader_glsl_priv *priv = device->shader_priv;
4307 struct glsl_shader_prog_link *entry = NULL;
4308 GLhandleARB programId = 0;
4309 GLhandleARB reorder_shader_id = 0;
4312 struct ps_compile_args ps_compile_args;
4313 struct vs_compile_args vs_compile_args;
4315 if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4316 if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4318 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4321 priv->glsl_program = entry;
4325 /* If we get to this point, then no matching program exists, so we create one */
4326 programId = GL_EXTCALL(glCreateProgramObjectARB());
4327 TRACE("Created new GLSL shader program %u\n", programId);
4329 /* Create the entry */
4330 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4331 entry->programId = programId;
4332 entry->vshader = vshader;
4333 entry->pshader = pshader;
4334 entry->vs_args = vs_compile_args;
4335 entry->ps_args = ps_compile_args;
4336 entry->constant_version = 0;
4337 entry->np2Fixup_info = NULL;
4338 /* Add the hash table entry */
4339 add_glsl_program_entry(priv, entry);
4341 /* Set the current program */
4342 priv->glsl_program = entry;
4344 /* Attach GLSL vshader */
4347 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4348 WORD map = vshader->reg_maps.input_registers;
4351 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4352 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4353 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4354 checkGLcall("glAttachObjectARB");
4355 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4358 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4360 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4361 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4362 checkGLcall("glAttachObjectARB");
4364 /* Bind vertex attributes to a corresponding index number to match
4365 * the same index numbers as ARB_vertex_programs (makes loading
4366 * vertex attributes simpler). With this method, we can use the
4367 * exact same code to load the attributes later for both ARB and
4370 * We have to do this here because we need to know the Program ID
4371 * in order to make the bindings work, and it has to be done prior
4372 * to linking the GLSL program. */
4373 for (i = 0; map; map >>= 1, ++i)
4375 if (!(map & 1)) continue;
4377 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4378 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4380 checkGLcall("glBindAttribLocationARB");
4382 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4385 /* Attach GLSL pshader */
4388 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4389 pshader, &ps_compile_args, &entry->np2Fixup_info);
4390 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4391 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4392 checkGLcall("glAttachObjectARB");
4394 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4397 /* Link the program */
4398 TRACE("Linking GLSL shader program %u\n", programId);
4399 GL_EXTCALL(glLinkProgramARB(programId));
4400 shader_glsl_validate_link(gl_info, programId);
4402 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4403 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4404 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4406 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4407 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4409 for (i = 0; i < MAX_CONST_I; ++i)
4411 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4412 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4414 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4415 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4416 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4418 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4419 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4421 for (i = 0; i < MAX_CONST_I; ++i)
4423 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4424 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4430 for(i = 0; i < MAX_TEXTURES; i++) {
4431 sprintf(name, "bumpenvmat%u", i);
4432 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4433 sprintf(name, "luminancescale%u", i);
4434 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4435 sprintf(name, "luminanceoffset%u", i);
4436 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4439 if (ps_compile_args.np2_fixup) {
4440 if (entry->np2Fixup_info) {
4441 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4443 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4448 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4449 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4450 checkGLcall("Find glsl program uniform locations");
4452 if (pshader && pshader->reg_maps.shader_version.major >= 3
4453 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4455 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4456 entry->vertex_color_clamp = GL_FALSE;
4458 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4461 /* Set the shader to allow uniform loading on it */
4462 GL_EXTCALL(glUseProgramObjectARB(programId));
4463 checkGLcall("glUseProgramObjectARB(programId)");
4465 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4466 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4467 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4468 * vertex shader with fixed function pixel processing is used we make sure that the card
4469 * supports enough samplers to allow the max number of vertex samplers with all possible
4470 * fixed function fragment processing setups. So once the program is linked these samplers
4473 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4474 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4476 /* If the local constants do not have to be loaded with the environment constants,
4477 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4480 if (pshader && !pshader->load_local_constsF)
4481 hardcode_local_constants(pshader, gl_info, programId, 'P');
4482 if (vshader && !vshader->load_local_constsF)
4483 hardcode_local_constants(vshader, gl_info, programId, 'V');
4486 /* GL locking is done by the caller */
4487 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4489 GLhandleARB program_id;
4490 GLhandleARB vshader_id, pshader_id;
4491 const char *blt_pshader;
4493 static const char *blt_vshader =
4497 " gl_Position = gl_Vertex;\n"
4498 " gl_FrontColor = vec4(1.0);\n"
4499 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4502 static const char * const blt_pshaders_full[tex_type_count] =
4508 "uniform sampler2D sampler;\n"
4511 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4517 "uniform samplerCube sampler;\n"
4520 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4524 "#extension GL_ARB_texture_rectangle : enable\n"
4525 "uniform sampler2DRect sampler;\n"
4528 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4532 static const char * const blt_pshaders_masked[tex_type_count] =
4538 "uniform sampler2D sampler;\n"
4539 "uniform vec4 mask;\n"
4542 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4543 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4549 "uniform samplerCube sampler;\n"
4550 "uniform vec4 mask;\n"
4553 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4554 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4558 "#extension GL_ARB_texture_rectangle : enable\n"
4559 "uniform sampler2DRect sampler;\n"
4560 "uniform vec4 mask;\n"
4563 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4564 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4568 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4571 FIXME("tex_type %#x not supported\n", tex_type);
4575 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4576 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4578 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4579 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4581 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4582 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4583 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4584 GL_EXTCALL(glLinkProgramARB(program_id));
4586 shader_glsl_validate_link(gl_info, program_id);
4588 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4591 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4592 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4596 /* GL locking is done by the caller */
4597 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4599 const struct wined3d_gl_info *gl_info = context->gl_info;
4600 struct wined3d_device *device = context->swapchain->device;
4601 struct shader_glsl_priv *priv = device->shader_priv;
4602 GLhandleARB program_id = 0;
4603 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4605 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4607 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4608 else priv->glsl_program = NULL;
4610 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4612 if (old_vertex_color_clamp != current_vertex_color_clamp)
4614 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4616 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4617 checkGLcall("glClampColorARB");
4621 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4625 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4626 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4627 GL_EXTCALL(glUseProgramObjectARB(program_id));
4628 checkGLcall("glUseProgramObjectARB");
4630 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4631 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4632 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4633 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4635 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4639 /* GL locking is done by the caller */
4640 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4641 enum tex_types tex_type, const SIZE *ds_mask_size)
4643 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4644 struct shader_glsl_priv *priv = shader_priv;
4645 GLhandleARB *blt_program;
4648 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4651 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4652 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4653 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4654 GL_EXTCALL(glUniform1iARB(loc, 0));
4658 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4663 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4664 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4668 /* GL locking is done by the caller */
4669 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4671 struct shader_glsl_priv *priv = shader_priv;
4672 GLhandleARB program_id;
4674 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4675 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4677 GL_EXTCALL(glUseProgramObjectARB(program_id));
4678 checkGLcall("glUseProgramObjectARB");
4681 static void shader_glsl_destroy(struct wined3d_shader *shader)
4683 struct wined3d_device *device = shader->device;
4684 struct shader_glsl_priv *priv = device->shader_priv;
4685 const struct wined3d_gl_info *gl_info;
4686 const struct list *linked_programs;
4687 struct wined3d_context *context;
4689 char pshader = shader_is_pshader_version(shader->reg_maps.shader_version.type);
4693 struct glsl_pshader_private *shader_data = shader->backend_data;
4695 if (!shader_data || !shader_data->num_gl_shaders)
4697 HeapFree(GetProcessHeap(), 0, shader_data);
4698 shader->backend_data = NULL;
4702 context = context_acquire(device, NULL);
4703 gl_info = context->gl_info;
4705 if (priv->glsl_program && priv->glsl_program->pshader == shader)
4708 shader_glsl_select(context, FALSE, FALSE);
4714 struct glsl_vshader_private *shader_data = shader->backend_data;
4716 if (!shader_data || !shader_data->num_gl_shaders)
4718 HeapFree(GetProcessHeap(), 0, shader_data);
4719 shader->backend_data = NULL;
4723 context = context_acquire(device, NULL);
4724 gl_info = context->gl_info;
4726 if (priv->glsl_program && priv->glsl_program->vshader == shader)
4729 shader_glsl_select(context, FALSE, FALSE);
4734 linked_programs = &shader->linked_programs;
4736 TRACE("Deleting linked programs\n");
4737 if (linked_programs->next) {
4738 struct glsl_shader_prog_link *entry, *entry2;
4742 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4743 delete_glsl_program_entry(priv, gl_info, entry);
4746 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4747 delete_glsl_program_entry(priv, gl_info, entry);
4755 struct glsl_pshader_private *shader_data = shader->backend_data;
4759 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4760 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4761 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4762 checkGLcall("glDeleteObjectARB");
4765 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4769 struct glsl_vshader_private *shader_data = shader->backend_data;
4773 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4774 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4775 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4776 checkGLcall("glDeleteObjectARB");
4779 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4782 HeapFree(GetProcessHeap(), 0, shader->backend_data);
4783 shader->backend_data = NULL;
4785 context_release(context);
4788 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4790 const struct glsl_program_key *k = key;
4791 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4792 const struct glsl_shader_prog_link, program_lookup_entry);
4795 if (k->vshader > prog->vshader) return 1;
4796 else if (k->vshader < prog->vshader) return -1;
4798 if (k->pshader > prog->pshader) return 1;
4799 else if (k->pshader < prog->pshader) return -1;
4801 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4802 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4807 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4809 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4810 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4814 ERR("Failed to allocate memory\n");
4818 heap->entries = mem;
4819 heap->entries[1].version = 0;
4820 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4826 static void constant_heap_free(struct constant_heap *heap)
4828 HeapFree(GetProcessHeap(), 0, heap->entries);
4831 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4836 glsl_program_key_compare,
4839 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
4841 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4842 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4843 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4844 gl_info->limits.glsl_ps_float_constants)) + 1;
4846 if (!shader_buffer_init(&priv->shader_buffer))
4848 ERR("Failed to initialize shader buffer.\n");
4852 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4855 ERR("Failed to allocate memory.\n");
4859 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4861 ERR("Failed to initialize vertex shader constant heap\n");
4865 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4867 ERR("Failed to initialize pixel shader constant heap\n");
4871 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4873 ERR("Failed to initialize rbtree.\n");
4877 priv->next_constant_version = 1;
4879 device->shader_priv = priv;
4883 constant_heap_free(&priv->pconst_heap);
4884 constant_heap_free(&priv->vconst_heap);
4885 HeapFree(GetProcessHeap(), 0, priv->stack);
4886 shader_buffer_free(&priv->shader_buffer);
4887 HeapFree(GetProcessHeap(), 0, priv);
4888 return E_OUTOFMEMORY;
4891 /* Context activation is done by the caller. */
4892 static void shader_glsl_free(struct wined3d_device *device)
4894 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4895 struct shader_glsl_priv *priv = device->shader_priv;
4899 for (i = 0; i < tex_type_count; ++i)
4901 if (priv->depth_blt_program_full[i])
4903 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4905 if (priv->depth_blt_program_masked[i])
4907 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4912 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4913 constant_heap_free(&priv->pconst_heap);
4914 constant_heap_free(&priv->vconst_heap);
4915 HeapFree(GetProcessHeap(), 0, priv->stack);
4916 shader_buffer_free(&priv->shader_buffer);
4918 HeapFree(GetProcessHeap(), 0, device->shader_priv);
4919 device->shader_priv = NULL;
4922 static BOOL shader_glsl_dirty_const(void)
4924 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4928 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
4930 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
4931 * texldd and texldl instructions. */
4932 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
4934 caps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4935 caps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4939 caps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4940 caps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4943 caps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4944 caps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4946 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4947 * Direct3D minimum requirement.
4949 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4950 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4952 * The problem is that the refrast clamps temporary results in the shader to
4953 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4954 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4955 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4956 * offer a way to query this.
4958 caps->PixelShader1xMaxValue = 8.0;
4960 caps->VSClipping = TRUE;
4962 TRACE_(d3d_caps)("Hardware vertex shader version %u.%u enabled (GLSL).\n",
4963 (caps->VertexShaderVersion >> 8) & 0xff, caps->VertexShaderVersion & 0xff);
4964 TRACE_(d3d_caps)("Hardware pixel shader version %u.%u enabled (GLSL).\n",
4965 (caps->PixelShaderVersion >> 8) & 0xff, caps->PixelShaderVersion & 0xff);
4968 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4970 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4972 TRACE("Checking support for fixup:\n");
4973 dump_color_fixup_desc(fixup);
4976 /* We support everything except YUV conversions. */
4977 if (!is_complex_fixup(fixup))
4983 TRACE("[FAILED]\n");
4987 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4989 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4990 /* WINED3DSIH_ADD */ shader_glsl_arith,
4991 /* WINED3DSIH_AND */ NULL,
4992 /* WINED3DSIH_BEM */ shader_glsl_bem,
4993 /* WINED3DSIH_BREAK */ shader_glsl_break,
4994 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4995 /* WINED3DSIH_BREAKP */ NULL,
4996 /* WINED3DSIH_CALL */ shader_glsl_call,
4997 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4998 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4999 /* WINED3DSIH_CND */ shader_glsl_cnd,
5000 /* WINED3DSIH_CRS */ shader_glsl_cross,
5001 /* WINED3DSIH_CUT */ NULL,
5002 /* WINED3DSIH_DCL */ NULL,
5003 /* WINED3DSIH_DEF */ NULL,
5004 /* WINED3DSIH_DEFB */ NULL,
5005 /* WINED3DSIH_DEFI */ NULL,
5006 /* WINED3DSIH_DIV */ NULL,
5007 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5008 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5009 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5010 /* WINED3DSIH_DST */ shader_glsl_dst,
5011 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5012 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5013 /* WINED3DSIH_ELSE */ shader_glsl_else,
5014 /* WINED3DSIH_EMIT */ NULL,
5015 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5016 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5017 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5018 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5019 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5020 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5021 /* WINED3DSIH_FTOI */ NULL,
5022 /* WINED3DSIH_IADD */ NULL,
5023 /* WINED3DSIH_IEQ */ NULL,
5024 /* WINED3DSIH_IF */ shader_glsl_if,
5025 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5026 /* WINED3DSIH_IGE */ NULL,
5027 /* WINED3DSIH_IMUL */ NULL,
5028 /* WINED3DSIH_ITOF */ NULL,
5029 /* WINED3DSIH_LABEL */ shader_glsl_label,
5030 /* WINED3DSIH_LD */ NULL,
5031 /* WINED3DSIH_LIT */ shader_glsl_lit,
5032 /* WINED3DSIH_LOG */ shader_glsl_log,
5033 /* WINED3DSIH_LOGP */ shader_glsl_log,
5034 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5035 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5036 /* WINED3DSIH_LT */ NULL,
5037 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5038 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5039 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5040 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5041 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5042 /* WINED3DSIH_MAD */ shader_glsl_mad,
5043 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5044 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5045 /* WINED3DSIH_MOV */ shader_glsl_mov,
5046 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5047 /* WINED3DSIH_MOVC */ NULL,
5048 /* WINED3DSIH_MUL */ shader_glsl_arith,
5049 /* WINED3DSIH_NOP */ NULL,
5050 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5051 /* WINED3DSIH_PHASE */ NULL,
5052 /* WINED3DSIH_POW */ shader_glsl_pow,
5053 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5054 /* WINED3DSIH_REP */ shader_glsl_rep,
5055 /* WINED3DSIH_RET */ shader_glsl_ret,
5056 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5057 /* WINED3DSIH_SAMPLE */ NULL,
5058 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5059 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5060 /* WINED3DSIH_SETP */ NULL,
5061 /* WINED3DSIH_SGE */ shader_glsl_compare,
5062 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5063 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5064 /* WINED3DSIH_SLT */ shader_glsl_compare,
5065 /* WINED3DSIH_SQRT */ NULL,
5066 /* WINED3DSIH_SUB */ shader_glsl_arith,
5067 /* WINED3DSIH_TEX */ shader_glsl_tex,
5068 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5069 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5070 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5071 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5072 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5073 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5074 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5075 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5076 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5077 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5078 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5079 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5080 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5081 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5082 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5083 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5084 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5085 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5086 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5087 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5088 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5089 /* WINED3DSIH_UTOF */ NULL,
5092 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5093 SHADER_HANDLER hw_fct;
5095 /* Select handler */
5096 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5098 /* Unhandled opcode */
5101 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5106 shader_glsl_add_instruction_modifiers(ins);
5109 const struct wined3d_shader_backend_ops glsl_shader_backend =
5111 shader_glsl_handle_instruction,
5113 shader_glsl_select_depth_blt,
5114 shader_glsl_deselect_depth_blt,
5115 shader_glsl_update_float_vertex_constants,
5116 shader_glsl_update_float_pixel_constants,
5117 shader_glsl_load_constants,
5118 shader_glsl_load_np2fixup_constants,
5119 shader_glsl_destroy,
5122 shader_glsl_dirty_const,
5123 shader_glsl_get_caps,
5124 shader_glsl_color_fixup_supported,