wined3d: Fix context_apply_clear_state with ORM = backbuffer.
[wine.git] / dlls / wined3d / glsl_shader.c
blob86355fa15afae06c042f2a5b7f6151646c533149
1 /*
2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * D3D shader asm has swizzles on source parameters, and write masks for
26 * destination parameters. GLSL uses swizzles for both. The result of this is
27 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29 * mask for the destination parameter into account.
32 #include "config.h"
33 #include <limits.h>
34 #include <stdio.h>
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
47 typedef struct {
48 char reg_name[150];
49 char mask_str[6];
50 } glsl_dst_param_t;
52 typedef struct {
53 char reg_name[150];
54 char param_str[200];
55 } glsl_src_param_t;
57 typedef struct {
58 const char *name;
59 DWORD coord_mask;
60 } glsl_sample_function_t;
62 enum heap_node_op
64 HEAP_NODE_TRAVERSE_LEFT,
65 HEAP_NODE_TRAVERSE_RIGHT,
66 HEAP_NODE_POP,
69 struct constant_entry
71 unsigned int idx;
72 unsigned int version;
75 struct constant_heap
77 struct constant_entry *entries;
78 unsigned int *positions;
79 unsigned int size;
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;
89 unsigned char *stack;
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 IWineD3DVertexShader *vshader;
113 IWineD3DPixelShader *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 typedef struct {
121 IWineD3DVertexShader *vshader;
122 IWineD3DPixelShader *pshader;
123 struct ps_compile_args ps_args;
124 struct vs_compile_args vs_args;
125 } glsl_program_key_t;
127 struct shader_glsl_ctx_priv {
128 const struct vs_compile_args *cur_vs_args;
129 const struct ps_compile_args *cur_ps_args;
130 struct ps_np2fixup_info *cur_np2fixup_info;
133 struct glsl_ps_compiled_shader
135 struct ps_compile_args args;
136 struct ps_np2fixup_info np2fixup;
137 GLhandleARB prgId;
140 struct glsl_pshader_private
142 struct glsl_ps_compiled_shader *gl_shaders;
143 UINT num_gl_shaders, shader_array_size;
146 struct glsl_vs_compiled_shader
148 struct vs_compile_args args;
149 GLhandleARB prgId;
152 struct glsl_vshader_private
154 struct glsl_vs_compiled_shader *gl_shaders;
155 UINT num_gl_shaders, shader_array_size;
158 static const char *debug_gl_shader_type(GLenum type)
160 switch (type)
162 #define WINED3D_TO_STR(u) case u: return #u
163 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
164 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
165 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
166 #undef WINED3D_TO_STR
167 default:
168 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
172 /* Extract a line from the info log.
173 * Note that this modifies the source string. */
174 static char *get_info_log_line(char **ptr)
176 char *p, *q;
178 p = *ptr;
179 if (!(q = strstr(p, "\n")))
181 if (!*p) return NULL;
182 *ptr += strlen(p);
183 return p;
185 *q = '\0';
186 *ptr = q + 1;
188 return p;
191 /** Prints the GLSL info log which will contain error messages if they exist */
192 /* GL locking is done by the caller */
193 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
195 int infologLength = 0;
196 char *infoLog;
197 unsigned int i;
198 BOOL is_spam;
200 static const char * const spam[] =
202 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
203 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
204 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
205 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
206 "Fragment shader(s) linked, vertex shader(s) linked. \n", /* fglrx, with \n */
207 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
208 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \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.", /* fglrx, no \n */
211 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \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.", /* fglrx, no \n */
216 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
218 GL_EXTCALL(glGetObjectParameterivARB(obj,
219 GL_OBJECT_INFO_LOG_LENGTH_ARB,
220 &infologLength));
222 /* A size of 1 is just a null-terminated string, so the log should be bigger than
223 * that if there are errors. */
224 if (infologLength > 1)
226 char *ptr, *line;
228 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
229 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
231 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
232 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
233 is_spam = FALSE;
235 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
236 if(strcmp(infoLog, spam[i]) == 0) {
237 is_spam = TRUE;
238 break;
242 ptr = infoLog;
243 if (is_spam)
245 TRACE("Spam received from GLSL shader #%u:\n", obj);
246 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
248 else
250 FIXME("Error received from GLSL shader #%u:\n", obj);
251 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
253 HeapFree(GetProcessHeap(), 0, infoLog);
257 /* GL locking is done by the caller. */
258 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
260 GLint i, object_count, source_size = -1;
261 GLhandleARB *objects;
262 char *source = NULL;
264 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
265 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
266 if (!objects)
268 ERR("Failed to allocate object array memory.\n");
269 return;
272 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
273 for (i = 0; i < object_count; ++i)
275 char *ptr, *line;
276 GLint tmp;
278 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
280 if (source_size < tmp)
282 HeapFree(GetProcessHeap(), 0, source);
284 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
285 if (!source)
287 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
288 HeapFree(GetProcessHeap(), 0, objects);
289 return;
291 source_size = tmp;
294 FIXME("Object %u:\n", objects[i]);
295 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
296 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
297 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
298 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
299 FIXME("\n");
301 ptr = source;
302 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
303 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
304 FIXME("\n");
307 HeapFree(GetProcessHeap(), 0, source);
308 HeapFree(GetProcessHeap(), 0, objects);
311 /* GL locking is done by the caller. */
312 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
314 GLint tmp;
316 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
318 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
319 if (tmp == GL_PROGRAM_OBJECT_ARB)
321 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
322 if (!tmp)
324 FIXME("Program %u link status invalid.\n", program);
325 shader_glsl_dump_program_source(gl_info, program);
329 print_glsl_info_log(gl_info, program);
333 * Loads (pixel shader) samplers
335 /* GL locking is done by the caller */
336 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
337 DWORD *tex_unit_map, GLhandleARB programId)
339 GLint name_loc;
340 int i;
341 char sampler_name[20];
343 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
344 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
345 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
346 if (name_loc != -1) {
347 DWORD mapped_unit = tex_unit_map[i];
348 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
350 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
351 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
352 checkGLcall("glUniform1iARB");
353 } else {
354 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
360 /* GL locking is done by the caller */
361 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
362 DWORD *tex_unit_map, GLhandleARB programId)
364 GLint name_loc;
365 char sampler_name[20];
366 int i;
368 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
369 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
370 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
371 if (name_loc != -1) {
372 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
373 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
375 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
376 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
377 checkGLcall("glUniform1iARB");
378 } else {
379 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
385 /* GL locking is done by the caller */
386 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
387 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
389 int stack_idx = 0;
390 unsigned int heap_idx = 1;
391 unsigned int idx;
393 if (heap->entries[heap_idx].version <= version) return;
395 idx = heap->entries[heap_idx].idx;
396 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
397 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
399 while (stack_idx >= 0)
401 /* Note that we fall through to the next case statement. */
402 switch(stack[stack_idx])
404 case HEAP_NODE_TRAVERSE_LEFT:
406 unsigned int left_idx = heap_idx << 1;
407 if (left_idx < heap->size && heap->entries[left_idx].version > version)
409 heap_idx = left_idx;
410 idx = heap->entries[heap_idx].idx;
411 if (constant_locations[idx] != -1)
412 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
414 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
415 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
416 break;
420 case HEAP_NODE_TRAVERSE_RIGHT:
422 unsigned int right_idx = (heap_idx << 1) + 1;
423 if (right_idx < heap->size && heap->entries[right_idx].version > version)
425 heap_idx = right_idx;
426 idx = heap->entries[heap_idx].idx;
427 if (constant_locations[idx] != -1)
428 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
430 stack[stack_idx++] = HEAP_NODE_POP;
431 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
432 break;
436 case HEAP_NODE_POP:
438 heap_idx >>= 1;
439 --stack_idx;
440 break;
444 checkGLcall("walk_constant_heap()");
447 /* GL locking is done by the caller */
448 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
450 GLfloat clamped_constant[4];
452 if (location == -1) return;
454 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
455 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
456 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
457 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
459 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
462 /* GL locking is done by the caller */
463 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
464 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
466 int stack_idx = 0;
467 unsigned int heap_idx = 1;
468 unsigned int idx;
470 if (heap->entries[heap_idx].version <= version) return;
472 idx = heap->entries[heap_idx].idx;
473 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
474 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
476 while (stack_idx >= 0)
478 /* Note that we fall through to the next case statement. */
479 switch(stack[stack_idx])
481 case HEAP_NODE_TRAVERSE_LEFT:
483 unsigned int left_idx = heap_idx << 1;
484 if (left_idx < heap->size && heap->entries[left_idx].version > version)
486 heap_idx = left_idx;
487 idx = heap->entries[heap_idx].idx;
488 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
490 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
491 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
492 break;
496 case HEAP_NODE_TRAVERSE_RIGHT:
498 unsigned int right_idx = (heap_idx << 1) + 1;
499 if (right_idx < heap->size && heap->entries[right_idx].version > version)
501 heap_idx = right_idx;
502 idx = heap->entries[heap_idx].idx;
503 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
505 stack[stack_idx++] = HEAP_NODE_POP;
506 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
507 break;
511 case HEAP_NODE_POP:
513 heap_idx >>= 1;
514 --stack_idx;
515 break;
519 checkGLcall("walk_constant_heap_clamped()");
522 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
523 /* GL locking is done by the caller */
524 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
525 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
526 unsigned char *stack, UINT version)
528 const local_constant *lconst;
530 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
531 if (This->baseShader.reg_maps.shader_version.major == 1
532 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
533 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
534 else
535 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
537 if (!This->baseShader.load_local_constsF)
539 TRACE("No need to load local float constants for this shader\n");
540 return;
543 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
544 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
546 GLint location = constant_locations[lconst->idx];
547 /* We found this uniform name in the program - go ahead and send the data */
548 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
550 checkGLcall("glUniform4fvARB()");
553 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
554 /* GL locking is done by the caller */
555 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
556 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
558 unsigned int i;
559 struct list* ptr;
561 for (i = 0; constants_set; constants_set >>= 1, ++i)
563 if (!(constants_set & 1)) continue;
565 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
566 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
568 /* We found this uniform name in the program - go ahead and send the data */
569 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
570 checkGLcall("glUniform4ivARB");
573 /* Load immediate constants */
574 ptr = list_head(&This->baseShader.constantsI);
575 while (ptr) {
576 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
577 unsigned int idx = lconst->idx;
578 const GLint *values = (const GLint *)lconst->value;
580 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
581 values[0], values[1], values[2], values[3]);
583 /* We found this uniform name in the program - go ahead and send the data */
584 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
585 checkGLcall("glUniform4ivARB");
586 ptr = list_next(&This->baseShader.constantsI, ptr);
590 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
591 /* GL locking is done by the caller */
592 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
593 GLhandleARB programId, const BOOL *constants, WORD constants_set)
595 GLint tmp_loc;
596 unsigned int i;
597 char tmp_name[8];
598 const char *prefix;
599 struct list* ptr;
601 switch (This->baseShader.reg_maps.shader_version.type)
603 case WINED3D_SHADER_TYPE_VERTEX:
604 prefix = "VB";
605 break;
607 case WINED3D_SHADER_TYPE_GEOMETRY:
608 prefix = "GB";
609 break;
611 case WINED3D_SHADER_TYPE_PIXEL:
612 prefix = "PB";
613 break;
615 default:
616 FIXME("Unknown shader type %#x.\n",
617 This->baseShader.reg_maps.shader_version.type);
618 prefix = "UB";
619 break;
622 /* TODO: Benchmark and see if it would be beneficial to store the
623 * locations of the constants to avoid looking up each time */
624 for (i = 0; constants_set; constants_set >>= 1, ++i)
626 if (!(constants_set & 1)) continue;
628 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
630 /* TODO: Benchmark and see if it would be beneficial to store the
631 * locations of the constants to avoid looking up each time */
632 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
633 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
634 if (tmp_loc != -1)
636 /* We found this uniform name in the program - go ahead and send the data */
637 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
638 checkGLcall("glUniform1ivARB");
642 /* Load immediate constants */
643 ptr = list_head(&This->baseShader.constantsB);
644 while (ptr) {
645 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
646 unsigned int idx = lconst->idx;
647 const GLint *values = (const GLint *)lconst->value;
649 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
651 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
652 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
653 if (tmp_loc != -1) {
654 /* We found this uniform name in the program - go ahead and send the data */
655 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
656 checkGLcall("glUniform1ivARB");
658 ptr = list_next(&This->baseShader.constantsB, ptr);
662 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
664 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
668 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
670 /* GL locking is done by the caller (state handler) */
671 static void shader_glsl_load_np2fixup_constants(
672 IWineD3DDevice* device,
673 char usePixelShader,
674 char useVertexShader) {
676 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
677 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
679 if (!prog) {
680 /* No GLSL program set - nothing to do. */
681 return;
684 if (!usePixelShader) {
685 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
686 return;
689 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
690 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
691 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
692 UINT i;
693 UINT fixup = prog->ps_args.np2_fixup;
694 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
696 for (i = 0; fixup; fixup >>= 1, ++i) {
697 const unsigned char idx = prog->np2Fixup_info->idx[i];
698 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
699 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
701 if (!tex)
703 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
704 continue;
707 if (idx % 2) {
708 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
709 } else {
710 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
714 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
719 * Loads the app-supplied constants into the currently set GLSL program.
721 /* GL locking is done by the caller (state handler) */
722 static void shader_glsl_load_constants(const struct wined3d_context *context,
723 char usePixelShader, char useVertexShader)
725 const struct wined3d_gl_info *gl_info = context->gl_info;
726 IWineD3DDeviceImpl *device = context->swapchain->device;
727 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
728 struct shader_glsl_priv *priv = device->shader_priv;
730 GLhandleARB programId;
731 struct glsl_shader_prog_link *prog = priv->glsl_program;
732 UINT constant_version;
733 int i;
735 if (!prog) {
736 /* No GLSL program set - nothing to do. */
737 return;
739 programId = prog->programId;
740 constant_version = prog->constant_version;
742 if (useVertexShader) {
743 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
745 /* Load DirectX 9 float constants/uniforms for vertex shader */
746 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
747 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
749 /* Load DirectX 9 integer constants/uniforms for vertex shader */
750 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
751 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
753 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
754 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
755 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
757 /* Upload the position fixup params */
758 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
759 checkGLcall("glUniform4fvARB");
762 if (usePixelShader) {
764 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
766 /* Load DirectX 9 float constants/uniforms for pixel shader */
767 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
768 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
770 /* Load DirectX 9 integer constants/uniforms for pixel shader */
771 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
772 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
774 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
775 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
776 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
778 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
779 * It can't be 0 for a valid texbem instruction.
781 for(i = 0; i < MAX_TEXTURES; i++) {
782 const float *data;
784 if(prog->bumpenvmat_location[i] == -1) continue;
786 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
787 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
788 checkGLcall("glUniformMatrix2fvARB");
790 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
791 * is set too, so we can check that in the needsbumpmat check
793 if(prog->luminancescale_location[i] != -1) {
794 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
795 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
797 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
798 checkGLcall("glUniform1fvARB");
799 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
800 checkGLcall("glUniform1fvARB");
804 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
805 float correction_params[4];
807 if (context->render_offscreen)
809 correction_params[0] = 0.0f;
810 correction_params[1] = 1.0f;
811 } else {
812 /* position is window relative, not viewport relative */
813 correction_params[0] = context->current_rt->currentDesc.Height;
814 correction_params[1] = -1.0f;
816 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
820 if (priv->next_constant_version == UINT_MAX)
822 TRACE("Max constant version reached, resetting to 0.\n");
823 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
824 priv->next_constant_version = 1;
826 else
828 prog->constant_version = priv->next_constant_version++;
832 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
833 unsigned int heap_idx, DWORD new_version)
835 struct constant_entry *entries = heap->entries;
836 unsigned int *positions = heap->positions;
837 unsigned int parent_idx;
839 while (heap_idx > 1)
841 parent_idx = heap_idx >> 1;
843 if (new_version <= entries[parent_idx].version) break;
845 entries[heap_idx] = entries[parent_idx];
846 positions[entries[parent_idx].idx] = heap_idx;
847 heap_idx = parent_idx;
850 entries[heap_idx].version = new_version;
851 entries[heap_idx].idx = idx;
852 positions[idx] = heap_idx;
855 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
857 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
858 struct shader_glsl_priv *priv = This->shader_priv;
859 struct constant_heap *heap = &priv->vconst_heap;
860 UINT i;
862 for (i = start; i < count + start; ++i)
864 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
865 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
866 else
867 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
871 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
873 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
874 struct shader_glsl_priv *priv = This->shader_priv;
875 struct constant_heap *heap = &priv->pconst_heap;
876 UINT i;
878 for (i = start; i < count + start; ++i)
880 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
881 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
882 else
883 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
887 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
889 unsigned int ret = gl_info->limits.glsl_varyings / 4;
890 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
891 if(shader_major > 3) return ret;
893 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
894 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
895 return ret;
898 /** Generate the variable & register declarations for the GLSL output target */
899 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
900 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
901 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
903 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
904 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
905 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
906 const struct wined3d_gl_info *gl_info = context->gl_info;
907 unsigned int i, extra_constants_needed = 0;
908 const local_constant *lconst;
909 DWORD map;
911 /* There are some minor differences between pixel and vertex shaders */
912 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
913 char prefix = pshader ? 'P' : 'V';
915 /* Prototype the subroutines */
916 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
918 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
921 /* Declare the constants (aka uniforms) */
922 if (This->baseShader.limits.constant_float > 0) {
923 unsigned max_constantsF;
924 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
925 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
926 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
927 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
928 * a dx9 card, as long as it doesn't also use all the other constants.
930 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
931 * declare only the amount that we're assured to have.
933 * Thus we run into problems in these two cases:
934 * 1) The shader really uses more uniforms than supported
935 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
937 if (pshader)
939 /* No indirect addressing here. */
940 max_constantsF = gl_info->limits.glsl_ps_float_constants;
942 else
944 if(This->baseShader.reg_maps.usesrelconstF) {
945 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
946 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
947 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
948 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
950 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
952 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
953 if(ctx_priv->cur_vs_args->clip_enabled)
955 max_constantsF -= gl_info->limits.clipplanes;
957 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
958 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
959 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
960 * for now take this into account when calculating the number of available constants
962 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
963 /* Set by driver quirks in directx.c */
964 max_constantsF -= gl_info->reserved_glsl_constants;
966 else
968 max_constantsF = gl_info->limits.glsl_vs_float_constants;
971 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
972 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
975 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
976 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
978 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
979 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
981 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
982 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
984 if (!pshader)
986 shader_addline(buffer, "uniform vec4 posFixup;\n");
987 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
989 else
991 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
993 if (!(map & 1)) continue;
995 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
997 if (reg_maps->luminanceparams & (1 << i))
999 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1000 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1001 extra_constants_needed++;
1004 extra_constants_needed++;
1007 if (ps_args->srgb_correction)
1009 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1010 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1011 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1012 srgb_cmp);
1014 if (reg_maps->vpos || reg_maps->usesdsy)
1016 if (This->baseShader.limits.constant_float + extra_constants_needed
1017 + 1 < gl_info->limits.glsl_ps_float_constants)
1019 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1020 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1021 extra_constants_needed++;
1022 } else {
1023 /* This happens because we do not have proper tracking of the constant registers that are
1024 * actually used, only the max limit of the shader version
1026 FIXME("Cannot find a free uniform for vpos correction params\n");
1027 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1028 context->render_offscreen ? 0.0f : device->render_targets[0]->currentDesc.Height,
1029 context->render_offscreen ? 1.0f : -1.0f);
1031 shader_addline(buffer, "vec4 vpos;\n");
1035 /* Declare texture samplers */
1036 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1037 if (reg_maps->sampler_type[i])
1039 switch (reg_maps->sampler_type[i])
1041 case WINED3DSTT_1D:
1042 if (pshader && ps_args->shadow & (1 << i))
1043 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1044 else
1045 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1046 break;
1047 case WINED3DSTT_2D:
1048 if (pshader && ps_args->shadow & (1 << i))
1050 if (device->stateBlock->textures[i]
1051 && IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i])
1052 == GL_TEXTURE_RECTANGLE_ARB)
1053 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1054 else
1055 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1057 else
1059 if (device->stateBlock->textures[i]
1060 && IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i])
1061 == GL_TEXTURE_RECTANGLE_ARB)
1062 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1063 else
1064 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1066 break;
1067 case WINED3DSTT_CUBE:
1068 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1069 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1070 break;
1071 case WINED3DSTT_VOLUME:
1072 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1073 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1074 break;
1075 default:
1076 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1077 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1078 break;
1083 /* Declare uniforms for NP2 texcoord fixup:
1084 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1085 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1086 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1087 if (pshader && ps_args->np2_fixup) {
1089 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1090 UINT cur = 0;
1092 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1093 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1094 * samplerNP2Fixup stores texture dimensions and is updated through
1095 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1097 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1098 if (reg_maps->sampler_type[i]) {
1099 if (!(ps_args->np2_fixup & (1 << i))) continue;
1101 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1102 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1103 continue;
1106 fixup->idx[i] = cur++;
1110 fixup->num_consts = (cur + 1) >> 1;
1111 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1114 /* Declare address variables */
1115 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1117 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1120 /* Declare texture coordinate temporaries and initialize them */
1121 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1123 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1126 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1127 * helper function shader that is linked in at link time
1129 if (pshader && reg_maps->shader_version.major >= 3)
1131 if (use_vs(device->stateBlock))
1133 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1134 } else {
1135 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1136 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1137 * pixel shader that reads the fixed function color into the packed input registers.
1139 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1143 /* Declare output register temporaries */
1144 if(This->baseShader.limits.packed_output) {
1145 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1148 /* Declare temporary variables */
1149 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1151 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1154 /* Declare attributes */
1155 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1157 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1159 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1163 /* Declare loop registers aLx */
1164 for (i = 0; i < reg_maps->loop_depth; i++) {
1165 shader_addline(buffer, "int aL%u;\n", i);
1166 shader_addline(buffer, "int tmpInt%u;\n", i);
1169 /* Temporary variables for matrix operations */
1170 shader_addline(buffer, "vec4 tmp0;\n");
1171 shader_addline(buffer, "vec4 tmp1;\n");
1173 /* Local constants use a different name so they can be loaded once at shader link time
1174 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1175 * float -> string conversion can cause precision loss.
1177 if(!This->baseShader.load_local_constsF) {
1178 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1179 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1183 /* Start the main program */
1184 shader_addline(buffer, "void main() {\n");
1185 if(pshader && reg_maps->vpos) {
1186 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1187 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1188 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1189 * precision troubles when we just substract 0.5.
1191 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1193 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1195 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1196 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1197 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1198 * correctly on drivers that returns integer values.
1200 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1204 /*****************************************************************************
1205 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1207 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1208 ****************************************************************************/
1210 /* Prototypes */
1211 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1212 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1214 /** Used for opcode modifiers - They multiply the result by the specified amount */
1215 static const char * const shift_glsl_tab[] = {
1216 "", /* 0 (none) */
1217 "2.0 * ", /* 1 (x2) */
1218 "4.0 * ", /* 2 (x4) */
1219 "8.0 * ", /* 3 (x8) */
1220 "16.0 * ", /* 4 (x16) */
1221 "32.0 * ", /* 5 (x32) */
1222 "", /* 6 (x64) */
1223 "", /* 7 (x128) */
1224 "", /* 8 (d256) */
1225 "", /* 9 (d128) */
1226 "", /* 10 (d64) */
1227 "", /* 11 (d32) */
1228 "0.0625 * ", /* 12 (d16) */
1229 "0.125 * ", /* 13 (d8) */
1230 "0.25 * ", /* 14 (d4) */
1231 "0.5 * " /* 15 (d2) */
1234 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1235 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1237 out_str[0] = 0;
1239 switch (src_modifier)
1241 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1242 case WINED3DSPSM_DW:
1243 case WINED3DSPSM_NONE:
1244 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1245 break;
1246 case WINED3DSPSM_NEG:
1247 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1248 break;
1249 case WINED3DSPSM_NOT:
1250 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1251 break;
1252 case WINED3DSPSM_BIAS:
1253 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1254 break;
1255 case WINED3DSPSM_BIASNEG:
1256 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1257 break;
1258 case WINED3DSPSM_SIGN:
1259 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1260 break;
1261 case WINED3DSPSM_SIGNNEG:
1262 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1263 break;
1264 case WINED3DSPSM_COMP:
1265 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1266 break;
1267 case WINED3DSPSM_X2:
1268 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1269 break;
1270 case WINED3DSPSM_X2NEG:
1271 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1272 break;
1273 case WINED3DSPSM_ABS:
1274 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1275 break;
1276 case WINED3DSPSM_ABSNEG:
1277 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1278 break;
1279 default:
1280 FIXME("Unhandled modifier %u\n", src_modifier);
1281 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1285 /** Writes the GLSL variable name that corresponds to the register that the
1286 * DX opcode parameter is trying to access */
1287 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1288 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1290 /* oPos, oFog and oPts in D3D */
1291 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1293 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1294 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1295 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1297 *is_color = FALSE;
1299 switch (reg->type)
1301 case WINED3DSPR_TEMP:
1302 sprintf(register_name, "R%u", reg->idx);
1303 break;
1305 case WINED3DSPR_INPUT:
1306 /* vertex shaders */
1307 if (!pshader)
1309 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1310 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1311 sprintf(register_name, "attrib%u", reg->idx);
1312 break;
1315 /* pixel shaders >= 3.0 */
1316 if (This->baseShader.reg_maps.shader_version.major >= 3)
1318 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1319 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1321 if (reg->rel_addr)
1323 glsl_src_param_t rel_param;
1325 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1327 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1328 * operation there */
1329 if (idx)
1331 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1333 sprintf(register_name,
1334 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1335 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1336 rel_param.param_str, idx);
1338 else
1340 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1343 else
1345 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1347 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1348 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1349 rel_param.param_str);
1351 else
1353 sprintf(register_name, "IN[%s]", rel_param.param_str);
1357 else
1359 if (idx == in_count) sprintf(register_name, "gl_Color");
1360 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1361 else sprintf(register_name, "IN[%u]", idx);
1364 else
1366 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1367 else strcpy(register_name, "gl_SecondaryColor");
1368 break;
1370 break;
1372 case WINED3DSPR_CONST:
1374 const char prefix = pshader ? 'P' : 'V';
1376 /* Relative addressing */
1377 if (reg->rel_addr)
1379 glsl_src_param_t rel_param;
1380 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1381 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1382 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1384 else
1386 if (shader_constant_is_local(This, reg->idx))
1387 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1388 else
1389 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1392 break;
1394 case WINED3DSPR_CONSTINT:
1395 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1396 else sprintf(register_name, "VI[%u]", reg->idx);
1397 break;
1399 case WINED3DSPR_CONSTBOOL:
1400 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1401 else sprintf(register_name, "VB[%u]", reg->idx);
1402 break;
1404 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1405 if (pshader) sprintf(register_name, "T%u", reg->idx);
1406 else sprintf(register_name, "A%u", reg->idx);
1407 break;
1409 case WINED3DSPR_LOOP:
1410 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1411 break;
1413 case WINED3DSPR_SAMPLER:
1414 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1415 else sprintf(register_name, "Vsampler%u", reg->idx);
1416 break;
1418 case WINED3DSPR_COLOROUT:
1419 if (reg->idx >= gl_info->limits.buffers)
1420 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1422 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1423 break;
1425 case WINED3DSPR_RASTOUT:
1426 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1427 break;
1429 case WINED3DSPR_DEPTHOUT:
1430 sprintf(register_name, "gl_FragDepth");
1431 break;
1433 case WINED3DSPR_ATTROUT:
1434 if (reg->idx == 0) sprintf(register_name, "OUT[8]");
1435 else sprintf(register_name, "OUT[9]");
1436 break;
1438 case WINED3DSPR_TEXCRDOUT:
1439 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1440 sprintf(register_name, "OUT[%u]", reg->idx);
1441 break;
1443 case WINED3DSPR_MISCTYPE:
1444 if (reg->idx == 0)
1446 /* vPos */
1447 sprintf(register_name, "vpos");
1449 else if (reg->idx == 1)
1451 /* Note that gl_FrontFacing is a bool, while vFace is
1452 * a float for which the sign determines front/back */
1453 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1455 else
1457 FIXME("Unhandled misctype register %d\n", reg->idx);
1458 sprintf(register_name, "unrecognized_register");
1460 break;
1462 case WINED3DSPR_IMMCONST:
1463 switch (reg->immconst_type)
1465 case WINED3D_IMMCONST_FLOAT:
1466 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1467 break;
1469 case WINED3D_IMMCONST_FLOAT4:
1470 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1471 *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1472 *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1473 break;
1475 default:
1476 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1477 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1479 break;
1481 default:
1482 FIXME("Unhandled register name Type(%d)\n", reg->type);
1483 sprintf(register_name, "unrecognized_register");
1484 break;
1488 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1490 *str++ = '.';
1491 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1492 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1493 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1494 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1495 *str = '\0';
1498 /* Get the GLSL write mask for the destination register */
1499 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1501 DWORD mask = param->write_mask;
1503 if (shader_is_scalar(&param->reg))
1505 mask = WINED3DSP_WRITEMASK_0;
1506 *write_mask = '\0';
1508 else
1510 shader_glsl_write_mask_to_str(mask, write_mask);
1513 return mask;
1516 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1517 unsigned int size = 0;
1519 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1520 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1521 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1522 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1524 return size;
1527 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1529 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1530 * but addressed as "rgba". To fix this we need to swap the register's x
1531 * and z components. */
1532 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1534 *str++ = '.';
1535 /* swizzle bits fields: wwzzyyxx */
1536 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1537 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1538 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1539 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1540 *str = '\0';
1543 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1544 BOOL fixup, DWORD mask, char *swizzle_str)
1546 if (shader_is_scalar(&param->reg))
1547 *swizzle_str = '\0';
1548 else
1549 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1552 /* From a given parameter token, generate the corresponding GLSL string.
1553 * Also, return the actual register name and swizzle in case the
1554 * caller needs this information as well. */
1555 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1556 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1558 BOOL is_color = FALSE;
1559 char swizzle_str[6];
1561 glsl_src->reg_name[0] = '\0';
1562 glsl_src->param_str[0] = '\0';
1563 swizzle_str[0] = '\0';
1565 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1566 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1567 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1570 /* From a given parameter token, generate the corresponding GLSL string.
1571 * Also, return the actual register name and swizzle in case the
1572 * caller needs this information as well. */
1573 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1574 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1576 BOOL is_color = FALSE;
1578 glsl_dst->mask_str[0] = '\0';
1579 glsl_dst->reg_name[0] = '\0';
1581 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1582 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1585 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1586 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1587 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1589 glsl_dst_param_t glsl_dst;
1590 DWORD mask;
1592 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1593 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1595 return mask;
1598 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1599 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1601 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1604 /** Process GLSL instruction modifiers */
1605 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1607 glsl_dst_param_t dst_param;
1608 DWORD modifiers;
1610 if (!ins->dst_count) return;
1612 modifiers = ins->dst[0].modifiers;
1613 if (!modifiers) return;
1615 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1617 if (modifiers & WINED3DSPDM_SATURATE)
1619 /* _SAT means to clamp the value of the register to between 0 and 1 */
1620 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1621 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1624 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1626 FIXME("_centroid modifier not handled\n");
1629 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1631 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1635 static inline const char *shader_get_comp_op(DWORD op)
1637 switch (op) {
1638 case COMPARISON_GT: return ">";
1639 case COMPARISON_EQ: return "==";
1640 case COMPARISON_GE: return ">=";
1641 case COMPARISON_LT: return "<";
1642 case COMPARISON_NE: return "!=";
1643 case COMPARISON_LE: return "<=";
1644 default:
1645 FIXME("Unrecognized comparison value: %u\n", op);
1646 return "(\?\?)";
1650 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1651 DWORD sampler_idx, DWORD flags, glsl_sample_function_t *sample_function)
1653 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1654 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1655 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1656 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1657 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1658 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1659 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1660 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1662 /* Note that there's no such thing as a projected cube texture. */
1663 switch(sampler_type) {
1664 case WINED3DSTT_1D:
1665 if (shadow)
1667 if (lod)
1669 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1671 else if (grad)
1673 if (gl_info->supported[EXT_GPU_SHADER4])
1674 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1675 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1676 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1677 else
1679 FIXME("Unsupported 1D shadow grad function.\n");
1680 sample_function->name = "unsupported1DGrad";
1683 else
1685 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1687 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1689 else
1691 if (lod)
1693 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1695 else if (grad)
1697 if (gl_info->supported[EXT_GPU_SHADER4])
1698 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1699 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1700 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1701 else
1703 FIXME("Unsupported 1D grad function.\n");
1704 sample_function->name = "unsupported1DGrad";
1707 else
1709 sample_function->name = projected ? "texture1DProj" : "texture1D";
1711 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1713 break;
1715 case WINED3DSTT_2D:
1716 if (shadow)
1718 if (texrect)
1720 if (lod)
1722 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1724 else if (grad)
1726 if (gl_info->supported[EXT_GPU_SHADER4])
1727 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1728 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1729 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1730 else
1732 FIXME("Unsupported RECT shadow grad function.\n");
1733 sample_function->name = "unsupported2DRectGrad";
1736 else
1738 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1741 else
1743 if (lod)
1745 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1747 else if (grad)
1749 if (gl_info->supported[EXT_GPU_SHADER4])
1750 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1751 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1752 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1753 else
1755 FIXME("Unsupported 2D shadow grad function.\n");
1756 sample_function->name = "unsupported2DGrad";
1759 else
1761 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1764 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1766 else
1768 if (texrect)
1770 if (lod)
1772 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1774 else if (grad)
1776 if (gl_info->supported[EXT_GPU_SHADER4])
1777 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1778 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1779 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1780 else
1782 FIXME("Unsupported RECT grad function.\n");
1783 sample_function->name = "unsupported2DRectGrad";
1786 else
1788 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1791 else
1793 if (lod)
1795 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1797 else if (grad)
1799 if (gl_info->supported[EXT_GPU_SHADER4])
1800 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1801 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1802 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1803 else
1805 FIXME("Unsupported 2D grad function.\n");
1806 sample_function->name = "unsupported2DGrad";
1809 else
1811 sample_function->name = projected ? "texture2DProj" : "texture2D";
1814 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1816 break;
1818 case WINED3DSTT_CUBE:
1819 if (shadow)
1821 FIXME("Unsupported Cube shadow function.\n");
1822 sample_function->name = "unsupportedCubeShadow";
1823 sample_function->coord_mask = 0;
1825 else
1827 if (lod)
1829 sample_function->name = "textureCubeLod";
1831 else if (grad)
1833 if (gl_info->supported[EXT_GPU_SHADER4])
1834 sample_function->name = "textureCubeGrad";
1835 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1836 sample_function->name = "textureCubeGradARB";
1837 else
1839 FIXME("Unsupported Cube grad function.\n");
1840 sample_function->name = "unsupportedCubeGrad";
1843 else
1845 sample_function->name = "textureCube";
1847 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1849 break;
1851 case WINED3DSTT_VOLUME:
1852 if (shadow)
1854 FIXME("Unsupported 3D shadow function.\n");
1855 sample_function->name = "unsupported3DShadow";
1856 sample_function->coord_mask = 0;
1858 else
1860 if (lod)
1862 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1864 else if (grad)
1866 if (gl_info->supported[EXT_GPU_SHADER4])
1867 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1868 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1869 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1870 else
1872 FIXME("Unsupported 3D grad function.\n");
1873 sample_function->name = "unsupported3DGrad";
1876 else
1878 sample_function->name = projected ? "texture3DProj" : "texture3D";
1880 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1882 break;
1884 default:
1885 sample_function->name = "";
1886 sample_function->coord_mask = 0;
1887 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1888 break;
1892 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1893 BOOL sign_fixup, enum fixup_channel_source channel_source)
1895 switch(channel_source)
1897 case CHANNEL_SOURCE_ZERO:
1898 strcat(arguments, "0.0");
1899 break;
1901 case CHANNEL_SOURCE_ONE:
1902 strcat(arguments, "1.0");
1903 break;
1905 case CHANNEL_SOURCE_X:
1906 strcat(arguments, reg_name);
1907 strcat(arguments, ".x");
1908 break;
1910 case CHANNEL_SOURCE_Y:
1911 strcat(arguments, reg_name);
1912 strcat(arguments, ".y");
1913 break;
1915 case CHANNEL_SOURCE_Z:
1916 strcat(arguments, reg_name);
1917 strcat(arguments, ".z");
1918 break;
1920 case CHANNEL_SOURCE_W:
1921 strcat(arguments, reg_name);
1922 strcat(arguments, ".w");
1923 break;
1925 default:
1926 FIXME("Unhandled channel source %#x\n", channel_source);
1927 strcat(arguments, "undefined");
1928 break;
1931 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1934 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1936 struct wined3d_shader_dst_param dst;
1937 unsigned int mask_size, remaining;
1938 glsl_dst_param_t dst_param;
1939 char arguments[256];
1940 DWORD mask;
1942 mask = 0;
1943 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1944 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1945 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1946 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1947 mask &= ins->dst[0].write_mask;
1949 if (!mask) return; /* Nothing to do */
1951 if (is_complex_fixup(fixup))
1953 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1954 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1955 return;
1958 mask_size = shader_glsl_get_write_mask_size(mask);
1960 dst = ins->dst[0];
1961 dst.write_mask = mask;
1962 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1964 arguments[0] = '\0';
1965 remaining = mask_size;
1966 if (mask & WINED3DSP_WRITEMASK_0)
1968 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1969 if (--remaining) strcat(arguments, ", ");
1971 if (mask & WINED3DSP_WRITEMASK_1)
1973 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1974 if (--remaining) strcat(arguments, ", ");
1976 if (mask & WINED3DSP_WRITEMASK_2)
1978 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1979 if (--remaining) strcat(arguments, ", ");
1981 if (mask & WINED3DSP_WRITEMASK_3)
1983 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1984 if (--remaining) strcat(arguments, ", ");
1987 if (mask_size > 1)
1989 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1990 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1992 else
1994 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1998 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1999 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
2000 const char *dx, const char *dy,
2001 const char *bias, const char *coord_reg_fmt, ...)
2003 const char *sampler_base;
2004 char dst_swizzle[6];
2005 struct color_fixup_desc fixup;
2006 BOOL np2_fixup = FALSE;
2007 va_list args;
2009 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2011 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2013 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2014 fixup = priv->cur_ps_args->color_fixup[sampler];
2015 sampler_base = "Psampler";
2017 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2018 if(bias) {
2019 FIXME("Biased sampling from NP2 textures is unsupported\n");
2020 } else {
2021 np2_fixup = TRUE;
2024 } else {
2025 sampler_base = "Vsampler";
2026 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2029 shader_glsl_append_dst(ins->ctx->buffer, ins);
2031 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2033 va_start(args, coord_reg_fmt);
2034 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2035 va_end(args);
2037 if(bias) {
2038 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2039 } else {
2040 if (np2_fixup) {
2041 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2042 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2044 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2045 (idx % 2) ? "zw" : "xy", dst_swizzle);
2046 } else if(dx && dy) {
2047 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2048 } else {
2049 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2053 if(!is_identity_fixup(fixup)) {
2054 shader_glsl_color_correction(ins, fixup);
2058 /*****************************************************************************
2059 * Begin processing individual instruction opcodes
2060 ****************************************************************************/
2062 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2063 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2065 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2066 glsl_src_param_t src0_param;
2067 glsl_src_param_t src1_param;
2068 DWORD write_mask;
2069 char op;
2071 /* Determine the GLSL operator to use based on the opcode */
2072 switch (ins->handler_idx)
2074 case WINED3DSIH_MUL: op = '*'; break;
2075 case WINED3DSIH_ADD: op = '+'; break;
2076 case WINED3DSIH_SUB: op = '-'; break;
2077 default:
2078 op = ' ';
2079 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2080 break;
2083 write_mask = shader_glsl_append_dst(buffer, ins);
2084 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2085 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2086 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2089 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2090 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2092 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2093 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2094 glsl_src_param_t src0_param;
2095 DWORD write_mask;
2097 write_mask = shader_glsl_append_dst(buffer, ins);
2098 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2100 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2101 * shader versions WINED3DSIO_MOVA is used for this. */
2102 if (ins->ctx->reg_maps->shader_version.major == 1
2103 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2104 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2106 /* This is a simple floor() */
2107 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2108 if (mask_size > 1) {
2109 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2110 } else {
2111 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2114 else if(ins->handler_idx == WINED3DSIH_MOVA)
2116 /* We need to *round* to the nearest int here. */
2117 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2119 if (gl_info->supported[EXT_GPU_SHADER4])
2121 if (mask_size > 1)
2122 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2123 else
2124 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2126 else
2128 if (mask_size > 1)
2129 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2130 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2131 else
2132 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2133 src0_param.param_str, src0_param.param_str);
2136 else
2138 shader_addline(buffer, "%s);\n", src0_param.param_str);
2142 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2143 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2145 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2146 glsl_src_param_t src0_param;
2147 glsl_src_param_t src1_param;
2148 DWORD dst_write_mask, src_write_mask;
2149 unsigned int dst_size = 0;
2151 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2152 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2154 /* dp3 works on vec3, dp4 on vec4 */
2155 if (ins->handler_idx == WINED3DSIH_DP4)
2157 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2158 } else {
2159 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2162 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2163 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2165 if (dst_size > 1) {
2166 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2167 } else {
2168 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2172 /* Note that this instruction has some restrictions. The destination write mask
2173 * can't contain the w component, and the source swizzles have to be .xyzw */
2174 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2176 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2177 glsl_src_param_t src0_param;
2178 glsl_src_param_t src1_param;
2179 char dst_mask[6];
2181 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2182 shader_glsl_append_dst(ins->ctx->buffer, ins);
2183 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2184 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2185 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2188 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2189 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2190 * GLSL uses the value as-is. */
2191 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2193 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2194 glsl_src_param_t src0_param;
2195 glsl_src_param_t src1_param;
2196 DWORD dst_write_mask;
2197 unsigned int dst_size;
2199 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2200 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2202 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2203 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2205 if (dst_size > 1)
2207 shader_addline(buffer, "vec%u(pow(abs(%s), %s)));\n",
2208 dst_size, src0_param.param_str, src1_param.param_str);
2210 else
2212 shader_addline(buffer, "pow(abs(%s), %s));\n",
2213 src0_param.param_str, src1_param.param_str);
2217 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2218 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2219 * GLSL uses the value as-is. */
2220 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2222 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2223 glsl_src_param_t src0_param;
2224 DWORD dst_write_mask;
2225 unsigned int dst_size;
2227 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2228 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2230 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2232 if (dst_size > 1)
2234 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2235 dst_size, src0_param.param_str);
2237 else
2239 shader_addline(buffer, "log2(abs(%s)));\n",
2240 src0_param.param_str);
2244 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2245 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2247 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2248 glsl_src_param_t src_param;
2249 const char *instruction;
2250 DWORD write_mask;
2251 unsigned i;
2253 /* Determine the GLSL function to use based on the opcode */
2254 /* TODO: Possibly make this a table for faster lookups */
2255 switch (ins->handler_idx)
2257 case WINED3DSIH_MIN: instruction = "min"; break;
2258 case WINED3DSIH_MAX: instruction = "max"; break;
2259 case WINED3DSIH_ABS: instruction = "abs"; break;
2260 case WINED3DSIH_FRC: instruction = "fract"; break;
2261 case WINED3DSIH_EXP: instruction = "exp2"; break;
2262 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2263 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2264 default: instruction = "";
2265 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2266 break;
2269 write_mask = shader_glsl_append_dst(buffer, ins);
2271 shader_addline(buffer, "%s(", instruction);
2273 if (ins->src_count)
2275 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2276 shader_addline(buffer, "%s", src_param.param_str);
2277 for (i = 1; i < ins->src_count; ++i)
2279 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2280 shader_addline(buffer, ", %s", src_param.param_str);
2284 shader_addline(buffer, "));\n");
2287 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2289 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2290 glsl_src_param_t src_param;
2291 unsigned int mask_size;
2292 DWORD write_mask;
2293 char dst_mask[6];
2295 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2296 mask_size = shader_glsl_get_write_mask_size(write_mask);
2297 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2299 shader_addline(buffer, "tmp0.x = length(%s);\n", src_param.param_str);
2300 shader_glsl_append_dst(buffer, ins);
2301 if (mask_size > 1)
2303 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s / tmp0.x));\n",
2304 mask_size, src_param.param_str);
2306 else
2308 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s / tmp0.x));\n",
2309 src_param.param_str);
2313 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2314 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2315 * dst.x = 2^(floor(src))
2316 * dst.y = src - floor(src)
2317 * dst.z = 2^src (partial precision is allowed, but optional)
2318 * dst.w = 1.0;
2319 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2320 * dst = 2^src; (partial precision is allowed, but optional)
2322 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2324 glsl_src_param_t src_param;
2326 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2328 if (ins->ctx->reg_maps->shader_version.major < 2)
2330 char dst_mask[6];
2332 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2333 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2334 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2335 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2337 shader_glsl_append_dst(ins->ctx->buffer, ins);
2338 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2339 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2340 } else {
2341 DWORD write_mask;
2342 unsigned int mask_size;
2344 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2345 mask_size = shader_glsl_get_write_mask_size(write_mask);
2347 if (mask_size > 1) {
2348 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2349 } else {
2350 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2355 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2356 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2358 glsl_src_param_t src_param;
2359 DWORD write_mask;
2360 unsigned int mask_size;
2362 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2363 mask_size = shader_glsl_get_write_mask_size(write_mask);
2364 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2366 if (mask_size > 1)
2368 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2369 mask_size, src_param.param_str);
2371 else
2373 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2374 src_param.param_str);
2378 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2380 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2381 glsl_src_param_t src_param;
2382 DWORD write_mask;
2383 unsigned int mask_size;
2385 write_mask = shader_glsl_append_dst(buffer, ins);
2386 mask_size = shader_glsl_get_write_mask_size(write_mask);
2388 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2390 if (mask_size > 1)
2392 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2393 mask_size, src_param.param_str);
2395 else
2397 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2398 src_param.param_str);
2402 /** Process signed comparison opcodes in GLSL. */
2403 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2405 glsl_src_param_t src0_param;
2406 glsl_src_param_t src1_param;
2407 DWORD write_mask;
2408 unsigned int mask_size;
2410 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2411 mask_size = shader_glsl_get_write_mask_size(write_mask);
2412 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2413 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2415 if (mask_size > 1) {
2416 const char *compare;
2418 switch(ins->handler_idx)
2420 case WINED3DSIH_SLT: compare = "lessThan"; break;
2421 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2422 default: compare = "";
2423 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2426 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2427 src0_param.param_str, src1_param.param_str);
2428 } else {
2429 switch(ins->handler_idx)
2431 case WINED3DSIH_SLT:
2432 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2433 * to return 0.0 but step returns 1.0 because step is not < x
2434 * An alternative is a bvec compare padded with an unused second component.
2435 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2436 * issue. Playing with not() is not possible either because not() does not accept
2437 * a scalar.
2439 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2440 src0_param.param_str, src1_param.param_str);
2441 break;
2442 case WINED3DSIH_SGE:
2443 /* Here we can use the step() function and safe a conditional */
2444 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2445 break;
2446 default:
2447 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2453 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2454 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2456 glsl_src_param_t src0_param;
2457 glsl_src_param_t src1_param;
2458 glsl_src_param_t src2_param;
2459 DWORD write_mask, cmp_channel = 0;
2460 unsigned int i, j;
2461 char mask_char[6];
2462 BOOL temp_destination = FALSE;
2464 if (shader_is_scalar(&ins->src[0].reg))
2466 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2468 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2469 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2470 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2472 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2473 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2474 } else {
2475 DWORD dst_mask = ins->dst[0].write_mask;
2476 struct wined3d_shader_dst_param dst = ins->dst[0];
2478 /* Cycle through all source0 channels */
2479 for (i=0; i<4; i++) {
2480 write_mask = 0;
2481 /* Find the destination channels which use the current source0 channel */
2482 for (j=0; j<4; j++) {
2483 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2485 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2486 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2489 dst.write_mask = dst_mask & write_mask;
2491 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2492 * The first lines may overwrite source parameters of the following lines.
2493 * Deal with that by using a temporary destination register if needed
2495 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2496 && ins->src[0].reg.type == ins->dst[0].reg.type)
2497 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2498 && ins->src[1].reg.type == ins->dst[0].reg.type)
2499 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2500 && ins->src[2].reg.type == ins->dst[0].reg.type))
2502 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2503 if (!write_mask) continue;
2504 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2505 temp_destination = TRUE;
2506 } else {
2507 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2508 if (!write_mask) continue;
2511 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2512 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2513 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2515 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2516 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2519 if(temp_destination) {
2520 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2521 shader_glsl_append_dst(ins->ctx->buffer, ins);
2522 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2528 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2529 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2530 * the compare is done per component of src0. */
2531 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2533 struct wined3d_shader_dst_param dst;
2534 glsl_src_param_t src0_param;
2535 glsl_src_param_t src1_param;
2536 glsl_src_param_t src2_param;
2537 DWORD write_mask, cmp_channel = 0;
2538 unsigned int i, j;
2539 DWORD dst_mask;
2540 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2541 ins->ctx->reg_maps->shader_version.minor);
2543 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2545 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2546 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2547 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2548 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2550 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2551 if (ins->coissue)
2553 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2554 } else {
2555 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2556 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2558 return;
2560 /* Cycle through all source0 channels */
2561 dst_mask = ins->dst[0].write_mask;
2562 dst = ins->dst[0];
2563 for (i=0; i<4; i++) {
2564 write_mask = 0;
2565 /* Find the destination channels which use the current source0 channel */
2566 for (j=0; j<4; j++) {
2567 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2569 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2570 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2574 dst.write_mask = dst_mask & write_mask;
2575 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2576 if (!write_mask) continue;
2578 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2579 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2580 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2582 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2583 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2587 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2588 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2590 glsl_src_param_t src0_param;
2591 glsl_src_param_t src1_param;
2592 glsl_src_param_t src2_param;
2593 DWORD write_mask;
2595 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2596 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2597 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2598 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2599 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2600 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2603 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2604 Vertex shaders to GLSL codes */
2605 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2607 int i;
2608 int nComponents = 0;
2609 struct wined3d_shader_dst_param tmp_dst = {{0}};
2610 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2611 struct wined3d_shader_instruction tmp_ins;
2613 memset(&tmp_ins, 0, sizeof(tmp_ins));
2615 /* Set constants for the temporary argument */
2616 tmp_ins.ctx = ins->ctx;
2617 tmp_ins.dst_count = 1;
2618 tmp_ins.dst = &tmp_dst;
2619 tmp_ins.src_count = 2;
2620 tmp_ins.src = tmp_src;
2622 switch(ins->handler_idx)
2624 case WINED3DSIH_M4x4:
2625 nComponents = 4;
2626 tmp_ins.handler_idx = WINED3DSIH_DP4;
2627 break;
2628 case WINED3DSIH_M4x3:
2629 nComponents = 3;
2630 tmp_ins.handler_idx = WINED3DSIH_DP4;
2631 break;
2632 case WINED3DSIH_M3x4:
2633 nComponents = 4;
2634 tmp_ins.handler_idx = WINED3DSIH_DP3;
2635 break;
2636 case WINED3DSIH_M3x3:
2637 nComponents = 3;
2638 tmp_ins.handler_idx = WINED3DSIH_DP3;
2639 break;
2640 case WINED3DSIH_M3x2:
2641 nComponents = 2;
2642 tmp_ins.handler_idx = WINED3DSIH_DP3;
2643 break;
2644 default:
2645 break;
2648 tmp_dst = ins->dst[0];
2649 tmp_src[0] = ins->src[0];
2650 tmp_src[1] = ins->src[1];
2651 for (i = 0; i < nComponents; ++i)
2653 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2654 shader_glsl_dot(&tmp_ins);
2655 ++tmp_src[1].reg.idx;
2660 The LRP instruction performs a component-wise linear interpolation
2661 between the second and third operands using the first operand as the
2662 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2663 This is equivalent to mix(src2, src1, src0);
2665 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2667 glsl_src_param_t src0_param;
2668 glsl_src_param_t src1_param;
2669 glsl_src_param_t src2_param;
2670 DWORD write_mask;
2672 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2674 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2675 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2676 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2678 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2679 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2682 /** Process the WINED3DSIO_LIT instruction in GLSL:
2683 * dst.x = dst.w = 1.0
2684 * dst.y = (src0.x > 0) ? src0.x
2685 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2686 * where src.w is clamped at +- 128
2688 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2690 glsl_src_param_t src0_param;
2691 glsl_src_param_t src1_param;
2692 glsl_src_param_t src3_param;
2693 char dst_mask[6];
2695 shader_glsl_append_dst(ins->ctx->buffer, ins);
2696 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2698 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2699 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2700 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2702 /* The sdk specifies the instruction like this
2703 * dst.x = 1.0;
2704 * if(src.x > 0.0) dst.y = src.x
2705 * else dst.y = 0.0.
2706 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2707 * else dst.z = 0.0;
2708 * dst.w = 1.0;
2710 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2711 * dst.x = 1.0 ... No further explanation needed
2712 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2713 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2714 * dst.w = 1.0. ... Nothing fancy.
2716 * So we still have one conditional in there. So do this:
2717 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2719 * 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),
2720 * 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.
2721 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2723 shader_addline(ins->ctx->buffer,
2724 "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",
2725 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2728 /** Process the WINED3DSIO_DST instruction in GLSL:
2729 * dst.x = 1.0
2730 * dst.y = src0.x * src0.y
2731 * dst.z = src0.z
2732 * dst.w = src1.w
2734 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2736 glsl_src_param_t src0y_param;
2737 glsl_src_param_t src0z_param;
2738 glsl_src_param_t src1y_param;
2739 glsl_src_param_t src1w_param;
2740 char dst_mask[6];
2742 shader_glsl_append_dst(ins->ctx->buffer, ins);
2743 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2745 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2746 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2747 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2748 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2750 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2751 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2754 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2755 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2756 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2758 * dst.x = cos(src0.?)
2759 * dst.y = sin(src0.?)
2760 * dst.z = dst.z
2761 * dst.w = dst.w
2763 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2765 glsl_src_param_t src0_param;
2766 DWORD write_mask;
2768 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2769 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2771 switch (write_mask) {
2772 case WINED3DSP_WRITEMASK_0:
2773 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2774 break;
2776 case WINED3DSP_WRITEMASK_1:
2777 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2778 break;
2780 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2781 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2782 break;
2784 default:
2785 ERR("Write mask should be .x, .y or .xy\n");
2786 break;
2790 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2791 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2792 * generate invalid code
2794 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2796 glsl_src_param_t src0_param;
2797 DWORD write_mask;
2799 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2800 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2802 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2805 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2806 * Start a for() loop where src1.y is the initial value of aL,
2807 * increment aL by src1.z for a total of src1.x iterations.
2808 * Need to use a temporary variable for this operation.
2810 /* FIXME: I don't think nested loops will work correctly this way. */
2811 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2813 glsl_src_param_t src1_param;
2814 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2815 const DWORD *control_values = NULL;
2816 const local_constant *constant;
2818 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2820 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2821 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2822 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2823 * addressing.
2825 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2827 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2828 if (constant->idx == ins->src[1].reg.idx)
2830 control_values = constant->value;
2831 break;
2836 if (control_values)
2838 struct wined3d_shader_loop_control loop_control;
2839 loop_control.count = control_values[0];
2840 loop_control.start = control_values[1];
2841 loop_control.step = (int)control_values[2];
2843 if (loop_control.step > 0)
2845 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2846 shader->baseShader.cur_loop_depth, loop_control.start,
2847 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2848 shader->baseShader.cur_loop_depth, loop_control.step);
2850 else if (loop_control.step < 0)
2852 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2853 shader->baseShader.cur_loop_depth, loop_control.start,
2854 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2855 shader->baseShader.cur_loop_depth, loop_control.step);
2857 else
2859 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2860 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2861 shader->baseShader.cur_loop_depth, loop_control.count,
2862 shader->baseShader.cur_loop_depth);
2864 } else {
2865 shader_addline(ins->ctx->buffer,
2866 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2867 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2868 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2869 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2872 shader->baseShader.cur_loop_depth++;
2873 shader->baseShader.cur_loop_regno++;
2876 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2878 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2880 shader_addline(ins->ctx->buffer, "}\n");
2882 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2884 shader->baseShader.cur_loop_depth--;
2885 shader->baseShader.cur_loop_regno--;
2888 if (ins->handler_idx == WINED3DSIH_ENDREP)
2890 shader->baseShader.cur_loop_depth--;
2894 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2896 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2897 glsl_src_param_t src0_param;
2898 const DWORD *control_values = NULL;
2899 const local_constant *constant;
2901 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2902 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2904 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2906 if (constant->idx == ins->src[0].reg.idx)
2908 control_values = constant->value;
2909 break;
2914 if(control_values) {
2915 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2916 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2917 control_values[0], shader->baseShader.cur_loop_depth);
2918 } else {
2919 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2920 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2921 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2922 src0_param.param_str, shader->baseShader.cur_loop_depth);
2924 shader->baseShader.cur_loop_depth++;
2927 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2929 glsl_src_param_t src0_param;
2931 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2932 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2935 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2937 glsl_src_param_t src0_param;
2938 glsl_src_param_t src1_param;
2940 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2941 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2943 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2944 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2947 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2949 shader_addline(ins->ctx->buffer, "} else {\n");
2952 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2954 shader_addline(ins->ctx->buffer, "break;\n");
2957 /* FIXME: According to MSDN the compare is done per component. */
2958 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2960 glsl_src_param_t src0_param;
2961 glsl_src_param_t src1_param;
2963 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2964 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2966 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2967 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2970 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2972 shader_addline(ins->ctx->buffer, "}\n");
2973 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2976 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2978 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2981 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2983 glsl_src_param_t src1_param;
2985 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2986 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2989 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
2991 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
2992 * function only suppresses the unhandled instruction warning
2996 /*********************************************
2997 * Pixel Shader Specific Code begins here
2998 ********************************************/
2999 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3001 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3002 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3003 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3004 ins->ctx->reg_maps->shader_version.minor);
3005 glsl_sample_function_t sample_function;
3006 DWORD sample_flags = 0;
3007 DWORD sampler_idx;
3008 DWORD mask = 0, swizzle;
3010 /* 1.0-1.4: Use destination register as sampler source.
3011 * 2.0+: Use provided sampler source. */
3012 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3013 else sampler_idx = ins->src[1].reg.idx;
3015 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3017 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3018 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3020 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3021 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3022 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3023 switch (flags & ~WINED3DTTFF_PROJECTED) {
3024 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3025 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3026 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3027 case WINED3DTTFF_COUNT4:
3028 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3032 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3034 DWORD src_mod = ins->src[0].modifiers;
3036 if (src_mod == WINED3DSPSM_DZ) {
3037 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3038 mask = WINED3DSP_WRITEMASK_2;
3039 } else if (src_mod == WINED3DSPSM_DW) {
3040 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3041 mask = WINED3DSP_WRITEMASK_3;
3043 } else {
3044 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3046 /* ps 2.0 texldp instruction always divides by the fourth component. */
3047 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3048 mask = WINED3DSP_WRITEMASK_3;
3052 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3053 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3054 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3057 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3058 mask |= sample_function.coord_mask;
3060 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3061 else swizzle = ins->src[1].swizzle;
3063 /* 1.0-1.3: Use destination register as coordinate source.
3064 1.4+: Use provided coordinate source register. */
3065 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3067 char coord_mask[6];
3068 shader_glsl_write_mask_to_str(mask, coord_mask);
3069 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3070 "T%u%s", sampler_idx, coord_mask);
3071 } else {
3072 glsl_src_param_t coord_param;
3073 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3074 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3076 glsl_src_param_t bias;
3077 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3078 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3079 "%s", coord_param.param_str);
3080 } else {
3081 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3082 "%s", coord_param.param_str);
3087 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3089 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3090 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3091 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3092 glsl_sample_function_t sample_function;
3093 glsl_src_param_t coord_param, dx_param, dy_param;
3094 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3095 DWORD sampler_idx;
3096 DWORD swizzle = ins->src[1].swizzle;
3098 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3100 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3101 return shader_glsl_tex(ins);
3104 sampler_idx = ins->src[1].reg.idx;
3105 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3106 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3107 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3110 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3111 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3112 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3113 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3115 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3116 "%s", coord_param.param_str);
3119 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3121 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3122 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3123 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3124 glsl_sample_function_t sample_function;
3125 glsl_src_param_t coord_param, lod_param;
3126 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3127 DWORD sampler_idx;
3128 DWORD swizzle = ins->src[1].swizzle;
3130 sampler_idx = ins->src[1].reg.idx;
3131 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3132 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3133 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3135 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3136 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3138 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3140 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3141 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3143 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
3144 * However, they seem to work just fine in fragment shaders as well. */
3145 WARN("Using %s in fragment shader.\n", sample_function.name);
3147 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3148 "%s", coord_param.param_str);
3151 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3153 /* FIXME: Make this work for more than just 2D textures */
3154 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3155 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3157 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3159 char dst_mask[6];
3161 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3162 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3163 ins->dst[0].reg.idx, dst_mask);
3164 } else {
3165 DWORD reg = ins->src[0].reg.idx;
3166 DWORD src_mod = ins->src[0].modifiers;
3167 char dst_swizzle[6];
3169 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3171 if (src_mod == WINED3DSPSM_DZ) {
3172 glsl_src_param_t div_param;
3173 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3174 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3176 if (mask_size > 1) {
3177 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3178 } else {
3179 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3181 } else if (src_mod == WINED3DSPSM_DW) {
3182 glsl_src_param_t div_param;
3183 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3184 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3186 if (mask_size > 1) {
3187 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3188 } else {
3189 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3191 } else {
3192 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3197 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3198 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3199 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3200 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3202 glsl_src_param_t src0_param;
3203 glsl_sample_function_t sample_function;
3204 DWORD sampler_idx = ins->dst[0].reg.idx;
3205 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3206 UINT mask_size;
3208 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3210 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3211 * scalar, and projected sampling would require 4.
3213 * It is a dependent read - not valid with conditional NP2 textures
3215 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3216 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3218 switch(mask_size)
3220 case 1:
3221 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3222 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3223 break;
3225 case 2:
3226 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3227 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3228 break;
3230 case 3:
3231 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3232 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3233 break;
3235 default:
3236 FIXME("Unexpected mask size %u\n", mask_size);
3237 break;
3241 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3242 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3243 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3245 glsl_src_param_t src0_param;
3246 DWORD dstreg = ins->dst[0].reg.idx;
3247 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3248 DWORD dst_mask;
3249 unsigned int mask_size;
3251 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3252 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3253 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3255 if (mask_size > 1) {
3256 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3257 } else {
3258 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3262 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3263 * Calculate the depth as dst.x / dst.y */
3264 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3266 glsl_dst_param_t dst_param;
3268 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3270 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3271 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3272 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3273 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3274 * >= 1.0 or < 0.0
3276 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3277 dst_param.reg_name, dst_param.reg_name);
3280 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3281 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3282 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3283 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3285 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3287 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3288 DWORD dstreg = ins->dst[0].reg.idx;
3289 glsl_src_param_t src0_param;
3291 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3293 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3294 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3297 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3298 * Calculate the 1st of a 2-row matrix multiplication. */
3299 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3301 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3302 DWORD reg = ins->dst[0].reg.idx;
3303 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3304 glsl_src_param_t src0_param;
3306 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3307 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3310 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3311 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3312 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3314 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3315 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3316 DWORD reg = ins->dst[0].reg.idx;
3317 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3318 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3319 glsl_src_param_t src0_param;
3321 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3322 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3323 current_state->texcoord_w[current_state->current_row++] = reg;
3326 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3328 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3329 DWORD reg = ins->dst[0].reg.idx;
3330 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3331 glsl_src_param_t src0_param;
3332 glsl_sample_function_t sample_function;
3334 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3335 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3337 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3339 /* Sample the texture using the calculated coordinates */
3340 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3343 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3344 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3345 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3347 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3348 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3349 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3350 glsl_src_param_t src0_param;
3351 DWORD reg = ins->dst[0].reg.idx;
3352 glsl_sample_function_t sample_function;
3354 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3355 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3357 /* Dependent read, not valid with conditional NP2 */
3358 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3360 /* Sample the texture using the calculated coordinates */
3361 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3363 current_state->current_row = 0;
3366 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3367 * Perform the 3rd row of a 3x3 matrix multiply */
3368 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3370 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3371 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3372 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3373 glsl_src_param_t src0_param;
3374 char dst_mask[6];
3375 DWORD reg = ins->dst[0].reg.idx;
3377 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3379 shader_glsl_append_dst(ins->ctx->buffer, ins);
3380 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3381 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3383 current_state->current_row = 0;
3386 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3387 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3388 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3390 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3391 DWORD reg = ins->dst[0].reg.idx;
3392 glsl_src_param_t src0_param;
3393 glsl_src_param_t src1_param;
3394 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3395 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3396 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3397 glsl_sample_function_t sample_function;
3399 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3400 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3402 /* Perform the last matrix multiply operation */
3403 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3404 /* Reflection calculation */
3405 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3407 /* Dependent read, not valid with conditional NP2 */
3408 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3410 /* Sample the texture */
3411 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3413 current_state->current_row = 0;
3416 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3417 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3418 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3420 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3421 DWORD reg = ins->dst[0].reg.idx;
3422 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3423 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3424 glsl_src_param_t src0_param;
3425 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3426 glsl_sample_function_t sample_function;
3428 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3430 /* Perform the last matrix multiply operation */
3431 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3433 /* Construct the eye-ray vector from w coordinates */
3434 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3435 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3436 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3438 /* Dependent read, not valid with conditional NP2 */
3439 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3441 /* Sample the texture using the calculated coordinates */
3442 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3444 current_state->current_row = 0;
3447 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3448 * Apply a fake bump map transform.
3449 * texbem is pshader <= 1.3 only, this saves a few version checks
3451 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3453 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3454 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3455 glsl_sample_function_t sample_function;
3456 glsl_src_param_t coord_param;
3457 DWORD sampler_idx;
3458 DWORD mask;
3459 DWORD flags;
3460 char coord_mask[6];
3462 sampler_idx = ins->dst[0].reg.idx;
3463 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3465 /* Dependent read, not valid with conditional NP2 */
3466 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3467 mask = sample_function.coord_mask;
3469 shader_glsl_write_mask_to_str(mask, coord_mask);
3471 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3472 * so we can't let the GL handle this.
3474 if (flags & WINED3DTTFF_PROJECTED) {
3475 DWORD div_mask=0;
3476 char coord_div_mask[3];
3477 switch (flags & ~WINED3DTTFF_PROJECTED) {
3478 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3479 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3480 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3481 case WINED3DTTFF_COUNT4:
3482 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3484 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3485 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3488 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3490 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3491 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3492 coord_param.param_str, coord_mask);
3494 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3496 glsl_src_param_t luminance_param;
3497 glsl_dst_param_t dst_param;
3499 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3500 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3502 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3503 dst_param.reg_name, dst_param.mask_str,
3504 luminance_param.param_str, sampler_idx, sampler_idx);
3508 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3510 glsl_src_param_t src0_param, src1_param;
3511 DWORD sampler_idx = ins->dst[0].reg.idx;
3513 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3514 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3516 shader_glsl_append_dst(ins->ctx->buffer, ins);
3517 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3518 src0_param.param_str, sampler_idx, src1_param.param_str);
3521 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3522 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3523 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3525 glsl_src_param_t src0_param;
3526 DWORD sampler_idx = ins->dst[0].reg.idx;
3527 glsl_sample_function_t sample_function;
3529 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3531 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3532 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3533 "%s.wx", src0_param.reg_name);
3536 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3537 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3538 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3540 glsl_src_param_t src0_param;
3541 DWORD sampler_idx = ins->dst[0].reg.idx;
3542 glsl_sample_function_t sample_function;
3544 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3546 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3547 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3548 "%s.yz", src0_param.reg_name);
3551 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3552 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3553 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3555 glsl_src_param_t src0_param;
3556 DWORD sampler_idx = ins->dst[0].reg.idx;
3557 glsl_sample_function_t sample_function;
3559 /* Dependent read, not valid with conditional NP2 */
3560 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3561 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3563 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3564 "%s", src0_param.param_str);
3567 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3568 * If any of the first 3 components are < 0, discard this pixel */
3569 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3571 glsl_dst_param_t dst_param;
3573 /* The argument is a destination parameter, and no writemasks are allowed */
3574 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3575 if (ins->ctx->reg_maps->shader_version.major >= 2)
3577 /* 2.0 shaders compare all 4 components in texkill */
3578 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3579 } else {
3580 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3581 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3582 * 4 components are defined, only the first 3 are used
3584 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3588 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3589 * dst = dot2(src0, src1) + src2 */
3590 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3592 glsl_src_param_t src0_param;
3593 glsl_src_param_t src1_param;
3594 glsl_src_param_t src2_param;
3595 DWORD write_mask;
3596 unsigned int mask_size;
3598 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3599 mask_size = shader_glsl_get_write_mask_size(write_mask);
3601 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3602 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3603 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3605 if (mask_size > 1) {
3606 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3607 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3608 } else {
3609 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3610 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3614 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3615 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3616 enum vertexprocessing_mode vertexprocessing)
3618 unsigned int i;
3619 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3620 WORD map = reg_maps->input_registers;
3622 for (i = 0; map; map >>= 1, ++i)
3624 const char *semantic_name;
3625 UINT semantic_idx;
3626 char reg_mask[6];
3628 /* Unused */
3629 if (!(map & 1)) continue;
3631 semantic_name = input_signature[i].semantic_name;
3632 semantic_idx = input_signature[i].semantic_idx;
3633 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3635 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3637 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3638 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3639 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3640 else
3641 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3642 This->input_reg_map[i], reg_mask, reg_mask);
3644 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3646 if (semantic_idx == 0)
3647 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3648 This->input_reg_map[i], reg_mask, reg_mask);
3649 else if (semantic_idx == 1)
3650 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3651 This->input_reg_map[i], reg_mask, reg_mask);
3652 else
3653 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3654 This->input_reg_map[i], reg_mask, reg_mask);
3656 else
3658 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3659 This->input_reg_map[i], reg_mask, reg_mask);
3664 /*********************************************
3665 * Vertex Shader Specific Code begins here
3666 ********************************************/
3668 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3669 glsl_program_key_t key;
3671 key.vshader = entry->vshader;
3672 key.pshader = entry->pshader;
3673 key.vs_args = entry->vs_args;
3674 key.ps_args = entry->ps_args;
3676 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3678 ERR("Failed to insert program entry.\n");
3682 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3683 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3684 struct ps_compile_args *ps_args) {
3685 struct wine_rb_entry *entry;
3686 glsl_program_key_t key;
3688 key.vshader = vshader;
3689 key.pshader = pshader;
3690 key.vs_args = *vs_args;
3691 key.ps_args = *ps_args;
3693 entry = wine_rb_get(&priv->program_lookup, &key);
3694 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3697 /* GL locking is done by the caller */
3698 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3699 struct glsl_shader_prog_link *entry)
3701 glsl_program_key_t key;
3703 key.vshader = entry->vshader;
3704 key.pshader = entry->pshader;
3705 key.vs_args = entry->vs_args;
3706 key.ps_args = entry->ps_args;
3707 wine_rb_remove(&priv->program_lookup, &key);
3709 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3710 if (entry->vshader) list_remove(&entry->vshader_entry);
3711 if (entry->pshader) list_remove(&entry->pshader_entry);
3712 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3713 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3714 HeapFree(GetProcessHeap(), 0, entry);
3717 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3718 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3719 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3721 unsigned int i, j;
3722 const char *semantic_name_in;
3723 UINT semantic_idx_in;
3724 DWORD *set;
3725 DWORD in_idx;
3726 unsigned int in_count = vec4_varyings(3, gl_info);
3727 char reg_mask[6];
3728 char destination[50];
3729 WORD input_map, output_map;
3731 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3733 input_map = reg_maps_in->input_registers;
3734 for (i = 0; input_map; input_map >>= 1, ++i)
3736 if (!(input_map & 1)) continue;
3738 in_idx = map[i];
3739 /* Declared, but not read register */
3740 if (in_idx == ~0U) continue;
3741 if (in_idx >= (in_count + 2))
3743 FIXME("More input varyings declared than supported, expect issues.\n");
3744 continue;
3747 if (in_idx == in_count) {
3748 sprintf(destination, "gl_FrontColor");
3749 } else if (in_idx == in_count + 1) {
3750 sprintf(destination, "gl_FrontSecondaryColor");
3751 } else {
3752 sprintf(destination, "IN[%u]", in_idx);
3755 semantic_name_in = input_signature[i].semantic_name;
3756 semantic_idx_in = input_signature[i].semantic_idx;
3757 set[in_idx] = ~0U;
3759 output_map = reg_maps_out->output_registers;
3760 for (j = 0; output_map; output_map >>= 1, ++j)
3762 DWORD mask;
3764 if (!(output_map & 1)
3765 || semantic_idx_in != output_signature[j].semantic_idx
3766 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3767 || !(mask = input_signature[i].mask & output_signature[j].mask))
3768 continue;
3770 set[in_idx] = mask;
3771 shader_glsl_write_mask_to_str(mask, reg_mask);
3773 shader_addline(buffer, "%s%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3774 destination, reg_mask, j, reg_mask);
3778 for (i = 0; i < in_count + 2; ++i)
3780 unsigned int size;
3782 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3783 continue;
3785 if (set[i] == ~0U) set[i] = 0;
3787 size = 0;
3788 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3789 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3790 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3791 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3792 reg_mask[size] = '\0';
3794 if (i == in_count) sprintf(destination, "gl_FrontColor");
3795 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3796 else sprintf(destination, "IN[%u]", i);
3798 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3799 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3802 HeapFree(GetProcessHeap(), 0, set);
3805 /* GL locking is done by the caller */
3806 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3807 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3809 GLhandleARB ret = 0;
3810 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3811 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3812 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3813 unsigned int i;
3814 const char *semantic_name;
3815 UINT semantic_idx;
3816 char reg_mask[6];
3817 const struct wined3d_shader_signature_element *output_signature = vs->baseShader.output_signature;
3818 WORD map = vs->baseShader.reg_maps.output_registers;
3820 shader_buffer_clear(buffer);
3822 shader_addline(buffer, "#version 120\n");
3823 shader_addline(buffer, "const float FLT_MAX = 1e38;\n");
3825 if (ps_major < 3)
3827 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3829 for (i = 0; map; map >>= 1, ++i)
3831 DWORD write_mask;
3833 if (!(map & 1)) continue;
3835 semantic_name = output_signature[i].semantic_name;
3836 semantic_idx = output_signature[i].semantic_idx;
3837 write_mask = output_signature[i].mask;
3838 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3840 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3842 if (semantic_idx == 0)
3843 shader_addline(buffer, "gl_FrontColor%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3844 reg_mask, i, reg_mask);
3845 else if (semantic_idx == 1)
3846 shader_addline(buffer, "gl_FrontSecondaryColor%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3847 reg_mask, i, reg_mask);
3849 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3851 shader_addline(buffer, "gl_Position%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3852 reg_mask, i, reg_mask);
3854 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3856 if (semantic_idx < 8)
3858 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3859 write_mask |= WINED3DSP_WRITEMASK_3;
3861 shader_addline(buffer, "gl_TexCoord[%u]%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3862 semantic_idx, reg_mask, i, reg_mask);
3863 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3864 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3867 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3869 shader_addline(buffer, "gl_PointSize = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3871 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3873 shader_addline(buffer, "gl_FogFragCoord = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3876 shader_addline(buffer, "}\n");
3879 else
3881 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3882 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3883 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3885 /* First, sort out position and point size. Those are not passed to the pixel shader */
3886 for (i = 0; map; map >>= 1, ++i)
3888 if (!(map & 1)) continue;
3890 semantic_name = output_signature[i].semantic_name;
3891 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3893 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3895 shader_addline(buffer, "gl_Position%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3896 reg_mask, i, reg_mask);
3898 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3900 shader_addline(buffer, "gl_PointSize = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3904 /* Then, fix the pixel shader input */
3905 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3906 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3908 shader_addline(buffer, "}\n");
3911 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3912 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3913 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
3914 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
3915 GL_EXTCALL(glCompileShaderARB(ret));
3916 checkGLcall("glCompileShaderARB(ret)");
3918 return ret;
3921 /* GL locking is done by the caller */
3922 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3923 GLhandleARB programId, char prefix)
3925 const local_constant *lconst;
3926 GLint tmp_loc;
3927 const float *value;
3928 char glsl_name[8];
3930 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3931 value = (const float *)lconst->value;
3932 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3933 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3934 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3936 checkGLcall("Hardcoding local constants");
3939 /* GL locking is done by the caller */
3940 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3941 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3942 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3944 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3945 const struct wined3d_gl_info *gl_info = context->gl_info;
3946 CONST DWORD *function = This->baseShader.function;
3947 struct shader_glsl_ctx_priv priv_ctx;
3949 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3950 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3952 memset(&priv_ctx, 0, sizeof(priv_ctx));
3953 priv_ctx.cur_ps_args = args;
3954 priv_ctx.cur_np2fixup_info = np2fixup_info;
3956 shader_addline(buffer, "#version 120\n");
3958 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
3960 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3962 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3964 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3965 * drivers write a warning if we don't do so
3967 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3969 if (gl_info->supported[EXT_GPU_SHADER4])
3971 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3974 /* Base Declarations */
3975 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3977 /* Pack 3.0 inputs */
3978 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3980 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
3981 This->baseShader.input_signature, reg_maps, args->vp_mode);
3984 /* Base Shader Body */
3985 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3987 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3988 if (reg_maps->shader_version.major < 2)
3990 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3991 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3994 if (args->srgb_correction)
3996 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
3997 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
3998 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
3999 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4000 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4001 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4003 /* Pixel shader < 3.0 do not replace the fog stage.
4004 * This implements linear fog computation and blending.
4005 * TODO: non linear fog
4006 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4007 * -1/(e-s) and e/(e-s) respectively.
4009 if (reg_maps->shader_version.major < 3)
4011 switch(args->fog) {
4012 case FOG_OFF: break;
4013 case FOG_LINEAR:
4014 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4015 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4016 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4017 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4018 break;
4019 case FOG_EXP:
4020 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4021 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4022 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4023 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4024 break;
4025 case FOG_EXP2:
4026 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4027 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4028 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4029 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4030 break;
4034 shader_addline(buffer, "}\n");
4036 TRACE("Compiling shader object %u\n", shader_obj);
4037 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4038 GL_EXTCALL(glCompileShaderARB(shader_obj));
4039 print_glsl_info_log(gl_info, shader_obj);
4041 /* Store the shader object */
4042 return shader_obj;
4045 /* GL locking is done by the caller */
4046 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4047 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4048 const struct vs_compile_args *args)
4050 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4051 const struct wined3d_gl_info *gl_info = context->gl_info;
4052 CONST DWORD *function = This->baseShader.function;
4053 struct shader_glsl_ctx_priv priv_ctx;
4055 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4056 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4058 shader_addline(buffer, "#version 120\n");
4060 if (gl_info->supported[EXT_GPU_SHADER4])
4062 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4065 memset(&priv_ctx, 0, sizeof(priv_ctx));
4066 priv_ctx.cur_vs_args = args;
4068 /* Base Declarations */
4069 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4071 /* Base Shader Body */
4072 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4074 /* Unpack outputs */
4075 shader_addline(buffer, "order_ps_input(OUT);\n");
4077 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4078 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4079 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4080 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4082 if(args->fog_src == VS_FOG_Z) {
4083 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4084 } else if (!reg_maps->fog) {
4085 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4088 /* Write the final position.
4090 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4091 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4092 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4093 * contains 1.0 to allow a mad.
4095 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4096 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4097 if(args->clip_enabled) {
4098 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4101 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4103 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4104 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4105 * which is the same as z = z * 2 - w.
4107 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4109 shader_addline(buffer, "}\n");
4111 TRACE("Compiling shader object %u\n", shader_obj);
4112 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4113 GL_EXTCALL(glCompileShaderARB(shader_obj));
4114 print_glsl_info_log(gl_info, shader_obj);
4116 return shader_obj;
4119 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4120 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4121 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4123 UINT i;
4124 DWORD new_size;
4125 struct glsl_ps_compiled_shader *new_array;
4126 struct glsl_pshader_private *shader_data;
4127 struct ps_np2fixup_info *np2fixup = NULL;
4128 GLhandleARB ret;
4130 if (!shader->baseShader.backend_data)
4132 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4133 if (!shader->baseShader.backend_data)
4135 ERR("Failed to allocate backend data.\n");
4136 return 0;
4139 shader_data = shader->baseShader.backend_data;
4141 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4142 * so a linear search is more performant than a hashmap or a binary search
4143 * (cache coherency etc)
4145 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4146 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4147 if(args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4148 return shader_data->gl_shaders[i].prgId;
4152 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4153 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4154 if (shader_data->num_gl_shaders)
4156 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4157 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4158 new_size * sizeof(*shader_data->gl_shaders));
4159 } else {
4160 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4161 new_size = 1;
4164 if(!new_array) {
4165 ERR("Out of memory\n");
4166 return 0;
4168 shader_data->gl_shaders = new_array;
4169 shader_data->shader_array_size = new_size;
4172 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4174 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4175 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4177 pixelshader_update_samplers(&shader->baseShader.reg_maps,
4178 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4180 shader_buffer_clear(buffer);
4181 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4182 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4183 *np2fixup_info = np2fixup;
4185 return ret;
4188 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4189 const DWORD use_map) {
4190 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4191 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4192 return stored->fog_src == new->fog_src;
4195 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4196 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4197 const struct vs_compile_args *args)
4199 UINT i;
4200 DWORD new_size;
4201 struct glsl_vs_compiled_shader *new_array;
4202 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4203 struct glsl_vshader_private *shader_data;
4204 GLhandleARB ret;
4206 if (!shader->baseShader.backend_data)
4208 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4209 if (!shader->baseShader.backend_data)
4211 ERR("Failed to allocate backend data.\n");
4212 return 0;
4215 shader_data = shader->baseShader.backend_data;
4217 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4218 * so a linear search is more performant than a hashmap or a binary search
4219 * (cache coherency etc)
4221 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4222 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4223 return shader_data->gl_shaders[i].prgId;
4227 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4229 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4230 if (shader_data->num_gl_shaders)
4232 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4233 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4234 new_size * sizeof(*shader_data->gl_shaders));
4235 } else {
4236 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4237 new_size = 1;
4240 if(!new_array) {
4241 ERR("Out of memory\n");
4242 return 0;
4244 shader_data->gl_shaders = new_array;
4245 shader_data->shader_array_size = new_size;
4248 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4250 shader_buffer_clear(buffer);
4251 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4252 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4254 return ret;
4257 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4258 * It sets the programId on the current StateBlock (because it should be called
4259 * inside of the DrawPrimitive() part of the render loop).
4261 * If a program for the given combination does not exist, create one, and store
4262 * the program in the hash table. If it creates a program, it will link the
4263 * given objects, too.
4266 /* GL locking is done by the caller */
4267 static void set_glsl_shader_program(const struct wined3d_context *context,
4268 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4270 IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
4271 IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
4272 const struct wined3d_gl_info *gl_info = context->gl_info;
4273 struct shader_glsl_priv *priv = device->shader_priv;
4274 struct glsl_shader_prog_link *entry = NULL;
4275 GLhandleARB programId = 0;
4276 GLhandleARB reorder_shader_id = 0;
4277 unsigned int i;
4278 char glsl_name[8];
4279 struct ps_compile_args ps_compile_args;
4280 struct vs_compile_args vs_compile_args;
4282 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4283 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4285 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4286 if (entry) {
4287 priv->glsl_program = entry;
4288 return;
4291 /* If we get to this point, then no matching program exists, so we create one */
4292 programId = GL_EXTCALL(glCreateProgramObjectARB());
4293 TRACE("Created new GLSL shader program %u\n", programId);
4295 /* Create the entry */
4296 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4297 entry->programId = programId;
4298 entry->vshader = vshader;
4299 entry->pshader = pshader;
4300 entry->vs_args = vs_compile_args;
4301 entry->ps_args = ps_compile_args;
4302 entry->constant_version = 0;
4303 entry->np2Fixup_info = NULL;
4304 /* Add the hash table entry */
4305 add_glsl_program_entry(priv, entry);
4307 /* Set the current program */
4308 priv->glsl_program = entry;
4310 /* Attach GLSL vshader */
4311 if (vshader)
4313 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4314 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4315 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4316 char tmp_name[10];
4318 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4319 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4320 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4321 checkGLcall("glAttachObjectARB");
4322 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4323 * is destroyed
4325 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4327 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4328 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4329 checkGLcall("glAttachObjectARB");
4331 /* Bind vertex attributes to a corresponding index number to match
4332 * the same index numbers as ARB_vertex_programs (makes loading
4333 * vertex attributes simpler). With this method, we can use the
4334 * exact same code to load the attributes later for both ARB and
4335 * GLSL shaders.
4337 * We have to do this here because we need to know the Program ID
4338 * in order to make the bindings work, and it has to be done prior
4339 * to linking the GLSL program. */
4340 for (i = 0; map; map >>= 1, ++i)
4342 if (!(map & 1)) continue;
4344 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4345 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4347 checkGLcall("glBindAttribLocationARB");
4349 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4352 /* Attach GLSL pshader */
4353 if (pshader)
4355 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4356 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4357 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4358 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4359 checkGLcall("glAttachObjectARB");
4361 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4364 /* Link the program */
4365 TRACE("Linking GLSL shader program %u\n", programId);
4366 GL_EXTCALL(glLinkProgramARB(programId));
4367 shader_glsl_validate_link(gl_info, programId);
4369 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4370 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4371 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4373 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4374 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4376 for (i = 0; i < MAX_CONST_I; ++i)
4378 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4379 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4381 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4382 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4383 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4385 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4386 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4388 for (i = 0; i < MAX_CONST_I; ++i)
4390 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4391 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4394 if(pshader) {
4395 char name[32];
4397 for(i = 0; i < MAX_TEXTURES; i++) {
4398 sprintf(name, "bumpenvmat%u", i);
4399 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4400 sprintf(name, "luminancescale%u", i);
4401 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4402 sprintf(name, "luminanceoffset%u", i);
4403 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4406 if (ps_compile_args.np2_fixup) {
4407 if (entry->np2Fixup_info) {
4408 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4409 } else {
4410 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4415 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4416 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4417 checkGLcall("Find glsl program uniform locations");
4419 if (pshader
4420 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4421 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4423 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4424 entry->vertex_color_clamp = GL_FALSE;
4425 } else {
4426 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4429 /* Set the shader to allow uniform loading on it */
4430 GL_EXTCALL(glUseProgramObjectARB(programId));
4431 checkGLcall("glUseProgramObjectARB(programId)");
4433 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4434 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4435 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4436 * vertex shader with fixed function pixel processing is used we make sure that the card
4437 * supports enough samplers to allow the max number of vertex samplers with all possible
4438 * fixed function fragment processing setups. So once the program is linked these samplers
4439 * won't change.
4441 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4442 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4444 /* If the local constants do not have to be loaded with the environment constants,
4445 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4446 * later
4448 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4450 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4452 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4454 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4458 /* GL locking is done by the caller */
4459 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4461 GLhandleARB program_id;
4462 GLhandleARB vshader_id, pshader_id;
4463 const char *blt_pshader;
4465 static const char *blt_vshader =
4466 "#version 120\n"
4467 "void main(void)\n"
4468 "{\n"
4469 " gl_Position = gl_Vertex;\n"
4470 " gl_FrontColor = vec4(1.0);\n"
4471 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4472 "}\n";
4474 static const char * const blt_pshaders_full[tex_type_count] =
4476 /* tex_1d */
4477 NULL,
4478 /* tex_2d */
4479 "#version 120\n"
4480 "uniform sampler2D sampler;\n"
4481 "void main(void)\n"
4482 "{\n"
4483 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4484 "}\n",
4485 /* tex_3d */
4486 NULL,
4487 /* tex_cube */
4488 "#version 120\n"
4489 "uniform samplerCube sampler;\n"
4490 "void main(void)\n"
4491 "{\n"
4492 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4493 "}\n",
4494 /* tex_rect */
4495 "#version 120\n"
4496 "#extension GL_ARB_texture_rectangle : enable\n"
4497 "uniform sampler2DRect sampler;\n"
4498 "void main(void)\n"
4499 "{\n"
4500 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4501 "}\n",
4504 static const char * const blt_pshaders_masked[tex_type_count] =
4506 /* tex_1d */
4507 NULL,
4508 /* tex_2d */
4509 "#version 120\n"
4510 "uniform sampler2D sampler;\n"
4511 "uniform vec4 mask;\n"
4512 "void main(void)\n"
4513 "{\n"
4514 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4515 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4516 "}\n",
4517 /* tex_3d */
4518 NULL,
4519 /* tex_cube */
4520 "#version 120\n"
4521 "uniform samplerCube sampler;\n"
4522 "uniform vec4 mask;\n"
4523 "void main(void)\n"
4524 "{\n"
4525 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4526 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4527 "}\n",
4528 /* tex_rect */
4529 "#version 120\n"
4530 "#extension GL_ARB_texture_rectangle : enable\n"
4531 "uniform sampler2DRect sampler;\n"
4532 "uniform vec4 mask;\n"
4533 "void main(void)\n"
4534 "{\n"
4535 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4536 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4537 "}\n",
4540 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4541 if (!blt_pshader)
4543 FIXME("tex_type %#x not supported\n", tex_type);
4544 tex_type = tex_2d;
4547 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4548 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, &blt_vshader, NULL));
4549 GL_EXTCALL(glCompileShaderARB(vshader_id));
4551 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4552 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshader, NULL));
4553 GL_EXTCALL(glCompileShaderARB(pshader_id));
4555 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4556 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4557 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4558 GL_EXTCALL(glLinkProgramARB(program_id));
4560 shader_glsl_validate_link(gl_info, program_id);
4562 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4563 * is destroyed
4565 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4566 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4567 return program_id;
4570 /* GL locking is done by the caller */
4571 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4573 const struct wined3d_gl_info *gl_info = context->gl_info;
4574 IWineD3DDeviceImpl *device = context->swapchain->device;
4575 struct shader_glsl_priv *priv = device->shader_priv;
4576 GLhandleARB program_id = 0;
4577 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4579 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4581 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4582 else priv->glsl_program = NULL;
4584 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4586 if (old_vertex_color_clamp != current_vertex_color_clamp)
4588 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4590 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4591 checkGLcall("glClampColorARB");
4593 else
4595 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4599 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4600 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4601 GL_EXTCALL(glUseProgramObjectARB(program_id));
4602 checkGLcall("glUseProgramObjectARB");
4604 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4605 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4606 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4607 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4609 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4613 /* GL locking is done by the caller */
4614 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface,
4615 enum tex_types tex_type, const SIZE *ds_mask_size)
4617 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4618 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4619 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4620 struct shader_glsl_priv *priv = This->shader_priv;
4621 GLhandleARB *blt_program;
4622 GLint loc;
4624 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4625 if (!*blt_program)
4627 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4628 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4629 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4630 GL_EXTCALL(glUniform1iARB(loc, 0));
4632 else
4634 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4637 if (masked)
4639 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4640 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4644 /* GL locking is done by the caller */
4645 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4646 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4647 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4648 struct shader_glsl_priv *priv = This->shader_priv;
4649 GLhandleARB program_id;
4651 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4652 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4654 GL_EXTCALL(glUseProgramObjectARB(program_id));
4655 checkGLcall("glUseProgramObjectARB");
4658 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4659 const struct list *linked_programs;
4660 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4661 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4662 struct shader_glsl_priv *priv = device->shader_priv;
4663 const struct wined3d_gl_info *gl_info;
4664 struct wined3d_context *context;
4666 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4667 * can be called from IWineD3DBaseShader::Release
4669 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4671 if(pshader) {
4672 struct glsl_pshader_private *shader_data;
4673 shader_data = This->baseShader.backend_data;
4674 if(!shader_data || shader_data->num_gl_shaders == 0)
4676 HeapFree(GetProcessHeap(), 0, shader_data);
4677 This->baseShader.backend_data = NULL;
4678 return;
4681 context = context_acquire(device, NULL);
4682 gl_info = context->gl_info;
4684 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4686 ENTER_GL();
4687 shader_glsl_select(context, FALSE, FALSE);
4688 LEAVE_GL();
4690 } else {
4691 struct glsl_vshader_private *shader_data;
4692 shader_data = This->baseShader.backend_data;
4693 if(!shader_data || shader_data->num_gl_shaders == 0)
4695 HeapFree(GetProcessHeap(), 0, shader_data);
4696 This->baseShader.backend_data = NULL;
4697 return;
4700 context = context_acquire(device, NULL);
4701 gl_info = context->gl_info;
4703 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4705 ENTER_GL();
4706 shader_glsl_select(context, FALSE, FALSE);
4707 LEAVE_GL();
4711 linked_programs = &This->baseShader.linked_programs;
4713 TRACE("Deleting linked programs\n");
4714 if (linked_programs->next) {
4715 struct glsl_shader_prog_link *entry, *entry2;
4717 ENTER_GL();
4718 if(pshader) {
4719 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4720 delete_glsl_program_entry(priv, gl_info, entry);
4722 } else {
4723 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4724 delete_glsl_program_entry(priv, gl_info, entry);
4727 LEAVE_GL();
4730 if(pshader) {
4731 UINT i;
4732 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
4734 ENTER_GL();
4735 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4736 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4737 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4738 checkGLcall("glDeleteObjectARB");
4740 LEAVE_GL();
4741 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4743 else
4745 UINT i;
4746 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
4748 ENTER_GL();
4749 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4750 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4751 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4752 checkGLcall("glDeleteObjectARB");
4754 LEAVE_GL();
4755 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4758 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
4759 This->baseShader.backend_data = NULL;
4761 context_release(context);
4764 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4766 const glsl_program_key_t *k = key;
4767 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4768 const struct glsl_shader_prog_link, program_lookup_entry);
4769 int cmp;
4771 if (k->vshader > prog->vshader) return 1;
4772 else if (k->vshader < prog->vshader) return -1;
4774 if (k->pshader > prog->pshader) return 1;
4775 else if (k->pshader < prog->pshader) return -1;
4777 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4778 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4780 return 0;
4783 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4785 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4786 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4788 if (!mem)
4790 ERR("Failed to allocate memory\n");
4791 return FALSE;
4794 heap->entries = mem;
4795 heap->entries[1].version = 0;
4796 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4797 heap->size = 1;
4799 return TRUE;
4802 static void constant_heap_free(struct constant_heap *heap)
4804 HeapFree(GetProcessHeap(), 0, heap->entries);
4807 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4809 wined3d_rb_alloc,
4810 wined3d_rb_realloc,
4811 wined3d_rb_free,
4812 glsl_program_key_compare,
4815 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4816 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4817 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4818 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4819 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4820 gl_info->limits.glsl_ps_float_constants)) + 1;
4822 if (!shader_buffer_init(&priv->shader_buffer))
4824 ERR("Failed to initialize shader buffer.\n");
4825 goto fail;
4828 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4829 if (!priv->stack)
4831 ERR("Failed to allocate memory.\n");
4832 goto fail;
4835 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4837 ERR("Failed to initialize vertex shader constant heap\n");
4838 goto fail;
4841 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4843 ERR("Failed to initialize pixel shader constant heap\n");
4844 goto fail;
4847 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4849 ERR("Failed to initialize rbtree.\n");
4850 goto fail;
4853 priv->next_constant_version = 1;
4855 This->shader_priv = priv;
4856 return WINED3D_OK;
4858 fail:
4859 constant_heap_free(&priv->pconst_heap);
4860 constant_heap_free(&priv->vconst_heap);
4861 HeapFree(GetProcessHeap(), 0, priv->stack);
4862 shader_buffer_free(&priv->shader_buffer);
4863 HeapFree(GetProcessHeap(), 0, priv);
4864 return E_OUTOFMEMORY;
4867 /* Context activation is done by the caller. */
4868 static void shader_glsl_free(IWineD3DDevice *iface) {
4869 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4870 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4871 struct shader_glsl_priv *priv = This->shader_priv;
4872 int i;
4874 ENTER_GL();
4875 for (i = 0; i < tex_type_count; ++i)
4877 if (priv->depth_blt_program_full[i])
4879 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4881 if (priv->depth_blt_program_masked[i])
4883 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4886 LEAVE_GL();
4888 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4889 constant_heap_free(&priv->pconst_heap);
4890 constant_heap_free(&priv->vconst_heap);
4891 HeapFree(GetProcessHeap(), 0, priv->stack);
4892 shader_buffer_free(&priv->shader_buffer);
4894 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4895 This->shader_priv = NULL;
4898 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4899 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4900 return FALSE;
4903 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4905 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4906 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4907 * on the version of NV_vertex_program.
4908 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4909 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4910 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4911 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4913 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4914 || gl_info->limits.arb_ps_instructions <= 512)
4915 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4916 else
4917 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4918 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4919 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4921 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4922 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4923 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4924 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4925 * in max native instructions. Intel and others also offer the info in this extension but they
4926 * don't support GLSL (at least on Windows).
4928 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4929 * of instructions is 512 or less we have to do with ps2.0 hardware.
4930 * NOTE: ps3.0 hardware requires 512 or more instructions but ati and nvidia offer 'enough' (1024 vs 4096) on their most basic ps3.0 hardware.
4932 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4933 || gl_info->limits.arb_ps_instructions <= 512)
4934 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4935 else
4936 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4938 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4940 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4941 * Direct3D minimum requirement.
4943 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4944 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4946 * The problem is that the refrast clamps temporary results in the shader to
4947 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4948 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4949 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4950 * offer a way to query this.
4952 pCaps->PixelShader1xMaxValue = 8.0;
4953 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4955 pCaps->VSClipping = TRUE;
4958 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4960 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4962 TRACE("Checking support for fixup:\n");
4963 dump_color_fixup_desc(fixup);
4966 /* We support everything except YUV conversions. */
4967 if (!is_complex_fixup(fixup))
4969 TRACE("[OK]\n");
4970 return TRUE;
4973 TRACE("[FAILED]\n");
4974 return FALSE;
4977 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4979 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4980 /* WINED3DSIH_ADD */ shader_glsl_arith,
4981 /* WINED3DSIH_BEM */ shader_glsl_bem,
4982 /* WINED3DSIH_BREAK */ shader_glsl_break,
4983 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4984 /* WINED3DSIH_BREAKP */ NULL,
4985 /* WINED3DSIH_CALL */ shader_glsl_call,
4986 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4987 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4988 /* WINED3DSIH_CND */ shader_glsl_cnd,
4989 /* WINED3DSIH_CRS */ shader_glsl_cross,
4990 /* WINED3DSIH_CUT */ NULL,
4991 /* WINED3DSIH_DCL */ NULL,
4992 /* WINED3DSIH_DEF */ NULL,
4993 /* WINED3DSIH_DEFB */ NULL,
4994 /* WINED3DSIH_DEFI */ NULL,
4995 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4996 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4997 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4998 /* WINED3DSIH_DST */ shader_glsl_dst,
4999 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5000 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5001 /* WINED3DSIH_ELSE */ shader_glsl_else,
5002 /* WINED3DSIH_EMIT */ NULL,
5003 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5004 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5005 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5006 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5007 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5008 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5009 /* WINED3DSIH_IADD */ NULL,
5010 /* WINED3DSIH_IF */ shader_glsl_if,
5011 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5012 /* WINED3DSIH_IGE */ NULL,
5013 /* WINED3DSIH_LABEL */ shader_glsl_label,
5014 /* WINED3DSIH_LIT */ shader_glsl_lit,
5015 /* WINED3DSIH_LOG */ shader_glsl_log,
5016 /* WINED3DSIH_LOGP */ shader_glsl_log,
5017 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5018 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5019 /* WINED3DSIH_LT */ NULL,
5020 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5021 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5022 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5023 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5024 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5025 /* WINED3DSIH_MAD */ shader_glsl_mad,
5026 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5027 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5028 /* WINED3DSIH_MOV */ shader_glsl_mov,
5029 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5030 /* WINED3DSIH_MUL */ shader_glsl_arith,
5031 /* WINED3DSIH_NOP */ NULL,
5032 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5033 /* WINED3DSIH_PHASE */ NULL,
5034 /* WINED3DSIH_POW */ shader_glsl_pow,
5035 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5036 /* WINED3DSIH_REP */ shader_glsl_rep,
5037 /* WINED3DSIH_RET */ shader_glsl_ret,
5038 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5039 /* WINED3DSIH_SETP */ NULL,
5040 /* WINED3DSIH_SGE */ shader_glsl_compare,
5041 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5042 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5043 /* WINED3DSIH_SLT */ shader_glsl_compare,
5044 /* WINED3DSIH_SUB */ shader_glsl_arith,
5045 /* WINED3DSIH_TEX */ shader_glsl_tex,
5046 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5047 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5048 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5049 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5050 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5051 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5052 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5053 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5054 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5055 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5056 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5057 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5058 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5059 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5060 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5061 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5062 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5063 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5064 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5065 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5066 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5069 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5070 SHADER_HANDLER hw_fct;
5072 /* Select handler */
5073 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5075 /* Unhandled opcode */
5076 if (!hw_fct)
5078 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5079 return;
5081 hw_fct(ins);
5083 shader_glsl_add_instruction_modifiers(ins);
5086 const shader_backend_t glsl_shader_backend = {
5087 shader_glsl_handle_instruction,
5088 shader_glsl_select,
5089 shader_glsl_select_depth_blt,
5090 shader_glsl_deselect_depth_blt,
5091 shader_glsl_update_float_vertex_constants,
5092 shader_glsl_update_float_pixel_constants,
5093 shader_glsl_load_constants,
5094 shader_glsl_load_np2fixup_constants,
5095 shader_glsl_destroy,
5096 shader_glsl_alloc,
5097 shader_glsl_free,
5098 shader_glsl_dirty_const,
5099 shader_glsl_get_caps,
5100 shader_glsl_color_fixup_supported,