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 wine_rb_tree program_lookup;
87 struct glsl_shader_prog_link *glsl_program;
88 struct constant_heap vconst_heap;
89 struct constant_heap pconst_heap;
91 GLhandleARB depth_blt_program[tex_type_count];
92 UINT next_constant_version;
95 /* Struct to maintain data about a linked GLSL program */
96 struct glsl_shader_prog_link {
97 struct wine_rb_entry program_lookup_entry;
98 struct list vshader_entry;
99 struct list pshader_entry;
100 GLhandleARB programId;
101 GLint *vuniformF_locations;
102 GLint *puniformF_locations;
103 GLint vuniformI_locations[MAX_CONST_I];
104 GLint puniformI_locations[MAX_CONST_I];
105 GLint posFixup_location;
106 GLint np2Fixup_location[MAX_FRAGMENT_SAMPLERS];
107 GLint bumpenvmat_location[MAX_TEXTURES];
108 GLint luminancescale_location[MAX_TEXTURES];
109 GLint luminanceoffset_location[MAX_TEXTURES];
110 GLint ycorrection_location;
111 GLenum vertex_color_clamp;
112 IWineD3DVertexShader *vshader;
113 IWineD3DPixelShader *pshader;
114 struct vs_compile_args vs_args;
115 struct ps_compile_args ps_args;
116 UINT constant_version;
120 IWineD3DVertexShader *vshader;
121 IWineD3DPixelShader *pshader;
122 struct ps_compile_args ps_args;
123 struct vs_compile_args vs_args;
124 } glsl_program_key_t;
126 struct shader_glsl_ctx_priv {
127 const struct vs_compile_args *cur_vs_args;
128 const struct ps_compile_args *cur_ps_args;
131 struct glsl_ps_compiled_shader
133 struct ps_compile_args args;
137 struct glsl_pshader_private
139 struct glsl_ps_compiled_shader *gl_shaders;
140 UINT num_gl_shaders, shader_array_size;
143 struct glsl_vs_compiled_shader
145 struct vs_compile_args args;
149 struct glsl_vshader_private
151 struct glsl_vs_compiled_shader *gl_shaders;
152 UINT num_gl_shaders, shader_array_size;
155 /* Extract a line from the info log.
156 * Note that this modifies the source string. */
157 static char *get_info_log_line(char **ptr)
162 if (!(q = strstr(p, "\n")))
164 if (!*p) return NULL;
174 /** Prints the GLSL info log which will contain error messages if they exist */
175 /* GL locking is done by the caller */
176 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
178 int infologLength = 0;
183 static const char * const spam[] =
185 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
186 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx */
187 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
188 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
189 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
190 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
191 "Fragment shader was successfully compiled to run on hardware.\n"
192 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
193 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
194 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
195 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n" /* MacOS ati */
198 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
200 GL_EXTCALL(glGetObjectParameterivARB(obj,
201 GL_OBJECT_INFO_LOG_LENGTH_ARB,
204 /* A size of 1 is just a null-terminated string, so the log should be bigger than
205 * that if there are errors. */
206 if (infologLength > 1)
210 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
211 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
213 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
214 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
217 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
218 if(strcmp(infoLog, spam[i]) == 0) {
227 TRACE("Spam received from GLSL shader #%u:\n", obj);
228 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
232 FIXME("Error received from GLSL shader #%u:\n", obj);
233 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
235 HeapFree(GetProcessHeap(), 0, infoLog);
240 * Loads (pixel shader) samplers
242 /* GL locking is done by the caller */
243 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
247 char sampler_name[20];
249 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
250 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
251 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
252 if (name_loc != -1) {
253 DWORD mapped_unit = tex_unit_map[i];
254 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(fragment_samplers))
256 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
257 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
258 checkGLcall("glUniform1iARB");
260 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
266 /* GL locking is done by the caller */
267 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
270 char sampler_name[20];
273 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
274 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
275 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
276 if (name_loc != -1) {
277 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
278 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(combined_samplers))
280 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
281 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
282 checkGLcall("glUniform1iARB");
284 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
290 /* GL locking is done by the caller */
291 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
292 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
295 unsigned int heap_idx = 1;
298 if (heap->entries[heap_idx].version <= version) return;
300 idx = heap->entries[heap_idx].idx;
301 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
302 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
304 while (stack_idx >= 0)
306 /* Note that we fall through to the next case statement. */
307 switch(stack[stack_idx])
309 case HEAP_NODE_TRAVERSE_LEFT:
311 unsigned int left_idx = heap_idx << 1;
312 if (left_idx < heap->size && heap->entries[left_idx].version > version)
315 idx = heap->entries[heap_idx].idx;
316 if (constant_locations[idx] != -1)
317 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
319 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
320 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
325 case HEAP_NODE_TRAVERSE_RIGHT:
327 unsigned int right_idx = (heap_idx << 1) + 1;
328 if (right_idx < heap->size && heap->entries[right_idx].version > version)
330 heap_idx = right_idx;
331 idx = heap->entries[heap_idx].idx;
332 if (constant_locations[idx] != -1)
333 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
335 stack[stack_idx++] = HEAP_NODE_POP;
336 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
349 checkGLcall("walk_constant_heap()");
352 /* GL locking is done by the caller */
353 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
355 GLfloat clamped_constant[4];
357 if (location == -1) return;
359 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
360 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
361 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
362 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
364 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
367 /* GL locking is done by the caller */
368 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
369 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
372 unsigned int heap_idx = 1;
375 if (heap->entries[heap_idx].version <= version) return;
377 idx = heap->entries[heap_idx].idx;
378 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
379 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
381 while (stack_idx >= 0)
383 /* Note that we fall through to the next case statement. */
384 switch(stack[stack_idx])
386 case HEAP_NODE_TRAVERSE_LEFT:
388 unsigned int left_idx = heap_idx << 1;
389 if (left_idx < heap->size && heap->entries[left_idx].version > version)
392 idx = heap->entries[heap_idx].idx;
393 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
395 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
396 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
401 case HEAP_NODE_TRAVERSE_RIGHT:
403 unsigned int right_idx = (heap_idx << 1) + 1;
404 if (right_idx < heap->size && heap->entries[right_idx].version > version)
406 heap_idx = right_idx;
407 idx = heap->entries[heap_idx].idx;
408 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
410 stack[stack_idx++] = HEAP_NODE_POP;
411 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
424 checkGLcall("walk_constant_heap_clamped()");
427 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
428 /* GL locking is done by the caller */
429 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
430 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
431 unsigned char *stack, UINT version)
433 const local_constant *lconst;
435 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
436 if (This->baseShader.reg_maps.shader_version.major == 1
437 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
438 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
440 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
442 if (!This->baseShader.load_local_constsF)
444 TRACE("No need to load local float constants for this shader\n");
448 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
449 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
451 GLint location = constant_locations[lconst->idx];
452 /* We found this uniform name in the program - go ahead and send the data */
453 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
455 checkGLcall("glUniform4fvARB()");
458 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
459 /* GL locking is done by the caller */
460 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
461 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
466 for (i = 0; constants_set; constants_set >>= 1, ++i)
468 if (!(constants_set & 1)) continue;
470 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
471 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
473 /* We found this uniform name in the program - go ahead and send the data */
474 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
475 checkGLcall("glUniform4ivARB");
478 /* Load immediate constants */
479 ptr = list_head(&This->baseShader.constantsI);
481 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
482 unsigned int idx = lconst->idx;
483 const GLint *values = (const GLint *)lconst->value;
485 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
486 values[0], values[1], values[2], values[3]);
488 /* We found this uniform name in the program - go ahead and send the data */
489 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
490 checkGLcall("glUniform4ivARB");
491 ptr = list_next(&This->baseShader.constantsI, ptr);
495 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
496 /* GL locking is done by the caller */
497 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
498 GLhandleARB programId, const BOOL *constants, WORD constants_set)
503 char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
504 const char* prefix = is_pshader? "PB":"VB";
507 /* TODO: Benchmark and see if it would be beneficial to store the
508 * locations of the constants to avoid looking up each time */
509 for (i = 0; constants_set; constants_set >>= 1, ++i)
511 if (!(constants_set & 1)) continue;
513 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
515 /* TODO: Benchmark and see if it would be beneficial to store the
516 * locations of the constants to avoid looking up each time */
517 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
518 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
521 /* We found this uniform name in the program - go ahead and send the data */
522 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
523 checkGLcall("glUniform1ivARB");
527 /* Load immediate constants */
528 ptr = list_head(&This->baseShader.constantsB);
530 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
531 unsigned int idx = lconst->idx;
532 const GLint *values = (const GLint *)lconst->value;
534 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
536 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
537 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
539 /* We found this uniform name in the program - go ahead and send the data */
540 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
541 checkGLcall("glUniform1ivARB");
543 ptr = list_next(&This->baseShader.constantsB, ptr);
547 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
549 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
553 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
555 /* GL locking is done by the caller (state handler) */
556 static void shader_glsl_load_np2fixup_constants(
557 IWineD3DDevice* device,
559 char useVertexShader) {
561 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
562 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
565 /* No GLSL program set - nothing to do. */
569 if (!usePixelShader) {
570 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
574 if (prog->ps_args.np2_fixup) {
576 UINT fixup = prog->ps_args.np2_fixup;
577 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
578 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
580 for (i = 0; fixup; fixup >>= 1, ++i) {
581 if (-1 != prog->np2Fixup_location[i]) {
582 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
584 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
587 const float tex_dim[2] = {tex->baseTexture.pow2Matrix[0], tex->baseTexture.pow2Matrix[5]};
588 GL_EXTCALL(glUniform2fvARB(prog->np2Fixup_location[i], 1, tex_dim));
596 * Loads the app-supplied constants into the currently set GLSL program.
598 /* GL locking is done by the caller (state handler) */
599 static void shader_glsl_load_constants(
600 IWineD3DDevice* device,
602 char useVertexShader) {
604 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
605 struct shader_glsl_priv *priv = deviceImpl->shader_priv;
606 IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
607 const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
609 GLhandleARB programId;
610 struct glsl_shader_prog_link *prog = priv->glsl_program;
611 UINT constant_version;
615 /* No GLSL program set - nothing to do. */
618 programId = prog->programId;
619 constant_version = prog->constant_version;
621 if (useVertexShader) {
622 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
624 /* Load DirectX 9 float constants/uniforms for vertex shader */
625 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
626 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
628 /* Load DirectX 9 integer constants/uniforms for vertex shader */
629 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
630 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
632 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
633 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
634 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
636 /* Upload the position fixup params */
637 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
638 checkGLcall("glUniform4fvARB");
641 if (usePixelShader) {
643 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
645 /* Load DirectX 9 float constants/uniforms for pixel shader */
646 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
647 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
649 /* Load DirectX 9 integer constants/uniforms for pixel shader */
650 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
651 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
653 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
654 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
655 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
657 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
658 * It can't be 0 for a valid texbem instruction.
660 for(i = 0; i < ((IWineD3DPixelShaderImpl *) pshader)->numbumpenvmatconsts; i++) {
661 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pshader;
662 int stage = ps->luminanceconst[i].texunit;
664 const float *data = (const float *)&stateBlock->textureState[(int)ps->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
665 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
666 checkGLcall("glUniformMatrix2fvARB");
668 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
669 * is set too, so we can check that in the needsbumpmat check
671 if(ps->baseShader.reg_maps.luminanceparams[stage]) {
672 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
673 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
675 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
676 checkGLcall("glUniform1fvARB");
677 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
678 checkGLcall("glUniform1fvARB");
682 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
683 float correction_params[4];
684 if(deviceImpl->render_offscreen) {
685 correction_params[0] = 0.0;
686 correction_params[1] = 1.0;
688 /* position is window relative, not viewport relative */
689 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
690 correction_params[1] = -1.0;
692 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
696 if (priv->next_constant_version == UINT_MAX)
698 TRACE("Max constant version reached, resetting to 0.\n");
699 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
700 priv->next_constant_version = 1;
704 prog->constant_version = priv->next_constant_version++;
708 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
709 unsigned int heap_idx, DWORD new_version)
711 struct constant_entry *entries = heap->entries;
712 unsigned int *positions = heap->positions;
713 unsigned int parent_idx;
717 parent_idx = heap_idx >> 1;
719 if (new_version <= entries[parent_idx].version) break;
721 entries[heap_idx] = entries[parent_idx];
722 positions[entries[parent_idx].idx] = heap_idx;
723 heap_idx = parent_idx;
726 entries[heap_idx].version = new_version;
727 entries[heap_idx].idx = idx;
728 positions[idx] = heap_idx;
731 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
733 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
734 struct shader_glsl_priv *priv = This->shader_priv;
735 struct constant_heap *heap = &priv->vconst_heap;
738 for (i = start; i < count + start; ++i)
740 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
741 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
743 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
747 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
749 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
750 struct shader_glsl_priv *priv = This->shader_priv;
751 struct constant_heap *heap = &priv->pconst_heap;
754 for (i = start; i < count + start; ++i)
756 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
757 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
759 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
763 static int vec4_varyings(DWORD shader_major, const WineD3D_GL_Info *gl_info)
765 int ret = GL_LIMITS(glsl_varyings) / 4;
766 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
767 if(shader_major > 3) return ret;
769 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
770 if(gl_info->glsl_clip_varying) ret -= 1;
774 /** Generate the variable & register declarations for the GLSL output target */
775 static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
776 SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info,
777 const struct ps_compile_args *ps_args)
779 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
780 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
781 unsigned int i, extra_constants_needed = 0;
782 const local_constant *lconst;
784 /* There are some minor differences between pixel and vertex shaders */
785 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
786 char prefix = pshader ? 'P' : 'V';
788 /* Prototype the subroutines */
789 for (i = 0; i < This->baseShader.limits.label; i++) {
790 if (reg_maps->labels[i])
791 shader_addline(buffer, "void subroutine%u();\n", i);
794 /* Declare the constants (aka uniforms) */
795 if (This->baseShader.limits.constant_float > 0) {
796 unsigned max_constantsF;
797 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
798 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
799 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
800 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
801 * a dx9 card, as long as it doesn't also use all the other constants.
803 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
804 * declare only the amount that we're assured to have.
806 * Thus we run into problems in these two cases:
807 * 1) The shader really uses more uniforms than supported
808 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
811 /* No indirect addressing here */
812 max_constantsF = GL_LIMITS(pshader_constantsF);
814 if(This->baseShader.reg_maps.usesrelconstF) {
815 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
816 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
817 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
818 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
820 * Writing gl_ClipPos requires one uniform for each clipplane as well.
822 max_constantsF = GL_LIMITS(vshader_constantsF) - 3 - GL_LIMITS(clipplanes);
823 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
824 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
825 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
826 * for now take this into account when calculating the number of available constants
828 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
829 /* Set by driver quirks in directx.c */
830 max_constantsF -= GLINFO_LOCATION.reserved_glsl_constants;
832 max_constantsF = GL_LIMITS(vshader_constantsF);
835 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
836 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
839 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
840 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
842 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
843 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
845 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
846 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
849 shader_addline(buffer, "uniform vec4 posFixup;\n");
850 /* Predeclaration; This function is added at link time based on the pixel shader.
851 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
852 * that. We know the input to the reorder function at vertex shader compile time, so
853 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
854 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
855 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
856 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
857 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
860 if (reg_maps->shader_version.major >= 3)
862 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
864 shader_addline(buffer, "void order_ps_input();\n");
867 IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
869 ps_impl->numbumpenvmatconsts = 0;
870 for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
871 if(!reg_maps->bumpmat[i]) {
875 ps_impl->bumpenvmatconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
876 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
878 if(reg_maps->luminanceparams) {
879 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
880 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
881 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
882 extra_constants_needed++;
884 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = -1;
887 extra_constants_needed++;
888 ps_impl->numbumpenvmatconsts++;
891 if(ps_args->srgb_correction) {
892 shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
893 srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
894 shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
895 srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
897 if(reg_maps->vpos || reg_maps->usesdsy) {
898 if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
899 shader_addline(buffer, "uniform vec4 ycorrection;\n");
900 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
901 extra_constants_needed++;
903 /* This happens because we do not have proper tracking of the constant registers that are
904 * actually used, only the max limit of the shader version
906 FIXME("Cannot find a free uniform for vpos correction params\n");
907 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
908 device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
909 device->render_offscreen ? 1.0 : -1.0);
911 shader_addline(buffer, "vec4 vpos;\n");
915 /* Declare texture samplers */
916 for (i = 0; i < This->baseShader.limits.sampler; i++) {
917 if (reg_maps->sampler_type[i])
919 switch (reg_maps->sampler_type[i])
922 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
925 if(device->stateBlock->textures[i] &&
926 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
927 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
929 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
932 if (pshader && ps_args->np2_fixup & (1 << i))
934 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
935 * while D3D has them in the (normalized) [0,1]x[0,1] range.
936 * samplerNP2Fixup stores texture dimensions and is updated through
937 * shader_glsl_load_np2fixup_constants when the sampler changes. */
938 shader_addline(buffer, "uniform vec2 %csamplerNP2Fixup%u;\n", prefix, i);
941 case WINED3DSTT_CUBE:
942 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
944 case WINED3DSTT_VOLUME:
945 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
948 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
949 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
955 /* Declare address variables */
956 for (i = 0; i < This->baseShader.limits.address; i++) {
957 if (reg_maps->address[i])
958 shader_addline(buffer, "ivec4 A%d;\n", i);
961 /* Declare texture coordinate temporaries and initialize them */
962 for (i = 0; i < This->baseShader.limits.texcoord; i++) {
963 if (reg_maps->texcoord[i])
964 shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
967 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
968 * helper function shader that is linked in at link time
970 if (pshader && reg_maps->shader_version.major >= 3)
972 if (use_vs(device->stateBlock))
974 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
976 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
977 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
978 * pixel shader that reads the fixed function color into the packed input registers.
980 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
984 /* Declare output register temporaries */
985 if(This->baseShader.limits.packed_output) {
986 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
989 /* Declare temporary variables */
990 for(i = 0; i < This->baseShader.limits.temporary; i++) {
991 if (reg_maps->temporary[i])
992 shader_addline(buffer, "vec4 R%u;\n", i);
995 /* Declare attributes */
996 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
998 WORD map = reg_maps->input_registers;
1000 for (i = 0; map; map >>= 1, ++i)
1002 if (!(map & 1)) continue;
1004 shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1008 /* Declare loop registers aLx */
1009 for (i = 0; i < reg_maps->loop_depth; i++) {
1010 shader_addline(buffer, "int aL%u;\n", i);
1011 shader_addline(buffer, "int tmpInt%u;\n", i);
1014 /* Temporary variables for matrix operations */
1015 shader_addline(buffer, "vec4 tmp0;\n");
1016 shader_addline(buffer, "vec4 tmp1;\n");
1018 /* Local constants use a different name so they can be loaded once at shader link time
1019 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1020 * float -> string conversion can cause precision loss.
1022 if(!This->baseShader.load_local_constsF) {
1023 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1024 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1028 /* Start the main program */
1029 shader_addline(buffer, "void main() {\n");
1030 if(pshader && reg_maps->vpos) {
1031 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1032 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1033 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1034 * precision troubles when we just substract 0.5.
1036 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1038 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1040 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1041 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1042 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1043 * correctly on drivers that returns integer values.
1045 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1049 /*****************************************************************************
1050 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1052 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1053 ****************************************************************************/
1056 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1057 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1059 /** Used for opcode modifiers - They multiply the result by the specified amount */
1060 static const char * const shift_glsl_tab[] = {
1062 "2.0 * ", /* 1 (x2) */
1063 "4.0 * ", /* 2 (x4) */
1064 "8.0 * ", /* 3 (x8) */
1065 "16.0 * ", /* 4 (x16) */
1066 "32.0 * ", /* 5 (x32) */
1073 "0.0625 * ", /* 12 (d16) */
1074 "0.125 * ", /* 13 (d8) */
1075 "0.25 * ", /* 14 (d4) */
1076 "0.5 * " /* 15 (d2) */
1079 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1080 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1084 switch (src_modifier)
1086 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1087 case WINED3DSPSM_DW:
1088 case WINED3DSPSM_NONE:
1089 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1091 case WINED3DSPSM_NEG:
1092 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1094 case WINED3DSPSM_NOT:
1095 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1097 case WINED3DSPSM_BIAS:
1098 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1100 case WINED3DSPSM_BIASNEG:
1101 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1103 case WINED3DSPSM_SIGN:
1104 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1106 case WINED3DSPSM_SIGNNEG:
1107 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1109 case WINED3DSPSM_COMP:
1110 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1112 case WINED3DSPSM_X2:
1113 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1115 case WINED3DSPSM_X2NEG:
1116 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1118 case WINED3DSPSM_ABS:
1119 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1121 case WINED3DSPSM_ABSNEG:
1122 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1125 FIXME("Unhandled modifier %u\n", src_modifier);
1126 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1130 /** Writes the GLSL variable name that corresponds to the register that the
1131 * DX opcode parameter is trying to access */
1132 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1133 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1135 /* oPos, oFog and oPts in D3D */
1136 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1138 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1139 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1140 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
1141 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1147 case WINED3DSPR_TEMP:
1148 sprintf(register_name, "R%u", reg->idx);
1151 case WINED3DSPR_INPUT:
1152 /* vertex shaders */
1155 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1156 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1157 sprintf(register_name, "attrib%u", reg->idx);
1161 /* pixel shaders >= 3.0 */
1162 if (This->baseShader.reg_maps.shader_version.major >= 3)
1164 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1165 DWORD in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1169 glsl_src_param_t rel_param;
1171 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1173 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1174 * operation there */
1177 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1179 sprintf(register_name,
1180 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1181 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1182 rel_param.param_str, idx);
1186 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1191 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1193 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1194 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1195 rel_param.param_str);
1199 sprintf(register_name, "IN[%s]", rel_param.param_str);
1205 if (idx == in_count) sprintf(register_name, "gl_Color");
1206 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1207 else sprintf(register_name, "IN[%u]", idx);
1212 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1213 else strcpy(register_name, "gl_SecondaryColor");
1218 case WINED3DSPR_CONST:
1220 const char prefix = pshader ? 'P' : 'V';
1222 /* Relative addressing */
1225 glsl_src_param_t rel_param;
1226 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1227 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1228 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1232 if (shader_constant_is_local(This, reg->idx))
1233 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1235 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1240 case WINED3DSPR_CONSTINT:
1241 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1242 else sprintf(register_name, "VI[%u]", reg->idx);
1245 case WINED3DSPR_CONSTBOOL:
1246 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1247 else sprintf(register_name, "VB[%u]", reg->idx);
1250 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1251 if (pshader) sprintf(register_name, "T%u", reg->idx);
1252 else sprintf(register_name, "A%u", reg->idx);
1255 case WINED3DSPR_LOOP:
1256 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1259 case WINED3DSPR_SAMPLER:
1260 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1261 else sprintf(register_name, "Vsampler%u", reg->idx);
1264 case WINED3DSPR_COLOROUT:
1265 if (reg->idx >= GL_LIMITS(buffers))
1266 WARN("Write to render target %u, only %d supported\n", reg->idx, GL_LIMITS(buffers));
1268 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) sprintf(register_name, "gl_FragData[%u]", reg->idx);
1269 /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
1270 else sprintf(register_name, "gl_FragColor");
1273 case WINED3DSPR_RASTOUT:
1274 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1277 case WINED3DSPR_DEPTHOUT:
1278 sprintf(register_name, "gl_FragDepth");
1281 case WINED3DSPR_ATTROUT:
1282 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1283 else sprintf(register_name, "gl_FrontSecondaryColor");
1286 case WINED3DSPR_TEXCRDOUT:
1287 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1288 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1289 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1292 case WINED3DSPR_MISCTYPE:
1296 sprintf(register_name, "vpos");
1298 else if (reg->idx == 1)
1300 /* Note that gl_FrontFacing is a bool, while vFace is
1301 * a float for which the sign determines front/back */
1302 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1306 FIXME("Unhandled misctype register %d\n", reg->idx);
1307 sprintf(register_name, "unrecognized_register");
1311 case WINED3DSPR_IMMCONST:
1312 switch (reg->immconst_type)
1314 case WINED3D_IMMCONST_FLOAT:
1315 sprintf(register_name, "%.8e", *(float *)reg->immconst_data);
1318 case WINED3D_IMMCONST_FLOAT4:
1319 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1320 *(float *)®->immconst_data[0], *(float *)®->immconst_data[1],
1321 *(float *)®->immconst_data[2], *(float *)®->immconst_data[3]);
1325 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1326 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1331 FIXME("Unhandled register name Type(%d)\n", reg->type);
1332 sprintf(register_name, "unrecognized_register");
1337 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1340 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1341 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1342 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1343 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1347 /* Get the GLSL write mask for the destination register */
1348 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1350 DWORD mask = param->write_mask;
1352 if (shader_is_scalar(¶m->reg))
1354 mask = WINED3DSP_WRITEMASK_0;
1359 shader_glsl_write_mask_to_str(mask, write_mask);
1365 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1366 unsigned int size = 0;
1368 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1369 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1370 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1371 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1376 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1378 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1379 * but addressed as "rgba". To fix this we need to swap the register's x
1380 * and z components. */
1381 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1384 /* swizzle bits fields: wwzzyyxx */
1385 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1386 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1387 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1388 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1392 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1393 BOOL fixup, DWORD mask, char *swizzle_str)
1395 if (shader_is_scalar(¶m->reg))
1396 *swizzle_str = '\0';
1398 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1401 /* From a given parameter token, generate the corresponding GLSL string.
1402 * Also, return the actual register name and swizzle in case the
1403 * caller needs this information as well. */
1404 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1405 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1407 BOOL is_color = FALSE;
1408 char swizzle_str[6];
1410 glsl_src->reg_name[0] = '\0';
1411 glsl_src->param_str[0] = '\0';
1412 swizzle_str[0] = '\0';
1414 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1415 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1416 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1419 /* From a given parameter token, generate the corresponding GLSL string.
1420 * Also, return the actual register name and swizzle in case the
1421 * caller needs this information as well. */
1422 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1423 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1425 BOOL is_color = FALSE;
1427 glsl_dst->mask_str[0] = '\0';
1428 glsl_dst->reg_name[0] = '\0';
1430 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1431 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1434 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1435 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer,
1436 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1438 glsl_dst_param_t glsl_dst;
1441 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1442 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1447 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1448 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, const struct wined3d_shader_instruction *ins)
1450 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1453 /** Process GLSL instruction modifiers */
1454 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1456 glsl_dst_param_t dst_param;
1459 if (!ins->dst_count) return;
1461 modifiers = ins->dst[0].modifiers;
1462 if (!modifiers) return;
1464 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1466 if (modifiers & WINED3DSPDM_SATURATE)
1468 /* _SAT means to clamp the value of the register to between 0 and 1 */
1469 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1470 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1473 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1475 FIXME("_centroid modifier not handled\n");
1478 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1480 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1484 static inline const char *shader_get_comp_op(DWORD op)
1487 case COMPARISON_GT: return ">";
1488 case COMPARISON_EQ: return "==";
1489 case COMPARISON_GE: return ">=";
1490 case COMPARISON_LT: return "<";
1491 case COMPARISON_NE: return "!=";
1492 case COMPARISON_LE: return "<=";
1494 FIXME("Unrecognized comparison value: %u\n", op);
1499 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1501 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1502 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1503 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1504 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1506 /* Note that there's no such thing as a projected cube texture. */
1507 switch(sampler_type) {
1510 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1512 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1514 sample_function->name = projected ? "texture1DProj" : "texture1D";
1516 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1521 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1523 /* What good are texrect grad functions? I don't know, but GL_EXT_gpu_shader4 defines them.
1524 * There is no GL_ARB_shader_texture_lod spec yet, so I don't know if they're defined there
1526 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1528 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1532 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1534 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1536 sample_function->name = projected ? "texture2DProj" : "texture2D";
1539 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1541 case WINED3DSTT_CUBE:
1543 sample_function->name = "textureCubeLod";
1545 sample_function->name = "textureCubeGradARB";
1547 sample_function->name = "textureCube";
1549 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1551 case WINED3DSTT_VOLUME:
1553 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1555 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1557 sample_function->name = projected ? "texture3DProj" : "texture3D";
1559 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1562 sample_function->name = "";
1563 sample_function->coord_mask = 0;
1564 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1569 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1570 BOOL sign_fixup, enum fixup_channel_source channel_source)
1572 switch(channel_source)
1574 case CHANNEL_SOURCE_ZERO:
1575 strcat(arguments, "0.0");
1578 case CHANNEL_SOURCE_ONE:
1579 strcat(arguments, "1.0");
1582 case CHANNEL_SOURCE_X:
1583 strcat(arguments, reg_name);
1584 strcat(arguments, ".x");
1587 case CHANNEL_SOURCE_Y:
1588 strcat(arguments, reg_name);
1589 strcat(arguments, ".y");
1592 case CHANNEL_SOURCE_Z:
1593 strcat(arguments, reg_name);
1594 strcat(arguments, ".z");
1597 case CHANNEL_SOURCE_W:
1598 strcat(arguments, reg_name);
1599 strcat(arguments, ".w");
1603 FIXME("Unhandled channel source %#x\n", channel_source);
1604 strcat(arguments, "undefined");
1608 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1611 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1613 struct wined3d_shader_dst_param dst;
1614 unsigned int mask_size, remaining;
1615 glsl_dst_param_t dst_param;
1616 char arguments[256];
1620 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1621 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1622 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1623 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1624 mask &= ins->dst[0].write_mask;
1626 if (!mask) return; /* Nothing to do */
1628 if (is_yuv_fixup(fixup))
1630 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1631 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1635 mask_size = shader_glsl_get_write_mask_size(mask);
1638 dst.write_mask = mask;
1639 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1641 arguments[0] = '\0';
1642 remaining = mask_size;
1643 if (mask & WINED3DSP_WRITEMASK_0)
1645 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1646 if (--remaining) strcat(arguments, ", ");
1648 if (mask & WINED3DSP_WRITEMASK_1)
1650 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1651 if (--remaining) strcat(arguments, ", ");
1653 if (mask & WINED3DSP_WRITEMASK_2)
1655 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1656 if (--remaining) strcat(arguments, ", ");
1658 if (mask & WINED3DSP_WRITEMASK_3)
1660 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1661 if (--remaining) strcat(arguments, ", ");
1666 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1667 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1671 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1675 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1676 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1677 const char *dx, const char *dy,
1678 const char *bias, const char *coord_reg_fmt, ...)
1680 const char *sampler_base;
1681 char dst_swizzle[6];
1682 struct color_fixup_desc fixup;
1683 BOOL np2_fixup = FALSE;
1686 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1688 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1690 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1691 fixup = priv->cur_ps_args->color_fixup[sampler];
1692 sampler_base = "Psampler";
1694 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
1696 FIXME("Biased sampling from NP2 textures is unsupported\n");
1702 sampler_base = "Vsampler";
1703 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1706 shader_glsl_append_dst(ins->ctx->buffer, ins);
1708 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1710 va_start(args, coord_reg_fmt);
1711 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1715 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1718 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup%u)%s);\n", sampler, dst_swizzle);
1719 } else if(dx && dy) {
1720 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1722 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1726 if(!is_identity_fixup(fixup)) {
1727 shader_glsl_color_correction(ins, fixup);
1731 /*****************************************************************************
1733 * Begin processing individual instruction opcodes
1735 ****************************************************************************/
1737 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1738 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1740 SHADER_BUFFER *buffer = ins->ctx->buffer;
1741 glsl_src_param_t src0_param;
1742 glsl_src_param_t src1_param;
1746 /* Determine the GLSL operator to use based on the opcode */
1747 switch (ins->handler_idx)
1749 case WINED3DSIH_MUL: op = '*'; break;
1750 case WINED3DSIH_ADD: op = '+'; break;
1751 case WINED3DSIH_SUB: op = '-'; break;
1754 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1758 write_mask = shader_glsl_append_dst(buffer, ins);
1759 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1760 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1761 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1764 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1765 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1767 SHADER_BUFFER *buffer = ins->ctx->buffer;
1768 glsl_src_param_t src0_param;
1771 write_mask = shader_glsl_append_dst(buffer, ins);
1772 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1774 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1775 * shader versions WINED3DSIO_MOVA is used for this. */
1776 if (ins->ctx->reg_maps->shader_version.major == 1
1777 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1778 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1780 /* This is a simple floor() */
1781 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1782 if (mask_size > 1) {
1783 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1785 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1788 else if(ins->handler_idx == WINED3DSIH_MOVA)
1790 /* We need to *round* to the nearest int here. */
1791 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1792 if (mask_size > 1) {
1793 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n", mask_size, src0_param.param_str, mask_size, src0_param.param_str);
1795 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1798 shader_addline(buffer, "%s);\n", src0_param.param_str);
1802 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1803 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1805 SHADER_BUFFER *buffer = ins->ctx->buffer;
1806 glsl_src_param_t src0_param;
1807 glsl_src_param_t src1_param;
1808 DWORD dst_write_mask, src_write_mask;
1809 unsigned int dst_size = 0;
1811 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1812 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1814 /* dp3 works on vec3, dp4 on vec4 */
1815 if (ins->handler_idx == WINED3DSIH_DP4)
1817 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1819 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1822 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
1823 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
1826 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1828 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1832 /* Note that this instruction has some restrictions. The destination write mask
1833 * can't contain the w component, and the source swizzles have to be .xyzw */
1834 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1836 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1837 glsl_src_param_t src0_param;
1838 glsl_src_param_t src1_param;
1841 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1842 shader_glsl_append_dst(ins->ctx->buffer, ins);
1843 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
1844 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
1845 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1848 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1849 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1850 * GLSL uses the value as-is. */
1851 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1853 SHADER_BUFFER *buffer = ins->ctx->buffer;
1854 glsl_src_param_t src0_param;
1855 glsl_src_param_t src1_param;
1856 DWORD dst_write_mask;
1857 unsigned int dst_size;
1859 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1860 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1862 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1863 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
1866 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1868 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1872 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1873 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1874 * GLSL uses the value as-is. */
1875 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1877 SHADER_BUFFER *buffer = ins->ctx->buffer;
1878 glsl_src_param_t src0_param;
1879 DWORD dst_write_mask;
1880 unsigned int dst_size;
1882 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1883 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1885 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1888 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1890 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1894 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1895 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1897 SHADER_BUFFER *buffer = ins->ctx->buffer;
1898 glsl_src_param_t src_param;
1899 const char *instruction;
1903 /* Determine the GLSL function to use based on the opcode */
1904 /* TODO: Possibly make this a table for faster lookups */
1905 switch (ins->handler_idx)
1907 case WINED3DSIH_MIN: instruction = "min"; break;
1908 case WINED3DSIH_MAX: instruction = "max"; break;
1909 case WINED3DSIH_ABS: instruction = "abs"; break;
1910 case WINED3DSIH_FRC: instruction = "fract"; break;
1911 case WINED3DSIH_NRM: instruction = "normalize"; break;
1912 case WINED3DSIH_EXP: instruction = "exp2"; break;
1913 case WINED3DSIH_SGN: instruction = "sign"; break;
1914 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1915 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1916 default: instruction = "";
1917 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1921 write_mask = shader_glsl_append_dst(buffer, ins);
1923 shader_addline(buffer, "%s(", instruction);
1927 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
1928 shader_addline(buffer, "%s", src_param.param_str);
1929 for (i = 1; i < ins->src_count; ++i)
1931 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
1932 shader_addline(buffer, ", %s", src_param.param_str);
1936 shader_addline(buffer, "));\n");
1939 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1940 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1941 * dst.x = 2^(floor(src))
1942 * dst.y = src - floor(src)
1943 * dst.z = 2^src (partial precision is allowed, but optional)
1945 * For 2.0 shaders, just do this (honoring writemask and swizzle):
1946 * dst = 2^src; (partial precision is allowed, but optional)
1948 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
1950 glsl_src_param_t src_param;
1952 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
1954 if (ins->ctx->reg_maps->shader_version.major < 2)
1958 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1959 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1960 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1961 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
1963 shader_glsl_append_dst(ins->ctx->buffer, ins);
1964 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1965 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
1968 unsigned int mask_size;
1970 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1971 mask_size = shader_glsl_get_write_mask_size(write_mask);
1973 if (mask_size > 1) {
1974 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1976 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
1981 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1982 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
1984 glsl_src_param_t src_param;
1986 unsigned int mask_size;
1988 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1989 mask_size = shader_glsl_get_write_mask_size(write_mask);
1990 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
1992 if (mask_size > 1) {
1993 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1995 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
1999 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2001 SHADER_BUFFER *buffer = ins->ctx->buffer;
2002 glsl_src_param_t src_param;
2004 unsigned int mask_size;
2006 write_mask = shader_glsl_append_dst(buffer, ins);
2007 mask_size = shader_glsl_get_write_mask_size(write_mask);
2009 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2011 if (mask_size > 1) {
2012 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
2014 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
2018 /** Process signed comparison opcodes in GLSL. */
2019 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2021 glsl_src_param_t src0_param;
2022 glsl_src_param_t src1_param;
2024 unsigned int mask_size;
2026 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2027 mask_size = shader_glsl_get_write_mask_size(write_mask);
2028 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2029 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2031 if (mask_size > 1) {
2032 const char *compare;
2034 switch(ins->handler_idx)
2036 case WINED3DSIH_SLT: compare = "lessThan"; break;
2037 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2038 default: compare = "";
2039 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2042 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2043 src0_param.param_str, src1_param.param_str);
2045 switch(ins->handler_idx)
2047 case WINED3DSIH_SLT:
2048 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2049 * to return 0.0 but step returns 1.0 because step is not < x
2050 * An alternative is a bvec compare padded with an unused second component.
2051 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2052 * issue. Playing with not() is not possible either because not() does not accept
2055 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2056 src0_param.param_str, src1_param.param_str);
2058 case WINED3DSIH_SGE:
2059 /* Here we can use the step() function and safe a conditional */
2060 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2063 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2069 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2070 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2072 glsl_src_param_t src0_param;
2073 glsl_src_param_t src1_param;
2074 glsl_src_param_t src2_param;
2075 DWORD write_mask, cmp_channel = 0;
2078 BOOL temp_destination = FALSE;
2080 if (shader_is_scalar(&ins->src[0].reg))
2082 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2084 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2085 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2086 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2088 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2089 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2091 DWORD dst_mask = ins->dst[0].write_mask;
2092 struct wined3d_shader_dst_param dst = ins->dst[0];
2094 /* Cycle through all source0 channels */
2095 for (i=0; i<4; i++) {
2097 /* Find the destination channels which use the current source0 channel */
2098 for (j=0; j<4; j++) {
2099 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2101 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2102 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2105 dst.write_mask = dst_mask & write_mask;
2107 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2108 * The first lines may overwrite source parameters of the following lines.
2109 * Deal with that by using a temporary destination register if needed
2111 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2112 && ins->src[0].reg.type == ins->dst[0].reg.type)
2113 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2114 && ins->src[1].reg.type == ins->dst[0].reg.type)
2115 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2116 && ins->src[2].reg.type == ins->dst[0].reg.type))
2118 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2119 if (!write_mask) continue;
2120 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2121 temp_destination = TRUE;
2123 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2124 if (!write_mask) continue;
2127 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2128 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2129 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2131 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2132 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2135 if(temp_destination) {
2136 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2137 shader_glsl_append_dst(ins->ctx->buffer, ins);
2138 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2144 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2145 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2146 * the compare is done per component of src0. */
2147 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2149 struct wined3d_shader_dst_param dst;
2150 glsl_src_param_t src0_param;
2151 glsl_src_param_t src1_param;
2152 glsl_src_param_t src2_param;
2153 DWORD write_mask, cmp_channel = 0;
2156 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2157 ins->ctx->reg_maps->shader_version.minor);
2159 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2161 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2162 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2163 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2164 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2166 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2169 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2171 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2172 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2176 /* Cycle through all source0 channels */
2177 dst_mask = ins->dst[0].write_mask;
2179 for (i=0; i<4; i++) {
2181 /* Find the destination channels which use the current source0 channel */
2182 for (j=0; j<4; j++) {
2183 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2185 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2186 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2190 dst.write_mask = dst_mask & write_mask;
2191 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2192 if (!write_mask) continue;
2194 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2195 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2196 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2198 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2199 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2203 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2204 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2206 glsl_src_param_t src0_param;
2207 glsl_src_param_t src1_param;
2208 glsl_src_param_t src2_param;
2211 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2212 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2213 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2214 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2215 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2216 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2219 /** Handles transforming all WINED3DSIO_M?x? opcodes for
2220 Vertex shaders to GLSL codes */
2221 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2224 int nComponents = 0;
2225 struct wined3d_shader_dst_param tmp_dst = {{0}};
2226 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2227 struct wined3d_shader_instruction tmp_ins;
2229 memset(&tmp_ins, 0, sizeof(tmp_ins));
2231 /* Set constants for the temporary argument */
2232 tmp_ins.ctx = ins->ctx;
2233 tmp_ins.dst_count = 1;
2234 tmp_ins.dst = &tmp_dst;
2235 tmp_ins.src_count = 2;
2236 tmp_ins.src = tmp_src;
2238 switch(ins->handler_idx)
2240 case WINED3DSIH_M4x4:
2242 tmp_ins.handler_idx = WINED3DSIH_DP4;
2244 case WINED3DSIH_M4x3:
2246 tmp_ins.handler_idx = WINED3DSIH_DP4;
2248 case WINED3DSIH_M3x4:
2250 tmp_ins.handler_idx = WINED3DSIH_DP3;
2252 case WINED3DSIH_M3x3:
2254 tmp_ins.handler_idx = WINED3DSIH_DP3;
2256 case WINED3DSIH_M3x2:
2258 tmp_ins.handler_idx = WINED3DSIH_DP3;
2264 tmp_dst = ins->dst[0];
2265 tmp_src[0] = ins->src[0];
2266 tmp_src[1] = ins->src[1];
2267 for (i = 0; i < nComponents; ++i)
2269 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2270 shader_glsl_dot(&tmp_ins);
2271 ++tmp_src[1].reg.idx;
2276 The LRP instruction performs a component-wise linear interpolation
2277 between the second and third operands using the first operand as the
2278 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2279 This is equivalent to mix(src2, src1, src0);
2281 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2283 glsl_src_param_t src0_param;
2284 glsl_src_param_t src1_param;
2285 glsl_src_param_t src2_param;
2288 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2290 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2291 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2292 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2294 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2295 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2298 /** Process the WINED3DSIO_LIT instruction in GLSL:
2299 * dst.x = dst.w = 1.0
2300 * dst.y = (src0.x > 0) ? src0.x
2301 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2302 * where src.w is clamped at +- 128
2304 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2306 glsl_src_param_t src0_param;
2307 glsl_src_param_t src1_param;
2308 glsl_src_param_t src3_param;
2311 shader_glsl_append_dst(ins->ctx->buffer, ins);
2312 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2314 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2315 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2316 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2318 /* The sdk specifies the instruction like this
2320 * if(src.x > 0.0) dst.y = src.x
2322 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2326 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2327 * dst.x = 1.0 ... No further explanation needed
2328 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2329 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2330 * dst.w = 1.0. ... Nothing fancy.
2332 * So we still have one conditional in there. So do this:
2333 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2335 * 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),
2336 * 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.
2337 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2339 shader_addline(ins->ctx->buffer,
2340 "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",
2341 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2344 /** Process the WINED3DSIO_DST instruction in GLSL:
2346 * dst.y = src0.x * src0.y
2350 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2352 glsl_src_param_t src0y_param;
2353 glsl_src_param_t src0z_param;
2354 glsl_src_param_t src1y_param;
2355 glsl_src_param_t src1w_param;
2358 shader_glsl_append_dst(ins->ctx->buffer, ins);
2359 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2361 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2362 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2363 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2364 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2366 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2367 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2370 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2371 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2372 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2374 * dst.x = cos(src0.?)
2375 * dst.y = sin(src0.?)
2379 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2381 glsl_src_param_t src0_param;
2384 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2385 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2387 switch (write_mask) {
2388 case WINED3DSP_WRITEMASK_0:
2389 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2392 case WINED3DSP_WRITEMASK_1:
2393 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2396 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2397 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2401 ERR("Write mask should be .x, .y or .xy\n");
2406 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2407 * Start a for() loop where src1.y is the initial value of aL,
2408 * increment aL by src1.z for a total of src1.x iterations.
2409 * Need to use a temporary variable for this operation.
2411 /* FIXME: I don't think nested loops will work correctly this way. */
2412 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2414 glsl_src_param_t src1_param;
2415 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2416 const DWORD *control_values = NULL;
2417 const local_constant *constant;
2419 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2421 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2422 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2423 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2426 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2428 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2429 if (constant->idx == ins->src[1].reg.idx)
2431 control_values = constant->value;
2437 if(control_values) {
2438 if(control_values[2] > 0) {
2439 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
2440 shader->baseShader.cur_loop_depth, control_values[1],
2441 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2442 shader->baseShader.cur_loop_depth, control_values[2]);
2443 } else if(control_values[2] == 0) {
2444 shader_addline(ins->ctx->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
2445 shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
2446 shader->baseShader.cur_loop_depth, control_values[0],
2447 shader->baseShader.cur_loop_depth);
2449 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
2450 shader->baseShader.cur_loop_depth, control_values[1],
2451 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2452 shader->baseShader.cur_loop_depth, control_values[2]);
2455 shader_addline(ins->ctx->buffer,
2456 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2457 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2458 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2459 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2462 shader->baseShader.cur_loop_depth++;
2463 shader->baseShader.cur_loop_regno++;
2466 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2468 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2470 shader_addline(ins->ctx->buffer, "}\n");
2472 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2474 shader->baseShader.cur_loop_depth--;
2475 shader->baseShader.cur_loop_regno--;
2478 if (ins->handler_idx == WINED3DSIH_ENDREP)
2480 shader->baseShader.cur_loop_depth--;
2484 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2486 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2487 glsl_src_param_t src0_param;
2488 const DWORD *control_values = NULL;
2489 const local_constant *constant;
2491 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2492 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2494 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2496 if (constant->idx == ins->src[0].reg.idx)
2498 control_values = constant->value;
2504 if(control_values) {
2505 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2506 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2507 control_values[0], shader->baseShader.cur_loop_depth);
2509 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2510 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2511 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2512 src0_param.param_str, shader->baseShader.cur_loop_depth);
2514 shader->baseShader.cur_loop_depth++;
2517 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2519 glsl_src_param_t src0_param;
2521 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2522 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2525 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2527 glsl_src_param_t src0_param;
2528 glsl_src_param_t src1_param;
2530 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2531 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2533 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2534 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2537 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2539 shader_addline(ins->ctx->buffer, "} else {\n");
2542 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2544 shader_addline(ins->ctx->buffer, "break;\n");
2547 /* FIXME: According to MSDN the compare is done per component. */
2548 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2550 glsl_src_param_t src0_param;
2551 glsl_src_param_t src1_param;
2553 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2554 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2556 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2557 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2560 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2562 shader_addline(ins->ctx->buffer, "}\n");
2563 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2566 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2568 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2571 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2573 glsl_src_param_t src1_param;
2575 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2576 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2579 /*********************************************
2580 * Pixel Shader Specific Code begins here
2581 ********************************************/
2582 static void pshader_glsl_tex(const struct wined3d_shader_instruction *ins)
2584 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2585 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2586 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2587 ins->ctx->reg_maps->shader_version.minor);
2588 glsl_sample_function_t sample_function;
2589 DWORD sample_flags = 0;
2590 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2592 DWORD mask = 0, swizzle;
2594 /* 1.0-1.4: Use destination register as sampler source.
2595 * 2.0+: Use provided sampler source. */
2596 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2597 else sampler_idx = ins->src[1].reg.idx;
2598 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2600 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2602 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2604 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2605 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2606 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2607 switch (flags & ~WINED3DTTFF_PROJECTED) {
2608 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2609 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2610 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2611 case WINED3DTTFF_COUNT4:
2612 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2616 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2618 DWORD src_mod = ins->src[0].modifiers;
2620 if (src_mod == WINED3DSPSM_DZ) {
2621 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2622 mask = WINED3DSP_WRITEMASK_2;
2623 } else if (src_mod == WINED3DSPSM_DW) {
2624 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2625 mask = WINED3DSP_WRITEMASK_3;
2628 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2630 /* ps 2.0 texldp instruction always divides by the fourth component. */
2631 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2632 mask = WINED3DSP_WRITEMASK_3;
2636 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2637 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2638 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2641 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2642 mask |= sample_function.coord_mask;
2644 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2645 else swizzle = ins->src[1].swizzle;
2647 /* 1.0-1.3: Use destination register as coordinate source.
2648 1.4+: Use provided coordinate source register. */
2649 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2652 shader_glsl_write_mask_to_str(mask, coord_mask);
2653 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2654 "T%u%s", sampler_idx, coord_mask);
2656 glsl_src_param_t coord_param;
2657 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2658 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2660 glsl_src_param_t bias;
2661 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2662 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2663 "%s", coord_param.param_str);
2665 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2666 "%s", coord_param.param_str);
2671 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2673 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2674 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2675 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
2676 glsl_sample_function_t sample_function;
2677 glsl_src_param_t coord_param, dx_param, dy_param;
2678 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2681 DWORD swizzle = ins->src[1].swizzle;
2683 if(!GL_SUPPORT(ARB_SHADER_TEXTURE_LOD)) {
2684 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2685 return pshader_glsl_tex(ins);
2688 sampler_idx = ins->src[1].reg.idx;
2689 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2690 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2691 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2692 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2695 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2696 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2697 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2698 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2700 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2701 "%s", coord_param.param_str);
2704 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2706 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2707 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2708 glsl_sample_function_t sample_function;
2709 glsl_src_param_t coord_param, lod_param;
2710 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2713 DWORD swizzle = ins->src[1].swizzle;
2715 sampler_idx = ins->src[1].reg.idx;
2716 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2717 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2718 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2719 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2721 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2722 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2724 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2726 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2728 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2729 * However, they seem to work just fine in fragment shaders as well. */
2730 WARN("Using %s in fragment shader.\n", sample_function.name);
2732 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
2733 "%s", coord_param.param_str);
2736 static void pshader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2738 /* FIXME: Make this work for more than just 2D textures */
2739 SHADER_BUFFER *buffer = ins->ctx->buffer;
2740 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2742 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
2746 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2747 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2748 ins->dst[0].reg.idx, dst_mask);
2750 DWORD reg = ins->src[0].reg.idx;
2751 DWORD src_mod = ins->src[0].modifiers;
2752 char dst_swizzle[6];
2754 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
2756 if (src_mod == WINED3DSPSM_DZ) {
2757 glsl_src_param_t div_param;
2758 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2759 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
2761 if (mask_size > 1) {
2762 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2764 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2766 } else if (src_mod == WINED3DSPSM_DW) {
2767 glsl_src_param_t div_param;
2768 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2769 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
2771 if (mask_size > 1) {
2772 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2774 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2777 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2782 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2783 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2784 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2785 static void pshader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2787 glsl_src_param_t src0_param;
2788 glsl_sample_function_t sample_function;
2789 DWORD sampler_idx = ins->dst[0].reg.idx;
2790 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2791 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2794 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2796 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2797 * scalar, and projected sampling would require 4.
2799 * It is a dependent read - not valid with conditional NP2 textures
2801 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2802 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2807 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2808 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2812 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2813 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2817 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2818 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2822 FIXME("Unexpected mask size %u\n", mask_size);
2827 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2828 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2829 static void pshader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2831 glsl_src_param_t src0_param;
2832 DWORD dstreg = ins->dst[0].reg.idx;
2833 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2835 unsigned int mask_size;
2837 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2838 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2839 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2841 if (mask_size > 1) {
2842 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2844 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2848 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2849 * Calculate the depth as dst.x / dst.y */
2850 static void pshader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2852 glsl_dst_param_t dst_param;
2854 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2856 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2857 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2858 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2859 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2862 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2863 dst_param.reg_name, dst_param.reg_name);
2866 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2867 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2868 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2869 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2871 static void pshader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2873 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2874 DWORD dstreg = ins->dst[0].reg.idx;
2875 glsl_src_param_t src0_param;
2877 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2879 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2880 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2883 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2884 * Calculate the 1st of a 2-row matrix multiplication. */
2885 static void pshader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2887 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2888 DWORD reg = ins->dst[0].reg.idx;
2889 SHADER_BUFFER *buffer = ins->ctx->buffer;
2890 glsl_src_param_t src0_param;
2892 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2893 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2896 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2897 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2898 static void pshader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
2900 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2901 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2902 DWORD reg = ins->dst[0].reg.idx;
2903 SHADER_BUFFER *buffer = ins->ctx->buffer;
2904 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2905 glsl_src_param_t src0_param;
2907 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2908 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2909 current_state->texcoord_w[current_state->current_row++] = reg;
2912 static void pshader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
2914 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2915 DWORD reg = ins->dst[0].reg.idx;
2916 SHADER_BUFFER *buffer = ins->ctx->buffer;
2917 glsl_src_param_t src0_param;
2918 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2919 glsl_sample_function_t sample_function;
2921 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2922 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2924 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2926 /* Sample the texture using the calculated coordinates */
2927 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
2930 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2931 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2932 static void pshader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
2934 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2935 glsl_src_param_t src0_param;
2936 DWORD reg = ins->dst[0].reg.idx;
2937 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2938 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2939 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2940 glsl_sample_function_t sample_function;
2942 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2943 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2945 /* Dependent read, not valid with conditional NP2 */
2946 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2948 /* Sample the texture using the calculated coordinates */
2949 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
2951 current_state->current_row = 0;
2954 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2955 * Perform the 3rd row of a 3x3 matrix multiply */
2956 static void pshader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
2958 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2959 glsl_src_param_t src0_param;
2961 DWORD reg = ins->dst[0].reg.idx;
2962 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2963 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2965 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2967 shader_glsl_append_dst(ins->ctx->buffer, ins);
2968 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2969 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2971 current_state->current_row = 0;
2974 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
2975 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2976 static void pshader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
2978 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2979 DWORD reg = ins->dst[0].reg.idx;
2980 glsl_src_param_t src0_param;
2981 glsl_src_param_t src1_param;
2982 SHADER_BUFFER *buffer = ins->ctx->buffer;
2983 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2984 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
2985 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2986 glsl_sample_function_t sample_function;
2988 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2989 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2991 /* Perform the last matrix multiply operation */
2992 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2993 /* Reflection calculation */
2994 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2996 /* Dependent read, not valid with conditional NP2 */
2997 shader_glsl_get_sample_function(stype, 0, &sample_function);
2999 /* Sample the texture */
3000 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3002 current_state->current_row = 0;
3005 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3006 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3007 static void pshader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3009 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3010 DWORD reg = ins->dst[0].reg.idx;
3011 SHADER_BUFFER *buffer = ins->ctx->buffer;
3012 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3013 glsl_src_param_t src0_param;
3014 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3015 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3016 glsl_sample_function_t sample_function;
3018 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3020 /* Perform the last matrix multiply operation */
3021 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3023 /* Construct the eye-ray vector from w coordinates */
3024 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3025 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3026 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3028 /* Dependent read, not valid with conditional NP2 */
3029 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3031 /* Sample the texture using the calculated coordinates */
3032 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3034 current_state->current_row = 0;
3037 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3038 * Apply a fake bump map transform.
3039 * texbem is pshader <= 1.3 only, this saves a few version checks
3041 static void pshader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3043 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3044 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3045 glsl_sample_function_t sample_function;
3046 glsl_src_param_t coord_param;
3047 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3053 sampler_idx = ins->dst[0].reg.idx;
3054 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3056 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3057 /* Dependent read, not valid with conditional NP2 */
3058 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3059 mask = sample_function.coord_mask;
3061 shader_glsl_write_mask_to_str(mask, coord_mask);
3063 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3064 * so we can't let the GL handle this.
3066 if (flags & WINED3DTTFF_PROJECTED) {
3068 char coord_div_mask[3];
3069 switch (flags & ~WINED3DTTFF_PROJECTED) {
3070 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3071 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3072 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3073 case WINED3DTTFF_COUNT4:
3074 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3076 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3077 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3080 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3082 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3083 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3084 coord_param.param_str, coord_mask);
3086 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3088 glsl_src_param_t luminance_param;
3089 glsl_dst_param_t dst_param;
3091 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3092 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3094 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3095 dst_param.reg_name, dst_param.mask_str,
3096 luminance_param.param_str, sampler_idx, sampler_idx);
3100 static void pshader_glsl_bem(const struct wined3d_shader_instruction *ins)
3102 glsl_src_param_t src0_param, src1_param;
3103 DWORD sampler_idx = ins->dst[0].reg.idx;
3105 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3106 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3108 shader_glsl_append_dst(ins->ctx->buffer, ins);
3109 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3110 src0_param.param_str, sampler_idx, src1_param.param_str);
3113 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3114 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3115 static void pshader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3117 glsl_src_param_t src0_param;
3118 DWORD sampler_idx = ins->dst[0].reg.idx;
3119 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3120 glsl_sample_function_t sample_function;
3122 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3124 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3125 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3126 "%s.wx", src0_param.reg_name);
3129 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3130 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3131 static void pshader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3133 glsl_src_param_t src0_param;
3134 DWORD sampler_idx = ins->dst[0].reg.idx;
3135 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3136 glsl_sample_function_t sample_function;
3138 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3140 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3141 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3142 "%s.yz", src0_param.reg_name);
3145 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3146 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3147 static void pshader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3149 glsl_src_param_t src0_param;
3150 DWORD sampler_idx = ins->dst[0].reg.idx;
3151 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3152 glsl_sample_function_t sample_function;
3154 /* Dependent read, not valid with conditional NP2 */
3155 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3156 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3158 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3159 "%s", src0_param.param_str);
3162 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3163 * If any of the first 3 components are < 0, discard this pixel */
3164 static void pshader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3166 glsl_dst_param_t dst_param;
3168 /* The argument is a destination parameter, and no writemasks are allowed */
3169 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3170 if (ins->ctx->reg_maps->shader_version.major >= 2)
3172 /* 2.0 shaders compare all 4 components in texkill */
3173 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3175 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3176 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3177 * 4 components are defined, only the first 3 are used
3179 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3183 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3184 * dst = dot2(src0, src1) + src2 */
3185 static void pshader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3187 glsl_src_param_t src0_param;
3188 glsl_src_param_t src1_param;
3189 glsl_src_param_t src2_param;
3191 unsigned int mask_size;
3193 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3194 mask_size = shader_glsl_get_write_mask_size(write_mask);
3196 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3197 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3198 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3200 if (mask_size > 1) {
3201 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3202 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3204 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3205 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3209 static void pshader_glsl_input_pack(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer,
3210 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3211 enum vertexprocessing_mode vertexprocessing)
3214 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3215 WORD map = reg_maps->input_registers;
3217 for (i = 0; map; map >>= 1, ++i)
3219 const char *semantic_name;
3224 if (!(map & 1)) continue;
3226 semantic_name = input_signature[i].semantic_name;
3227 semantic_idx = input_signature[i].semantic_idx;
3228 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3230 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3232 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3233 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3234 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3236 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3237 This->input_reg_map[i], reg_mask, reg_mask);
3239 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3241 if (semantic_idx == 0)
3242 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3243 This->input_reg_map[i], reg_mask, reg_mask);
3244 else if (semantic_idx == 1)
3245 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3246 This->input_reg_map[i], reg_mask, reg_mask);
3248 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3249 This->input_reg_map[i], reg_mask, reg_mask);
3253 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3254 This->input_reg_map[i], reg_mask, reg_mask);
3259 /*********************************************
3260 * Vertex Shader Specific Code begins here
3261 ********************************************/
3263 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3264 glsl_program_key_t key;
3266 key.vshader = entry->vshader;
3267 key.pshader = entry->pshader;
3268 key.vs_args = entry->vs_args;
3269 key.ps_args = entry->ps_args;
3271 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3273 ERR("Failed to insert program entry.\n");
3277 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3278 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3279 struct ps_compile_args *ps_args) {
3280 struct wine_rb_entry *entry;
3281 glsl_program_key_t key;
3283 key.vshader = vshader;
3284 key.pshader = pshader;
3285 key.vs_args = *vs_args;
3286 key.ps_args = *ps_args;
3288 entry = wine_rb_get(&priv->program_lookup, &key);
3289 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3292 /* GL locking is done by the caller */
3293 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
3294 struct glsl_shader_prog_link *entry)
3296 glsl_program_key_t key;
3298 key.vshader = entry->vshader;
3299 key.pshader = entry->pshader;
3300 key.vs_args = entry->vs_args;
3301 key.ps_args = entry->ps_args;
3302 wine_rb_remove(&priv->program_lookup, &key);
3304 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3305 if (entry->vshader) list_remove(&entry->vshader_entry);
3306 if (entry->pshader) list_remove(&entry->pshader_entry);
3307 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3308 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3309 HeapFree(GetProcessHeap(), 0, entry);
3312 static void handle_ps3_input(SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, const DWORD *map,
3313 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3314 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3317 const char *semantic_name_in, *semantic_name_out;
3318 UINT semantic_idx_in, semantic_idx_out;
3321 DWORD in_count = vec4_varyings(3, gl_info);
3322 char reg_mask[6], reg_mask_out[6];
3323 char destination[50];
3324 WORD input_map, output_map;
3326 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3328 if (!output_signature)
3330 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3331 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3332 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3335 input_map = reg_maps_in->input_registers;
3336 for (i = 0; input_map; input_map >>= 1, ++i)
3338 if (!(input_map & 1)) continue;
3341 if (in_idx >= (in_count + 2)) {
3342 FIXME("More input varyings declared than supported, expect issues\n");
3345 else if (map[i] == ~0U)
3347 /* Declared, but not read register */
3351 if (in_idx == in_count) {
3352 sprintf(destination, "gl_FrontColor");
3353 } else if (in_idx == in_count + 1) {
3354 sprintf(destination, "gl_FrontSecondaryColor");
3356 sprintf(destination, "IN[%u]", in_idx);
3359 semantic_name_in = input_signature[i].semantic_name;
3360 semantic_idx_in = input_signature[i].semantic_idx;
3361 set[map[i]] = input_signature[i].mask;
3362 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3364 if (!output_signature)
3366 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3368 if (semantic_idx_in == 0)
3369 shader_addline(buffer, "%s%s = front_color%s;\n",
3370 destination, reg_mask, reg_mask);
3371 else if (semantic_idx_in == 1)
3372 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3373 destination, reg_mask, reg_mask);
3375 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3376 destination, reg_mask, reg_mask);
3378 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3380 if (semantic_idx_in < 8)
3382 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3383 destination, reg_mask, semantic_idx_in, reg_mask);
3387 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3388 destination, reg_mask, reg_mask);
3391 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3393 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3394 destination, reg_mask, reg_mask);
3398 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3399 destination, reg_mask, reg_mask);
3404 output_map = reg_maps_out->output_registers;
3405 for (j = 0; output_map; output_map >>= 1, ++j)
3407 if (!(output_map & 1)) continue;
3409 semantic_name_out = output_signature[j].semantic_name;
3410 semantic_idx_out = output_signature[j].semantic_idx;
3411 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3413 if (semantic_idx_in == semantic_idx_out
3414 && !strcmp(semantic_name_in, semantic_name_out))
3416 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3417 destination, reg_mask, j, reg_mask);
3422 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3423 destination, reg_mask, reg_mask);
3428 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3429 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3430 * input varyings are assigned above, if the optimizer works properly.
3432 for(i = 0; i < in_count + 2; i++) {
3433 if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3434 unsigned int size = 0;
3435 memset(reg_mask, 0, sizeof(reg_mask));
3436 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3437 reg_mask[size] = 'x';
3440 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3441 reg_mask[size] = 'y';
3444 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3445 reg_mask[size] = 'z';
3448 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3449 reg_mask[size] = 'w';
3453 if (i == in_count) {
3454 sprintf(destination, "gl_FrontColor");
3455 } else if (i == in_count + 1) {
3456 sprintf(destination, "gl_FrontSecondaryColor");
3458 sprintf(destination, "IN[%u]", i);
3462 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3464 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3469 HeapFree(GetProcessHeap(), 0, set);
3472 /* GL locking is done by the caller */
3473 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3474 IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3476 GLhandleARB ret = 0;
3477 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3478 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3479 IWineD3DDeviceImpl *device;
3480 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3481 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3483 SHADER_BUFFER buffer;
3484 const char *semantic_name;
3487 const struct wined3d_shader_signature_element *output_signature;
3489 shader_buffer_init(&buffer);
3491 shader_addline(&buffer, "#version 120\n");
3493 if(vs_major < 3 && ps_major < 3) {
3494 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3495 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3497 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3498 if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3499 !device->frag_pipe->ffp_proj_control) {
3500 shader_addline(&buffer, "void order_ps_input() {\n");
3501 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3502 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3503 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3504 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3507 shader_addline(&buffer, "}\n");
3509 shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3511 } else if(ps_major < 3 && vs_major >= 3) {
3512 WORD map = vs->baseShader.reg_maps.output_registers;
3514 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3515 output_signature = vs->output_signature;
3517 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3518 for (i = 0; map; map >>= 1, ++i)
3522 if (!(map & 1)) continue;
3524 semantic_name = output_signature[i].semantic_name;
3525 semantic_idx = output_signature[i].semantic_idx;
3526 write_mask = output_signature[i].mask;
3527 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3529 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3531 if (semantic_idx == 0)
3532 shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3533 else if (semantic_idx == 1)
3534 shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3536 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3538 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3540 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3542 if (semantic_idx < 8)
3544 if (!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) write_mask |= WINED3DSP_WRITEMASK_3;
3546 shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3547 semantic_idx, reg_mask, i, reg_mask);
3548 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3549 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3552 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3554 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3556 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3558 shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3561 shader_addline(&buffer, "}\n");
3563 } else if(ps_major >= 3 && vs_major >= 3) {
3564 WORD map = vs->baseShader.reg_maps.output_registers;
3566 output_signature = vs->output_signature;
3568 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3569 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3570 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3572 /* First, sort out position and point size. Those are not passed to the pixel shader */
3573 for (i = 0; map; map >>= 1, ++i)
3575 if (!(map & 1)) continue;
3577 semantic_name = output_signature[i].semantic_name;
3578 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3580 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3582 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3584 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3586 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3590 /* Then, fix the pixel shader input */
3591 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->input_signature,
3592 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3594 shader_addline(&buffer, "}\n");
3595 } else if(ps_major >= 3 && vs_major < 3) {
3596 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3597 shader_addline(&buffer, "void order_ps_input() {\n");
3598 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3599 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3600 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3602 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->input_signature,
3603 &ps->baseShader.reg_maps, NULL, NULL);
3604 shader_addline(&buffer, "}\n");
3606 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3609 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3610 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3611 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3612 checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3613 GL_EXTCALL(glCompileShaderARB(ret));
3614 checkGLcall("glCompileShaderARB(ret)");
3616 shader_buffer_free(&buffer);
3620 /* GL locking is done by the caller */
3621 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3622 GLhandleARB programId, char prefix)
3624 const local_constant *lconst;
3629 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3630 value = (const float *)lconst->value;
3631 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3632 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3633 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3635 checkGLcall("Hardcoding local constants\n");
3638 /* GL locking is done by the caller */
3639 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShaderImpl *This,
3640 SHADER_BUFFER *buffer, const struct ps_compile_args *args)
3642 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3643 CONST DWORD *function = This->baseShader.function;
3644 const char *fragcolor;
3645 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3646 struct shader_glsl_ctx_priv priv_ctx;
3648 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3649 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3651 memset(&priv_ctx, 0, sizeof(priv_ctx));
3652 priv_ctx.cur_ps_args = args;
3654 shader_addline(buffer, "#version 120\n");
3656 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3657 shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
3659 if(GL_SUPPORT(ARB_SHADER_TEXTURE_LOD) && reg_maps->usestexldd) {
3660 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3662 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3663 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3664 * drivers write a warning if we don't do so
3666 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3669 /* Base Declarations */
3670 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
3672 /* Pack 3.0 inputs */
3673 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3675 pshader_glsl_input_pack((IWineD3DPixelShader *) This, buffer, This->input_signature, reg_maps, args->vp_mode);
3678 /* Base Shader Body */
3679 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3681 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3682 if (reg_maps->shader_version.major < 2)
3684 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3685 if(GL_SUPPORT(ARB_DRAW_BUFFERS))
3686 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3688 shader_addline(buffer, "gl_FragColor = R0;\n");
3691 if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3692 fragcolor = "gl_FragData[0]";
3694 fragcolor = "gl_FragColor";
3696 if(args->srgb_correction) {
3697 shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
3698 fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
3699 srgb_sub_high, srgb_sub_high, srgb_sub_high);
3700 shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
3701 shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
3702 shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
3703 shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
3704 shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
3706 /* Pixel shader < 3.0 do not replace the fog stage.
3707 * This implements linear fog computation and blending.
3708 * TODO: non linear fog
3709 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3710 * -1/(e-s) and e/(e-s) respectively.
3712 if (reg_maps->shader_version.major < 3)
3715 case FOG_OFF: break;
3717 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3718 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3719 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3720 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3723 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3724 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3725 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3726 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3729 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3730 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3731 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3732 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3737 shader_addline(buffer, "}\n");
3739 TRACE("Compiling shader object %u\n", shader_obj);
3740 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3741 GL_EXTCALL(glCompileShaderARB(shader_obj));
3742 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
3744 /* Store the shader object */
3748 /* GL locking is done by the caller */
3749 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShaderImpl *This,
3750 SHADER_BUFFER *buffer, const struct vs_compile_args *args)
3752 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3753 CONST DWORD *function = This->baseShader.function;
3754 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3755 struct shader_glsl_ctx_priv priv_ctx;
3757 /* Create the hw GLSL shader program and assign it as the shader->prgId */
3758 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3760 shader_addline(buffer, "#version 120\n");
3762 memset(&priv_ctx, 0, sizeof(priv_ctx));
3763 priv_ctx.cur_vs_args = args;
3765 /* Base Declarations */
3766 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
3768 /* Base Shader Body */
3769 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
3771 /* Unpack 3.0 outputs */
3772 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
3773 else shader_addline(buffer, "order_ps_input();\n");
3775 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
3776 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
3777 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
3778 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
3780 if(args->fog_src == VS_FOG_Z) {
3781 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
3782 } else if (!reg_maps->fog) {
3783 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
3786 /* Write the final position.
3788 * OpenGL coordinates specify the center of the pixel while d3d coords specify
3789 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
3790 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3791 * contains 1.0 to allow a mad.
3793 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
3794 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
3795 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
3797 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3799 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
3800 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
3801 * which is the same as z = z * 2 - w.
3803 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
3805 shader_addline(buffer, "}\n");
3807 TRACE("Compiling shader object %u\n", shader_obj);
3808 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3809 GL_EXTCALL(glCompileShaderARB(shader_obj));
3810 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
3815 static GLhandleARB find_glsl_pshader(IWineD3DPixelShaderImpl *shader, const struct ps_compile_args *args)
3819 struct glsl_ps_compiled_shader *new_array;
3820 SHADER_BUFFER buffer;
3821 struct glsl_pshader_private *shader_data;
3824 if(!shader->backend_priv) {
3825 shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3827 shader_data = shader->backend_priv;
3829 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3830 * so a linear search is more performant than a hashmap or a binary search
3831 * (cache coherency etc)
3833 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3834 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
3835 return shader_data->gl_shaders[i].prgId;
3839 TRACE("No matching GL shader found, compiling a new shader\n");
3840 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3841 if (shader_data->num_gl_shaders)
3843 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3844 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3845 new_size * sizeof(*shader_data->gl_shaders));
3847 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3852 ERR("Out of memory\n");
3855 shader_data->gl_shaders = new_array;
3856 shader_data->shader_array_size = new_size;
3859 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3861 pixelshader_update_samplers(&shader->baseShader.reg_maps,
3862 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
3864 shader_buffer_init(&buffer);
3865 ret = shader_glsl_generate_pshader(shader, &buffer, args);
3866 shader_buffer_free(&buffer);
3867 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3872 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
3873 const DWORD use_map) {
3874 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
3875 return stored->fog_src == new->fog_src;
3878 static GLhandleARB find_glsl_vshader(IWineD3DVertexShaderImpl *shader, const struct vs_compile_args *args)
3882 struct glsl_vs_compiled_shader *new_array;
3883 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
3884 SHADER_BUFFER buffer;
3885 struct glsl_vshader_private *shader_data;
3888 if(!shader->backend_priv) {
3889 shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3891 shader_data = shader->backend_priv;
3893 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3894 * so a linear search is more performant than a hashmap or a binary search
3895 * (cache coherency etc)
3897 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3898 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
3899 return shader_data->gl_shaders[i].prgId;
3903 TRACE("No matching GL shader found, compiling a new shader\n");
3905 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3906 if (shader_data->num_gl_shaders)
3908 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3909 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3910 new_size * sizeof(*shader_data->gl_shaders));
3912 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3917 ERR("Out of memory\n");
3920 shader_data->gl_shaders = new_array;
3921 shader_data->shader_array_size = new_size;
3924 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3926 shader_buffer_init(&buffer);
3927 ret = shader_glsl_generate_vshader(shader, &buffer, args);
3928 shader_buffer_free(&buffer);
3929 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3934 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3935 * It sets the programId on the current StateBlock (because it should be called
3936 * inside of the DrawPrimitive() part of the render loop).
3938 * If a program for the given combination does not exist, create one, and store
3939 * the program in the hash table. If it creates a program, it will link the
3940 * given objects, too.
3943 /* GL locking is done by the caller */
3944 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3945 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3946 struct shader_glsl_priv *priv = This->shader_priv;
3947 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3948 IWineD3DPixelShader *pshader = use_ps ? This->stateBlock->pixelShader : NULL;
3949 IWineD3DVertexShader *vshader = use_vs ? This->stateBlock->vertexShader : NULL;
3950 struct glsl_shader_prog_link *entry = NULL;
3951 GLhandleARB programId = 0;
3952 GLhandleARB reorder_shader_id = 0;
3955 GLhandleARB vshader_id, pshader_id;
3956 struct ps_compile_args ps_compile_args;
3957 struct vs_compile_args vs_compile_args;
3960 find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3962 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3963 memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3966 find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3968 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3969 memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3971 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3973 priv->glsl_program = entry;
3977 /* If we get to this point, then no matching program exists, so we create one */
3978 programId = GL_EXTCALL(glCreateProgramObjectARB());
3979 TRACE("Created new GLSL shader program %u\n", programId);
3981 /* Create the entry */
3982 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3983 entry->programId = programId;
3984 entry->vshader = vshader;
3985 entry->pshader = pshader;
3986 entry->vs_args = vs_compile_args;
3987 entry->ps_args = ps_compile_args;
3988 entry->constant_version = 0;
3989 /* Add the hash table entry */
3990 add_glsl_program_entry(priv, entry);
3992 /* Set the current program */
3993 priv->glsl_program = entry;
3996 vshader_id = find_glsl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
4001 /* Attach GLSL vshader */
4003 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4006 reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
4007 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4008 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4009 checkGLcall("glAttachObjectARB");
4010 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4013 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4015 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4016 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4017 checkGLcall("glAttachObjectARB");
4019 /* Bind vertex attributes to a corresponding index number to match
4020 * the same index numbers as ARB_vertex_programs (makes loading
4021 * vertex attributes simpler). With this method, we can use the
4022 * exact same code to load the attributes later for both ARB and
4025 * We have to do this here because we need to know the Program ID
4026 * in order to make the bindings work, and it has to be done prior
4027 * to linking the GLSL program. */
4028 for (i = 0; map; map >>= 1, ++i)
4030 if (!(map & 1)) continue;
4032 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4033 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4035 checkGLcall("glBindAttribLocationARB");
4037 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4041 pshader_id = find_glsl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
4046 /* Attach GLSL pshader */
4048 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4049 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4050 checkGLcall("glAttachObjectARB");
4052 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4055 /* Link the program */
4056 TRACE("Linking GLSL shader program %u\n", programId);
4057 GL_EXTCALL(glLinkProgramARB(programId));
4058 print_glsl_info_log(&GLINFO_LOCATION, programId);
4060 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
4061 for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
4062 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4063 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4065 for (i = 0; i < MAX_CONST_I; ++i) {
4066 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4067 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4069 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
4070 for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
4071 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4072 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4074 for (i = 0; i < MAX_CONST_I; ++i) {
4075 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4076 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4080 for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
4082 sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
4083 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4084 sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
4085 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4086 sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
4087 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4091 if (use_ps && ps_compile_args.np2_fixup) {
4093 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
4094 if (ps_compile_args.np2_fixup & (1 << i)) {
4095 sprintf(name, "PsamplerNP2Fixup%u", i);
4096 entry->np2Fixup_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4098 entry->np2Fixup_location[i] = -1;
4103 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4104 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4105 checkGLcall("Find glsl program uniform locations");
4108 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4109 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4111 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4112 entry->vertex_color_clamp = GL_FALSE;
4114 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4117 /* Set the shader to allow uniform loading on it */
4118 GL_EXTCALL(glUseProgramObjectARB(programId));
4119 checkGLcall("glUseProgramObjectARB(programId)");
4121 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4122 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4123 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4124 * vertex shader with fixed function pixel processing is used we make sure that the card
4125 * supports enough samplers to allow the max number of vertex samplers with all possible
4126 * fixed function fragment processing setups. So once the program is linked these samplers
4130 /* Load vertex shader samplers */
4131 shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
4134 /* Load pixel shader samplers */
4135 shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
4138 /* If the local constants do not have to be loaded with the environment constants,
4139 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4142 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
4143 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4145 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
4146 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4150 /* GL locking is done by the caller */
4151 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
4153 GLhandleARB program_id;
4154 GLhandleARB vshader_id, pshader_id;
4155 static const char *blt_vshader[] =
4160 " gl_Position = gl_Vertex;\n"
4161 " gl_FrontColor = vec4(1.0);\n"
4162 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4166 static const char *blt_pshaders[tex_type_count] =
4172 "uniform sampler2D sampler;\n"
4175 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4181 "uniform samplerCube sampler;\n"
4184 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4188 "#extension GL_ARB_texture_rectangle : enable\n"
4189 "uniform sampler2DRect sampler;\n"
4192 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4196 if (!blt_pshaders[tex_type])
4198 FIXME("tex_type %#x not supported\n", tex_type);
4202 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4203 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4204 GL_EXTCALL(glCompileShaderARB(vshader_id));
4206 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4207 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4208 GL_EXTCALL(glCompileShaderARB(pshader_id));
4210 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4211 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4212 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4213 GL_EXTCALL(glLinkProgramARB(program_id));
4215 print_glsl_info_log(&GLINFO_LOCATION, program_id);
4217 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4220 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4221 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4225 /* GL locking is done by the caller */
4226 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
4227 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4228 struct shader_glsl_priv *priv = This->shader_priv;
4229 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4230 GLhandleARB program_id = 0;
4231 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4233 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4235 if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
4236 else priv->glsl_program = NULL;
4238 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4240 if (old_vertex_color_clamp != current_vertex_color_clamp) {
4241 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
4242 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4243 checkGLcall("glClampColorARB");
4245 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4249 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4250 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4251 GL_EXTCALL(glUseProgramObjectARB(program_id));
4252 checkGLcall("glUseProgramObjectARB");
4255 /* GL locking is done by the caller */
4256 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4257 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4258 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4259 struct shader_glsl_priv *priv = This->shader_priv;
4260 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4262 if (!*blt_program) {
4264 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4265 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4266 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4267 GL_EXTCALL(glUniform1iARB(loc, 0));
4269 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4273 /* GL locking is done by the caller */
4274 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4275 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4276 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4277 struct shader_glsl_priv *priv = This->shader_priv;
4278 GLhandleARB program_id;
4280 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4281 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4283 GL_EXTCALL(glUseProgramObjectARB(program_id));
4284 checkGLcall("glUseProgramObjectARB");
4287 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4288 const struct list *linked_programs;
4289 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4290 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4291 struct shader_glsl_priv *priv = device->shader_priv;
4292 const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
4293 IWineD3DPixelShaderImpl *ps = NULL;
4294 IWineD3DVertexShaderImpl *vs = NULL;
4296 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4297 * can be called from IWineD3DBaseShader::Release
4299 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4301 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4304 struct glsl_pshader_private *shader_data;
4305 ps = (IWineD3DPixelShaderImpl *) This;
4306 shader_data = ps->backend_priv;
4307 if(!shader_data || shader_data->num_gl_shaders == 0)
4309 HeapFree(GetProcessHeap(), 0, shader_data);
4310 ps->backend_priv = NULL;
4314 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4317 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
4321 struct glsl_vshader_private *shader_data;
4322 vs = (IWineD3DVertexShaderImpl *) This;
4323 shader_data = vs->backend_priv;
4324 if(!shader_data || shader_data->num_gl_shaders == 0)
4326 HeapFree(GetProcessHeap(), 0, shader_data);
4327 vs->backend_priv = NULL;
4331 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4334 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
4339 linked_programs = &This->baseShader.linked_programs;
4341 TRACE("Deleting linked programs\n");
4342 if (linked_programs->next) {
4343 struct glsl_shader_prog_link *entry, *entry2;
4347 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4348 delete_glsl_program_entry(priv, gl_info, entry);
4351 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4352 delete_glsl_program_entry(priv, gl_info, entry);
4360 struct glsl_pshader_private *shader_data = ps->backend_priv;
4363 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4364 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4365 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4366 checkGLcall("glDeleteObjectARB");
4369 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4370 HeapFree(GetProcessHeap(), 0, shader_data);
4371 ps->backend_priv = NULL;
4374 struct glsl_vshader_private *shader_data = vs->backend_priv;
4377 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4378 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4379 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4380 checkGLcall("glDeleteObjectARB");
4383 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4384 HeapFree(GetProcessHeap(), 0, shader_data);
4385 vs->backend_priv = NULL;
4389 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4391 const glsl_program_key_t *k = key;
4392 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4393 const struct glsl_shader_prog_link, program_lookup_entry);
4396 if (k->vshader > prog->vshader) return 1;
4397 else if (k->vshader < prog->vshader) return -1;
4399 if (k->pshader > prog->pshader) return 1;
4400 else if (k->pshader < prog->pshader) return -1;
4402 cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args));
4403 if (cmp) return cmp;
4405 cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args));
4409 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4411 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4412 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4416 ERR("Failed to allocate memory\n");
4420 heap->entries = mem;
4421 heap->entries[1].version = 0;
4422 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4428 static void constant_heap_free(struct constant_heap *heap)
4430 HeapFree(GetProcessHeap(), 0, heap->entries);
4433 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4438 glsl_program_key_compare,
4441 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4442 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4443 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4444 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4445 SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
4447 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4450 ERR("Failed to allocate memory.\n");
4451 HeapFree(GetProcessHeap(), 0, priv);
4452 return E_OUTOFMEMORY;
4455 if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
4457 ERR("Failed to initialize vertex shader constant heap\n");
4458 HeapFree(GetProcessHeap(), 0, priv->stack);
4459 HeapFree(GetProcessHeap(), 0, priv);
4460 return E_OUTOFMEMORY;
4463 if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
4465 ERR("Failed to initialize pixel shader constant heap\n");
4466 constant_heap_free(&priv->vconst_heap);
4467 HeapFree(GetProcessHeap(), 0, priv->stack);
4468 HeapFree(GetProcessHeap(), 0, priv);
4469 return E_OUTOFMEMORY;
4472 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4474 ERR("Failed to initialize rbtree.\n");
4475 constant_heap_free(&priv->pconst_heap);
4476 constant_heap_free(&priv->vconst_heap);
4477 HeapFree(GetProcessHeap(), 0, priv->stack);
4478 HeapFree(GetProcessHeap(), 0, priv);
4479 return E_OUTOFMEMORY;
4482 priv->next_constant_version = 1;
4484 This->shader_priv = priv;
4488 static void shader_glsl_free(IWineD3DDevice *iface) {
4489 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4490 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4491 struct shader_glsl_priv *priv = This->shader_priv;
4495 for (i = 0; i < tex_type_count; ++i)
4497 if (priv->depth_blt_program[i])
4499 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4504 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4505 constant_heap_free(&priv->pconst_heap);
4506 constant_heap_free(&priv->vconst_heap);
4507 HeapFree(GetProcessHeap(), 0, priv->stack);
4509 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4510 This->shader_priv = NULL;
4513 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4514 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4518 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4520 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4521 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4522 * vs_nv_version which is based on NV_vertex_program.
4523 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4524 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4525 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4526 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4528 if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4529 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4531 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4532 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4533 pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4535 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4536 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4537 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4538 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4539 * in max native instructions. Intel and others also offer the info in this extension but they
4540 * don't support GLSL (at least on Windows).
4542 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4543 * of instructions is 512 or less we have to do with ps2.0 hardware.
4544 * 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.
4546 if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4547 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4549 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4551 pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
4553 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4554 * Direct3D minimum requirement.
4556 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4557 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4559 * The problem is that the refrast clamps temporary results in the shader to
4560 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4561 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4562 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4563 * offer a way to query this.
4565 pCaps->PixelShader1xMaxValue = 8.0;
4566 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4568 pCaps->VSClipping = TRUE;
4571 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4573 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4575 TRACE("Checking support for fixup:\n");
4576 dump_color_fixup_desc(fixup);
4579 /* We support everything except YUV conversions. */
4580 if (!is_yuv_fixup(fixup))
4586 TRACE("[FAILED]\n");
4590 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4592 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4593 /* WINED3DSIH_ADD */ shader_glsl_arith,
4594 /* WINED3DSIH_BEM */ pshader_glsl_bem,
4595 /* WINED3DSIH_BREAK */ shader_glsl_break,
4596 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4597 /* WINED3DSIH_BREAKP */ NULL,
4598 /* WINED3DSIH_CALL */ shader_glsl_call,
4599 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4600 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4601 /* WINED3DSIH_CND */ shader_glsl_cnd,
4602 /* WINED3DSIH_CRS */ shader_glsl_cross,
4603 /* WINED3DSIH_DCL */ NULL,
4604 /* WINED3DSIH_DEF */ NULL,
4605 /* WINED3DSIH_DEFB */ NULL,
4606 /* WINED3DSIH_DEFI */ NULL,
4607 /* WINED3DSIH_DP2ADD */ pshader_glsl_dp2add,
4608 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4609 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4610 /* WINED3DSIH_DST */ shader_glsl_dst,
4611 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4612 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4613 /* WINED3DSIH_ELSE */ shader_glsl_else,
4614 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4615 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4616 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4617 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4618 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4619 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4620 /* WINED3DSIH_IF */ shader_glsl_if,
4621 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4622 /* WINED3DSIH_LABEL */ shader_glsl_label,
4623 /* WINED3DSIH_LIT */ shader_glsl_lit,
4624 /* WINED3DSIH_LOG */ shader_glsl_log,
4625 /* WINED3DSIH_LOGP */ shader_glsl_log,
4626 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4627 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4628 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4629 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4630 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4631 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4632 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4633 /* WINED3DSIH_MAD */ shader_glsl_mad,
4634 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4635 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4636 /* WINED3DSIH_MOV */ shader_glsl_mov,
4637 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4638 /* WINED3DSIH_MUL */ shader_glsl_arith,
4639 /* WINED3DSIH_NOP */ NULL,
4640 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4641 /* WINED3DSIH_PHASE */ NULL,
4642 /* WINED3DSIH_POW */ shader_glsl_pow,
4643 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4644 /* WINED3DSIH_REP */ shader_glsl_rep,
4645 /* WINED3DSIH_RET */ NULL,
4646 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4647 /* WINED3DSIH_SETP */ NULL,
4648 /* WINED3DSIH_SGE */ shader_glsl_compare,
4649 /* WINED3DSIH_SGN */ shader_glsl_map2gl,
4650 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4651 /* WINED3DSIH_SLT */ shader_glsl_compare,
4652 /* WINED3DSIH_SUB */ shader_glsl_arith,
4653 /* WINED3DSIH_TEX */ pshader_glsl_tex,
4654 /* WINED3DSIH_TEXBEM */ pshader_glsl_texbem,
4655 /* WINED3DSIH_TEXBEML */ pshader_glsl_texbem,
4656 /* WINED3DSIH_TEXCOORD */ pshader_glsl_texcoord,
4657 /* WINED3DSIH_TEXDEPTH */ pshader_glsl_texdepth,
4658 /* WINED3DSIH_TEXDP3 */ pshader_glsl_texdp3,
4659 /* WINED3DSIH_TEXDP3TEX */ pshader_glsl_texdp3tex,
4660 /* WINED3DSIH_TEXKILL */ pshader_glsl_texkill,
4661 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4662 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4663 /* WINED3DSIH_TEXM3x2DEPTH */ pshader_glsl_texm3x2depth,
4664 /* WINED3DSIH_TEXM3x2PAD */ pshader_glsl_texm3x2pad,
4665 /* WINED3DSIH_TEXM3x2TEX */ pshader_glsl_texm3x2tex,
4666 /* WINED3DSIH_TEXM3x3 */ pshader_glsl_texm3x3,
4667 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4668 /* WINED3DSIH_TEXM3x3PAD */ pshader_glsl_texm3x3pad,
4669 /* WINED3DSIH_TEXM3x3SPEC */ pshader_glsl_texm3x3spec,
4670 /* WINED3DSIH_TEXM3x3TEX */ pshader_glsl_texm3x3tex,
4671 /* WINED3DSIH_TEXM3x3VSPEC */ pshader_glsl_texm3x3vspec,
4672 /* WINED3DSIH_TEXREG2AR */ pshader_glsl_texreg2ar,
4673 /* WINED3DSIH_TEXREG2GB */ pshader_glsl_texreg2gb,
4674 /* WINED3DSIH_TEXREG2RGB */ pshader_glsl_texreg2rgb,
4677 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
4678 SHADER_HANDLER hw_fct;
4680 /* Select handler */
4681 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
4683 /* Unhandled opcode */
4686 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
4691 shader_glsl_add_instruction_modifiers(ins);
4694 const shader_backend_t glsl_shader_backend = {
4695 shader_glsl_handle_instruction,
4697 shader_glsl_select_depth_blt,
4698 shader_glsl_deselect_depth_blt,
4699 shader_glsl_update_float_vertex_constants,
4700 shader_glsl_update_float_pixel_constants,
4701 shader_glsl_load_constants,
4702 shader_glsl_load_np2fixup_constants,
4703 shader_glsl_destroy,
4706 shader_glsl_dirty_const,
4707 shader_glsl_get_caps,
4708 shader_glsl_color_fixup_supported,