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.
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 GLINFO_LOCATION (*gl_info)
44 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
45 #define WINED3D_GLSL_SAMPLE_RECT 0x2
46 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
62 } glsl_sample_function_t;
66 HEAP_NODE_TRAVERSE_LEFT,
67 HEAP_NODE_TRAVERSE_RIGHT,
79 struct constant_entry *entries;
80 unsigned int *positions;
84 /* GLSL shader private data */
85 struct shader_glsl_priv {
86 struct wined3d_shader_buffer shader_buffer;
87 struct wine_rb_tree program_lookup;
88 struct glsl_shader_prog_link *glsl_program;
89 struct constant_heap vconst_heap;
90 struct constant_heap pconst_heap;
92 GLhandleARB depth_blt_program[tex_type_count];
93 UINT next_constant_version;
96 /* Struct to maintain data about a linked GLSL program */
97 struct glsl_shader_prog_link {
98 struct wine_rb_entry program_lookup_entry;
99 struct list vshader_entry;
100 struct list pshader_entry;
101 GLhandleARB programId;
102 GLint *vuniformF_locations;
103 GLint *puniformF_locations;
104 GLint vuniformI_locations[MAX_CONST_I];
105 GLint puniformI_locations[MAX_CONST_I];
106 GLint posFixup_location;
107 GLint np2Fixup_location;
108 GLint bumpenvmat_location[MAX_TEXTURES];
109 GLint luminancescale_location[MAX_TEXTURES];
110 GLint luminanceoffset_location[MAX_TEXTURES];
111 GLint ycorrection_location;
112 GLenum vertex_color_clamp;
113 IWineD3DVertexShader *vshader;
114 IWineD3DPixelShader *pshader;
115 struct vs_compile_args vs_args;
116 struct ps_compile_args ps_args;
117 UINT constant_version;
118 const struct ps_np2fixup_info *np2Fixup_info;
122 IWineD3DVertexShader *vshader;
123 IWineD3DPixelShader *pshader;
124 struct ps_compile_args ps_args;
125 struct vs_compile_args vs_args;
126 } glsl_program_key_t;
128 struct shader_glsl_ctx_priv {
129 const struct vs_compile_args *cur_vs_args;
130 const struct ps_compile_args *cur_ps_args;
131 struct ps_np2fixup_info *cur_np2fixup_info;
134 struct glsl_ps_compiled_shader
136 struct ps_compile_args args;
137 struct ps_np2fixup_info np2fixup;
141 struct glsl_pshader_private
143 struct glsl_ps_compiled_shader *gl_shaders;
144 UINT num_gl_shaders, shader_array_size;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
153 struct glsl_vshader_private
155 struct glsl_vs_compiled_shader *gl_shaders;
156 UINT num_gl_shaders, shader_array_size;
159 /* Extract a line from the info log.
160 * Note that this modifies the source string. */
161 static char *get_info_log_line(char **ptr)
166 if (!(q = strstr(p, "\n")))
168 if (!*p) return NULL;
178 /** Prints the GLSL info log which will contain error messages if they exist */
179 /* GL locking is done by the caller */
180 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
182 int infologLength = 0;
187 static const char * const spam[] =
189 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
190 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
191 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
192 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
193 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
194 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
195 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
196 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
197 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
200 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
202 GL_EXTCALL(glGetObjectParameterivARB(obj,
203 GL_OBJECT_INFO_LOG_LENGTH_ARB,
206 /* A size of 1 is just a null-terminated string, so the log should be bigger than
207 * that if there are errors. */
208 if (infologLength > 1)
212 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
213 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
215 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
216 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
219 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
220 if(strcmp(infoLog, spam[i]) == 0) {
229 TRACE("Spam received from GLSL shader #%u:\n", obj);
230 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
234 FIXME("Error received from GLSL shader #%u:\n", obj);
235 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
237 HeapFree(GetProcessHeap(), 0, infoLog);
242 * Loads (pixel shader) samplers
244 /* GL locking is done by the caller */
245 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
246 DWORD *tex_unit_map, GLhandleARB programId)
250 char sampler_name[20];
252 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
253 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
254 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
255 if (name_loc != -1) {
256 DWORD mapped_unit = tex_unit_map[i];
257 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
259 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
260 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
261 checkGLcall("glUniform1iARB");
263 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
269 /* GL locking is done by the caller */
270 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
271 DWORD *tex_unit_map, GLhandleARB programId)
274 char sampler_name[20];
277 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
278 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
279 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
280 if (name_loc != -1) {
281 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
282 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
284 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
285 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
286 checkGLcall("glUniform1iARB");
288 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
294 /* GL locking is done by the caller */
295 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
296 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
299 unsigned int heap_idx = 1;
302 if (heap->entries[heap_idx].version <= version) return;
304 idx = heap->entries[heap_idx].idx;
305 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
306 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
308 while (stack_idx >= 0)
310 /* Note that we fall through to the next case statement. */
311 switch(stack[stack_idx])
313 case HEAP_NODE_TRAVERSE_LEFT:
315 unsigned int left_idx = heap_idx << 1;
316 if (left_idx < heap->size && heap->entries[left_idx].version > version)
319 idx = heap->entries[heap_idx].idx;
320 if (constant_locations[idx] != -1)
321 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
323 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
324 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
329 case HEAP_NODE_TRAVERSE_RIGHT:
331 unsigned int right_idx = (heap_idx << 1) + 1;
332 if (right_idx < heap->size && heap->entries[right_idx].version > version)
334 heap_idx = right_idx;
335 idx = heap->entries[heap_idx].idx;
336 if (constant_locations[idx] != -1)
337 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
339 stack[stack_idx++] = HEAP_NODE_POP;
340 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
353 checkGLcall("walk_constant_heap()");
356 /* GL locking is done by the caller */
357 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
359 GLfloat clamped_constant[4];
361 if (location == -1) return;
363 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
364 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
365 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
366 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
368 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
371 /* GL locking is done by the caller */
372 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
373 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
376 unsigned int heap_idx = 1;
379 if (heap->entries[heap_idx].version <= version) return;
381 idx = heap->entries[heap_idx].idx;
382 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
383 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
385 while (stack_idx >= 0)
387 /* Note that we fall through to the next case statement. */
388 switch(stack[stack_idx])
390 case HEAP_NODE_TRAVERSE_LEFT:
392 unsigned int left_idx = heap_idx << 1;
393 if (left_idx < heap->size && heap->entries[left_idx].version > version)
396 idx = heap->entries[heap_idx].idx;
397 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
399 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
400 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
405 case HEAP_NODE_TRAVERSE_RIGHT:
407 unsigned int right_idx = (heap_idx << 1) + 1;
408 if (right_idx < heap->size && heap->entries[right_idx].version > version)
410 heap_idx = right_idx;
411 idx = heap->entries[heap_idx].idx;
412 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
414 stack[stack_idx++] = HEAP_NODE_POP;
415 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
428 checkGLcall("walk_constant_heap_clamped()");
431 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
432 /* GL locking is done by the caller */
433 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
434 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
435 unsigned char *stack, UINT version)
437 const local_constant *lconst;
439 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
440 if (This->baseShader.reg_maps.shader_version.major == 1
441 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
442 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
444 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
446 if (!This->baseShader.load_local_constsF)
448 TRACE("No need to load local float constants for this shader\n");
452 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
453 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
455 GLint location = constant_locations[lconst->idx];
456 /* We found this uniform name in the program - go ahead and send the data */
457 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
459 checkGLcall("glUniform4fvARB()");
462 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
463 /* GL locking is done by the caller */
464 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
465 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
470 for (i = 0; constants_set; constants_set >>= 1, ++i)
472 if (!(constants_set & 1)) continue;
474 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
475 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
477 /* We found this uniform name in the program - go ahead and send the data */
478 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
479 checkGLcall("glUniform4ivARB");
482 /* Load immediate constants */
483 ptr = list_head(&This->baseShader.constantsI);
485 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
486 unsigned int idx = lconst->idx;
487 const GLint *values = (const GLint *)lconst->value;
489 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
490 values[0], values[1], values[2], values[3]);
492 /* We found this uniform name in the program - go ahead and send the data */
493 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
494 checkGLcall("glUniform4ivARB");
495 ptr = list_next(&This->baseShader.constantsI, ptr);
499 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
500 /* GL locking is done by the caller */
501 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
502 GLhandleARB programId, const BOOL *constants, WORD constants_set)
510 switch (This->baseShader.reg_maps.shader_version.type)
512 case WINED3D_SHADER_TYPE_VERTEX:
516 case WINED3D_SHADER_TYPE_GEOMETRY:
520 case WINED3D_SHADER_TYPE_PIXEL:
525 FIXME("Unknown shader type %#x.\n",
526 This->baseShader.reg_maps.shader_version.type);
531 /* TODO: Benchmark and see if it would be beneficial to store the
532 * locations of the constants to avoid looking up each time */
533 for (i = 0; constants_set; constants_set >>= 1, ++i)
535 if (!(constants_set & 1)) continue;
537 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
539 /* TODO: Benchmark and see if it would be beneficial to store the
540 * locations of the constants to avoid looking up each time */
541 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
542 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
545 /* We found this uniform name in the program - go ahead and send the data */
546 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
547 checkGLcall("glUniform1ivARB");
551 /* Load immediate constants */
552 ptr = list_head(&This->baseShader.constantsB);
554 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
555 unsigned int idx = lconst->idx;
556 const GLint *values = (const GLint *)lconst->value;
558 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
560 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
561 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
563 /* We found this uniform name in the program - go ahead and send the data */
564 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
565 checkGLcall("glUniform1ivARB");
567 ptr = list_next(&This->baseShader.constantsB, ptr);
571 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
573 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
577 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
579 /* GL locking is done by the caller (state handler) */
580 static void shader_glsl_load_np2fixup_constants(
581 IWineD3DDevice* device,
583 char useVertexShader) {
585 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
586 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
589 /* No GLSL program set - nothing to do. */
593 if (!usePixelShader) {
594 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
598 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
599 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
600 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
602 UINT fixup = prog->ps_args.np2_fixup;
603 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
605 for (i = 0; fixup; fixup >>= 1, ++i) {
606 const unsigned char idx = prog->np2Fixup_info->idx[i];
607 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
608 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
611 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
616 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
618 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
622 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
627 * Loads the app-supplied constants into the currently set GLSL program.
629 /* GL locking is done by the caller (state handler) */
630 static void shader_glsl_load_constants(const struct wined3d_context *context,
631 char usePixelShader, char useVertexShader)
633 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
634 const struct wined3d_gl_info *gl_info = context->gl_info;
635 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
636 struct shader_glsl_priv *priv = device->shader_priv;
638 GLhandleARB programId;
639 struct glsl_shader_prog_link *prog = priv->glsl_program;
640 UINT constant_version;
644 /* No GLSL program set - nothing to do. */
647 programId = prog->programId;
648 constant_version = prog->constant_version;
650 if (useVertexShader) {
651 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
653 /* Load DirectX 9 float constants/uniforms for vertex shader */
654 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
655 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
657 /* Load DirectX 9 integer constants/uniforms for vertex shader */
658 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
659 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
661 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
662 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
663 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
665 /* Upload the position fixup params */
666 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
667 checkGLcall("glUniform4fvARB");
670 if (usePixelShader) {
672 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
674 /* Load DirectX 9 float constants/uniforms for pixel shader */
675 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
676 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
678 /* Load DirectX 9 integer constants/uniforms for pixel shader */
679 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
680 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
682 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
683 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
684 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
686 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
687 * It can't be 0 for a valid texbem instruction.
689 for(i = 0; i < MAX_TEXTURES; i++) {
692 if(prog->bumpenvmat_location[i] == -1) continue;
694 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
695 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
696 checkGLcall("glUniformMatrix2fvARB");
698 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
699 * is set too, so we can check that in the needsbumpmat check
701 if(prog->luminancescale_location[i] != -1) {
702 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
703 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
705 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
706 checkGLcall("glUniform1fvARB");
707 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
708 checkGLcall("glUniform1fvARB");
712 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
713 float correction_params[4];
715 if (context->render_offscreen)
717 correction_params[0] = 0.0f;
718 correction_params[1] = 1.0f;
720 /* position is window relative, not viewport relative */
721 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
722 correction_params[1] = -1.0f;
724 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
728 if (priv->next_constant_version == UINT_MAX)
730 TRACE("Max constant version reached, resetting to 0.\n");
731 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
732 priv->next_constant_version = 1;
736 prog->constant_version = priv->next_constant_version++;
740 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
741 unsigned int heap_idx, DWORD new_version)
743 struct constant_entry *entries = heap->entries;
744 unsigned int *positions = heap->positions;
745 unsigned int parent_idx;
749 parent_idx = heap_idx >> 1;
751 if (new_version <= entries[parent_idx].version) break;
753 entries[heap_idx] = entries[parent_idx];
754 positions[entries[parent_idx].idx] = heap_idx;
755 heap_idx = parent_idx;
758 entries[heap_idx].version = new_version;
759 entries[heap_idx].idx = idx;
760 positions[idx] = heap_idx;
763 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
765 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
766 struct shader_glsl_priv *priv = This->shader_priv;
767 struct constant_heap *heap = &priv->vconst_heap;
770 for (i = start; i < count + start; ++i)
772 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
773 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
775 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
779 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
781 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
782 struct shader_glsl_priv *priv = This->shader_priv;
783 struct constant_heap *heap = &priv->pconst_heap;
786 for (i = start; i < count + start; ++i)
788 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
789 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
791 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
795 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
797 unsigned int ret = gl_info->limits.glsl_varyings / 4;
798 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
799 if(shader_major > 3) return ret;
801 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
802 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
806 /** Generate the variable & register declarations for the GLSL output target */
807 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
808 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
809 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
811 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
812 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
813 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
814 const struct wined3d_gl_info *gl_info = context->gl_info;
815 unsigned int i, extra_constants_needed = 0;
816 const local_constant *lconst;
819 /* There are some minor differences between pixel and vertex shaders */
820 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
821 char prefix = pshader ? 'P' : 'V';
823 /* Prototype the subroutines */
824 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
826 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
829 /* Declare the constants (aka uniforms) */
830 if (This->baseShader.limits.constant_float > 0) {
831 unsigned max_constantsF;
832 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
833 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
834 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
835 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
836 * a dx9 card, as long as it doesn't also use all the other constants.
838 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
839 * declare only the amount that we're assured to have.
841 * Thus we run into problems in these two cases:
842 * 1) The shader really uses more uniforms than supported
843 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
847 /* No indirect addressing here. */
848 max_constantsF = gl_info->limits.glsl_ps_float_constants;
852 if(This->baseShader.reg_maps.usesrelconstF) {
853 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
854 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
855 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
856 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
858 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
860 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
861 if(ctx_priv->cur_vs_args->clip_enabled)
863 max_constantsF -= gl_info->limits.clipplanes;
865 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
866 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
867 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
868 * for now take this into account when calculating the number of available constants
870 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
871 /* Set by driver quirks in directx.c */
872 max_constantsF -= gl_info->reserved_glsl_constants;
876 max_constantsF = gl_info->limits.glsl_vs_float_constants;
879 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
880 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
883 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
884 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
886 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
887 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
889 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
890 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
893 shader_addline(buffer, "uniform vec4 posFixup;\n");
894 /* Predeclaration; This function is added at link time based on the pixel shader.
895 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
896 * that. We know the input to the reorder function at vertex shader compile time, so
897 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
898 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
899 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
900 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
901 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
904 if (reg_maps->shader_version.major >= 3)
906 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
908 shader_addline(buffer, "void order_ps_input();\n");
911 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
913 if (!(map & 1)) continue;
915 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
917 if (reg_maps->luminanceparams & (1 << i))
919 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
920 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
921 extra_constants_needed++;
924 extra_constants_needed++;
927 if (ps_args->srgb_correction)
929 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
930 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
931 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
934 if (reg_maps->vpos || reg_maps->usesdsy)
936 if (This->baseShader.limits.constant_float + extra_constants_needed
937 + 1 < gl_info->limits.glsl_ps_float_constants)
939 shader_addline(buffer, "uniform vec4 ycorrection;\n");
940 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
941 extra_constants_needed++;
943 /* This happens because we do not have proper tracking of the constant registers that are
944 * actually used, only the max limit of the shader version
946 FIXME("Cannot find a free uniform for vpos correction params\n");
947 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
948 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
949 context->render_offscreen ? 1.0f : -1.0f);
951 shader_addline(buffer, "vec4 vpos;\n");
955 /* Declare texture samplers */
956 for (i = 0; i < This->baseShader.limits.sampler; i++) {
957 if (reg_maps->sampler_type[i])
959 switch (reg_maps->sampler_type[i])
962 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
965 if(device->stateBlock->textures[i] &&
966 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
967 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
969 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
972 case WINED3DSTT_CUBE:
973 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
975 case WINED3DSTT_VOLUME:
976 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
979 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
980 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
986 /* Declare uniforms for NP2 texcoord fixup:
987 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
988 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
989 * Modern cards just skip the code anyway, so put it inside a separate loop. */
990 if (pshader && ps_args->np2_fixup) {
992 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
995 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
996 * while D3D has them in the (normalized) [0,1]x[0,1] range.
997 * samplerNP2Fixup stores texture dimensions and is updated through
998 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1000 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1001 if (reg_maps->sampler_type[i]) {
1002 if (!(ps_args->np2_fixup & (1 << i))) continue;
1004 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1005 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1009 fixup->idx[i] = cur++;
1013 fixup->num_consts = (cur + 1) >> 1;
1014 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1017 /* Declare address variables */
1018 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1020 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1023 /* Declare texture coordinate temporaries and initialize them */
1024 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1026 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1029 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1030 * helper function shader that is linked in at link time
1032 if (pshader && reg_maps->shader_version.major >= 3)
1034 if (use_vs(device->stateBlock))
1036 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1038 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1039 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1040 * pixel shader that reads the fixed function color into the packed input registers.
1042 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1046 /* Declare output register temporaries */
1047 if(This->baseShader.limits.packed_output) {
1048 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1051 /* Declare temporary variables */
1052 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1054 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1057 /* Declare attributes */
1058 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1060 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1062 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1066 /* Declare loop registers aLx */
1067 for (i = 0; i < reg_maps->loop_depth; i++) {
1068 shader_addline(buffer, "int aL%u;\n", i);
1069 shader_addline(buffer, "int tmpInt%u;\n", i);
1072 /* Temporary variables for matrix operations */
1073 shader_addline(buffer, "vec4 tmp0;\n");
1074 shader_addline(buffer, "vec4 tmp1;\n");
1076 /* Local constants use a different name so they can be loaded once at shader link time
1077 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1078 * float -> string conversion can cause precision loss.
1080 if(!This->baseShader.load_local_constsF) {
1081 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1082 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1086 /* Start the main program */
1087 shader_addline(buffer, "void main() {\n");
1088 if(pshader && reg_maps->vpos) {
1089 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1090 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1091 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1092 * precision troubles when we just substract 0.5.
1094 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1096 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1098 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1099 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1100 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1101 * correctly on drivers that returns integer values.
1103 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1107 /*****************************************************************************
1108 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1110 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1111 ****************************************************************************/
1114 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1115 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1117 /** Used for opcode modifiers - They multiply the result by the specified amount */
1118 static const char * const shift_glsl_tab[] = {
1120 "2.0 * ", /* 1 (x2) */
1121 "4.0 * ", /* 2 (x4) */
1122 "8.0 * ", /* 3 (x8) */
1123 "16.0 * ", /* 4 (x16) */
1124 "32.0 * ", /* 5 (x32) */
1131 "0.0625 * ", /* 12 (d16) */
1132 "0.125 * ", /* 13 (d8) */
1133 "0.25 * ", /* 14 (d4) */
1134 "0.5 * " /* 15 (d2) */
1137 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1138 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1142 switch (src_modifier)
1144 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1145 case WINED3DSPSM_DW:
1146 case WINED3DSPSM_NONE:
1147 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1149 case WINED3DSPSM_NEG:
1150 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1152 case WINED3DSPSM_NOT:
1153 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1155 case WINED3DSPSM_BIAS:
1156 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1158 case WINED3DSPSM_BIASNEG:
1159 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1161 case WINED3DSPSM_SIGN:
1162 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1164 case WINED3DSPSM_SIGNNEG:
1165 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1167 case WINED3DSPSM_COMP:
1168 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1170 case WINED3DSPSM_X2:
1171 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1173 case WINED3DSPSM_X2NEG:
1174 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1176 case WINED3DSPSM_ABS:
1177 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1179 case WINED3DSPSM_ABSNEG:
1180 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1183 FIXME("Unhandled modifier %u\n", src_modifier);
1184 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1188 /** Writes the GLSL variable name that corresponds to the register that the
1189 * DX opcode parameter is trying to access */
1190 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1191 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1193 /* oPos, oFog and oPts in D3D */
1194 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1196 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1197 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1198 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1204 case WINED3DSPR_TEMP:
1205 sprintf(register_name, "R%u", reg->idx);
1208 case WINED3DSPR_INPUT:
1209 /* vertex shaders */
1212 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1213 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1214 sprintf(register_name, "attrib%u", reg->idx);
1218 /* pixel shaders >= 3.0 */
1219 if (This->baseShader.reg_maps.shader_version.major >= 3)
1221 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1222 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1226 glsl_src_param_t rel_param;
1228 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1230 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1231 * operation there */
1234 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1236 sprintf(register_name,
1237 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1238 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1239 rel_param.param_str, idx);
1243 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1248 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1250 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1251 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1252 rel_param.param_str);
1256 sprintf(register_name, "IN[%s]", rel_param.param_str);
1262 if (idx == in_count) sprintf(register_name, "gl_Color");
1263 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1264 else sprintf(register_name, "IN[%u]", idx);
1269 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1270 else strcpy(register_name, "gl_SecondaryColor");
1275 case WINED3DSPR_CONST:
1277 const char prefix = pshader ? 'P' : 'V';
1279 /* Relative addressing */
1282 glsl_src_param_t rel_param;
1283 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1284 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1285 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1289 if (shader_constant_is_local(This, reg->idx))
1290 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1292 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1297 case WINED3DSPR_CONSTINT:
1298 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1299 else sprintf(register_name, "VI[%u]", reg->idx);
1302 case WINED3DSPR_CONSTBOOL:
1303 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1304 else sprintf(register_name, "VB[%u]", reg->idx);
1307 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1308 if (pshader) sprintf(register_name, "T%u", reg->idx);
1309 else sprintf(register_name, "A%u", reg->idx);
1312 case WINED3DSPR_LOOP:
1313 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1316 case WINED3DSPR_SAMPLER:
1317 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1318 else sprintf(register_name, "Vsampler%u", reg->idx);
1321 case WINED3DSPR_COLOROUT:
1322 if (reg->idx >= gl_info->limits.buffers)
1323 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1325 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1328 case WINED3DSPR_RASTOUT:
1329 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1332 case WINED3DSPR_DEPTHOUT:
1333 sprintf(register_name, "gl_FragDepth");
1336 case WINED3DSPR_ATTROUT:
1337 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1338 else sprintf(register_name, "gl_FrontSecondaryColor");
1341 case WINED3DSPR_TEXCRDOUT:
1342 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1343 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1344 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1347 case WINED3DSPR_MISCTYPE:
1351 sprintf(register_name, "vpos");
1353 else if (reg->idx == 1)
1355 /* Note that gl_FrontFacing is a bool, while vFace is
1356 * a float for which the sign determines front/back */
1357 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1361 FIXME("Unhandled misctype register %d\n", reg->idx);
1362 sprintf(register_name, "unrecognized_register");
1366 case WINED3DSPR_IMMCONST:
1367 switch (reg->immconst_type)
1369 case WINED3D_IMMCONST_FLOAT:
1370 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1373 case WINED3D_IMMCONST_FLOAT4:
1374 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1375 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1376 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1380 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1381 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1386 FIXME("Unhandled register name Type(%d)\n", reg->type);
1387 sprintf(register_name, "unrecognized_register");
1392 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1395 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1396 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1397 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1398 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1402 /* Get the GLSL write mask for the destination register */
1403 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1405 DWORD mask = param->write_mask;
1407 if (shader_is_scalar(¶m->reg))
1409 mask = WINED3DSP_WRITEMASK_0;
1414 shader_glsl_write_mask_to_str(mask, write_mask);
1420 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1421 unsigned int size = 0;
1423 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1424 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1425 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1426 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1431 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1433 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1434 * but addressed as "rgba". To fix this we need to swap the register's x
1435 * and z components. */
1436 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1439 /* swizzle bits fields: wwzzyyxx */
1440 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1441 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1442 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1443 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1447 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1448 BOOL fixup, DWORD mask, char *swizzle_str)
1450 if (shader_is_scalar(¶m->reg))
1451 *swizzle_str = '\0';
1453 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1456 /* From a given parameter token, generate the corresponding GLSL string.
1457 * Also, return the actual register name and swizzle in case the
1458 * caller needs this information as well. */
1459 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1460 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1462 BOOL is_color = FALSE;
1463 char swizzle_str[6];
1465 glsl_src->reg_name[0] = '\0';
1466 glsl_src->param_str[0] = '\0';
1467 swizzle_str[0] = '\0';
1469 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1470 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1471 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1474 /* From a given parameter token, generate the corresponding GLSL string.
1475 * Also, return the actual register name and swizzle in case the
1476 * caller needs this information as well. */
1477 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1478 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1480 BOOL is_color = FALSE;
1482 glsl_dst->mask_str[0] = '\0';
1483 glsl_dst->reg_name[0] = '\0';
1485 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1486 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1489 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1490 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1491 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1493 glsl_dst_param_t glsl_dst;
1496 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1497 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1502 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1503 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1505 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1508 /** Process GLSL instruction modifiers */
1509 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1511 glsl_dst_param_t dst_param;
1514 if (!ins->dst_count) return;
1516 modifiers = ins->dst[0].modifiers;
1517 if (!modifiers) return;
1519 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1521 if (modifiers & WINED3DSPDM_SATURATE)
1523 /* _SAT means to clamp the value of the register to between 0 and 1 */
1524 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1525 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1528 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1530 FIXME("_centroid modifier not handled\n");
1533 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1535 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1539 static inline const char *shader_get_comp_op(DWORD op)
1542 case COMPARISON_GT: return ">";
1543 case COMPARISON_EQ: return "==";
1544 case COMPARISON_GE: return ">=";
1545 case COMPARISON_LT: return "<";
1546 case COMPARISON_NE: return "!=";
1547 case COMPARISON_LE: return "<=";
1549 FIXME("Unrecognized comparison value: %u\n", op);
1554 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1556 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1557 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1558 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1559 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1561 /* Note that there's no such thing as a projected cube texture. */
1562 switch(sampler_type) {
1565 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1567 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1569 sample_function->name = projected ? "texture1DProj" : "texture1D";
1571 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1576 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1578 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1580 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1584 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1586 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1588 sample_function->name = projected ? "texture2DProj" : "texture2D";
1591 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1593 case WINED3DSTT_CUBE:
1595 sample_function->name = "textureCubeLod";
1597 sample_function->name = "textureCubeGradARB";
1599 sample_function->name = "textureCube";
1601 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1603 case WINED3DSTT_VOLUME:
1605 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1607 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1609 sample_function->name = projected ? "texture3DProj" : "texture3D";
1611 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1614 sample_function->name = "";
1615 sample_function->coord_mask = 0;
1616 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1621 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1622 BOOL sign_fixup, enum fixup_channel_source channel_source)
1624 switch(channel_source)
1626 case CHANNEL_SOURCE_ZERO:
1627 strcat(arguments, "0.0");
1630 case CHANNEL_SOURCE_ONE:
1631 strcat(arguments, "1.0");
1634 case CHANNEL_SOURCE_X:
1635 strcat(arguments, reg_name);
1636 strcat(arguments, ".x");
1639 case CHANNEL_SOURCE_Y:
1640 strcat(arguments, reg_name);
1641 strcat(arguments, ".y");
1644 case CHANNEL_SOURCE_Z:
1645 strcat(arguments, reg_name);
1646 strcat(arguments, ".z");
1649 case CHANNEL_SOURCE_W:
1650 strcat(arguments, reg_name);
1651 strcat(arguments, ".w");
1655 FIXME("Unhandled channel source %#x\n", channel_source);
1656 strcat(arguments, "undefined");
1660 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1663 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1665 struct wined3d_shader_dst_param dst;
1666 unsigned int mask_size, remaining;
1667 glsl_dst_param_t dst_param;
1668 char arguments[256];
1672 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1673 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1674 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1675 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1676 mask &= ins->dst[0].write_mask;
1678 if (!mask) return; /* Nothing to do */
1680 if (is_yuv_fixup(fixup))
1682 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1683 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1687 mask_size = shader_glsl_get_write_mask_size(mask);
1690 dst.write_mask = mask;
1691 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1693 arguments[0] = '\0';
1694 remaining = mask_size;
1695 if (mask & WINED3DSP_WRITEMASK_0)
1697 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1698 if (--remaining) strcat(arguments, ", ");
1700 if (mask & WINED3DSP_WRITEMASK_1)
1702 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1703 if (--remaining) strcat(arguments, ", ");
1705 if (mask & WINED3DSP_WRITEMASK_2)
1707 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1708 if (--remaining) strcat(arguments, ", ");
1710 if (mask & WINED3DSP_WRITEMASK_3)
1712 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1713 if (--remaining) strcat(arguments, ", ");
1718 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1719 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1723 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1727 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1728 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1729 const char *dx, const char *dy,
1730 const char *bias, const char *coord_reg_fmt, ...)
1732 const char *sampler_base;
1733 char dst_swizzle[6];
1734 struct color_fixup_desc fixup;
1735 BOOL np2_fixup = FALSE;
1738 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1740 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1742 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1743 fixup = priv->cur_ps_args->color_fixup[sampler];
1744 sampler_base = "Psampler";
1746 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
1748 FIXME("Biased sampling from NP2 textures is unsupported\n");
1754 sampler_base = "Vsampler";
1755 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1758 shader_glsl_append_dst(ins->ctx->buffer, ins);
1760 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1762 va_start(args, coord_reg_fmt);
1763 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1767 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1770 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1771 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
1773 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
1774 (idx % 2) ? "zw" : "xy", dst_swizzle);
1775 } else if(dx && dy) {
1776 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1778 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1782 if(!is_identity_fixup(fixup)) {
1783 shader_glsl_color_correction(ins, fixup);
1787 /*****************************************************************************
1788 * Begin processing individual instruction opcodes
1789 ****************************************************************************/
1791 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1792 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1794 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1795 glsl_src_param_t src0_param;
1796 glsl_src_param_t src1_param;
1800 /* Determine the GLSL operator to use based on the opcode */
1801 switch (ins->handler_idx)
1803 case WINED3DSIH_MUL: op = '*'; break;
1804 case WINED3DSIH_ADD: op = '+'; break;
1805 case WINED3DSIH_SUB: op = '-'; break;
1808 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1812 write_mask = shader_glsl_append_dst(buffer, ins);
1813 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1814 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1815 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1818 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1819 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1821 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1822 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1823 glsl_src_param_t src0_param;
1826 write_mask = shader_glsl_append_dst(buffer, ins);
1827 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1829 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1830 * shader versions WINED3DSIO_MOVA is used for this. */
1831 if (ins->ctx->reg_maps->shader_version.major == 1
1832 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1833 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1835 /* This is a simple floor() */
1836 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1837 if (mask_size > 1) {
1838 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1840 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1843 else if(ins->handler_idx == WINED3DSIH_MOVA)
1845 /* We need to *round* to the nearest int here. */
1846 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1848 if (gl_info->supported[EXT_GPU_SHADER4])
1851 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
1853 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
1858 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
1859 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
1861 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
1862 src0_param.param_str, src0_param.param_str);
1867 shader_addline(buffer, "%s);\n", src0_param.param_str);
1871 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1872 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1874 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1875 glsl_src_param_t src0_param;
1876 glsl_src_param_t src1_param;
1877 DWORD dst_write_mask, src_write_mask;
1878 unsigned int dst_size = 0;
1880 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1881 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1883 /* dp3 works on vec3, dp4 on vec4 */
1884 if (ins->handler_idx == WINED3DSIH_DP4)
1886 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1888 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1891 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
1892 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
1895 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1897 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1901 /* Note that this instruction has some restrictions. The destination write mask
1902 * can't contain the w component, and the source swizzles have to be .xyzw */
1903 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1905 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1906 glsl_src_param_t src0_param;
1907 glsl_src_param_t src1_param;
1910 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1911 shader_glsl_append_dst(ins->ctx->buffer, ins);
1912 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
1913 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
1914 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1917 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1918 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1919 * GLSL uses the value as-is. */
1920 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1922 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1923 glsl_src_param_t src0_param;
1924 glsl_src_param_t src1_param;
1925 DWORD dst_write_mask;
1926 unsigned int dst_size;
1928 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1929 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1931 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1932 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
1935 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1937 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1941 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1942 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1943 * GLSL uses the value as-is. */
1944 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1946 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1947 glsl_src_param_t src0_param;
1948 DWORD dst_write_mask;
1949 unsigned int dst_size;
1951 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1952 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1954 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1957 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1959 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1963 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1964 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1966 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1967 glsl_src_param_t src_param;
1968 const char *instruction;
1972 /* Determine the GLSL function to use based on the opcode */
1973 /* TODO: Possibly make this a table for faster lookups */
1974 switch (ins->handler_idx)
1976 case WINED3DSIH_MIN: instruction = "min"; break;
1977 case WINED3DSIH_MAX: instruction = "max"; break;
1978 case WINED3DSIH_ABS: instruction = "abs"; break;
1979 case WINED3DSIH_FRC: instruction = "fract"; break;
1980 case WINED3DSIH_NRM: instruction = "normalize"; break;
1981 case WINED3DSIH_EXP: instruction = "exp2"; break;
1982 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1983 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1984 default: instruction = "";
1985 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1989 write_mask = shader_glsl_append_dst(buffer, ins);
1991 shader_addline(buffer, "%s(", instruction);
1995 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
1996 shader_addline(buffer, "%s", src_param.param_str);
1997 for (i = 1; i < ins->src_count; ++i)
1999 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2000 shader_addline(buffer, ", %s", src_param.param_str);
2004 shader_addline(buffer, "));\n");
2007 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2008 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2009 * dst.x = 2^(floor(src))
2010 * dst.y = src - floor(src)
2011 * dst.z = 2^src (partial precision is allowed, but optional)
2013 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2014 * dst = 2^src; (partial precision is allowed, but optional)
2016 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2018 glsl_src_param_t src_param;
2020 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2022 if (ins->ctx->reg_maps->shader_version.major < 2)
2026 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2027 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2028 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2029 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2031 shader_glsl_append_dst(ins->ctx->buffer, ins);
2032 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2033 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2036 unsigned int mask_size;
2038 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2039 mask_size = shader_glsl_get_write_mask_size(write_mask);
2041 if (mask_size > 1) {
2042 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2044 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2049 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2050 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2052 glsl_src_param_t src_param;
2054 unsigned int mask_size;
2056 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2057 mask_size = shader_glsl_get_write_mask_size(write_mask);
2058 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2060 if (mask_size > 1) {
2061 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
2063 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
2067 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2069 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2070 glsl_src_param_t src_param;
2072 unsigned int mask_size;
2074 write_mask = shader_glsl_append_dst(buffer, ins);
2075 mask_size = shader_glsl_get_write_mask_size(write_mask);
2077 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2079 if (mask_size > 1) {
2080 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
2082 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
2086 /** Process signed comparison opcodes in GLSL. */
2087 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2089 glsl_src_param_t src0_param;
2090 glsl_src_param_t src1_param;
2092 unsigned int mask_size;
2094 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2095 mask_size = shader_glsl_get_write_mask_size(write_mask);
2096 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2097 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2099 if (mask_size > 1) {
2100 const char *compare;
2102 switch(ins->handler_idx)
2104 case WINED3DSIH_SLT: compare = "lessThan"; break;
2105 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2106 default: compare = "";
2107 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2110 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2111 src0_param.param_str, src1_param.param_str);
2113 switch(ins->handler_idx)
2115 case WINED3DSIH_SLT:
2116 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2117 * to return 0.0 but step returns 1.0 because step is not < x
2118 * An alternative is a bvec compare padded with an unused second component.
2119 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2120 * issue. Playing with not() is not possible either because not() does not accept
2123 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2124 src0_param.param_str, src1_param.param_str);
2126 case WINED3DSIH_SGE:
2127 /* Here we can use the step() function and safe a conditional */
2128 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2131 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2137 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2138 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2140 glsl_src_param_t src0_param;
2141 glsl_src_param_t src1_param;
2142 glsl_src_param_t src2_param;
2143 DWORD write_mask, cmp_channel = 0;
2146 BOOL temp_destination = FALSE;
2148 if (shader_is_scalar(&ins->src[0].reg))
2150 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2152 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2153 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2154 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2156 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2157 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2159 DWORD dst_mask = ins->dst[0].write_mask;
2160 struct wined3d_shader_dst_param dst = ins->dst[0];
2162 /* Cycle through all source0 channels */
2163 for (i=0; i<4; i++) {
2165 /* Find the destination channels which use the current source0 channel */
2166 for (j=0; j<4; j++) {
2167 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2169 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2170 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2173 dst.write_mask = dst_mask & write_mask;
2175 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2176 * The first lines may overwrite source parameters of the following lines.
2177 * Deal with that by using a temporary destination register if needed
2179 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2180 && ins->src[0].reg.type == ins->dst[0].reg.type)
2181 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2182 && ins->src[1].reg.type == ins->dst[0].reg.type)
2183 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2184 && ins->src[2].reg.type == ins->dst[0].reg.type))
2186 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2187 if (!write_mask) continue;
2188 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2189 temp_destination = TRUE;
2191 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2192 if (!write_mask) continue;
2195 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2196 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2197 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2199 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2200 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2203 if(temp_destination) {
2204 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2205 shader_glsl_append_dst(ins->ctx->buffer, ins);
2206 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2212 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2213 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2214 * the compare is done per component of src0. */
2215 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2217 struct wined3d_shader_dst_param dst;
2218 glsl_src_param_t src0_param;
2219 glsl_src_param_t src1_param;
2220 glsl_src_param_t src2_param;
2221 DWORD write_mask, cmp_channel = 0;
2224 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2225 ins->ctx->reg_maps->shader_version.minor);
2227 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2229 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2230 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2231 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2232 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2234 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2237 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2239 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2240 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2244 /* Cycle through all source0 channels */
2245 dst_mask = ins->dst[0].write_mask;
2247 for (i=0; i<4; i++) {
2249 /* Find the destination channels which use the current source0 channel */
2250 for (j=0; j<4; j++) {
2251 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2253 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2254 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2258 dst.write_mask = dst_mask & write_mask;
2259 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2260 if (!write_mask) continue;
2262 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2263 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2264 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2266 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2267 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2271 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2272 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2274 glsl_src_param_t src0_param;
2275 glsl_src_param_t src1_param;
2276 glsl_src_param_t src2_param;
2279 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2280 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2281 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2282 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2283 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2284 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2287 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2288 Vertex shaders to GLSL codes */
2289 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2292 int nComponents = 0;
2293 struct wined3d_shader_dst_param tmp_dst = {{0}};
2294 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2295 struct wined3d_shader_instruction tmp_ins;
2297 memset(&tmp_ins, 0, sizeof(tmp_ins));
2299 /* Set constants for the temporary argument */
2300 tmp_ins.ctx = ins->ctx;
2301 tmp_ins.dst_count = 1;
2302 tmp_ins.dst = &tmp_dst;
2303 tmp_ins.src_count = 2;
2304 tmp_ins.src = tmp_src;
2306 switch(ins->handler_idx)
2308 case WINED3DSIH_M4x4:
2310 tmp_ins.handler_idx = WINED3DSIH_DP4;
2312 case WINED3DSIH_M4x3:
2314 tmp_ins.handler_idx = WINED3DSIH_DP4;
2316 case WINED3DSIH_M3x4:
2318 tmp_ins.handler_idx = WINED3DSIH_DP3;
2320 case WINED3DSIH_M3x3:
2322 tmp_ins.handler_idx = WINED3DSIH_DP3;
2324 case WINED3DSIH_M3x2:
2326 tmp_ins.handler_idx = WINED3DSIH_DP3;
2332 tmp_dst = ins->dst[0];
2333 tmp_src[0] = ins->src[0];
2334 tmp_src[1] = ins->src[1];
2335 for (i = 0; i < nComponents; ++i)
2337 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2338 shader_glsl_dot(&tmp_ins);
2339 ++tmp_src[1].reg.idx;
2344 The LRP instruction performs a component-wise linear interpolation
2345 between the second and third operands using the first operand as the
2346 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2347 This is equivalent to mix(src2, src1, src0);
2349 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2351 glsl_src_param_t src0_param;
2352 glsl_src_param_t src1_param;
2353 glsl_src_param_t src2_param;
2356 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2358 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2359 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2360 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2362 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2363 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2366 /** Process the WINED3DSIO_LIT instruction in GLSL:
2367 * dst.x = dst.w = 1.0
2368 * dst.y = (src0.x > 0) ? src0.x
2369 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2370 * where src.w is clamped at +- 128
2372 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2374 glsl_src_param_t src0_param;
2375 glsl_src_param_t src1_param;
2376 glsl_src_param_t src3_param;
2379 shader_glsl_append_dst(ins->ctx->buffer, ins);
2380 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2382 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2383 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2384 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2386 /* The sdk specifies the instruction like this
2388 * if(src.x > 0.0) dst.y = src.x
2390 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2394 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2395 * dst.x = 1.0 ... No further explanation needed
2396 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2397 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2398 * dst.w = 1.0. ... Nothing fancy.
2400 * So we still have one conditional in there. So do this:
2401 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2403 * 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),
2404 * 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.
2405 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2407 shader_addline(ins->ctx->buffer,
2408 "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",
2409 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2412 /** Process the WINED3DSIO_DST instruction in GLSL:
2414 * dst.y = src0.x * src0.y
2418 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2420 glsl_src_param_t src0y_param;
2421 glsl_src_param_t src0z_param;
2422 glsl_src_param_t src1y_param;
2423 glsl_src_param_t src1w_param;
2426 shader_glsl_append_dst(ins->ctx->buffer, ins);
2427 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2429 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2430 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2431 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2432 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2434 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2435 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2438 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2439 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2440 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2442 * dst.x = cos(src0.?)
2443 * dst.y = sin(src0.?)
2447 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2449 glsl_src_param_t src0_param;
2452 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2453 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2455 switch (write_mask) {
2456 case WINED3DSP_WRITEMASK_0:
2457 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2460 case WINED3DSP_WRITEMASK_1:
2461 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2464 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2465 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2469 ERR("Write mask should be .x, .y or .xy\n");
2474 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2475 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2476 * generate invalid code
2478 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2480 glsl_src_param_t src0_param;
2483 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2484 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2486 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2489 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2490 * Start a for() loop where src1.y is the initial value of aL,
2491 * increment aL by src1.z for a total of src1.x iterations.
2492 * Need to use a temporary variable for this operation.
2494 /* FIXME: I don't think nested loops will work correctly this way. */
2495 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2497 glsl_src_param_t src1_param;
2498 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2499 const DWORD *control_values = NULL;
2500 const local_constant *constant;
2502 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2504 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2505 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2506 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2509 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2511 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2512 if (constant->idx == ins->src[1].reg.idx)
2514 control_values = constant->value;
2522 struct wined3d_shader_loop_control loop_control;
2523 loop_control.count = control_values[0];
2524 loop_control.start = control_values[1];
2525 loop_control.step = (int)control_values[2];
2527 if (loop_control.step > 0)
2529 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2530 shader->baseShader.cur_loop_depth, loop_control.start,
2531 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2532 shader->baseShader.cur_loop_depth, loop_control.step);
2534 else if (loop_control.step < 0)
2536 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2537 shader->baseShader.cur_loop_depth, loop_control.start,
2538 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2539 shader->baseShader.cur_loop_depth, loop_control.step);
2543 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2544 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2545 shader->baseShader.cur_loop_depth, loop_control.count,
2546 shader->baseShader.cur_loop_depth);
2549 shader_addline(ins->ctx->buffer,
2550 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2551 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2552 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2553 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2556 shader->baseShader.cur_loop_depth++;
2557 shader->baseShader.cur_loop_regno++;
2560 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2562 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2564 shader_addline(ins->ctx->buffer, "}\n");
2566 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2568 shader->baseShader.cur_loop_depth--;
2569 shader->baseShader.cur_loop_regno--;
2572 if (ins->handler_idx == WINED3DSIH_ENDREP)
2574 shader->baseShader.cur_loop_depth--;
2578 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2580 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2581 glsl_src_param_t src0_param;
2582 const DWORD *control_values = NULL;
2583 const local_constant *constant;
2585 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2586 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2588 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2590 if (constant->idx == ins->src[0].reg.idx)
2592 control_values = constant->value;
2598 if(control_values) {
2599 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2600 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2601 control_values[0], shader->baseShader.cur_loop_depth);
2603 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2604 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2605 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2606 src0_param.param_str, shader->baseShader.cur_loop_depth);
2608 shader->baseShader.cur_loop_depth++;
2611 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2613 glsl_src_param_t src0_param;
2615 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2616 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2619 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2621 glsl_src_param_t src0_param;
2622 glsl_src_param_t src1_param;
2624 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2625 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2627 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2628 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2631 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2633 shader_addline(ins->ctx->buffer, "} else {\n");
2636 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2638 shader_addline(ins->ctx->buffer, "break;\n");
2641 /* FIXME: According to MSDN the compare is done per component. */
2642 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2644 glsl_src_param_t src0_param;
2645 glsl_src_param_t src1_param;
2647 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2648 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2650 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2651 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2654 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2656 shader_addline(ins->ctx->buffer, "}\n");
2657 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2660 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2662 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2665 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2667 glsl_src_param_t src1_param;
2669 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2670 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2673 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
2675 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
2676 * function only suppresses the unhandled instruction warning
2680 /*********************************************
2681 * Pixel Shader Specific Code begins here
2682 ********************************************/
2683 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
2685 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2686 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2687 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2688 ins->ctx->reg_maps->shader_version.minor);
2689 glsl_sample_function_t sample_function;
2690 DWORD sample_flags = 0;
2691 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2693 DWORD mask = 0, swizzle;
2695 /* 1.0-1.4: Use destination register as sampler source.
2696 * 2.0+: Use provided sampler source. */
2697 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2698 else sampler_idx = ins->src[1].reg.idx;
2699 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2701 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2703 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2705 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2706 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2707 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2708 switch (flags & ~WINED3DTTFF_PROJECTED) {
2709 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2710 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2711 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2712 case WINED3DTTFF_COUNT4:
2713 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2717 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2719 DWORD src_mod = ins->src[0].modifiers;
2721 if (src_mod == WINED3DSPSM_DZ) {
2722 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2723 mask = WINED3DSP_WRITEMASK_2;
2724 } else if (src_mod == WINED3DSPSM_DW) {
2725 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2726 mask = WINED3DSP_WRITEMASK_3;
2729 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2731 /* ps 2.0 texldp instruction always divides by the fourth component. */
2732 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2733 mask = WINED3DSP_WRITEMASK_3;
2737 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2738 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2739 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2742 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2743 mask |= sample_function.coord_mask;
2745 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2746 else swizzle = ins->src[1].swizzle;
2748 /* 1.0-1.3: Use destination register as coordinate source.
2749 1.4+: Use provided coordinate source register. */
2750 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2753 shader_glsl_write_mask_to_str(mask, coord_mask);
2754 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2755 "T%u%s", sampler_idx, coord_mask);
2757 glsl_src_param_t coord_param;
2758 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2759 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2761 glsl_src_param_t bias;
2762 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2763 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2764 "%s", coord_param.param_str);
2766 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2767 "%s", coord_param.param_str);
2772 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2774 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2775 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2776 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2777 glsl_sample_function_t sample_function;
2778 glsl_src_param_t coord_param, dx_param, dy_param;
2779 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2782 DWORD swizzle = ins->src[1].swizzle;
2784 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD])
2786 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2787 return shader_glsl_tex(ins);
2790 sampler_idx = ins->src[1].reg.idx;
2791 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2792 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2793 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2794 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2797 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2798 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2799 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2800 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2802 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2803 "%s", coord_param.param_str);
2806 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2808 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2809 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2810 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2811 glsl_sample_function_t sample_function;
2812 glsl_src_param_t coord_param, lod_param;
2813 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2816 DWORD swizzle = ins->src[1].swizzle;
2818 sampler_idx = ins->src[1].reg.idx;
2819 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2820 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2821 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2822 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2824 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2825 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2827 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2829 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD]
2830 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2832 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2833 * However, they seem to work just fine in fragment shaders as well. */
2834 WARN("Using %s in fragment shader.\n", sample_function.name);
2836 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
2837 "%s", coord_param.param_str);
2840 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2842 /* FIXME: Make this work for more than just 2D textures */
2843 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2844 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2846 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
2850 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2851 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2852 ins->dst[0].reg.idx, dst_mask);
2854 DWORD reg = ins->src[0].reg.idx;
2855 DWORD src_mod = ins->src[0].modifiers;
2856 char dst_swizzle[6];
2858 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
2860 if (src_mod == WINED3DSPSM_DZ) {
2861 glsl_src_param_t div_param;
2862 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2863 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
2865 if (mask_size > 1) {
2866 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2868 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2870 } else if (src_mod == WINED3DSPSM_DW) {
2871 glsl_src_param_t div_param;
2872 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2873 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
2875 if (mask_size > 1) {
2876 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2878 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2881 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2886 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2887 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2888 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2889 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2891 glsl_src_param_t src0_param;
2892 glsl_sample_function_t sample_function;
2893 DWORD sampler_idx = ins->dst[0].reg.idx;
2894 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2895 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2898 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2900 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2901 * scalar, and projected sampling would require 4.
2903 * It is a dependent read - not valid with conditional NP2 textures
2905 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2906 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2911 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2912 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2916 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2917 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2921 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2922 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2926 FIXME("Unexpected mask size %u\n", mask_size);
2931 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2932 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2933 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2935 glsl_src_param_t src0_param;
2936 DWORD dstreg = ins->dst[0].reg.idx;
2937 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2939 unsigned int mask_size;
2941 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2942 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2943 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2945 if (mask_size > 1) {
2946 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2948 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2952 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2953 * Calculate the depth as dst.x / dst.y */
2954 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2956 glsl_dst_param_t dst_param;
2958 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2960 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2961 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2962 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2963 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2966 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2967 dst_param.reg_name, dst_param.reg_name);
2970 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2971 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2972 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2973 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2975 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2977 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2978 DWORD dstreg = ins->dst[0].reg.idx;
2979 glsl_src_param_t src0_param;
2981 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2983 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2984 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2987 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2988 * Calculate the 1st of a 2-row matrix multiplication. */
2989 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2991 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2992 DWORD reg = ins->dst[0].reg.idx;
2993 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2994 glsl_src_param_t src0_param;
2996 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2997 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3000 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3001 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3002 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3004 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3005 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3006 DWORD reg = ins->dst[0].reg.idx;
3007 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3008 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3009 glsl_src_param_t src0_param;
3011 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3012 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3013 current_state->texcoord_w[current_state->current_row++] = reg;
3016 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3018 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3019 DWORD reg = ins->dst[0].reg.idx;
3020 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3021 glsl_src_param_t src0_param;
3022 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3023 glsl_sample_function_t sample_function;
3025 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3026 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3028 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3030 /* Sample the texture using the calculated coordinates */
3031 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3034 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3035 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3036 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3038 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3039 glsl_src_param_t src0_param;
3040 DWORD reg = ins->dst[0].reg.idx;
3041 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3042 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
3043 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3044 glsl_sample_function_t sample_function;
3046 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3047 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3049 /* Dependent read, not valid with conditional NP2 */
3050 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3052 /* Sample the texture using the calculated coordinates */
3053 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3055 current_state->current_row = 0;
3058 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3059 * Perform the 3rd row of a 3x3 matrix multiply */
3060 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3062 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3063 glsl_src_param_t src0_param;
3065 DWORD reg = ins->dst[0].reg.idx;
3066 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3067 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
3069 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3071 shader_glsl_append_dst(ins->ctx->buffer, ins);
3072 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3073 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3075 current_state->current_row = 0;
3078 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3079 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3080 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3082 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3083 DWORD reg = ins->dst[0].reg.idx;
3084 glsl_src_param_t src0_param;
3085 glsl_src_param_t src1_param;
3086 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3087 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3088 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3089 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3090 glsl_sample_function_t sample_function;
3092 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3093 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3095 /* Perform the last matrix multiply operation */
3096 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3097 /* Reflection calculation */
3098 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3100 /* Dependent read, not valid with conditional NP2 */
3101 shader_glsl_get_sample_function(stype, 0, &sample_function);
3103 /* Sample the texture */
3104 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3106 current_state->current_row = 0;
3109 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3110 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3111 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3113 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3114 DWORD reg = ins->dst[0].reg.idx;
3115 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3116 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3117 glsl_src_param_t src0_param;
3118 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3119 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3120 glsl_sample_function_t sample_function;
3122 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3124 /* Perform the last matrix multiply operation */
3125 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3127 /* Construct the eye-ray vector from w coordinates */
3128 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3129 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3130 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3132 /* Dependent read, not valid with conditional NP2 */
3133 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3135 /* Sample the texture using the calculated coordinates */
3136 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3138 current_state->current_row = 0;
3141 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3142 * Apply a fake bump map transform.
3143 * texbem is pshader <= 1.3 only, this saves a few version checks
3145 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3147 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3148 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3149 glsl_sample_function_t sample_function;
3150 glsl_src_param_t coord_param;
3151 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3157 sampler_idx = ins->dst[0].reg.idx;
3158 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3160 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3161 /* Dependent read, not valid with conditional NP2 */
3162 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3163 mask = sample_function.coord_mask;
3165 shader_glsl_write_mask_to_str(mask, coord_mask);
3167 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3168 * so we can't let the GL handle this.
3170 if (flags & WINED3DTTFF_PROJECTED) {
3172 char coord_div_mask[3];
3173 switch (flags & ~WINED3DTTFF_PROJECTED) {
3174 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3175 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3176 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3177 case WINED3DTTFF_COUNT4:
3178 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3180 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3181 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3184 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3186 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3187 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3188 coord_param.param_str, coord_mask);
3190 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3192 glsl_src_param_t luminance_param;
3193 glsl_dst_param_t dst_param;
3195 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3196 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3198 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3199 dst_param.reg_name, dst_param.mask_str,
3200 luminance_param.param_str, sampler_idx, sampler_idx);
3204 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3206 glsl_src_param_t src0_param, src1_param;
3207 DWORD sampler_idx = ins->dst[0].reg.idx;
3209 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3210 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3212 shader_glsl_append_dst(ins->ctx->buffer, ins);
3213 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3214 src0_param.param_str, sampler_idx, src1_param.param_str);
3217 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3218 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3219 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3221 glsl_src_param_t src0_param;
3222 DWORD sampler_idx = ins->dst[0].reg.idx;
3223 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3224 glsl_sample_function_t sample_function;
3226 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3228 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3229 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3230 "%s.wx", src0_param.reg_name);
3233 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3234 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3235 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3237 glsl_src_param_t src0_param;
3238 DWORD sampler_idx = ins->dst[0].reg.idx;
3239 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3240 glsl_sample_function_t sample_function;
3242 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3244 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3245 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3246 "%s.yz", src0_param.reg_name);
3249 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3250 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3251 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3253 glsl_src_param_t src0_param;
3254 DWORD sampler_idx = ins->dst[0].reg.idx;
3255 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3256 glsl_sample_function_t sample_function;
3258 /* Dependent read, not valid with conditional NP2 */
3259 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3260 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3262 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3263 "%s", src0_param.param_str);
3266 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3267 * If any of the first 3 components are < 0, discard this pixel */
3268 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3270 glsl_dst_param_t dst_param;
3272 /* The argument is a destination parameter, and no writemasks are allowed */
3273 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3274 if (ins->ctx->reg_maps->shader_version.major >= 2)
3276 /* 2.0 shaders compare all 4 components in texkill */
3277 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3279 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3280 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3281 * 4 components are defined, only the first 3 are used
3283 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3287 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3288 * dst = dot2(src0, src1) + src2 */
3289 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3291 glsl_src_param_t src0_param;
3292 glsl_src_param_t src1_param;
3293 glsl_src_param_t src2_param;
3295 unsigned int mask_size;
3297 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3298 mask_size = shader_glsl_get_write_mask_size(write_mask);
3300 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3301 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3302 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3304 if (mask_size > 1) {
3305 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3306 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3308 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3309 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3313 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3314 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3315 enum vertexprocessing_mode vertexprocessing)
3318 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3319 WORD map = reg_maps->input_registers;
3321 for (i = 0; map; map >>= 1, ++i)
3323 const char *semantic_name;
3328 if (!(map & 1)) continue;
3330 semantic_name = input_signature[i].semantic_name;
3331 semantic_idx = input_signature[i].semantic_idx;
3332 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3334 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3336 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3337 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3338 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3340 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3341 This->input_reg_map[i], reg_mask, reg_mask);
3343 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3345 if (semantic_idx == 0)
3346 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3347 This->input_reg_map[i], reg_mask, reg_mask);
3348 else if (semantic_idx == 1)
3349 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3350 This->input_reg_map[i], reg_mask, reg_mask);
3352 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3353 This->input_reg_map[i], reg_mask, reg_mask);
3357 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3358 This->input_reg_map[i], reg_mask, reg_mask);
3363 /*********************************************
3364 * Vertex Shader Specific Code begins here
3365 ********************************************/
3367 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3368 glsl_program_key_t key;
3370 key.vshader = entry->vshader;
3371 key.pshader = entry->pshader;
3372 key.vs_args = entry->vs_args;
3373 key.ps_args = entry->ps_args;
3375 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3377 ERR("Failed to insert program entry.\n");
3381 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3382 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3383 struct ps_compile_args *ps_args) {
3384 struct wine_rb_entry *entry;
3385 glsl_program_key_t key;
3387 key.vshader = vshader;
3388 key.pshader = pshader;
3389 key.vs_args = *vs_args;
3390 key.ps_args = *ps_args;
3392 entry = wine_rb_get(&priv->program_lookup, &key);
3393 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3396 /* GL locking is done by the caller */
3397 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3398 struct glsl_shader_prog_link *entry)
3400 glsl_program_key_t key;
3402 key.vshader = entry->vshader;
3403 key.pshader = entry->pshader;
3404 key.vs_args = entry->vs_args;
3405 key.ps_args = entry->ps_args;
3406 wine_rb_remove(&priv->program_lookup, &key);
3408 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3409 if (entry->vshader) list_remove(&entry->vshader_entry);
3410 if (entry->pshader) list_remove(&entry->pshader_entry);
3411 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3412 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3413 HeapFree(GetProcessHeap(), 0, entry);
3416 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3417 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3418 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3421 const char *semantic_name_in, *semantic_name_out;
3422 UINT semantic_idx_in, semantic_idx_out;
3425 unsigned int in_count = vec4_varyings(3, gl_info);
3426 char reg_mask[6], reg_mask_out[6];
3427 char destination[50];
3428 WORD input_map, output_map;
3430 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3432 if (!output_signature)
3434 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3435 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3436 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3439 input_map = reg_maps_in->input_registers;
3440 for (i = 0; input_map; input_map >>= 1, ++i)
3442 if (!(input_map & 1)) continue;
3445 if (in_idx >= (in_count + 2)) {
3446 FIXME("More input varyings declared than supported, expect issues\n");
3449 else if (map[i] == ~0U)
3451 /* Declared, but not read register */
3455 if (in_idx == in_count) {
3456 sprintf(destination, "gl_FrontColor");
3457 } else if (in_idx == in_count + 1) {
3458 sprintf(destination, "gl_FrontSecondaryColor");
3460 sprintf(destination, "IN[%u]", in_idx);
3463 semantic_name_in = input_signature[i].semantic_name;
3464 semantic_idx_in = input_signature[i].semantic_idx;
3465 set[map[i]] = input_signature[i].mask;
3466 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3468 if (!output_signature)
3470 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3472 if (semantic_idx_in == 0)
3473 shader_addline(buffer, "%s%s = front_color%s;\n",
3474 destination, reg_mask, reg_mask);
3475 else if (semantic_idx_in == 1)
3476 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3477 destination, reg_mask, reg_mask);
3479 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3480 destination, reg_mask, reg_mask);
3482 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3484 if (semantic_idx_in < 8)
3486 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3487 destination, reg_mask, semantic_idx_in, reg_mask);
3491 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3492 destination, reg_mask, reg_mask);
3495 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3497 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3498 destination, reg_mask, reg_mask);
3502 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3503 destination, reg_mask, reg_mask);
3508 output_map = reg_maps_out->output_registers;
3509 for (j = 0; output_map; output_map >>= 1, ++j)
3511 if (!(output_map & 1)) continue;
3513 semantic_name_out = output_signature[j].semantic_name;
3514 semantic_idx_out = output_signature[j].semantic_idx;
3515 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3517 if (semantic_idx_in == semantic_idx_out
3518 && !strcmp(semantic_name_in, semantic_name_out))
3520 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3521 destination, reg_mask, j, reg_mask);
3526 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3527 destination, reg_mask, reg_mask);
3532 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3533 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3534 * input varyings are assigned above, if the optimizer works properly.
3536 for(i = 0; i < in_count + 2; i++) {
3537 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
3539 unsigned int size = 0;
3540 memset(reg_mask, 0, sizeof(reg_mask));
3541 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3542 reg_mask[size] = 'x';
3545 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3546 reg_mask[size] = 'y';
3549 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3550 reg_mask[size] = 'z';
3553 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3554 reg_mask[size] = 'w';
3558 if (i == in_count) {
3559 sprintf(destination, "gl_FrontColor");
3560 } else if (i == in_count + 1) {
3561 sprintf(destination, "gl_FrontSecondaryColor");
3563 sprintf(destination, "IN[%u]", i);
3567 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3569 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3574 HeapFree(GetProcessHeap(), 0, set);
3577 /* GL locking is done by the caller */
3578 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3579 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3581 GLhandleARB ret = 0;
3582 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3583 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3584 IWineD3DDeviceImpl *device;
3585 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3586 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3588 const char *semantic_name;
3591 const struct wined3d_shader_signature_element *output_signature;
3593 shader_buffer_clear(buffer);
3595 shader_addline(buffer, "#version 120\n");
3597 if(vs_major < 3 && ps_major < 3) {
3598 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3599 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3601 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3602 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
3603 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
3605 shader_addline(buffer, "void order_ps_input() {\n");
3606 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3607 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3608 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3609 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3612 shader_addline(buffer, "}\n");
3614 shader_addline(buffer, "void order_ps_input() { /* do nothing */ }\n");
3616 } else if(ps_major < 3 && vs_major >= 3) {
3617 WORD map = vs->baseShader.reg_maps.output_registers;
3619 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3620 output_signature = vs->baseShader.output_signature;
3622 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3623 for (i = 0; map; map >>= 1, ++i)
3627 if (!(map & 1)) continue;
3629 semantic_name = output_signature[i].semantic_name;
3630 semantic_idx = output_signature[i].semantic_idx;
3631 write_mask = output_signature[i].mask;
3632 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3634 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3636 if (semantic_idx == 0)
3637 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3638 else if (semantic_idx == 1)
3639 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3641 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3643 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3645 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3647 if (semantic_idx < 8)
3649 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3650 write_mask |= WINED3DSP_WRITEMASK_3;
3652 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3653 semantic_idx, reg_mask, i, reg_mask);
3654 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3655 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3658 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3660 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3662 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3664 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3667 shader_addline(buffer, "}\n");
3669 } else if(ps_major >= 3 && vs_major >= 3) {
3670 WORD map = vs->baseShader.reg_maps.output_registers;
3672 output_signature = vs->baseShader.output_signature;
3674 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3675 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3676 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3678 /* First, sort out position and point size. Those are not passed to the pixel shader */
3679 for (i = 0; map; map >>= 1, ++i)
3681 if (!(map & 1)) continue;
3683 semantic_name = output_signature[i].semantic_name;
3684 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3686 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3688 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3690 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3692 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3696 /* Then, fix the pixel shader input */
3697 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3698 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3700 shader_addline(buffer, "}\n");
3701 } else if(ps_major >= 3 && vs_major < 3) {
3702 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3703 shader_addline(buffer, "void order_ps_input() {\n");
3704 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3705 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3706 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3708 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3709 &ps->baseShader.reg_maps, NULL, NULL);
3710 shader_addline(buffer, "}\n");
3712 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3715 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3716 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3717 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
3718 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
3719 GL_EXTCALL(glCompileShaderARB(ret));
3720 checkGLcall("glCompileShaderARB(ret)");
3725 /* GL locking is done by the caller */
3726 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3727 GLhandleARB programId, char prefix)
3729 const local_constant *lconst;
3734 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3735 value = (const float *)lconst->value;
3736 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3737 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3738 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3740 checkGLcall("Hardcoding local constants");
3743 /* GL locking is done by the caller */
3744 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3745 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3746 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3748 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3749 const struct wined3d_gl_info *gl_info = context->gl_info;
3750 CONST DWORD *function = This->baseShader.function;
3751 struct shader_glsl_ctx_priv priv_ctx;
3753 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3754 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3756 memset(&priv_ctx, 0, sizeof(priv_ctx));
3757 priv_ctx.cur_ps_args = args;
3758 priv_ctx.cur_np2fixup_info = np2fixup_info;
3760 shader_addline(buffer, "#version 120\n");
3762 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
3764 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3766 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3768 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3769 * drivers write a warning if we don't do so
3771 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3773 if (gl_info->supported[EXT_GPU_SHADER4])
3775 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3778 /* Base Declarations */
3779 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3781 /* Pack 3.0 inputs */
3782 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3784 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
3785 This->baseShader.input_signature, reg_maps, args->vp_mode);
3788 /* Base Shader Body */
3789 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3791 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3792 if (reg_maps->shader_version.major < 2)
3794 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3795 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3798 if (args->srgb_correction)
3800 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
3801 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
3802 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
3803 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
3804 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
3805 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
3807 /* Pixel shader < 3.0 do not replace the fog stage.
3808 * This implements linear fog computation and blending.
3809 * TODO: non linear fog
3810 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3811 * -1/(e-s) and e/(e-s) respectively.
3813 if (reg_maps->shader_version.major < 3)
3816 case FOG_OFF: break;
3818 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3819 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3820 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3821 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3824 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3825 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3826 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3827 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3830 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3831 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3832 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3833 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3838 shader_addline(buffer, "}\n");
3840 TRACE("Compiling shader object %u\n", shader_obj);
3841 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3842 GL_EXTCALL(glCompileShaderARB(shader_obj));
3843 print_glsl_info_log(gl_info, shader_obj);
3845 /* Store the shader object */
3849 /* GL locking is done by the caller */
3850 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
3851 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
3852 const struct vs_compile_args *args)
3854 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3855 const struct wined3d_gl_info *gl_info = context->gl_info;
3856 CONST DWORD *function = This->baseShader.function;
3857 struct shader_glsl_ctx_priv priv_ctx;
3859 /* Create the hw GLSL shader program and assign it as the shader->prgId */
3860 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3862 shader_addline(buffer, "#version 120\n");
3864 if (gl_info->supported[EXT_GPU_SHADER4])
3866 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3869 memset(&priv_ctx, 0, sizeof(priv_ctx));
3870 priv_ctx.cur_vs_args = args;
3872 /* Base Declarations */
3873 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3875 /* Base Shader Body */
3876 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
3878 /* Unpack 3.0 outputs */
3879 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
3880 else shader_addline(buffer, "order_ps_input();\n");
3882 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
3883 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
3884 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
3885 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
3887 if(args->fog_src == VS_FOG_Z) {
3888 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
3889 } else if (!reg_maps->fog) {
3890 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
3893 /* Write the final position.
3895 * OpenGL coordinates specify the center of the pixel while d3d coords specify
3896 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
3897 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3898 * contains 1.0 to allow a mad.
3900 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
3901 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
3902 if(args->clip_enabled) {
3903 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
3906 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3908 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
3909 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
3910 * which is the same as z = z * 2 - w.
3912 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
3914 shader_addline(buffer, "}\n");
3916 TRACE("Compiling shader object %u\n", shader_obj);
3917 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3918 GL_EXTCALL(glCompileShaderARB(shader_obj));
3919 print_glsl_info_log(gl_info, shader_obj);
3924 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
3925 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
3926 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
3930 struct glsl_ps_compiled_shader *new_array;
3931 struct glsl_pshader_private *shader_data;
3932 struct ps_np2fixup_info *np2fixup = NULL;
3935 if (!shader->baseShader.backend_data)
3937 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3938 if (!shader->baseShader.backend_data)
3940 ERR("Failed to allocate backend data.\n");
3944 shader_data = shader->baseShader.backend_data;
3946 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3947 * so a linear search is more performant than a hashmap or a binary search
3948 * (cache coherency etc)
3950 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3951 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
3952 if(args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
3953 return shader_data->gl_shaders[i].prgId;
3957 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
3958 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3959 if (shader_data->num_gl_shaders)
3961 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3962 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3963 new_size * sizeof(*shader_data->gl_shaders));
3965 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3970 ERR("Out of memory\n");
3973 shader_data->gl_shaders = new_array;
3974 shader_data->shader_array_size = new_size;
3977 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3979 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
3980 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
3982 pixelshader_update_samplers(&shader->baseShader.reg_maps,
3983 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
3985 shader_buffer_clear(buffer);
3986 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
3987 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3988 *np2fixup_info = np2fixup;
3993 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
3994 const DWORD use_map) {
3995 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
3996 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
3997 return stored->fog_src == new->fog_src;
4000 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4001 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4002 const struct vs_compile_args *args)
4006 struct glsl_vs_compiled_shader *new_array;
4007 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4008 struct glsl_vshader_private *shader_data;
4011 if (!shader->baseShader.backend_data)
4013 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4014 if (!shader->baseShader.backend_data)
4016 ERR("Failed to allocate backend data.\n");
4020 shader_data = shader->baseShader.backend_data;
4022 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4023 * so a linear search is more performant than a hashmap or a binary search
4024 * (cache coherency etc)
4026 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4027 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4028 return shader_data->gl_shaders[i].prgId;
4032 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4034 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4035 if (shader_data->num_gl_shaders)
4037 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4038 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4039 new_size * sizeof(*shader_data->gl_shaders));
4041 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4046 ERR("Out of memory\n");
4049 shader_data->gl_shaders = new_array;
4050 shader_data->shader_array_size = new_size;
4053 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4055 shader_buffer_clear(buffer);
4056 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4057 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4062 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4063 * It sets the programId on the current StateBlock (because it should be called
4064 * inside of the DrawPrimitive() part of the render loop).
4066 * If a program for the given combination does not exist, create one, and store
4067 * the program in the hash table. If it creates a program, it will link the
4068 * given objects, too.
4071 /* GL locking is done by the caller */
4072 static void set_glsl_shader_program(const struct wined3d_context *context,
4073 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4075 IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
4076 IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
4077 const struct wined3d_gl_info *gl_info = context->gl_info;
4078 struct shader_glsl_priv *priv = device->shader_priv;
4079 struct glsl_shader_prog_link *entry = NULL;
4080 GLhandleARB programId = 0;
4081 GLhandleARB reorder_shader_id = 0;
4084 struct ps_compile_args ps_compile_args;
4085 struct vs_compile_args vs_compile_args;
4087 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4088 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4090 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4092 priv->glsl_program = entry;
4096 /* If we get to this point, then no matching program exists, so we create one */
4097 programId = GL_EXTCALL(glCreateProgramObjectARB());
4098 TRACE("Created new GLSL shader program %u\n", programId);
4100 /* Create the entry */
4101 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4102 entry->programId = programId;
4103 entry->vshader = vshader;
4104 entry->pshader = pshader;
4105 entry->vs_args = vs_compile_args;
4106 entry->ps_args = ps_compile_args;
4107 entry->constant_version = 0;
4108 entry->np2Fixup_info = NULL;
4109 /* Add the hash table entry */
4110 add_glsl_program_entry(priv, entry);
4112 /* Set the current program */
4113 priv->glsl_program = entry;
4115 /* Attach GLSL vshader */
4118 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4119 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4120 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4123 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4124 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4125 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4126 checkGLcall("glAttachObjectARB");
4127 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4130 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4132 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4133 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4134 checkGLcall("glAttachObjectARB");
4136 /* Bind vertex attributes to a corresponding index number to match
4137 * the same index numbers as ARB_vertex_programs (makes loading
4138 * vertex attributes simpler). With this method, we can use the
4139 * exact same code to load the attributes later for both ARB and
4142 * We have to do this here because we need to know the Program ID
4143 * in order to make the bindings work, and it has to be done prior
4144 * to linking the GLSL program. */
4145 for (i = 0; map; map >>= 1, ++i)
4147 if (!(map & 1)) continue;
4149 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4150 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4152 checkGLcall("glBindAttribLocationARB");
4154 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4157 /* Attach GLSL pshader */
4160 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4161 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4162 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4163 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4164 checkGLcall("glAttachObjectARB");
4166 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4169 /* Link the program */
4170 TRACE("Linking GLSL shader program %u\n", programId);
4171 GL_EXTCALL(glLinkProgramARB(programId));
4172 print_glsl_info_log(gl_info, programId);
4174 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4175 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4176 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4178 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4179 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4181 for (i = 0; i < MAX_CONST_I; ++i)
4183 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4184 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4186 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4187 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4188 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4190 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4191 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4193 for (i = 0; i < MAX_CONST_I; ++i)
4195 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4196 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4202 for(i = 0; i < MAX_TEXTURES; i++) {
4203 sprintf(name, "bumpenvmat%u", i);
4204 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4205 sprintf(name, "luminancescale%u", i);
4206 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4207 sprintf(name, "luminanceoffset%u", i);
4208 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4211 if (ps_compile_args.np2_fixup) {
4212 if (entry->np2Fixup_info) {
4213 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4215 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4220 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4221 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4222 checkGLcall("Find glsl program uniform locations");
4225 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4226 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4228 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4229 entry->vertex_color_clamp = GL_FALSE;
4231 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4234 /* Set the shader to allow uniform loading on it */
4235 GL_EXTCALL(glUseProgramObjectARB(programId));
4236 checkGLcall("glUseProgramObjectARB(programId)");
4238 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4239 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4240 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4241 * vertex shader with fixed function pixel processing is used we make sure that the card
4242 * supports enough samplers to allow the max number of vertex samplers with all possible
4243 * fixed function fragment processing setups. So once the program is linked these samplers
4246 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4247 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4249 /* If the local constants do not have to be loaded with the environment constants,
4250 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4253 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
4254 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4256 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
4257 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4261 /* GL locking is done by the caller */
4262 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4264 GLhandleARB program_id;
4265 GLhandleARB vshader_id, pshader_id;
4266 static const char *blt_vshader[] =
4271 " gl_Position = gl_Vertex;\n"
4272 " gl_FrontColor = vec4(1.0);\n"
4273 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4277 static const char *blt_pshaders[tex_type_count] =
4283 "uniform sampler2D sampler;\n"
4286 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4292 "uniform samplerCube sampler;\n"
4295 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4299 "#extension GL_ARB_texture_rectangle : enable\n"
4300 "uniform sampler2DRect sampler;\n"
4303 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4307 if (!blt_pshaders[tex_type])
4309 FIXME("tex_type %#x not supported\n", tex_type);
4313 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4314 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4315 GL_EXTCALL(glCompileShaderARB(vshader_id));
4317 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4318 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4319 GL_EXTCALL(glCompileShaderARB(pshader_id));
4321 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4322 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4323 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4324 GL_EXTCALL(glLinkProgramARB(program_id));
4326 print_glsl_info_log(gl_info, program_id);
4328 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4331 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4332 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4336 /* GL locking is done by the caller */
4337 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4339 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
4340 const struct wined3d_gl_info *gl_info = context->gl_info;
4341 struct shader_glsl_priv *priv = device->shader_priv;
4342 GLhandleARB program_id = 0;
4343 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4345 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4347 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4348 else priv->glsl_program = NULL;
4350 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4352 if (old_vertex_color_clamp != current_vertex_color_clamp)
4354 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4356 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4357 checkGLcall("glClampColorARB");
4361 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4365 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4366 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4367 GL_EXTCALL(glUseProgramObjectARB(program_id));
4368 checkGLcall("glUseProgramObjectARB");
4370 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4371 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4372 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4373 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4375 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4379 /* GL locking is done by the caller */
4380 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4381 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4382 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4383 struct shader_glsl_priv *priv = This->shader_priv;
4384 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4386 if (!*blt_program) {
4388 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4389 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4390 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4391 GL_EXTCALL(glUniform1iARB(loc, 0));
4393 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4397 /* GL locking is done by the caller */
4398 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4399 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4400 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4401 struct shader_glsl_priv *priv = This->shader_priv;
4402 GLhandleARB program_id;
4404 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4405 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4407 GL_EXTCALL(glUseProgramObjectARB(program_id));
4408 checkGLcall("glUseProgramObjectARB");
4411 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4412 const struct list *linked_programs;
4413 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4414 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4415 struct shader_glsl_priv *priv = device->shader_priv;
4416 const struct wined3d_gl_info *gl_info;
4417 IWineD3DPixelShaderImpl *ps = NULL;
4418 IWineD3DVertexShaderImpl *vs = NULL;
4419 struct wined3d_context *context;
4421 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4422 * can be called from IWineD3DBaseShader::Release
4424 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4427 struct glsl_pshader_private *shader_data;
4428 ps = (IWineD3DPixelShaderImpl *) This;
4429 shader_data = ps->baseShader.backend_data;
4430 if(!shader_data || shader_data->num_gl_shaders == 0)
4432 HeapFree(GetProcessHeap(), 0, shader_data);
4433 ps->baseShader.backend_data = NULL;
4437 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4438 gl_info = context->gl_info;
4440 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4443 shader_glsl_select(context, FALSE, FALSE);
4447 struct glsl_vshader_private *shader_data;
4448 vs = (IWineD3DVertexShaderImpl *) This;
4449 shader_data = vs->baseShader.backend_data;
4450 if(!shader_data || shader_data->num_gl_shaders == 0)
4452 HeapFree(GetProcessHeap(), 0, shader_data);
4453 vs->baseShader.backend_data = NULL;
4457 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4458 gl_info = context->gl_info;
4460 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4463 shader_glsl_select(context, FALSE, FALSE);
4468 linked_programs = &This->baseShader.linked_programs;
4470 TRACE("Deleting linked programs\n");
4471 if (linked_programs->next) {
4472 struct glsl_shader_prog_link *entry, *entry2;
4476 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4477 delete_glsl_program_entry(priv, gl_info, entry);
4480 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4481 delete_glsl_program_entry(priv, gl_info, entry);
4489 struct glsl_pshader_private *shader_data = ps->baseShader.backend_data;
4492 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4493 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4494 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4495 checkGLcall("glDeleteObjectARB");
4498 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4499 HeapFree(GetProcessHeap(), 0, shader_data);
4500 ps->baseShader.backend_data = NULL;
4503 struct glsl_vshader_private *shader_data = vs->baseShader.backend_data;
4506 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4507 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4508 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4509 checkGLcall("glDeleteObjectARB");
4512 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4513 HeapFree(GetProcessHeap(), 0, shader_data);
4514 vs->baseShader.backend_data = NULL;
4517 context_release(context);
4520 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4522 const glsl_program_key_t *k = key;
4523 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4524 const struct glsl_shader_prog_link, program_lookup_entry);
4527 if (k->vshader > prog->vshader) return 1;
4528 else if (k->vshader < prog->vshader) return -1;
4530 if (k->pshader > prog->pshader) return 1;
4531 else if (k->pshader < prog->pshader) return -1;
4533 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4534 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4539 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4541 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4542 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4546 ERR("Failed to allocate memory\n");
4550 heap->entries = mem;
4551 heap->entries[1].version = 0;
4552 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4558 static void constant_heap_free(struct constant_heap *heap)
4560 HeapFree(GetProcessHeap(), 0, heap->entries);
4563 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4568 glsl_program_key_compare,
4571 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4572 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4573 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4574 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4575 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4576 gl_info->limits.glsl_ps_float_constants)) + 1;
4578 if (!shader_buffer_init(&priv->shader_buffer))
4580 ERR("Failed to initialize shader buffer.\n");
4584 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4587 ERR("Failed to allocate memory.\n");
4591 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4593 ERR("Failed to initialize vertex shader constant heap\n");
4597 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4599 ERR("Failed to initialize pixel shader constant heap\n");
4603 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4605 ERR("Failed to initialize rbtree.\n");
4609 priv->next_constant_version = 1;
4611 This->shader_priv = priv;
4615 constant_heap_free(&priv->pconst_heap);
4616 constant_heap_free(&priv->vconst_heap);
4617 HeapFree(GetProcessHeap(), 0, priv->stack);
4618 shader_buffer_free(&priv->shader_buffer);
4619 HeapFree(GetProcessHeap(), 0, priv);
4620 return E_OUTOFMEMORY;
4623 /* Context activation is done by the caller. */
4624 static void shader_glsl_free(IWineD3DDevice *iface) {
4625 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4626 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4627 struct shader_glsl_priv *priv = This->shader_priv;
4631 for (i = 0; i < tex_type_count; ++i)
4633 if (priv->depth_blt_program[i])
4635 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4640 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4641 constant_heap_free(&priv->pconst_heap);
4642 constant_heap_free(&priv->vconst_heap);
4643 HeapFree(GetProcessHeap(), 0, priv->stack);
4644 shader_buffer_free(&priv->shader_buffer);
4646 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4647 This->shader_priv = NULL;
4650 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4651 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4655 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype,
4656 const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4658 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4659 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4660 * on the version of NV_vertex_program.
4661 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4662 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4663 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4664 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4666 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4667 || gl_info->limits.arb_ps_instructions <= 512)
4668 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4670 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4671 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4672 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4674 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4675 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4676 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4677 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4678 * in max native instructions. Intel and others also offer the info in this extension but they
4679 * don't support GLSL (at least on Windows).
4681 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4682 * of instructions is 512 or less we have to do with ps2.0 hardware.
4683 * 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.
4685 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4686 || gl_info->limits.arb_ps_instructions <= 512)
4687 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4689 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4691 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4693 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4694 * Direct3D minimum requirement.
4696 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4697 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4699 * The problem is that the refrast clamps temporary results in the shader to
4700 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4701 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4702 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4703 * offer a way to query this.
4705 pCaps->PixelShader1xMaxValue = 8.0;
4706 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4708 pCaps->VSClipping = TRUE;
4711 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4713 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4715 TRACE("Checking support for fixup:\n");
4716 dump_color_fixup_desc(fixup);
4719 /* We support everything except YUV conversions. */
4720 if (!is_yuv_fixup(fixup))
4726 TRACE("[FAILED]\n");
4730 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4732 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4733 /* WINED3DSIH_ADD */ shader_glsl_arith,
4734 /* WINED3DSIH_BEM */ shader_glsl_bem,
4735 /* WINED3DSIH_BREAK */ shader_glsl_break,
4736 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4737 /* WINED3DSIH_BREAKP */ NULL,
4738 /* WINED3DSIH_CALL */ shader_glsl_call,
4739 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4740 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4741 /* WINED3DSIH_CND */ shader_glsl_cnd,
4742 /* WINED3DSIH_CRS */ shader_glsl_cross,
4743 /* WINED3DSIH_CUT */ NULL,
4744 /* WINED3DSIH_DCL */ NULL,
4745 /* WINED3DSIH_DEF */ NULL,
4746 /* WINED3DSIH_DEFB */ NULL,
4747 /* WINED3DSIH_DEFI */ NULL,
4748 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4749 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4750 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4751 /* WINED3DSIH_DST */ shader_glsl_dst,
4752 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4753 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4754 /* WINED3DSIH_ELSE */ shader_glsl_else,
4755 /* WINED3DSIH_EMIT */ NULL,
4756 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4757 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4758 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4759 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4760 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4761 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4762 /* WINED3DSIH_IADD */ NULL,
4763 /* WINED3DSIH_IF */ shader_glsl_if,
4764 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4765 /* WINED3DSIH_IGE */ NULL,
4766 /* WINED3DSIH_LABEL */ shader_glsl_label,
4767 /* WINED3DSIH_LIT */ shader_glsl_lit,
4768 /* WINED3DSIH_LOG */ shader_glsl_log,
4769 /* WINED3DSIH_LOGP */ shader_glsl_log,
4770 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4771 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4772 /* WINED3DSIH_LT */ NULL,
4773 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4774 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4775 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4776 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4777 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4778 /* WINED3DSIH_MAD */ shader_glsl_mad,
4779 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4780 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4781 /* WINED3DSIH_MOV */ shader_glsl_mov,
4782 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4783 /* WINED3DSIH_MUL */ shader_glsl_arith,
4784 /* WINED3DSIH_NOP */ NULL,
4785 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4786 /* WINED3DSIH_PHASE */ NULL,
4787 /* WINED3DSIH_POW */ shader_glsl_pow,
4788 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4789 /* WINED3DSIH_REP */ shader_glsl_rep,
4790 /* WINED3DSIH_RET */ shader_glsl_ret,
4791 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4792 /* WINED3DSIH_SETP */ NULL,
4793 /* WINED3DSIH_SGE */ shader_glsl_compare,
4794 /* WINED3DSIH_SGN */ shader_glsl_sgn,
4795 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4796 /* WINED3DSIH_SLT */ shader_glsl_compare,
4797 /* WINED3DSIH_SUB */ shader_glsl_arith,
4798 /* WINED3DSIH_TEX */ shader_glsl_tex,
4799 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
4800 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
4801 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
4802 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
4803 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
4804 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
4805 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
4806 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4807 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4808 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
4809 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
4810 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
4811 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
4812 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4813 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
4814 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
4815 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
4816 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
4817 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
4818 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
4819 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
4822 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
4823 SHADER_HANDLER hw_fct;
4825 /* Select handler */
4826 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
4828 /* Unhandled opcode */
4831 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
4836 shader_glsl_add_instruction_modifiers(ins);
4839 const shader_backend_t glsl_shader_backend = {
4840 shader_glsl_handle_instruction,
4842 shader_glsl_select_depth_blt,
4843 shader_glsl_deselect_depth_blt,
4844 shader_glsl_update_float_vertex_constants,
4845 shader_glsl_update_float_pixel_constants,
4846 shader_glsl_load_constants,
4847 shader_glsl_load_np2fixup_constants,
4848 shader_glsl_destroy,
4851 shader_glsl_dirty_const,
4852 shader_glsl_get_caps,
4853 shader_glsl_color_fixup_supported,