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 hash_table_t *glsl_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 list vshader_entry;
98 struct list pshader_entry;
99 GLhandleARB programId;
100 GLint *vuniformF_locations;
101 GLint *puniformF_locations;
102 GLint vuniformI_locations[MAX_CONST_I];
103 GLint puniformI_locations[MAX_CONST_I];
104 GLint posFixup_location;
105 GLint np2Fixup_location[MAX_FRAGMENT_SAMPLERS];
106 GLint bumpenvmat_location[MAX_TEXTURES];
107 GLint luminancescale_location[MAX_TEXTURES];
108 GLint luminanceoffset_location[MAX_TEXTURES];
109 GLint ycorrection_location;
110 GLenum vertex_color_clamp;
111 IWineD3DVertexShader *vshader;
112 IWineD3DPixelShader *pshader;
113 struct vs_compile_args vs_args;
114 struct ps_compile_args ps_args;
115 UINT constant_version;
119 IWineD3DVertexShader *vshader;
120 IWineD3DPixelShader *pshader;
121 struct ps_compile_args ps_args;
122 struct vs_compile_args vs_args;
123 } glsl_program_key_t;
125 struct shader_glsl_ctx_priv {
126 const struct vs_compile_args *cur_vs_args;
127 const struct ps_compile_args *cur_ps_args;
130 struct glsl_ps_compiled_shader
132 struct ps_compile_args args;
136 struct glsl_pshader_private
138 struct glsl_ps_compiled_shader *gl_shaders;
139 UINT num_gl_shaders, shader_array_size;
142 struct glsl_vs_compiled_shader
144 struct vs_compile_args args;
148 struct glsl_vshader_private
150 struct glsl_vs_compiled_shader *gl_shaders;
151 UINT num_gl_shaders, shader_array_size;
154 /* Extract a line from the info log.
155 * Note that this modifies the source string. */
156 static char *get_info_log_line(char **ptr)
161 if (!(q = strstr(p, "\n")))
163 if (!*p) return NULL;
173 /** Prints the GLSL info log which will contain error messages if they exist */
174 /* GL locking is done by the caller */
175 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
177 int infologLength = 0;
182 static const char * const spam[] =
184 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
185 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx */
186 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
187 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
188 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
189 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
190 "Fragment shader was successfully compiled to run on hardware.\n"
191 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
192 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
193 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
194 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n" /* MacOS ati */
197 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
199 GL_EXTCALL(glGetObjectParameterivARB(obj,
200 GL_OBJECT_INFO_LOG_LENGTH_ARB,
203 /* A size of 1 is just a null-terminated string, so the log should be bigger than
204 * that if there are errors. */
205 if (infologLength > 1)
209 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
210 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
212 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
213 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
216 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
217 if(strcmp(infoLog, spam[i]) == 0) {
226 TRACE("Spam received from GLSL shader #%u:\n", obj);
227 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
231 FIXME("Error received from GLSL shader #%u:\n", obj);
232 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
234 HeapFree(GetProcessHeap(), 0, infoLog);
239 * Loads (pixel shader) samplers
241 /* GL locking is done by the caller */
242 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
246 char sampler_name[20];
248 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
249 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
250 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
251 if (name_loc != -1) {
252 DWORD mapped_unit = tex_unit_map[i];
253 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(fragment_samplers))
255 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
256 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
257 checkGLcall("glUniform1iARB");
259 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
265 /* GL locking is done by the caller */
266 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
269 char sampler_name[20];
272 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
273 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
274 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
275 if (name_loc != -1) {
276 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
277 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(combined_samplers))
279 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
280 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
281 checkGLcall("glUniform1iARB");
283 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
289 /* GL locking is done by the caller */
290 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
291 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
294 unsigned int heap_idx = 1;
297 if (heap->entries[heap_idx].version <= version) return;
299 idx = heap->entries[heap_idx].idx;
300 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
301 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
303 while (stack_idx >= 0)
305 /* Note that we fall through to the next case statement. */
306 switch(stack[stack_idx])
308 case HEAP_NODE_TRAVERSE_LEFT:
310 unsigned int left_idx = heap_idx << 1;
311 if (left_idx < heap->size && heap->entries[left_idx].version > version)
314 idx = heap->entries[heap_idx].idx;
315 if (constant_locations[idx] != -1)
316 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
318 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
319 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
324 case HEAP_NODE_TRAVERSE_RIGHT:
326 unsigned int right_idx = (heap_idx << 1) + 1;
327 if (right_idx < heap->size && heap->entries[right_idx].version > version)
329 heap_idx = right_idx;
330 idx = heap->entries[heap_idx].idx;
331 if (constant_locations[idx] != -1)
332 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
334 stack[stack_idx++] = HEAP_NODE_POP;
335 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
348 checkGLcall("walk_constant_heap()");
351 /* GL locking is done by the caller */
352 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
354 GLfloat clamped_constant[4];
356 if (location == -1) return;
358 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
359 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
360 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
361 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
363 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
366 /* GL locking is done by the caller */
367 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
368 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
371 unsigned int heap_idx = 1;
374 if (heap->entries[heap_idx].version <= version) return;
376 idx = heap->entries[heap_idx].idx;
377 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
378 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
380 while (stack_idx >= 0)
382 /* Note that we fall through to the next case statement. */
383 switch(stack[stack_idx])
385 case HEAP_NODE_TRAVERSE_LEFT:
387 unsigned int left_idx = heap_idx << 1;
388 if (left_idx < heap->size && heap->entries[left_idx].version > version)
391 idx = heap->entries[heap_idx].idx;
392 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
394 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
395 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
400 case HEAP_NODE_TRAVERSE_RIGHT:
402 unsigned int right_idx = (heap_idx << 1) + 1;
403 if (right_idx < heap->size && heap->entries[right_idx].version > version)
405 heap_idx = right_idx;
406 idx = heap->entries[heap_idx].idx;
407 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
409 stack[stack_idx++] = HEAP_NODE_POP;
410 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
423 checkGLcall("walk_constant_heap_clamped()");
426 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
427 /* GL locking is done by the caller */
428 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
429 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
430 unsigned char *stack, UINT version)
432 const local_constant *lconst;
434 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
435 if (This->baseShader.reg_maps.shader_version.major == 1
436 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
437 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
439 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
441 if (!This->baseShader.load_local_constsF)
443 TRACE("No need to load local float constants for this shader\n");
447 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
448 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
450 GLint location = constant_locations[lconst->idx];
451 /* We found this uniform name in the program - go ahead and send the data */
452 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
454 checkGLcall("glUniform4fvARB()");
457 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
458 /* GL locking is done by the caller */
459 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
460 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
465 for (i = 0; constants_set; constants_set >>= 1, ++i)
467 if (!(constants_set & 1)) continue;
469 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
470 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
472 /* We found this uniform name in the program - go ahead and send the data */
473 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
474 checkGLcall("glUniform4ivARB");
477 /* Load immediate constants */
478 ptr = list_head(&This->baseShader.constantsI);
480 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
481 unsigned int idx = lconst->idx;
482 const GLint *values = (const GLint *)lconst->value;
484 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
485 values[0], values[1], values[2], values[3]);
487 /* We found this uniform name in the program - go ahead and send the data */
488 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
489 checkGLcall("glUniform4ivARB");
490 ptr = list_next(&This->baseShader.constantsI, ptr);
494 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
495 /* GL locking is done by the caller */
496 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
497 GLhandleARB programId, const BOOL *constants, WORD constants_set)
502 char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
503 const char* prefix = is_pshader? "PB":"VB";
506 /* TODO: Benchmark and see if it would be beneficial to store the
507 * locations of the constants to avoid looking up each time */
508 for (i = 0; constants_set; constants_set >>= 1, ++i)
510 if (!(constants_set & 1)) continue;
512 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
514 /* TODO: Benchmark and see if it would be beneficial to store the
515 * locations of the constants to avoid looking up each time */
516 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
517 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
520 /* We found this uniform name in the program - go ahead and send the data */
521 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
522 checkGLcall("glUniform1ivARB");
526 /* Load immediate constants */
527 ptr = list_head(&This->baseShader.constantsB);
529 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
530 unsigned int idx = lconst->idx;
531 const GLint *values = (const GLint *)lconst->value;
533 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
535 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
536 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
538 /* We found this uniform name in the program - go ahead and send the data */
539 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
540 checkGLcall("glUniform1ivARB");
542 ptr = list_next(&This->baseShader.constantsB, ptr);
546 static void reset_program_constant_version(void *value, void *context)
548 struct glsl_shader_prog_link *entry = value;
549 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 hash_table_for_each_entry(priv->glsl_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 = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3267 key->vshader = entry->vshader;
3268 key->pshader = entry->pshader;
3269 key->vs_args = entry->vs_args;
3270 key->ps_args = entry->ps_args;
3272 hash_table_put(priv->glsl_program_lookup, key, entry);
3275 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3276 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3277 struct ps_compile_args *ps_args) {
3278 glsl_program_key_t key;
3280 key.vshader = vshader;
3281 key.pshader = pshader;
3282 key.vs_args = *vs_args;
3283 key.ps_args = *ps_args;
3285 return hash_table_get(priv->glsl_program_lookup, &key);
3288 /* GL locking is done by the caller */
3289 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
3290 struct glsl_shader_prog_link *entry)
3292 glsl_program_key_t *key;
3294 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3295 key->vshader = entry->vshader;
3296 key->pshader = entry->pshader;
3297 key->vs_args = entry->vs_args;
3298 key->ps_args = entry->ps_args;
3299 hash_table_remove(priv->glsl_program_lookup, key);
3301 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3302 if (entry->vshader) list_remove(&entry->vshader_entry);
3303 if (entry->pshader) list_remove(&entry->pshader_entry);
3304 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3305 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3306 HeapFree(GetProcessHeap(), 0, entry);
3309 static void handle_ps3_input(SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, const DWORD *map,
3310 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3311 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3314 const char *semantic_name_in, *semantic_name_out;
3315 UINT semantic_idx_in, semantic_idx_out;
3318 DWORD in_count = vec4_varyings(3, gl_info);
3319 char reg_mask[6], reg_mask_out[6];
3320 char destination[50];
3321 WORD input_map, output_map;
3323 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3325 if (!output_signature)
3327 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3328 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3329 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3332 input_map = reg_maps_in->input_registers;
3333 for (i = 0; input_map; input_map >>= 1, ++i)
3335 if (!(input_map & 1)) continue;
3338 if (in_idx >= (in_count + 2)) {
3339 FIXME("More input varyings declared than supported, expect issues\n");
3342 else if (map[i] == ~0U)
3344 /* Declared, but not read register */
3348 if (in_idx == in_count) {
3349 sprintf(destination, "gl_FrontColor");
3350 } else if (in_idx == in_count + 1) {
3351 sprintf(destination, "gl_FrontSecondaryColor");
3353 sprintf(destination, "IN[%u]", in_idx);
3356 semantic_name_in = input_signature[i].semantic_name;
3357 semantic_idx_in = input_signature[i].semantic_idx;
3358 set[map[i]] = input_signature[i].mask;
3359 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3361 if (!output_signature)
3363 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3365 if (semantic_idx_in == 0)
3366 shader_addline(buffer, "%s%s = front_color%s;\n",
3367 destination, reg_mask, reg_mask);
3368 else if (semantic_idx_in == 1)
3369 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3370 destination, reg_mask, reg_mask);
3372 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3373 destination, reg_mask, reg_mask);
3375 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3377 if (semantic_idx_in < 8)
3379 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3380 destination, reg_mask, semantic_idx_in, reg_mask);
3384 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3385 destination, reg_mask, reg_mask);
3388 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3390 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3391 destination, reg_mask, reg_mask);
3395 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3396 destination, reg_mask, reg_mask);
3401 output_map = reg_maps_out->output_registers;
3402 for (j = 0; output_map; output_map >>= 1, ++j)
3404 if (!(output_map & 1)) continue;
3406 semantic_name_out = output_signature[j].semantic_name;
3407 semantic_idx_out = output_signature[j].semantic_idx;
3408 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3410 if (semantic_idx_in == semantic_idx_out
3411 && !strcmp(semantic_name_in, semantic_name_out))
3413 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3414 destination, reg_mask, j, reg_mask_out);
3419 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3420 destination, reg_mask, reg_mask);
3425 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3426 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3427 * input varyings are assigned above, if the optimizer works properly.
3429 for(i = 0; i < in_count + 2; i++) {
3430 if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3431 unsigned int size = 0;
3432 memset(reg_mask, 0, sizeof(reg_mask));
3433 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3434 reg_mask[size] = 'x';
3437 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3438 reg_mask[size] = 'y';
3441 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3442 reg_mask[size] = 'z';
3445 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3446 reg_mask[size] = 'w';
3450 if (i == in_count) {
3451 sprintf(destination, "gl_FrontColor");
3452 } else if (i == in_count + 1) {
3453 sprintf(destination, "gl_FrontSecondaryColor");
3455 sprintf(destination, "IN[%u]", i);
3459 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3461 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3466 HeapFree(GetProcessHeap(), 0, set);
3469 /* GL locking is done by the caller */
3470 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3471 IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3473 GLhandleARB ret = 0;
3474 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3475 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3476 IWineD3DDeviceImpl *device;
3477 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3478 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3480 SHADER_BUFFER buffer;
3481 const char *semantic_name;
3484 const struct wined3d_shader_signature_element *output_signature;
3486 shader_buffer_init(&buffer);
3488 shader_addline(&buffer, "#version 120\n");
3490 if(vs_major < 3 && ps_major < 3) {
3491 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3492 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3494 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3495 if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3496 !device->frag_pipe->ffp_proj_control) {
3497 shader_addline(&buffer, "void order_ps_input() {\n");
3498 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3499 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3500 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3501 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3504 shader_addline(&buffer, "}\n");
3506 shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3508 } else if(ps_major < 3 && vs_major >= 3) {
3509 WORD map = vs->baseShader.reg_maps.output_registers;
3511 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3512 output_signature = vs->output_signature;
3514 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3515 for (i = 0; map; map >>= 1, ++i)
3519 if (!(map & 1)) continue;
3521 semantic_name = output_signature[i].semantic_name;
3522 semantic_idx = output_signature[i].semantic_idx;
3523 write_mask = output_signature[i].mask;
3524 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3526 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3528 if (semantic_idx == 0)
3529 shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3530 else if (semantic_idx == 1)
3531 shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3533 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3535 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3537 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3539 if (semantic_idx < 8)
3541 if (!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) write_mask |= WINED3DSP_WRITEMASK_3;
3543 shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3544 semantic_idx, reg_mask, i, reg_mask);
3545 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3546 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3549 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3551 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3553 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3555 shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3558 shader_addline(&buffer, "}\n");
3560 } else if(ps_major >= 3 && vs_major >= 3) {
3561 WORD map = vs->baseShader.reg_maps.output_registers;
3563 output_signature = vs->output_signature;
3565 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3566 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3567 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3569 /* First, sort out position and point size. Those are not passed to the pixel shader */
3570 for (i = 0; map; map >>= 1, ++i)
3572 if (!(map & 1)) continue;
3574 semantic_name = output_signature[i].semantic_name;
3575 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3577 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3579 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3581 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3583 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3587 /* Then, fix the pixel shader input */
3588 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->input_signature,
3589 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3591 shader_addline(&buffer, "}\n");
3592 } else if(ps_major >= 3 && vs_major < 3) {
3593 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3594 shader_addline(&buffer, "void order_ps_input() {\n");
3595 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3596 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3597 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3599 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->input_signature,
3600 &ps->baseShader.reg_maps, NULL, NULL);
3601 shader_addline(&buffer, "}\n");
3603 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3606 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3607 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3608 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3609 checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3610 GL_EXTCALL(glCompileShaderARB(ret));
3611 checkGLcall("glCompileShaderARB(ret)");
3613 shader_buffer_free(&buffer);
3617 /* GL locking is done by the caller */
3618 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3619 GLhandleARB programId, char prefix)
3621 const local_constant *lconst;
3626 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3627 value = (const float *)lconst->value;
3628 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3629 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3630 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3632 checkGLcall("Hardcoding local constants\n");
3635 /* GL locking is done by the caller */
3636 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShaderImpl *This,
3637 SHADER_BUFFER *buffer, const struct ps_compile_args *args)
3639 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3640 CONST DWORD *function = This->baseShader.function;
3641 const char *fragcolor;
3642 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3643 struct shader_glsl_ctx_priv priv_ctx;
3645 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3646 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3648 memset(&priv_ctx, 0, sizeof(priv_ctx));
3649 priv_ctx.cur_ps_args = args;
3651 shader_addline(buffer, "#version 120\n");
3653 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3654 shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
3656 if(GL_SUPPORT(ARB_SHADER_TEXTURE_LOD) && reg_maps->usestexldd) {
3657 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3659 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3660 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3661 * drivers write a warning if we don't do so
3663 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3666 /* Base Declarations */
3667 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
3669 /* Pack 3.0 inputs */
3670 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3672 pshader_glsl_input_pack((IWineD3DPixelShader *) This, buffer, This->input_signature, reg_maps, args->vp_mode);
3675 /* Base Shader Body */
3676 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3678 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3679 if (reg_maps->shader_version.major < 2)
3681 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3682 if(GL_SUPPORT(ARB_DRAW_BUFFERS))
3683 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3685 shader_addline(buffer, "gl_FragColor = R0;\n");
3688 if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3689 fragcolor = "gl_FragData[0]";
3691 fragcolor = "gl_FragColor";
3693 if(args->srgb_correction) {
3694 shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
3695 fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
3696 srgb_sub_high, srgb_sub_high, srgb_sub_high);
3697 shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
3698 shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
3699 shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
3700 shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
3701 shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
3703 /* Pixel shader < 3.0 do not replace the fog stage.
3704 * This implements linear fog computation and blending.
3705 * TODO: non linear fog
3706 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3707 * -1/(e-s) and e/(e-s) respectively.
3709 if (reg_maps->shader_version.major < 3)
3712 case FOG_OFF: break;
3714 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3715 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3716 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3717 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3720 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3721 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3722 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3723 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3726 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3727 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3728 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3729 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
3734 shader_addline(buffer, "}\n");
3736 TRACE("Compiling shader object %u\n", shader_obj);
3737 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3738 GL_EXTCALL(glCompileShaderARB(shader_obj));
3739 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
3741 /* Store the shader object */
3745 /* GL locking is done by the caller */
3746 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShaderImpl *This,
3747 SHADER_BUFFER *buffer, const struct vs_compile_args *args)
3749 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3750 CONST DWORD *function = This->baseShader.function;
3751 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3752 struct shader_glsl_ctx_priv priv_ctx;
3754 /* Create the hw GLSL shader program and assign it as the shader->prgId */
3755 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3757 shader_addline(buffer, "#version 120\n");
3759 memset(&priv_ctx, 0, sizeof(priv_ctx));
3760 priv_ctx.cur_vs_args = args;
3762 /* Base Declarations */
3763 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
3765 /* Base Shader Body */
3766 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
3768 /* Unpack 3.0 outputs */
3769 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
3770 else shader_addline(buffer, "order_ps_input();\n");
3772 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
3773 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
3774 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
3775 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
3777 if(args->fog_src == VS_FOG_Z) {
3778 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
3779 } else if (!reg_maps->fog) {
3780 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
3783 /* Write the final position.
3785 * OpenGL coordinates specify the center of the pixel while d3d coords specify
3786 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
3787 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3788 * contains 1.0 to allow a mad.
3790 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
3791 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
3792 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
3794 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3796 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
3797 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
3798 * which is the same as z = z * 2 - w.
3800 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
3802 shader_addline(buffer, "}\n");
3804 TRACE("Compiling shader object %u\n", shader_obj);
3805 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3806 GL_EXTCALL(glCompileShaderARB(shader_obj));
3807 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
3812 static GLhandleARB find_glsl_pshader(IWineD3DPixelShaderImpl *shader, const struct ps_compile_args *args)
3816 struct glsl_ps_compiled_shader *new_array;
3817 SHADER_BUFFER buffer;
3818 struct glsl_pshader_private *shader_data;
3821 if(!shader->backend_priv) {
3822 shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3824 shader_data = shader->backend_priv;
3826 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3827 * so a linear search is more performant than a hashmap or a binary search
3828 * (cache coherency etc)
3830 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3831 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
3832 return shader_data->gl_shaders[i].prgId;
3836 TRACE("No matching GL shader found, compiling a new shader\n");
3837 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3838 if (shader_data->num_gl_shaders)
3840 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3841 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3842 new_size * sizeof(*shader_data->gl_shaders));
3844 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3849 ERR("Out of memory\n");
3852 shader_data->gl_shaders = new_array;
3853 shader_data->shader_array_size = new_size;
3856 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3858 pixelshader_update_samplers(&shader->baseShader.reg_maps,
3859 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
3861 shader_buffer_init(&buffer);
3862 ret = shader_glsl_generate_pshader(shader, &buffer, args);
3863 shader_buffer_free(&buffer);
3864 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3869 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
3870 const DWORD use_map) {
3871 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
3872 return stored->fog_src == new->fog_src;
3875 static GLhandleARB find_glsl_vshader(IWineD3DVertexShaderImpl *shader, const struct vs_compile_args *args)
3879 struct glsl_vs_compiled_shader *new_array;
3880 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
3881 SHADER_BUFFER buffer;
3882 struct glsl_vshader_private *shader_data;
3885 if(!shader->backend_priv) {
3886 shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3888 shader_data = shader->backend_priv;
3890 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3891 * so a linear search is more performant than a hashmap or a binary search
3892 * (cache coherency etc)
3894 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3895 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
3896 return shader_data->gl_shaders[i].prgId;
3900 TRACE("No matching GL shader found, compiling a new shader\n");
3902 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3903 if (shader_data->num_gl_shaders)
3905 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3906 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3907 new_size * sizeof(*shader_data->gl_shaders));
3909 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3914 ERR("Out of memory\n");
3917 shader_data->gl_shaders = new_array;
3918 shader_data->shader_array_size = new_size;
3921 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3923 shader_buffer_init(&buffer);
3924 ret = shader_glsl_generate_vshader(shader, &buffer, args);
3925 shader_buffer_free(&buffer);
3926 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3931 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3932 * It sets the programId on the current StateBlock (because it should be called
3933 * inside of the DrawPrimitive() part of the render loop).
3935 * If a program for the given combination does not exist, create one, and store
3936 * the program in the hash table. If it creates a program, it will link the
3937 * given objects, too.
3940 /* GL locking is done by the caller */
3941 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3942 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3943 struct shader_glsl_priv *priv = This->shader_priv;
3944 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3945 IWineD3DPixelShader *pshader = This->stateBlock->pixelShader;
3946 IWineD3DVertexShader *vshader = This->stateBlock->vertexShader;
3947 struct glsl_shader_prog_link *entry = NULL;
3948 GLhandleARB programId = 0;
3949 GLhandleARB reorder_shader_id = 0;
3952 GLhandleARB vshader_id, pshader_id;
3953 struct ps_compile_args ps_compile_args;
3954 struct vs_compile_args vs_compile_args;
3957 find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3959 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3960 memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3963 find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3965 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3966 memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3968 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3970 priv->glsl_program = entry;
3974 /* If we get to this point, then no matching program exists, so we create one */
3975 programId = GL_EXTCALL(glCreateProgramObjectARB());
3976 TRACE("Created new GLSL shader program %u\n", programId);
3978 /* Create the entry */
3979 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3980 entry->programId = programId;
3981 entry->vshader = vshader;
3982 entry->pshader = pshader;
3983 entry->vs_args = vs_compile_args;
3984 entry->ps_args = ps_compile_args;
3985 entry->constant_version = 0;
3986 /* Add the hash table entry */
3987 add_glsl_program_entry(priv, entry);
3989 /* Set the current program */
3990 priv->glsl_program = entry;
3993 vshader_id = find_glsl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
3998 /* Attach GLSL vshader */
4000 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4003 reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
4004 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4005 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4006 checkGLcall("glAttachObjectARB");
4007 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4010 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4012 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4013 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4014 checkGLcall("glAttachObjectARB");
4016 /* Bind vertex attributes to a corresponding index number to match
4017 * the same index numbers as ARB_vertex_programs (makes loading
4018 * vertex attributes simpler). With this method, we can use the
4019 * exact same code to load the attributes later for both ARB and
4022 * We have to do this here because we need to know the Program ID
4023 * in order to make the bindings work, and it has to be done prior
4024 * to linking the GLSL program. */
4025 for (i = 0; map; map >>= 1, ++i)
4027 if (!(map & 1)) continue;
4029 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4030 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4032 checkGLcall("glBindAttribLocationARB");
4034 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4038 pshader_id = find_glsl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
4043 /* Attach GLSL pshader */
4045 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4046 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4047 checkGLcall("glAttachObjectARB");
4049 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4052 /* Link the program */
4053 TRACE("Linking GLSL shader program %u\n", programId);
4054 GL_EXTCALL(glLinkProgramARB(programId));
4055 print_glsl_info_log(&GLINFO_LOCATION, programId);
4057 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
4058 for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
4059 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4060 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4062 for (i = 0; i < MAX_CONST_I; ++i) {
4063 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4064 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4066 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
4067 for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
4068 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4069 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4071 for (i = 0; i < MAX_CONST_I; ++i) {
4072 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4073 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4077 for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
4079 sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
4080 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4081 sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
4082 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4083 sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
4084 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4088 if (use_ps && ps_compile_args.np2_fixup) {
4090 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
4091 if (ps_compile_args.np2_fixup & (1 << i)) {
4092 sprintf(name, "PsamplerNP2Fixup%u", i);
4093 entry->np2Fixup_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4095 entry->np2Fixup_location[i] = -1;
4100 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4101 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4102 checkGLcall("Find glsl program uniform locations");
4105 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4106 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4108 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4109 entry->vertex_color_clamp = GL_FALSE;
4111 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4114 /* Set the shader to allow uniform loading on it */
4115 GL_EXTCALL(glUseProgramObjectARB(programId));
4116 checkGLcall("glUseProgramObjectARB(programId)");
4118 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4119 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4120 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4121 * vertex shader with fixed function pixel processing is used we make sure that the card
4122 * supports enough samplers to allow the max number of vertex samplers with all possible
4123 * fixed function fragment processing setups. So once the program is linked these samplers
4127 /* Load vertex shader samplers */
4128 shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
4131 /* Load pixel shader samplers */
4132 shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
4135 /* If the local constants do not have to be loaded with the environment constants,
4136 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4139 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
4140 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4142 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
4143 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4147 /* GL locking is done by the caller */
4148 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
4150 GLhandleARB program_id;
4151 GLhandleARB vshader_id, pshader_id;
4152 static const char *blt_vshader[] =
4157 " gl_Position = gl_Vertex;\n"
4158 " gl_FrontColor = vec4(1.0);\n"
4159 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4163 static const char *blt_pshaders[tex_type_count] =
4169 "uniform sampler2D sampler;\n"
4172 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4178 "uniform samplerCube sampler;\n"
4181 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4185 "#extension GL_ARB_texture_rectangle : enable\n"
4186 "uniform sampler2DRect sampler;\n"
4189 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4193 if (!blt_pshaders[tex_type])
4195 FIXME("tex_type %#x not supported\n", tex_type);
4199 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4200 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4201 GL_EXTCALL(glCompileShaderARB(vshader_id));
4203 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4204 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4205 GL_EXTCALL(glCompileShaderARB(pshader_id));
4207 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4208 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4209 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4210 GL_EXTCALL(glLinkProgramARB(program_id));
4212 print_glsl_info_log(&GLINFO_LOCATION, program_id);
4214 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4217 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4218 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4222 /* GL locking is done by the caller */
4223 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
4224 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4225 struct shader_glsl_priv *priv = This->shader_priv;
4226 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4227 GLhandleARB program_id = 0;
4228 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4230 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4232 if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
4233 else priv->glsl_program = NULL;
4235 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4237 if (old_vertex_color_clamp != current_vertex_color_clamp) {
4238 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
4239 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4240 checkGLcall("glClampColorARB");
4242 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4246 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4247 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4248 GL_EXTCALL(glUseProgramObjectARB(program_id));
4249 checkGLcall("glUseProgramObjectARB");
4252 /* GL locking is done by the caller */
4253 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4254 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4255 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4256 struct shader_glsl_priv *priv = This->shader_priv;
4257 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4259 if (!*blt_program) {
4261 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4262 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4263 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4264 GL_EXTCALL(glUniform1iARB(loc, 0));
4266 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4270 /* GL locking is done by the caller */
4271 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4272 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4273 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4274 struct shader_glsl_priv *priv = This->shader_priv;
4275 GLhandleARB program_id;
4277 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4278 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4280 GL_EXTCALL(glUseProgramObjectARB(program_id));
4281 checkGLcall("glUseProgramObjectARB");
4284 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4285 const struct list *linked_programs;
4286 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4287 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4288 struct shader_glsl_priv *priv = device->shader_priv;
4289 const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
4290 IWineD3DPixelShaderImpl *ps = NULL;
4291 IWineD3DVertexShaderImpl *vs = NULL;
4293 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4294 * can be called from IWineD3DBaseShader::Release
4296 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4298 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4301 struct glsl_pshader_private *shader_data;
4302 ps = (IWineD3DPixelShaderImpl *) This;
4303 shader_data = ps->backend_priv;
4304 if(!shader_data || shader_data->num_gl_shaders == 0)
4306 HeapFree(GetProcessHeap(), 0, shader_data);
4307 ps->backend_priv = NULL;
4311 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4314 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
4318 struct glsl_vshader_private *shader_data;
4319 vs = (IWineD3DVertexShaderImpl *) This;
4320 shader_data = vs->backend_priv;
4321 if(!shader_data || shader_data->num_gl_shaders == 0)
4323 HeapFree(GetProcessHeap(), 0, shader_data);
4324 vs->backend_priv = NULL;
4328 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4331 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
4336 linked_programs = &This->baseShader.linked_programs;
4338 TRACE("Deleting linked programs\n");
4339 if (linked_programs->next) {
4340 struct glsl_shader_prog_link *entry, *entry2;
4344 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4345 delete_glsl_program_entry(priv, gl_info, entry);
4348 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4349 delete_glsl_program_entry(priv, gl_info, entry);
4357 struct glsl_pshader_private *shader_data = ps->backend_priv;
4360 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4361 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4362 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4363 checkGLcall("glDeleteObjectARB");
4366 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4367 HeapFree(GetProcessHeap(), 0, shader_data);
4368 ps->backend_priv = NULL;
4371 struct glsl_vshader_private *shader_data = vs->backend_priv;
4374 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4375 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4376 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4377 checkGLcall("glDeleteObjectARB");
4380 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4381 HeapFree(GetProcessHeap(), 0, shader_data);
4382 vs->backend_priv = NULL;
4386 static unsigned int glsl_program_key_hash(const void *key)
4388 const glsl_program_key_t *k = key;
4390 unsigned int hash = ((DWORD_PTR) k->vshader) | ((DWORD_PTR) k->pshader) << 16;
4391 hash += ~(hash << 15);
4392 hash ^= (hash >> 10);
4393 hash += (hash << 3);
4394 hash ^= (hash >> 6);
4395 hash += ~(hash << 11);
4396 hash ^= (hash >> 16);
4401 static BOOL glsl_program_key_compare(const void *keya, const void *keyb)
4403 const glsl_program_key_t *ka = keya;
4404 const glsl_program_key_t *kb = keyb;
4406 return ka->vshader == kb->vshader && ka->pshader == kb->pshader &&
4407 (memcmp(&ka->ps_args, &kb->ps_args, sizeof(kb->ps_args)) == 0) &&
4408 (memcmp(&ka->vs_args, &kb->vs_args, sizeof(kb->vs_args)) == 0);
4411 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4413 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4414 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4418 ERR("Failed to allocate memory\n");
4422 heap->entries = mem;
4423 heap->entries[1].version = 0;
4424 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4430 static void constant_heap_free(struct constant_heap *heap)
4432 HeapFree(GetProcessHeap(), 0, heap->entries);
4435 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4436 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4437 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4438 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4439 SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
4441 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4444 ERR("Failed to allocate memory.\n");
4445 HeapFree(GetProcessHeap(), 0, priv);
4446 return E_OUTOFMEMORY;
4449 if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
4451 ERR("Failed to initialize vertex shader constant heap\n");
4452 HeapFree(GetProcessHeap(), 0, priv->stack);
4453 HeapFree(GetProcessHeap(), 0, priv);
4454 return E_OUTOFMEMORY;
4457 if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
4459 ERR("Failed to initialize pixel shader constant heap\n");
4460 constant_heap_free(&priv->vconst_heap);
4461 HeapFree(GetProcessHeap(), 0, priv->stack);
4462 HeapFree(GetProcessHeap(), 0, priv);
4463 return E_OUTOFMEMORY;
4466 priv->glsl_program_lookup = hash_table_create(glsl_program_key_hash, glsl_program_key_compare);
4467 priv->next_constant_version = 1;
4469 This->shader_priv = priv;
4473 static void shader_glsl_free(IWineD3DDevice *iface) {
4474 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4475 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4476 struct shader_glsl_priv *priv = This->shader_priv;
4480 for (i = 0; i < tex_type_count; ++i)
4482 if (priv->depth_blt_program[i])
4484 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4489 hash_table_destroy(priv->glsl_program_lookup, NULL, NULL);
4490 constant_heap_free(&priv->pconst_heap);
4491 constant_heap_free(&priv->vconst_heap);
4493 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4494 This->shader_priv = NULL;
4497 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4498 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4502 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4504 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4505 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4506 * vs_nv_version which is based on NV_vertex_program.
4507 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4508 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4509 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4510 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4512 if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4513 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4515 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4516 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4517 pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4519 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4520 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4521 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4522 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4523 * in max native instructions. Intel and others also offer the info in this extension but they
4524 * don't support GLSL (at least on Windows).
4526 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4527 * of instructions is 512 or less we have to do with ps2.0 hardware.
4528 * 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.
4530 if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4531 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4533 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4535 pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
4537 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4538 * Direct3D minimum requirement.
4540 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4541 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4543 * The problem is that the refrast clamps temporary results in the shader to
4544 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4545 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4546 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4547 * offer a way to query this.
4549 pCaps->PixelShader1xMaxValue = 8.0;
4550 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4552 pCaps->VSClipping = TRUE;
4555 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4557 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4559 TRACE("Checking support for fixup:\n");
4560 dump_color_fixup_desc(fixup);
4563 /* We support everything except YUV conversions. */
4564 if (!is_yuv_fixup(fixup))
4570 TRACE("[FAILED]\n");
4574 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4576 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4577 /* WINED3DSIH_ADD */ shader_glsl_arith,
4578 /* WINED3DSIH_BEM */ pshader_glsl_bem,
4579 /* WINED3DSIH_BREAK */ shader_glsl_break,
4580 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4581 /* WINED3DSIH_BREAKP */ NULL,
4582 /* WINED3DSIH_CALL */ shader_glsl_call,
4583 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4584 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4585 /* WINED3DSIH_CND */ shader_glsl_cnd,
4586 /* WINED3DSIH_CRS */ shader_glsl_cross,
4587 /* WINED3DSIH_DCL */ NULL,
4588 /* WINED3DSIH_DEF */ NULL,
4589 /* WINED3DSIH_DEFB */ NULL,
4590 /* WINED3DSIH_DEFI */ NULL,
4591 /* WINED3DSIH_DP2ADD */ pshader_glsl_dp2add,
4592 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4593 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4594 /* WINED3DSIH_DST */ shader_glsl_dst,
4595 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4596 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4597 /* WINED3DSIH_ELSE */ shader_glsl_else,
4598 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4599 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4600 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4601 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4602 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4603 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4604 /* WINED3DSIH_IF */ shader_glsl_if,
4605 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4606 /* WINED3DSIH_LABEL */ shader_glsl_label,
4607 /* WINED3DSIH_LIT */ shader_glsl_lit,
4608 /* WINED3DSIH_LOG */ shader_glsl_log,
4609 /* WINED3DSIH_LOGP */ shader_glsl_log,
4610 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4611 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4612 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4613 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4614 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4615 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4616 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4617 /* WINED3DSIH_MAD */ shader_glsl_mad,
4618 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4619 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4620 /* WINED3DSIH_MOV */ shader_glsl_mov,
4621 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4622 /* WINED3DSIH_MUL */ shader_glsl_arith,
4623 /* WINED3DSIH_NOP */ NULL,
4624 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4625 /* WINED3DSIH_PHASE */ NULL,
4626 /* WINED3DSIH_POW */ shader_glsl_pow,
4627 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4628 /* WINED3DSIH_REP */ shader_glsl_rep,
4629 /* WINED3DSIH_RET */ NULL,
4630 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4631 /* WINED3DSIH_SETP */ NULL,
4632 /* WINED3DSIH_SGE */ shader_glsl_compare,
4633 /* WINED3DSIH_SGN */ shader_glsl_map2gl,
4634 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4635 /* WINED3DSIH_SLT */ shader_glsl_compare,
4636 /* WINED3DSIH_SUB */ shader_glsl_arith,
4637 /* WINED3DSIH_TEX */ pshader_glsl_tex,
4638 /* WINED3DSIH_TEXBEM */ pshader_glsl_texbem,
4639 /* WINED3DSIH_TEXBEML */ pshader_glsl_texbem,
4640 /* WINED3DSIH_TEXCOORD */ pshader_glsl_texcoord,
4641 /* WINED3DSIH_TEXDEPTH */ pshader_glsl_texdepth,
4642 /* WINED3DSIH_TEXDP3 */ pshader_glsl_texdp3,
4643 /* WINED3DSIH_TEXDP3TEX */ pshader_glsl_texdp3tex,
4644 /* WINED3DSIH_TEXKILL */ pshader_glsl_texkill,
4645 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4646 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4647 /* WINED3DSIH_TEXM3x2DEPTH */ pshader_glsl_texm3x2depth,
4648 /* WINED3DSIH_TEXM3x2PAD */ pshader_glsl_texm3x2pad,
4649 /* WINED3DSIH_TEXM3x2TEX */ pshader_glsl_texm3x2tex,
4650 /* WINED3DSIH_TEXM3x3 */ pshader_glsl_texm3x3,
4651 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4652 /* WINED3DSIH_TEXM3x3PAD */ pshader_glsl_texm3x3pad,
4653 /* WINED3DSIH_TEXM3x3SPEC */ pshader_glsl_texm3x3spec,
4654 /* WINED3DSIH_TEXM3x3TEX */ pshader_glsl_texm3x3tex,
4655 /* WINED3DSIH_TEXM3x3VSPEC */ pshader_glsl_texm3x3vspec,
4656 /* WINED3DSIH_TEXREG2AR */ pshader_glsl_texreg2ar,
4657 /* WINED3DSIH_TEXREG2GB */ pshader_glsl_texreg2gb,
4658 /* WINED3DSIH_TEXREG2RGB */ pshader_glsl_texreg2rgb,
4661 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
4662 SHADER_HANDLER hw_fct;
4664 /* Select handler */
4665 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
4667 /* Unhandled opcode */
4670 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
4675 shader_glsl_add_instruction_modifiers(ins);
4678 const shader_backend_t glsl_shader_backend = {
4679 shader_glsl_handle_instruction,
4681 shader_glsl_select_depth_blt,
4682 shader_glsl_deselect_depth_blt,
4683 shader_glsl_update_float_vertex_constants,
4684 shader_glsl_update_float_pixel_constants,
4685 shader_glsl_load_constants,
4686 shader_glsl_load_np2fixup_constants,
4687 shader_glsl_destroy,
4690 shader_glsl_dirty_const,
4691 shader_glsl_get_caps,
4692 shader_glsl_color_fixup_supported,