push d0760662e4c9af92a52cfc83b053a1228de45087
[wine/hacks.git] / dlls / wined3d / glsl_shader.c
blob3c8eac145d4e12294d3019e5f6fd549461e321f0
1 /*
2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * D3D shader asm has swizzles on source parameters, and write masks for
25 * destination parameters. GLSL uses swizzles for both. The result of this is
26 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
27 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
28 * mask for the destination parameter into account.
31 #include "config.h"
32 #include <limits.h>
33 #include <stdio.h>
34 #include "wined3d_private.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d);
41 #define GLINFO_LOCATION (*gl_info)
43 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
44 #define WINED3D_GLSL_SAMPLE_RECT 0x2
45 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 typedef struct {
48 char reg_name[150];
49 char mask_str[6];
50 } glsl_dst_param_t;
52 typedef struct {
53 char reg_name[150];
54 char param_str[100];
55 } glsl_src_param_t;
57 typedef struct {
58 const char *name;
59 DWORD coord_mask;
60 } glsl_sample_function_t;
62 enum heap_node_op
64 HEAP_NODE_TRAVERSE_LEFT,
65 HEAP_NODE_TRAVERSE_RIGHT,
66 HEAP_NODE_POP,
69 struct constant_entry
71 unsigned int idx;
72 unsigned int version;
75 struct constant_heap
77 struct constant_entry *entries;
78 unsigned int *positions;
79 unsigned int size;
82 /* GLSL shader private data */
83 struct shader_glsl_priv {
84 struct hash_table_t *glsl_program_lookup;
85 struct glsl_shader_prog_link *glsl_program;
86 struct constant_heap vconst_heap;
87 struct constant_heap pconst_heap;
88 unsigned char *stack;
89 GLhandleARB depth_blt_program[tex_type_count];
90 UINT next_constant_version;
93 /* Struct to maintain data about a linked GLSL program */
94 struct glsl_shader_prog_link {
95 struct list vshader_entry;
96 struct list pshader_entry;
97 GLhandleARB programId;
98 GLint *vuniformF_locations;
99 GLint *puniformF_locations;
100 GLint vuniformI_locations[MAX_CONST_I];
101 GLint puniformI_locations[MAX_CONST_I];
102 GLint posFixup_location;
103 GLint np2Fixup_location[MAX_FRAGMENT_SAMPLERS];
104 GLint bumpenvmat_location[MAX_TEXTURES];
105 GLint luminancescale_location[MAX_TEXTURES];
106 GLint luminanceoffset_location[MAX_TEXTURES];
107 GLint ycorrection_location;
108 GLenum vertex_color_clamp;
109 IWineD3DVertexShader *vshader;
110 IWineD3DPixelShader *pshader;
111 struct vs_compile_args vs_args;
112 struct ps_compile_args ps_args;
113 UINT constant_version;
116 typedef struct {
117 IWineD3DVertexShader *vshader;
118 IWineD3DPixelShader *pshader;
119 struct ps_compile_args ps_args;
120 struct vs_compile_args vs_args;
121 } glsl_program_key_t;
124 /** Prints the GLSL info log which will contain error messages if they exist */
125 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
127 int infologLength = 0;
128 char *infoLog;
129 unsigned int i;
130 BOOL is_spam;
132 static const char * const spam[] =
134 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
135 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx */
136 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
137 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
138 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
139 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
140 "Fragment shader was successfully compiled to run on hardware.\n"
141 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
142 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
143 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
144 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n" /* MacOS ati */
147 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
149 GL_EXTCALL(glGetObjectParameterivARB(obj,
150 GL_OBJECT_INFO_LOG_LENGTH_ARB,
151 &infologLength));
153 /* A size of 1 is just a null-terminated string, so the log should be bigger than
154 * that if there are errors. */
155 if (infologLength > 1)
157 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
158 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
160 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
161 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
162 is_spam = FALSE;
164 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
165 if(strcmp(infoLog, spam[i]) == 0) {
166 is_spam = TRUE;
167 break;
170 if(is_spam) {
171 TRACE("Spam received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
172 } else {
173 FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
175 HeapFree(GetProcessHeap(), 0, infoLog);
180 * Loads (pixel shader) samplers
182 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
184 GLint name_loc;
185 int i;
186 char sampler_name[20];
188 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
189 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
190 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
191 if (name_loc != -1) {
192 DWORD mapped_unit = tex_unit_map[i];
193 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(fragment_samplers))
195 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
196 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
197 checkGLcall("glUniform1iARB");
198 } else {
199 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
205 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
207 GLint name_loc;
208 char sampler_name[20];
209 int i;
211 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
212 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
213 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
214 if (name_loc != -1) {
215 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
216 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(combined_samplers))
218 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
219 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
220 checkGLcall("glUniform1iARB");
221 } else {
222 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
228 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
229 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
231 int stack_idx = 0;
232 unsigned int heap_idx = 1;
233 unsigned int idx;
235 if (heap->entries[heap_idx].version <= version) return;
237 idx = heap->entries[heap_idx].idx;
238 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
239 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
241 while (stack_idx >= 0)
243 /* Note that we fall through to the next case statement. */
244 switch(stack[stack_idx])
246 case HEAP_NODE_TRAVERSE_LEFT:
248 unsigned int left_idx = heap_idx << 1;
249 if (left_idx < heap->size && heap->entries[left_idx].version > version)
251 heap_idx = left_idx;
252 idx = heap->entries[heap_idx].idx;
253 if (constant_locations[idx] != -1)
254 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
256 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
257 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
258 break;
262 case HEAP_NODE_TRAVERSE_RIGHT:
264 unsigned int right_idx = (heap_idx << 1) + 1;
265 if (right_idx < heap->size && heap->entries[right_idx].version > version)
267 heap_idx = right_idx;
268 idx = heap->entries[heap_idx].idx;
269 if (constant_locations[idx] != -1)
270 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
272 stack[stack_idx++] = HEAP_NODE_POP;
273 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
274 break;
278 case HEAP_NODE_POP:
280 heap_idx >>= 1;
281 --stack_idx;
282 break;
286 checkGLcall("walk_constant_heap()");
289 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
291 GLfloat clamped_constant[4];
293 if (location == -1) return;
295 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
296 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
297 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
298 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
300 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
303 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
304 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
306 int stack_idx = 0;
307 unsigned int heap_idx = 1;
308 unsigned int idx;
310 if (heap->entries[heap_idx].version <= version) return;
312 idx = heap->entries[heap_idx].idx;
313 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
314 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
316 while (stack_idx >= 0)
318 /* Note that we fall through to the next case statement. */
319 switch(stack[stack_idx])
321 case HEAP_NODE_TRAVERSE_LEFT:
323 unsigned int left_idx = heap_idx << 1;
324 if (left_idx < heap->size && heap->entries[left_idx].version > version)
326 heap_idx = left_idx;
327 idx = heap->entries[heap_idx].idx;
328 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
330 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
331 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
332 break;
336 case HEAP_NODE_TRAVERSE_RIGHT:
338 unsigned int right_idx = (heap_idx << 1) + 1;
339 if (right_idx < heap->size && heap->entries[right_idx].version > version)
341 heap_idx = right_idx;
342 idx = heap->entries[heap_idx].idx;
343 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
345 stack[stack_idx++] = HEAP_NODE_POP;
346 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
347 break;
351 case HEAP_NODE_POP:
353 heap_idx >>= 1;
354 --stack_idx;
355 break;
359 checkGLcall("walk_constant_heap_clamped()");
362 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
363 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
364 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
365 unsigned char *stack, UINT version)
367 const local_constant *lconst;
369 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
370 if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.reg_maps.shader_version) == 1
371 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version))
372 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
373 else
374 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
376 if (!This->baseShader.load_local_constsF)
378 TRACE("No need to load local float constants for this shader\n");
379 return;
382 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
383 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
385 GLint location = constant_locations[lconst->idx];
386 /* We found this uniform name in the program - go ahead and send the data */
387 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
389 checkGLcall("glUniform4fvARB()");
392 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
393 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
394 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
396 unsigned int i;
397 struct list* ptr;
399 for (i = 0; constants_set; constants_set >>= 1, ++i)
401 if (!(constants_set & 1)) continue;
403 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
404 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
406 /* We found this uniform name in the program - go ahead and send the data */
407 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
408 checkGLcall("glUniform4ivARB");
411 /* Load immediate constants */
412 ptr = list_head(&This->baseShader.constantsI);
413 while (ptr) {
414 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
415 unsigned int idx = lconst->idx;
416 const GLint *values = (const GLint *)lconst->value;
418 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
419 values[0], values[1], values[2], values[3]);
421 /* We found this uniform name in the program - go ahead and send the data */
422 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
423 checkGLcall("glUniform4ivARB");
424 ptr = list_next(&This->baseShader.constantsI, ptr);
428 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
429 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
430 GLhandleARB programId, const BOOL *constants, WORD constants_set)
432 GLint tmp_loc;
433 unsigned int i;
434 char tmp_name[8];
435 char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
436 const char* prefix = is_pshader? "PB":"VB";
437 struct list* ptr;
439 /* TODO: Benchmark and see if it would be beneficial to store the
440 * locations of the constants to avoid looking up each time */
441 for (i = 0; constants_set; constants_set >>= 1, ++i)
443 if (!(constants_set & 1)) continue;
445 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
447 /* TODO: Benchmark and see if it would be beneficial to store the
448 * locations of the constants to avoid looking up each time */
449 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
450 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
451 if (tmp_loc != -1)
453 /* We found this uniform name in the program - go ahead and send the data */
454 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
455 checkGLcall("glUniform1ivARB");
459 /* Load immediate constants */
460 ptr = list_head(&This->baseShader.constantsB);
461 while (ptr) {
462 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
463 unsigned int idx = lconst->idx;
464 const GLint *values = (const GLint *)lconst->value;
466 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
468 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
469 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
470 if (tmp_loc != -1) {
471 /* We found this uniform name in the program - go ahead and send the data */
472 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
473 checkGLcall("glUniform1ivARB");
475 ptr = list_next(&This->baseShader.constantsB, ptr);
479 static void reset_program_constant_version(void *value, void *context)
481 struct glsl_shader_prog_link *entry = value;
482 entry->constant_version = 0;
486 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
488 static void shader_glsl_load_np2fixup_constants(
489 IWineD3DDevice* device,
490 char usePixelShader,
491 char useVertexShader) {
493 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
494 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
496 if (!prog) {
497 /* No GLSL program set - nothing to do. */
498 return;
501 if (!usePixelShader) {
502 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
503 return;
506 if (prog->ps_args.np2_fixup) {
507 UINT i;
508 UINT fixup = prog->ps_args.np2_fixup;
509 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
510 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
512 for (i = 0; fixup; fixup >>= 1, ++i) {
513 if (-1 != prog->np2Fixup_location[i]) {
514 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
515 if (!tex) {
516 FIXME("Non-existant texture is flagged for NP2 texcoord fixup\n");
517 continue;
518 } else {
519 const float tex_dim[2] = {tex->baseTexture.pow2Matrix[0], tex->baseTexture.pow2Matrix[5]};
520 GL_EXTCALL(glUniform2fvARB(prog->np2Fixup_location[i], 1, tex_dim));
528 * Loads the app-supplied constants into the currently set GLSL program.
530 static void shader_glsl_load_constants(
531 IWineD3DDevice* device,
532 char usePixelShader,
533 char useVertexShader) {
535 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
536 struct shader_glsl_priv *priv = deviceImpl->shader_priv;
537 IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
538 const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
540 GLhandleARB programId;
541 struct glsl_shader_prog_link *prog = priv->glsl_program;
542 UINT constant_version;
543 int i;
545 if (!prog) {
546 /* No GLSL program set - nothing to do. */
547 return;
549 programId = prog->programId;
550 constant_version = prog->constant_version;
552 if (useVertexShader) {
553 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
555 /* Load DirectX 9 float constants/uniforms for vertex shader */
556 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
557 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
559 /* Load DirectX 9 integer constants/uniforms for vertex shader */
560 if(vshader->baseShader.uses_int_consts) {
561 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations,
562 stateBlock->vertexShaderConstantI, stateBlock->changed.vertexShaderConstantsI);
565 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
566 if(vshader->baseShader.uses_bool_consts) {
567 shader_glsl_load_constantsB(vshader, gl_info, programId,
568 stateBlock->vertexShaderConstantB, stateBlock->changed.vertexShaderConstantsB);
571 /* Upload the position fixup params */
572 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
573 checkGLcall("glUniform4fvARB");
576 if (usePixelShader) {
578 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
580 /* Load DirectX 9 float constants/uniforms for pixel shader */
581 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
582 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
584 /* Load DirectX 9 integer constants/uniforms for pixel shader */
585 if(pshader->baseShader.uses_int_consts) {
586 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations,
587 stateBlock->pixelShaderConstantI, stateBlock->changed.pixelShaderConstantsI);
590 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
591 if(pshader->baseShader.uses_bool_consts) {
592 shader_glsl_load_constantsB(pshader, gl_info, programId,
593 stateBlock->pixelShaderConstantB, stateBlock->changed.pixelShaderConstantsB);
596 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
597 * It can't be 0 for a valid texbem instruction.
599 for(i = 0; i < ((IWineD3DPixelShaderImpl *) pshader)->numbumpenvmatconsts; i++) {
600 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pshader;
601 int stage = ps->luminanceconst[i].texunit;
603 const float *data = (const float *)&stateBlock->textureState[(int)ps->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
604 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
605 checkGLcall("glUniformMatrix2fvARB");
607 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
608 * is set too, so we can check that in the needsbumpmat check
610 if(ps->baseShader.reg_maps.luminanceparams[stage]) {
611 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
612 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
614 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
615 checkGLcall("glUniform1fvARB");
616 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
617 checkGLcall("glUniform1fvARB");
621 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
622 float correction_params[4];
623 if(deviceImpl->render_offscreen) {
624 correction_params[0] = 0.0;
625 correction_params[1] = 1.0;
626 } else {
627 /* position is window relative, not viewport relative */
628 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
629 correction_params[1] = -1.0;
631 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
635 if (priv->next_constant_version == UINT_MAX)
637 TRACE("Max constant version reached, resetting to 0.\n");
638 hash_table_for_each_entry(priv->glsl_program_lookup, reset_program_constant_version, NULL);
639 priv->next_constant_version = 1;
641 else
643 prog->constant_version = priv->next_constant_version++;
647 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
648 unsigned int heap_idx, DWORD new_version)
650 struct constant_entry *entries = heap->entries;
651 unsigned int *positions = heap->positions;
652 unsigned int parent_idx;
654 while (heap_idx > 1)
656 parent_idx = heap_idx >> 1;
658 if (new_version <= entries[parent_idx].version) break;
660 entries[heap_idx] = entries[parent_idx];
661 positions[entries[parent_idx].idx] = heap_idx;
662 heap_idx = parent_idx;
665 entries[heap_idx].version = new_version;
666 entries[heap_idx].idx = idx;
667 positions[idx] = heap_idx;
670 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
672 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
673 struct shader_glsl_priv *priv = This->shader_priv;
674 struct constant_heap *heap = &priv->vconst_heap;
675 UINT i;
677 for (i = start; i < count + start; ++i)
679 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
680 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
681 else
682 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
686 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
688 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
689 struct shader_glsl_priv *priv = This->shader_priv;
690 struct constant_heap *heap = &priv->pconst_heap;
691 UINT i;
693 for (i = start; i < count + start; ++i)
695 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
696 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
697 else
698 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
702 /** Generate the variable & register declarations for the GLSL output target */
703 static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
704 SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info,
705 const struct ps_compile_args *ps_args)
707 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
708 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
709 DWORD shader_version = reg_maps->shader_version;
710 unsigned int i, extra_constants_needed = 0;
711 const local_constant *lconst;
713 /* There are some minor differences between pixel and vertex shaders */
714 char pshader = shader_is_pshader_version(shader_version);
715 char prefix = pshader ? 'P' : 'V';
717 /* Prototype the subroutines */
718 for (i = 0; i < This->baseShader.limits.label; i++) {
719 if (reg_maps->labels[i])
720 shader_addline(buffer, "void subroutine%u();\n", i);
723 /* Declare the constants (aka uniforms) */
724 if (This->baseShader.limits.constant_float > 0) {
725 unsigned max_constantsF;
726 if(pshader) {
727 max_constantsF = GL_LIMITS(pshader_constantsF) - (MAX_CONST_B / 4) - MAX_CONST_I - 2;
728 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
729 } else {
730 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix) */
731 max_constantsF = GL_LIMITS(vshader_constantsF) - (MAX_CONST_B / 4) - MAX_CONST_I - 1;
732 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
734 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
737 if (This->baseShader.limits.constant_int > 0)
738 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
740 if (This->baseShader.limits.constant_bool > 0)
741 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
743 if(!pshader) {
744 shader_addline(buffer, "uniform vec4 posFixup;\n");
745 /* Predeclaration; This function is added at link time based on the pixel shader.
746 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
747 * that. We know the input to the reorder function at vertex shader compile time, so
748 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
749 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
750 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
751 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
752 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
753 * inout.
755 if (shader_version >= WINED3DVS_VERSION(3, 0))
757 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
758 } else {
759 shader_addline(buffer, "void order_ps_input();\n");
761 } else {
762 IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
764 ps_impl->numbumpenvmatconsts = 0;
765 for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
766 if(!reg_maps->bumpmat[i]) {
767 continue;
770 ps_impl->bumpenvmatconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
771 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
773 if(reg_maps->luminanceparams) {
774 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
775 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
776 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
777 extra_constants_needed++;
778 } else {
779 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = -1;
782 extra_constants_needed++;
783 ps_impl->numbumpenvmatconsts++;
786 if(ps_args->srgb_correction) {
787 shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
788 srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
789 shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
790 srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
792 if(reg_maps->vpos || reg_maps->usesdsy) {
793 if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
794 shader_addline(buffer, "uniform vec4 ycorrection;\n");
795 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
796 extra_constants_needed++;
797 } else {
798 /* This happens because we do not have proper tracking of the constant registers that are
799 * actually used, only the max limit of the shader version
801 FIXME("Cannot find a free uniform for vpos correction params\n");
802 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
803 device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
804 device->render_offscreen ? 1.0 : -1.0);
806 shader_addline(buffer, "vec4 vpos;\n");
810 /* Declare texture samplers */
811 for (i = 0; i < This->baseShader.limits.sampler; i++) {
812 if (reg_maps->samplers[i]) {
814 DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
815 switch (stype) {
817 case WINED3DSTT_1D:
818 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
819 break;
820 case WINED3DSTT_2D:
821 if(device->stateBlock->textures[i] &&
822 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
823 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
824 } else {
825 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
828 if (pshader && ps_args->np2_fixup & (1 << i))
830 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
831 * while D3D has them in the (normalized) [0,1]x[0,1] range.
832 * samplerNP2Fixup stores texture dimensions and is updated through
833 * shader_glsl_load_np2fixup_constants when the sampler changes. */
834 shader_addline(buffer, "uniform vec2 %csamplerNP2Fixup%u;\n", prefix, i);
836 break;
837 case WINED3DSTT_CUBE:
838 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
839 break;
840 case WINED3DSTT_VOLUME:
841 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
842 break;
843 default:
844 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
845 FIXME("Unrecognized sampler type: %#x\n", stype);
846 break;
851 /* Declare address variables */
852 for (i = 0; i < This->baseShader.limits.address; i++) {
853 if (reg_maps->address[i])
854 shader_addline(buffer, "ivec4 A%d;\n", i);
857 /* Declare texture coordinate temporaries and initialize them */
858 for (i = 0; i < This->baseShader.limits.texcoord; i++) {
859 if (reg_maps->texcoord[i])
860 shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
863 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
864 * helper function shader that is linked in at link time
866 if (pshader && shader_version >= WINED3DPS_VERSION(3, 0))
868 if (use_vs(device->stateBlock))
870 shader_addline(buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
871 } else {
872 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
873 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
874 * pixel shader that reads the fixed function color into the packed input registers.
876 shader_addline(buffer, "vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
880 /* Declare output register temporaries */
881 if(This->baseShader.limits.packed_output) {
882 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
885 /* Declare temporary variables */
886 for(i = 0; i < This->baseShader.limits.temporary; i++) {
887 if (reg_maps->temporary[i])
888 shader_addline(buffer, "vec4 R%u;\n", i);
891 /* Declare attributes */
892 for (i = 0; i < This->baseShader.limits.attributes; i++) {
893 if (reg_maps->attributes[i])
894 shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
897 /* Declare loop registers aLx */
898 for (i = 0; i < reg_maps->loop_depth; i++) {
899 shader_addline(buffer, "int aL%u;\n", i);
900 shader_addline(buffer, "int tmpInt%u;\n", i);
903 /* Temporary variables for matrix operations */
904 shader_addline(buffer, "vec4 tmp0;\n");
905 shader_addline(buffer, "vec4 tmp1;\n");
907 /* Local constants use a different name so they can be loaded once at shader link time
908 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
909 * float -> string conversion can cause precision loss.
911 if(!This->baseShader.load_local_constsF) {
912 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
913 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
917 /* Start the main program */
918 shader_addline(buffer, "void main() {\n");
919 if(pshader && reg_maps->vpos) {
920 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
921 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
922 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
923 * precision troubles when we just substract 0.5.
925 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
927 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
929 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
930 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
931 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
932 * correctly on drivers that returns integer values.
934 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
938 /*****************************************************************************
939 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
941 * For more information, see http://wiki.winehq.org/DirectX-Shaders
942 ****************************************************************************/
944 /* Prototypes */
945 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins, const DWORD param,
946 const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
948 /** Used for opcode modifiers - They multiply the result by the specified amount */
949 static const char * const shift_glsl_tab[] = {
950 "", /* 0 (none) */
951 "2.0 * ", /* 1 (x2) */
952 "4.0 * ", /* 2 (x4) */
953 "8.0 * ", /* 3 (x8) */
954 "16.0 * ", /* 4 (x16) */
955 "32.0 * ", /* 5 (x32) */
956 "", /* 6 (x64) */
957 "", /* 7 (x128) */
958 "", /* 8 (d256) */
959 "", /* 9 (d128) */
960 "", /* 10 (d64) */
961 "", /* 11 (d32) */
962 "0.0625 * ", /* 12 (d16) */
963 "0.125 * ", /* 13 (d8) */
964 "0.25 * ", /* 14 (d4) */
965 "0.5 * " /* 15 (d2) */
968 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
969 static void shader_glsl_gen_modifier (
970 const DWORD instr,
971 const char *in_reg,
972 const char *in_regswizzle,
973 char *out_str) {
975 out_str[0] = 0;
977 switch (instr & WINED3DSP_SRCMOD_MASK) {
978 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
979 case WINED3DSPSM_DW:
980 case WINED3DSPSM_NONE:
981 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
982 break;
983 case WINED3DSPSM_NEG:
984 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
985 break;
986 case WINED3DSPSM_NOT:
987 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
988 break;
989 case WINED3DSPSM_BIAS:
990 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
991 break;
992 case WINED3DSPSM_BIASNEG:
993 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
994 break;
995 case WINED3DSPSM_SIGN:
996 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
997 break;
998 case WINED3DSPSM_SIGNNEG:
999 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1000 break;
1001 case WINED3DSPSM_COMP:
1002 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1003 break;
1004 case WINED3DSPSM_X2:
1005 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1006 break;
1007 case WINED3DSPSM_X2NEG:
1008 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1009 break;
1010 case WINED3DSPSM_ABS:
1011 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1012 break;
1013 case WINED3DSPSM_ABSNEG:
1014 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1015 break;
1016 default:
1017 FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
1018 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1022 /** Writes the GLSL variable name that corresponds to the register that the
1023 * DX opcode parameter is trying to access */
1024 static void shader_glsl_get_register_name(WINED3DSHADER_PARAM_REGISTER_TYPE register_type, UINT register_idx,
1025 BOOL rel_addr, const DWORD addr_token, char *register_name, BOOL *is_color,
1026 const struct wined3d_shader_instruction *ins)
1028 /* oPos, oFog and oPts in D3D */
1029 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1031 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1032 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1033 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
1034 DWORD shader_version = This->baseShader.reg_maps.shader_version;
1035 char pshader = shader_is_pshader_version(shader_version);
1037 *is_color = FALSE;
1039 switch (register_type)
1041 case WINED3DSPR_TEMP:
1042 sprintf(register_name, "R%u", register_idx);
1043 break;
1044 case WINED3DSPR_INPUT:
1045 if (pshader) {
1046 /* Pixel shaders >= 3.0 */
1047 if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3)
1049 DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
1051 if (rel_addr)
1053 glsl_src_param_t rel_param;
1054 shader_glsl_add_src_param(ins, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
1056 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1057 * operation there
1059 if (((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx])
1061 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1062 sprintf(register_name, "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1063 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx], in_count - 1,
1064 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx], in_count,
1065 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx]);
1066 } else {
1067 sprintf(register_name, "IN[%s + %u]", rel_param.param_str,
1068 ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx]);
1070 } else {
1071 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1072 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1073 rel_param.param_str, in_count - 1,
1074 rel_param.param_str, in_count,
1075 rel_param.param_str);
1076 } else {
1077 sprintf(register_name, "IN[%s]", rel_param.param_str);
1080 } else {
1081 DWORD idx = ((IWineD3DPixelShaderImpl *) This)->input_reg_map[register_idx];
1082 if (idx == in_count) {
1083 sprintf(register_name, "gl_Color");
1084 } else if (idx == in_count + 1) {
1085 sprintf(register_name, "gl_SecondaryColor");
1086 } else {
1087 sprintf(register_name, "IN[%u]", idx);
1090 } else {
1091 if (register_idx == 0)
1092 strcpy(register_name, "gl_Color");
1093 else
1094 strcpy(register_name, "gl_SecondaryColor");
1096 } else {
1097 if (((IWineD3DVertexShaderImpl *)This)->cur_args->swizzle_map & (1 << register_idx)) *is_color = TRUE;
1098 sprintf(register_name, "attrib%u", register_idx);
1100 break;
1101 case WINED3DSPR_CONST:
1103 const char prefix = pshader? 'P':'V';
1105 /* Relative addressing */
1106 if (rel_addr)
1108 /* Relative addressing on shaders 2.0+ have a relative address token,
1109 * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
1110 if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 2)
1112 glsl_src_param_t rel_param;
1113 shader_glsl_add_src_param(ins, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
1114 if (register_idx)
1116 sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, register_idx);
1117 } else {
1118 sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1120 } else {
1121 if (register_idx)
1123 sprintf(register_name, "%cC[A0.x + %u]", prefix, register_idx);
1124 } else {
1125 sprintf(register_name, "%cC[A0.x]", prefix);
1129 } else {
1130 if (shader_constant_is_local(This, register_idx))
1132 sprintf(register_name, "%cLC%u", prefix, register_idx);
1133 } else {
1134 sprintf(register_name, "%cC[%u]", prefix, register_idx);
1138 break;
1140 case WINED3DSPR_CONSTINT:
1141 if (pshader)
1142 sprintf(register_name, "PI[%u]", register_idx);
1143 else
1144 sprintf(register_name, "VI[%u]", register_idx);
1145 break;
1146 case WINED3DSPR_CONSTBOOL:
1147 if (pshader)
1148 sprintf(register_name, "PB[%u]", register_idx);
1149 else
1150 sprintf(register_name, "VB[%u]", register_idx);
1151 break;
1152 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1153 if (pshader) {
1154 sprintf(register_name, "T%u", register_idx);
1155 } else {
1156 sprintf(register_name, "A%u", register_idx);
1158 break;
1159 case WINED3DSPR_LOOP:
1160 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1161 break;
1162 case WINED3DSPR_SAMPLER:
1163 if (pshader)
1164 sprintf(register_name, "Psampler%u", register_idx);
1165 else
1166 sprintf(register_name, "Vsampler%u", register_idx);
1167 break;
1168 case WINED3DSPR_COLOROUT:
1169 if (register_idx >= GL_LIMITS(buffers))
1170 WARN("Write to render target %u, only %d supported\n", register_idx, 4);
1172 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
1173 sprintf(register_name, "gl_FragData[%u]", register_idx);
1174 } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
1175 sprintf(register_name, "gl_FragColor");
1177 break;
1178 case WINED3DSPR_RASTOUT:
1179 sprintf(register_name, "%s", hwrastout_reg_names[register_idx]);
1180 break;
1181 case WINED3DSPR_DEPTHOUT:
1182 sprintf(register_name, "gl_FragDepth");
1183 break;
1184 case WINED3DSPR_ATTROUT:
1185 if (register_idx == 0)
1187 sprintf(register_name, "gl_FrontColor");
1188 } else {
1189 sprintf(register_name, "gl_FrontSecondaryColor");
1191 break;
1192 case WINED3DSPR_TEXCRDOUT:
1193 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1194 if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3) sprintf(register_name, "OUT[%u]", register_idx);
1195 else sprintf(register_name, "gl_TexCoord[%u]", register_idx);
1196 break;
1197 case WINED3DSPR_MISCTYPE:
1198 if (register_idx == 0)
1200 /* vPos */
1201 sprintf(register_name, "vpos");
1203 else if (register_idx == 1)
1205 /* Note that gl_FrontFacing is a bool, while vFace is
1206 * a float for which the sign determines front/back
1208 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1209 } else {
1210 FIXME("Unhandled misctype register %d\n", register_idx);
1211 sprintf(register_name, "unrecognized_register");
1213 break;
1214 default:
1215 FIXME("Unhandled register name Type(%d)\n", register_type);
1216 sprintf(register_name, "unrecognized_register");
1217 break;
1221 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1223 *str++ = '.';
1224 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1225 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1226 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1227 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1228 *str = '\0';
1231 /* Get the GLSL write mask for the destination register */
1232 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1234 DWORD mask = param->write_mask;
1236 if (shader_is_scalar(param->register_type, param->register_idx))
1238 mask = WINED3DSP_WRITEMASK_0;
1239 *write_mask = '\0';
1241 else
1243 shader_glsl_write_mask_to_str(mask, write_mask);
1246 return mask;
1249 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1250 unsigned int size = 0;
1252 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1253 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1254 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1255 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1257 return size;
1260 static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
1261 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1262 * but addressed as "rgba". To fix this we need to swap the register's x
1263 * and z components. */
1264 DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
1265 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1266 char *ptr = swizzle_str;
1268 if (!shader_is_scalar(shader_get_regtype(param), param & WINED3DSP_REGNUM_MASK))
1270 *ptr++ = '.';
1271 /* swizzle bits fields: wwzzyyxx */
1272 if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
1273 if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
1274 if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
1275 if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
1278 *ptr = '\0';
1281 /* From a given parameter token, generate the corresponding GLSL string.
1282 * Also, return the actual register name and swizzle in case the
1283 * caller needs this information as well. */
1284 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1285 const DWORD param, const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param)
1287 BOOL is_color = FALSE;
1288 char swizzle_str[6];
1290 src_param->reg_name[0] = '\0';
1291 src_param->param_str[0] = '\0';
1292 swizzle_str[0] = '\0';
1294 shader_glsl_get_register_name(shader_get_regtype(param), param & WINED3DSP_REGNUM_MASK,
1295 param & WINED3DSHADER_ADDRMODE_RELATIVE, addr_token, src_param->reg_name, &is_color, ins);
1297 shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
1298 shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
1301 /* From a given parameter token, generate the corresponding GLSL string.
1302 * Also, return the actual register name and swizzle in case the
1303 * caller needs this information as well. */
1304 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1305 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1307 BOOL is_color = FALSE;
1309 glsl_dst->mask_str[0] = '\0';
1310 glsl_dst->reg_name[0] = '\0';
1312 shader_glsl_get_register_name(wined3d_dst->register_type, wined3d_dst->register_idx,
1313 wined3d_dst->has_rel_addr, wined3d_dst->addr_token, glsl_dst->reg_name, &is_color, ins);
1314 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1317 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1318 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer,
1319 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1321 glsl_dst_param_t glsl_dst;
1322 DWORD mask;
1324 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1325 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1327 return mask;
1330 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1331 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, const struct wined3d_shader_instruction *ins)
1333 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1336 /** Process GLSL instruction modifiers */
1337 void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1339 glsl_dst_param_t dst_param;
1340 DWORD modifiers;
1342 if (!ins->dst_count) return;
1344 modifiers = ins->dst[0].modifiers;
1345 if (!modifiers) return;
1347 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1349 if (modifiers & WINED3DSPDM_SATURATE)
1351 /* _SAT means to clamp the value of the register to between 0 and 1 */
1352 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1353 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1356 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1358 FIXME("_centroid modifier not handled\n");
1361 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1363 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1367 static inline const char *shader_get_comp_op(DWORD flags)
1369 DWORD op = (flags & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
1370 switch (op) {
1371 case COMPARISON_GT: return ">";
1372 case COMPARISON_EQ: return "==";
1373 case COMPARISON_GE: return ">=";
1374 case COMPARISON_LT: return "<";
1375 case COMPARISON_NE: return "!=";
1376 case COMPARISON_LE: return "<=";
1377 default:
1378 FIXME("Unrecognized comparison value: %u\n", op);
1379 return "(\?\?)";
1383 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1385 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1386 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1387 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1389 /* Note that there's no such thing as a projected cube texture. */
1390 switch(sampler_type) {
1391 case WINED3DSTT_1D:
1392 if(lod) {
1393 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1394 } else {
1395 sample_function->name = projected ? "texture1DProj" : "texture1D";
1397 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1398 break;
1399 case WINED3DSTT_2D:
1400 if(texrect) {
1401 if(lod) {
1402 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1403 } else {
1404 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1406 } else {
1407 if(lod) {
1408 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1409 } else {
1410 sample_function->name = projected ? "texture2DProj" : "texture2D";
1413 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1414 break;
1415 case WINED3DSTT_CUBE:
1416 if(lod) {
1417 sample_function->name = "textureCubeLod";
1418 } else {
1419 sample_function->name = "textureCube";
1421 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1422 break;
1423 case WINED3DSTT_VOLUME:
1424 if(lod) {
1425 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1426 } else {
1427 sample_function->name = projected ? "texture3DProj" : "texture3D";
1429 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1430 break;
1431 default:
1432 sample_function->name = "";
1433 sample_function->coord_mask = 0;
1434 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1435 break;
1439 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1440 BOOL sign_fixup, enum fixup_channel_source channel_source)
1442 switch(channel_source)
1444 case CHANNEL_SOURCE_ZERO:
1445 strcat(arguments, "0.0");
1446 break;
1448 case CHANNEL_SOURCE_ONE:
1449 strcat(arguments, "1.0");
1450 break;
1452 case CHANNEL_SOURCE_X:
1453 strcat(arguments, reg_name);
1454 strcat(arguments, ".x");
1455 break;
1457 case CHANNEL_SOURCE_Y:
1458 strcat(arguments, reg_name);
1459 strcat(arguments, ".y");
1460 break;
1462 case CHANNEL_SOURCE_Z:
1463 strcat(arguments, reg_name);
1464 strcat(arguments, ".z");
1465 break;
1467 case CHANNEL_SOURCE_W:
1468 strcat(arguments, reg_name);
1469 strcat(arguments, ".w");
1470 break;
1472 default:
1473 FIXME("Unhandled channel source %#x\n", channel_source);
1474 strcat(arguments, "undefined");
1475 break;
1478 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1481 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1483 struct wined3d_shader_dst_param dst;
1484 unsigned int mask_size, remaining;
1485 glsl_dst_param_t dst_param;
1486 char arguments[256];
1487 DWORD mask;
1489 mask = 0;
1490 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1491 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1492 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1493 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1494 mask &= ins->dst[0].write_mask;
1496 if (!mask) return; /* Nothing to do */
1498 if (is_yuv_fixup(fixup))
1500 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1501 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1502 return;
1505 mask_size = shader_glsl_get_write_mask_size(mask);
1507 dst = ins->dst[0];
1508 dst.write_mask = mask;
1509 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1511 arguments[0] = '\0';
1512 remaining = mask_size;
1513 if (mask & WINED3DSP_WRITEMASK_0)
1515 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1516 if (--remaining) strcat(arguments, ", ");
1518 if (mask & WINED3DSP_WRITEMASK_1)
1520 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1521 if (--remaining) strcat(arguments, ", ");
1523 if (mask & WINED3DSP_WRITEMASK_2)
1525 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1526 if (--remaining) strcat(arguments, ", ");
1528 if (mask & WINED3DSP_WRITEMASK_3)
1530 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1531 if (--remaining) strcat(arguments, ", ");
1534 if (mask_size > 1)
1536 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1537 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1539 else
1541 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1545 static void PRINTF_ATTR(6, 7) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1546 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1547 const char *bias, const char *coord_reg_fmt, ...)
1549 const char *sampler_base;
1550 char dst_swizzle[6];
1551 struct color_fixup_desc fixup;
1552 BOOL np2_fixup = FALSE;
1553 va_list args;
1555 shader_glsl_get_swizzle(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1557 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version))
1559 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1560 fixup = This->cur_args->color_fixup[sampler];
1561 sampler_base = "Psampler";
1563 if(This->cur_args->np2_fixup & (1 << sampler)) {
1564 if(bias) {
1565 FIXME("Biased sampling from NP2 textures is unsupported\n");
1566 } else {
1567 np2_fixup = TRUE;
1570 } else {
1571 sampler_base = "Vsampler";
1572 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1575 shader_glsl_append_dst(ins->ctx->buffer, ins);
1577 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1579 va_start(args, coord_reg_fmt);
1580 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1581 va_end(args);
1583 if(bias) {
1584 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1585 } else {
1586 if (np2_fixup) {
1587 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup%u)%s);\n", sampler, dst_swizzle);
1588 } else {
1589 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1593 if(!is_identity_fixup(fixup)) {
1594 shader_glsl_color_correction(ins, fixup);
1598 /*****************************************************************************
1600 * Begin processing individual instruction opcodes
1602 ****************************************************************************/
1604 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1605 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1607 SHADER_BUFFER *buffer = ins->ctx->buffer;
1608 glsl_src_param_t src0_param;
1609 glsl_src_param_t src1_param;
1610 DWORD write_mask;
1611 char op;
1613 /* Determine the GLSL operator to use based on the opcode */
1614 switch (ins->handler_idx)
1616 case WINED3DSIH_MUL: op = '*'; break;
1617 case WINED3DSIH_ADD: op = '+'; break;
1618 case WINED3DSIH_SUB: op = '-'; break;
1619 default:
1620 op = ' ';
1621 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1622 break;
1625 write_mask = shader_glsl_append_dst(buffer, ins);
1626 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src0_param);
1627 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
1628 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1631 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1632 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1634 SHADER_BUFFER *buffer = ins->ctx->buffer;
1635 glsl_src_param_t src0_param;
1636 DWORD write_mask;
1638 write_mask = shader_glsl_append_dst(buffer, ins);
1639 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src0_param);
1641 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1642 * shader versions WINED3DSIO_MOVA is used for this. */
1643 if ((WINED3DSHADER_VERSION_MAJOR(ins->ctx->reg_maps->shader_version) == 1
1644 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version)
1645 && ins->dst[0].register_type == WINED3DSPR_ADDR))
1647 /* This is a simple floor() */
1648 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1649 if (mask_size > 1) {
1650 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1651 } else {
1652 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1655 else if(ins->handler_idx == WINED3DSIH_MOVA)
1657 /* We need to *round* to the nearest int here. */
1658 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1659 if (mask_size > 1) {
1660 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);
1661 } else {
1662 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1664 } else {
1665 shader_addline(buffer, "%s);\n", src0_param.param_str);
1669 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1670 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1672 SHADER_BUFFER *buffer = ins->ctx->buffer;
1673 glsl_src_param_t src0_param;
1674 glsl_src_param_t src1_param;
1675 DWORD dst_write_mask, src_write_mask;
1676 unsigned int dst_size = 0;
1678 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1679 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1681 /* dp3 works on vec3, dp4 on vec4 */
1682 if (ins->handler_idx == WINED3DSIH_DP4)
1684 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1685 } else {
1686 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1689 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_write_mask, &src0_param);
1690 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, src_write_mask, &src1_param);
1692 if (dst_size > 1) {
1693 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1694 } else {
1695 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1699 /* Note that this instruction has some restrictions. The destination write mask
1700 * can't contain the w component, and the source swizzles have to be .xyzw */
1701 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1703 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1704 glsl_src_param_t src0_param;
1705 glsl_src_param_t src1_param;
1706 char dst_mask[6];
1708 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1709 shader_glsl_append_dst(ins->ctx->buffer, ins);
1710 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
1711 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, src_mask, &src1_param);
1712 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1715 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1716 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1717 * GLSL uses the value as-is. */
1718 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1720 SHADER_BUFFER *buffer = ins->ctx->buffer;
1721 glsl_src_param_t src0_param;
1722 glsl_src_param_t src1_param;
1723 DWORD dst_write_mask;
1724 unsigned int dst_size;
1726 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1727 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1729 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
1730 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_0, &src1_param);
1732 if (dst_size > 1) {
1733 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1734 } else {
1735 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1739 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1740 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1741 * GLSL uses the value as-is. */
1742 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1744 SHADER_BUFFER *buffer = ins->ctx->buffer;
1745 glsl_src_param_t src0_param;
1746 DWORD dst_write_mask;
1747 unsigned int dst_size;
1749 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1750 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1752 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
1754 if (dst_size > 1) {
1755 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1756 } else {
1757 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1761 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1762 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1764 SHADER_BUFFER *buffer = ins->ctx->buffer;
1765 glsl_src_param_t src_param;
1766 const char *instruction;
1767 DWORD write_mask;
1768 unsigned i;
1770 /* Determine the GLSL function to use based on the opcode */
1771 /* TODO: Possibly make this a table for faster lookups */
1772 switch (ins->handler_idx)
1774 case WINED3DSIH_MIN: instruction = "min"; break;
1775 case WINED3DSIH_MAX: instruction = "max"; break;
1776 case WINED3DSIH_ABS: instruction = "abs"; break;
1777 case WINED3DSIH_FRC: instruction = "fract"; break;
1778 case WINED3DSIH_NRM: instruction = "normalize"; break;
1779 case WINED3DSIH_EXP: instruction = "exp2"; break;
1780 case WINED3DSIH_SGN: instruction = "sign"; break;
1781 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1782 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1783 default: instruction = "";
1784 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1785 break;
1788 write_mask = shader_glsl_append_dst(buffer, ins);
1790 shader_addline(buffer, "%s(", instruction);
1792 if (ins->src_count)
1794 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src_param);
1795 shader_addline(buffer, "%s", src_param.param_str);
1796 for (i = 1; i < ins->src_count; ++i)
1798 shader_glsl_add_src_param(ins, ins->src[i].token, ins->src[i].addr_token, write_mask, &src_param);
1799 shader_addline(buffer, ", %s", src_param.param_str);
1803 shader_addline(buffer, "));\n");
1806 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1807 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1808 * dst.x = 2^(floor(src))
1809 * dst.y = src - floor(src)
1810 * dst.z = 2^src (partial precision is allowed, but optional)
1811 * dst.w = 1.0;
1812 * For 2.0 shaders, just do this (honoring writemask and swizzle):
1813 * dst = 2^src; (partial precision is allowed, but optional)
1815 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
1817 glsl_src_param_t src_param;
1819 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src_param);
1821 if (ins->ctx->reg_maps->shader_version < WINED3DPS_VERSION(2,0))
1823 char dst_mask[6];
1825 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1826 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1827 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1828 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
1830 shader_glsl_append_dst(ins->ctx->buffer, ins);
1831 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1832 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
1833 } else {
1834 DWORD write_mask;
1835 unsigned int mask_size;
1837 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1838 mask_size = shader_glsl_get_write_mask_size(write_mask);
1840 if (mask_size > 1) {
1841 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1842 } else {
1843 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
1848 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1849 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
1851 glsl_src_param_t src_param;
1852 DWORD write_mask;
1853 unsigned int mask_size;
1855 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1856 mask_size = shader_glsl_get_write_mask_size(write_mask);
1857 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &src_param);
1859 if (mask_size > 1) {
1860 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1861 } else {
1862 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
1866 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
1868 SHADER_BUFFER *buffer = ins->ctx->buffer;
1869 glsl_src_param_t src_param;
1870 DWORD write_mask;
1871 unsigned int mask_size;
1873 write_mask = shader_glsl_append_dst(buffer, ins);
1874 mask_size = shader_glsl_get_write_mask_size(write_mask);
1876 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &src_param);
1878 if (mask_size > 1) {
1879 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1880 } else {
1881 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1885 /** Process signed comparison opcodes in GLSL. */
1886 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
1888 glsl_src_param_t src0_param;
1889 glsl_src_param_t src1_param;
1890 DWORD write_mask;
1891 unsigned int mask_size;
1893 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1894 mask_size = shader_glsl_get_write_mask_size(write_mask);
1895 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src0_param);
1896 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
1898 if (mask_size > 1) {
1899 const char *compare;
1901 switch(ins->handler_idx)
1903 case WINED3DSIH_SLT: compare = "lessThan"; break;
1904 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
1905 default: compare = "";
1906 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
1909 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1910 src0_param.param_str, src1_param.param_str);
1911 } else {
1912 switch(ins->handler_idx)
1914 case WINED3DSIH_SLT:
1915 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
1916 * to return 0.0 but step returns 1.0 because step is not < x
1917 * An alternative is a bvec compare padded with an unused second component.
1918 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
1919 * issue. Playing with not() is not possible either because not() does not accept
1920 * a scalar.
1922 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
1923 src0_param.param_str, src1_param.param_str);
1924 break;
1925 case WINED3DSIH_SGE:
1926 /* Here we can use the step() function and safe a conditional */
1927 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
1928 break;
1929 default:
1930 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
1936 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1937 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
1939 glsl_src_param_t src0_param;
1940 glsl_src_param_t src1_param;
1941 glsl_src_param_t src2_param;
1942 DWORD write_mask, cmp_channel = 0;
1943 unsigned int i, j;
1944 char mask_char[6];
1945 BOOL temp_destination = FALSE;
1947 if (shader_is_scalar(ins->src[0].register_type, ins->src[0].register_idx))
1949 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1951 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_ALL, &src0_param);
1952 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
1953 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
1955 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
1956 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1957 } else {
1958 DWORD dst_mask = ins->dst[0].write_mask;
1959 struct wined3d_shader_dst_param dst = ins->dst[0];
1961 /* Cycle through all source0 channels */
1962 for (i=0; i<4; i++) {
1963 write_mask = 0;
1964 /* Find the destination channels which use the current source0 channel */
1965 for (j=0; j<4; j++) {
1966 if (((ins->src[0].token >> (WINED3DSP_SWIZZLE_SHIFT + 2 * j)) & 0x3) == i)
1968 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1969 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1972 dst.write_mask = dst_mask & write_mask;
1974 /* Splitting the cmp instruction up in multiple lines imposes a problem:
1975 * The first lines may overwrite source parameters of the following lines.
1976 * Deal with that by using a temporary destination register if needed
1978 if ((ins->src[0].register_idx == ins->dst[0].register_idx
1979 && ins->src[0].register_type == ins->dst[0].register_type)
1980 || (ins->src[1].register_idx == ins->dst[0].register_idx
1981 && ins->src[1].register_type == ins->dst[0].register_type)
1982 || (ins->src[2].register_idx == ins->dst[0].register_idx
1983 && ins->src[2].register_type == ins->dst[0].register_type))
1985 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
1986 if (!write_mask) continue;
1987 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
1988 temp_destination = TRUE;
1989 } else {
1990 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
1991 if (!write_mask) continue;
1994 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, cmp_channel, &src0_param);
1995 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
1996 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
1998 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
1999 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2002 if(temp_destination) {
2003 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2004 shader_glsl_append_dst(ins->ctx->buffer, ins);
2005 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2011 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2012 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2013 * the compare is done per component of src0. */
2014 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2016 struct wined3d_shader_dst_param dst;
2017 glsl_src_param_t src0_param;
2018 glsl_src_param_t src1_param;
2019 glsl_src_param_t src2_param;
2020 DWORD write_mask, cmp_channel = 0;
2021 unsigned int i, j;
2022 DWORD dst_mask;
2024 if (ins->ctx->reg_maps->shader_version < WINED3DPS_VERSION(1, 4))
2026 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2027 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2028 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
2029 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
2031 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2032 if (ins->coissue)
2034 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2035 } else {
2036 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2037 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2039 return;
2041 /* Cycle through all source0 channels */
2042 dst_mask = ins->dst[0].write_mask;
2043 dst = ins->dst[0];
2044 for (i=0; i<4; i++) {
2045 write_mask = 0;
2046 /* Find the destination channels which use the current source0 channel */
2047 for (j=0; j<4; j++) {
2048 if (((ins->src[0].token >> (WINED3DSP_SWIZZLE_SHIFT + 2 * j)) & 0x3) == i)
2050 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2051 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2055 dst.write_mask = dst_mask & write_mask;
2056 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2057 if (!write_mask) continue;
2059 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, cmp_channel, &src0_param);
2060 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
2061 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
2063 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2064 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2068 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2069 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2071 glsl_src_param_t src0_param;
2072 glsl_src_param_t src1_param;
2073 glsl_src_param_t src2_param;
2074 DWORD write_mask;
2076 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2077 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src0_param);
2078 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
2079 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
2080 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2081 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2084 /** Handles transforming all WINED3DSIO_M?x? opcodes for
2085 Vertex shaders to GLSL codes */
2086 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2088 int i;
2089 int nComponents = 0;
2090 struct wined3d_shader_dst_param tmp_dst = {0};
2091 struct wined3d_shader_src_param tmp_src[2] = {{0}};
2092 struct wined3d_shader_instruction tmp_ins;
2094 memset(&tmp_ins, 0, sizeof(tmp_ins));
2096 /* Set constants for the temporary argument */
2097 tmp_ins.ctx = ins->ctx;
2098 tmp_ins.dst_count = 1;
2099 tmp_ins.dst = &tmp_dst;
2100 tmp_ins.src_count = 2;
2101 tmp_ins.src = tmp_src;
2103 switch(ins->handler_idx)
2105 case WINED3DSIH_M4x4:
2106 nComponents = 4;
2107 tmp_ins.handler_idx = WINED3DSIH_DP4;
2108 break;
2109 case WINED3DSIH_M4x3:
2110 nComponents = 3;
2111 tmp_ins.handler_idx = WINED3DSIH_DP4;
2112 break;
2113 case WINED3DSIH_M3x4:
2114 nComponents = 4;
2115 tmp_ins.handler_idx = WINED3DSIH_DP3;
2116 break;
2117 case WINED3DSIH_M3x3:
2118 nComponents = 3;
2119 tmp_ins.handler_idx = WINED3DSIH_DP3;
2120 break;
2121 case WINED3DSIH_M3x2:
2122 nComponents = 2;
2123 tmp_ins.handler_idx = WINED3DSIH_DP3;
2124 break;
2125 default:
2126 break;
2129 tmp_dst = ins->dst[0];
2130 tmp_src[0] = ins->src[0];
2131 tmp_src[1] = ins->src[1];
2132 for (i = 0; i < nComponents; ++i)
2134 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2135 shader_glsl_dot(&tmp_ins);
2136 ++tmp_src[1].register_idx;
2137 ++tmp_src[1].token;
2142 The LRP instruction performs a component-wise linear interpolation
2143 between the second and third operands using the first operand as the
2144 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2145 This is equivalent to mix(src2, src1, src0);
2147 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2149 glsl_src_param_t src0_param;
2150 glsl_src_param_t src1_param;
2151 glsl_src_param_t src2_param;
2152 DWORD write_mask;
2154 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2156 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, write_mask, &src0_param);
2157 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, write_mask, &src1_param);
2158 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token, write_mask, &src2_param);
2160 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2161 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2164 /** Process the WINED3DSIO_LIT instruction in GLSL:
2165 * dst.x = dst.w = 1.0
2166 * dst.y = (src0.x > 0) ? src0.x
2167 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2168 * where src.w is clamped at +- 128
2170 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2172 glsl_src_param_t src0_param;
2173 glsl_src_param_t src1_param;
2174 glsl_src_param_t src3_param;
2175 char dst_mask[6];
2177 shader_glsl_append_dst(ins->ctx->buffer, ins);
2178 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2180 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2181 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_1, &src1_param);
2182 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &src3_param);
2184 /* The sdk specifies the instruction like this
2185 * dst.x = 1.0;
2186 * if(src.x > 0.0) dst.y = src.x
2187 * else dst.y = 0.0.
2188 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2189 * else dst.z = 0.0;
2190 * dst.w = 1.0;
2192 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2193 * dst.x = 1.0 ... No further explanation needed
2194 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2195 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2196 * dst.w = 1.0. ... Nothing fancy.
2198 * So we still have one conditional in there. So do this:
2199 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2201 * 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),
2202 * 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.
2203 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2205 shader_addline(ins->ctx->buffer,
2206 "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",
2207 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2210 /** Process the WINED3DSIO_DST instruction in GLSL:
2211 * dst.x = 1.0
2212 * dst.y = src0.x * src0.y
2213 * dst.z = src0.z
2214 * dst.w = src1.w
2216 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2218 glsl_src_param_t src0y_param;
2219 glsl_src_param_t src0z_param;
2220 glsl_src_param_t src1y_param;
2221 glsl_src_param_t src1w_param;
2222 char dst_mask[6];
2224 shader_glsl_append_dst(ins->ctx->buffer, ins);
2225 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2227 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_1, &src0y_param);
2228 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_2, &src0z_param);
2229 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_1, &src1y_param);
2230 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_3, &src1w_param);
2232 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2233 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2236 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2237 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2238 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2240 * dst.x = cos(src0.?)
2241 * dst.y = sin(src0.?)
2242 * dst.z = dst.z
2243 * dst.w = dst.w
2245 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2247 glsl_src_param_t src0_param;
2248 DWORD write_mask;
2250 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2251 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2253 switch (write_mask) {
2254 case WINED3DSP_WRITEMASK_0:
2255 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2256 break;
2258 case WINED3DSP_WRITEMASK_1:
2259 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2260 break;
2262 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2263 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2264 break;
2266 default:
2267 ERR("Write mask should be .x, .y or .xy\n");
2268 break;
2272 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2273 * Start a for() loop where src1.y is the initial value of aL,
2274 * increment aL by src1.z for a total of src1.x iterations.
2275 * Need to use a temporary variable for this operation.
2277 /* FIXME: I don't think nested loops will work correctly this way. */
2278 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2280 glsl_src_param_t src1_param;
2281 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2282 const DWORD *control_values = NULL;
2283 const local_constant *constant;
2285 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_ALL, &src1_param);
2287 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2288 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2289 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2290 * addressing.
2292 if (ins->src[1].register_type == WINED3DSPR_CONSTINT)
2294 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2295 if (constant->idx == ins->src[1].register_idx)
2297 control_values = constant->value;
2298 break;
2303 if(control_values) {
2304 if(control_values[2] > 0) {
2305 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
2306 shader->baseShader.cur_loop_depth, control_values[1],
2307 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2308 shader->baseShader.cur_loop_depth, control_values[2]);
2309 } else if(control_values[2] == 0) {
2310 shader_addline(ins->ctx->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
2311 shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
2312 shader->baseShader.cur_loop_depth, control_values[0],
2313 shader->baseShader.cur_loop_depth);
2314 } else {
2315 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
2316 shader->baseShader.cur_loop_depth, control_values[1],
2317 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2318 shader->baseShader.cur_loop_depth, control_values[2]);
2320 } else {
2321 shader_addline(ins->ctx->buffer,
2322 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2323 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2324 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2325 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2328 shader->baseShader.cur_loop_depth++;
2329 shader->baseShader.cur_loop_regno++;
2332 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2334 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2336 shader_addline(ins->ctx->buffer, "}\n");
2338 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2340 shader->baseShader.cur_loop_depth--;
2341 shader->baseShader.cur_loop_regno--;
2344 if (ins->handler_idx == WINED3DSIH_ENDREP)
2346 shader->baseShader.cur_loop_depth--;
2350 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2352 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2353 glsl_src_param_t src0_param;
2355 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2356 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2357 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2358 src0_param.param_str, shader->baseShader.cur_loop_depth);
2359 shader->baseShader.cur_loop_depth++;
2362 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2364 glsl_src_param_t src0_param;
2366 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2367 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2370 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2372 glsl_src_param_t src0_param;
2373 glsl_src_param_t src1_param;
2375 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2376 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_0, &src1_param);
2378 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2379 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2382 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2384 shader_addline(ins->ctx->buffer, "} else {\n");
2387 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2389 shader_addline(ins->ctx->buffer, "break;\n");
2392 /* FIXME: According to MSDN the compare is done per component. */
2393 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2395 glsl_src_param_t src0_param;
2396 glsl_src_param_t src1_param;
2398 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_0, &src0_param);
2399 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_0, &src1_param);
2401 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2402 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2405 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2407 shader_addline(ins->ctx->buffer, "}\n");
2408 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].register_idx);
2411 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2413 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].register_idx);
2416 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2418 glsl_src_param_t src1_param;
2420 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, WINED3DSP_WRITEMASK_0, &src1_param);
2421 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].register_idx);
2424 /*********************************************
2425 * Pixel Shader Specific Code begins here
2426 ********************************************/
2427 static void pshader_glsl_tex(const struct wined3d_shader_instruction *ins)
2429 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2430 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2431 DWORD shader_version = ins->ctx->reg_maps->shader_version;
2432 glsl_sample_function_t sample_function;
2433 DWORD sample_flags = 0;
2434 DWORD sampler_type;
2435 DWORD sampler_idx;
2436 DWORD mask = 0, swizzle;
2438 /* 1.0-1.4: Use destination register as sampler source.
2439 * 2.0+: Use provided sampler source. */
2440 if (shader_version < WINED3DPS_VERSION(2,0)) sampler_idx = ins->dst[0].register_idx;
2441 else sampler_idx = ins->src[1].register_idx;
2442 sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2444 if (shader_version < WINED3DPS_VERSION(1,4))
2446 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2448 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2449 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2450 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2451 switch (flags & ~WINED3DTTFF_PROJECTED) {
2452 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2453 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2454 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2455 case WINED3DTTFF_COUNT4:
2456 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2460 else if (shader_version < WINED3DPS_VERSION(2,0))
2462 DWORD src_mod = ins->src[0].modifiers;
2464 if (src_mod == WINED3DSPSM_DZ) {
2465 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2466 mask = WINED3DSP_WRITEMASK_2;
2467 } else if (src_mod == WINED3DSPSM_DW) {
2468 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2469 mask = WINED3DSP_WRITEMASK_3;
2471 } else {
2472 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2474 /* ps 2.0 texldp instruction always divides by the fourth component. */
2475 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2476 mask = WINED3DSP_WRITEMASK_3;
2480 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2481 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2482 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2485 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2486 mask |= sample_function.coord_mask;
2488 if (shader_version < WINED3DPS_VERSION(2,0)) swizzle = WINED3DVS_NOSWIZZLE;
2489 else swizzle = ins->src[1].token & WINED3DSP_SWIZZLE_MASK;
2491 /* 1.0-1.3: Use destination register as coordinate source.
2492 1.4+: Use provided coordinate source register. */
2493 if (shader_version < WINED3DPS_VERSION(1,4))
2495 char coord_mask[6];
2496 shader_glsl_write_mask_to_str(mask, coord_mask);
2497 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL,
2498 "T%u%s", sampler_idx, coord_mask);
2499 } else {
2500 glsl_src_param_t coord_param;
2501 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, mask, &coord_param);
2502 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2504 glsl_src_param_t bias;
2505 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &bias);
2506 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, bias.param_str,
2507 "%s", coord_param.param_str);
2508 } else {
2509 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL,
2510 "%s", coord_param.param_str);
2515 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2517 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2518 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2519 glsl_sample_function_t sample_function;
2520 glsl_src_param_t coord_param, lod_param;
2521 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2522 DWORD sampler_type;
2523 DWORD sampler_idx;
2524 DWORD swizzle = ins->src[1].token & WINED3DSP_SWIZZLE_MASK;
2526 sampler_idx = ins->src[1].register_idx;
2527 sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2528 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2529 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2530 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2532 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2533 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, sample_function.coord_mask, &coord_param);
2535 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &lod_param);
2537 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version))
2539 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2540 * However, they seem to work just fine in fragment shaders as well. */
2541 WARN("Using %s in fragment shader.\n", sample_function.name);
2543 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, lod_param.param_str,
2544 "%s", coord_param.param_str);
2547 static void pshader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2549 /* FIXME: Make this work for more than just 2D textures */
2550 SHADER_BUFFER *buffer = ins->ctx->buffer;
2551 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2553 if (ins->ctx->reg_maps->shader_version != WINED3DPS_VERSION(1,4))
2555 char dst_mask[6];
2557 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2558 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2559 ins->dst[0].register_idx, dst_mask);
2560 } else {
2561 DWORD reg = ins->src[0].register_idx;
2562 DWORD src_mod = ins->src[0].modifiers;
2563 char dst_swizzle[6];
2565 shader_glsl_get_swizzle(ins->src[0].token, FALSE, write_mask, dst_swizzle);
2567 if (src_mod == WINED3DSPSM_DZ) {
2568 glsl_src_param_t div_param;
2569 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2570 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_2, &div_param);
2572 if (mask_size > 1) {
2573 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2574 } else {
2575 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2577 } else if (src_mod == WINED3DSPSM_DW) {
2578 glsl_src_param_t div_param;
2579 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2580 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_3, &div_param);
2582 if (mask_size > 1) {
2583 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2584 } else {
2585 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2587 } else {
2588 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2593 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2594 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2595 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2596 static void pshader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2598 glsl_src_param_t src0_param;
2599 glsl_sample_function_t sample_function;
2600 DWORD sampler_idx = ins->dst[0].register_idx;
2601 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2602 DWORD sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2603 UINT mask_size;
2605 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2607 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2608 * scalar, and projected sampling would require 4.
2610 * It is a dependent read - not valid with conditional NP2 textures
2612 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2613 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2615 switch(mask_size)
2617 case 1:
2618 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2619 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2620 break;
2622 case 2:
2623 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2624 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2625 break;
2627 case 3:
2628 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2629 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2630 break;
2632 default:
2633 FIXME("Unexpected mask size %u\n", mask_size);
2634 break;
2638 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2639 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2640 static void pshader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2642 glsl_src_param_t src0_param;
2643 DWORD dstreg = ins->dst[0].register_idx;
2644 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2645 DWORD dst_mask;
2646 unsigned int mask_size;
2648 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2649 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2650 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2652 if (mask_size > 1) {
2653 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2654 } else {
2655 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2659 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2660 * Calculate the depth as dst.x / dst.y */
2661 static void pshader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2663 glsl_dst_param_t dst_param;
2665 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2667 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2668 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2669 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2670 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2671 * >= 1.0 or < 0.0
2673 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2674 dst_param.reg_name, dst_param.reg_name);
2677 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2678 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2679 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2680 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2682 static void pshader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2684 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2685 DWORD dstreg = ins->dst[0].register_idx;
2686 glsl_src_param_t src0_param;
2688 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2690 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2691 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2694 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2695 * Calculate the 1st of a 2-row matrix multiplication. */
2696 static void pshader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2698 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2699 DWORD reg = ins->dst[0].register_idx;
2700 SHADER_BUFFER *buffer = ins->ctx->buffer;
2701 glsl_src_param_t src0_param;
2703 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2704 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2707 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2708 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2709 static void pshader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
2711 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2712 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2713 DWORD reg = ins->dst[0].register_idx;
2714 SHADER_BUFFER *buffer = ins->ctx->buffer;
2715 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2716 glsl_src_param_t src0_param;
2718 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2719 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2720 current_state->texcoord_w[current_state->current_row++] = reg;
2723 static void pshader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
2725 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2726 DWORD reg = ins->dst[0].register_idx;
2727 SHADER_BUFFER *buffer = ins->ctx->buffer;
2728 glsl_src_param_t src0_param;
2729 DWORD sampler_type = ins->ctx->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2730 glsl_sample_function_t sample_function;
2732 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2733 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2735 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2737 /* Sample the texture using the calculated coordinates */
2738 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DVS_NOSWIZZLE, NULL, "tmp0.xy");
2741 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2742 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2743 static void pshader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
2745 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2746 glsl_src_param_t src0_param;
2747 DWORD reg = ins->dst[0].register_idx;
2748 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2749 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2750 DWORD sampler_type = ins->ctx->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2751 glsl_sample_function_t sample_function;
2753 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2754 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2756 /* Dependent read, not valid with conditional NP2 */
2757 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2759 /* Sample the texture using the calculated coordinates */
2760 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DVS_NOSWIZZLE, NULL, "tmp0.xyz");
2762 current_state->current_row = 0;
2765 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2766 * Perform the 3rd row of a 3x3 matrix multiply */
2767 static void pshader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
2769 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2770 glsl_src_param_t src0_param;
2771 char dst_mask[6];
2772 DWORD reg = ins->dst[0].register_idx;
2773 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2774 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2776 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2778 shader_glsl_append_dst(ins->ctx->buffer, ins);
2779 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2780 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2782 current_state->current_row = 0;
2785 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
2786 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2787 static void pshader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
2789 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2790 DWORD reg = ins->dst[0].register_idx;
2791 glsl_src_param_t src0_param;
2792 glsl_src_param_t src1_param;
2793 SHADER_BUFFER *buffer = ins->ctx->buffer;
2794 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2795 DWORD stype = ins->ctx->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2796 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2797 glsl_sample_function_t sample_function;
2799 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2800 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token, src_mask, &src1_param);
2802 /* Perform the last matrix multiply operation */
2803 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2804 /* Reflection calculation */
2805 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2807 /* Dependent read, not valid with conditional NP2 */
2808 shader_glsl_get_sample_function(stype, 0, &sample_function);
2810 /* Sample the texture */
2811 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DVS_NOSWIZZLE, NULL, "tmp0.xyz");
2813 current_state->current_row = 0;
2816 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
2817 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2818 static void pshader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
2820 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2821 DWORD reg = ins->dst[0].register_idx;
2822 SHADER_BUFFER *buffer = ins->ctx->buffer;
2823 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2824 glsl_src_param_t src0_param;
2825 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2826 DWORD sampler_type = ins->ctx->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2827 glsl_sample_function_t sample_function;
2829 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, src_mask, &src0_param);
2831 /* Perform the last matrix multiply operation */
2832 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2834 /* Construct the eye-ray vector from w coordinates */
2835 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2836 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2837 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2839 /* Dependent read, not valid with conditional NP2 */
2840 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2842 /* Sample the texture using the calculated coordinates */
2843 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DVS_NOSWIZZLE, NULL, "tmp0.xyz");
2845 current_state->current_row = 0;
2848 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2849 * Apply a fake bump map transform.
2850 * texbem is pshader <= 1.3 only, this saves a few version checks
2852 static void pshader_glsl_texbem(const struct wined3d_shader_instruction *ins)
2854 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2855 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2856 glsl_sample_function_t sample_function;
2857 glsl_src_param_t coord_param;
2858 DWORD sampler_type;
2859 DWORD sampler_idx;
2860 DWORD mask;
2861 DWORD flags;
2862 char coord_mask[6];
2864 sampler_idx = ins->dst[0].register_idx;
2865 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2867 sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2868 /* Dependent read, not valid with conditional NP2 */
2869 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2870 mask = sample_function.coord_mask;
2872 shader_glsl_write_mask_to_str(mask, coord_mask);
2874 /* with projective textures, texbem only divides the static texture coord, not the displacement,
2875 * so we can't let the GL handle this.
2877 if (flags & WINED3DTTFF_PROJECTED) {
2878 DWORD div_mask=0;
2879 char coord_div_mask[3];
2880 switch (flags & ~WINED3DTTFF_PROJECTED) {
2881 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2882 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2883 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2884 case WINED3DTTFF_COUNT4:
2885 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2887 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
2888 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2891 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token,
2892 WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
2894 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2895 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
2896 coord_param.param_str, coord_mask);
2898 if (ins->handler_idx == WINED3DSIH_TEXBEML)
2900 glsl_src_param_t luminance_param;
2901 glsl_dst_param_t dst_param;
2903 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_2, &luminance_param);
2904 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2906 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
2907 dst_param.reg_name, dst_param.mask_str,
2908 luminance_param.param_str, sampler_idx, sampler_idx);
2912 static void pshader_glsl_bem(const struct wined3d_shader_instruction *ins)
2914 glsl_src_param_t src0_param, src1_param;
2915 DWORD sampler_idx = ins->dst[0].register_idx;
2917 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token,
2918 WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2919 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token,
2920 WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2922 shader_glsl_append_dst(ins->ctx->buffer, ins);
2923 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
2924 src0_param.param_str, sampler_idx, src1_param.param_str);
2927 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2928 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2929 static void pshader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
2931 glsl_src_param_t src0_param;
2932 DWORD sampler_idx = ins->dst[0].register_idx;
2933 DWORD sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2934 glsl_sample_function_t sample_function;
2936 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_ALL, &src0_param);
2938 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2939 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2940 "%s.wx", src0_param.reg_name);
2943 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2944 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2945 static void pshader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
2947 glsl_src_param_t src0_param;
2948 DWORD sampler_idx = ins->dst[0].register_idx;
2949 DWORD sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2950 glsl_sample_function_t sample_function;
2952 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, WINED3DSP_WRITEMASK_ALL, &src0_param);
2954 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2955 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2956 "%s.yz", src0_param.reg_name);
2959 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2960 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2961 static void pshader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
2963 glsl_src_param_t src0_param;
2964 DWORD sampler_idx = ins->dst[0].register_idx;
2965 DWORD sampler_type = ins->ctx->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2966 glsl_sample_function_t sample_function;
2968 /* Dependent read, not valid with conditional NP2 */
2969 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2970 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token, sample_function.coord_mask, &src0_param);
2972 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DVS_NOSWIZZLE, NULL,
2973 "%s", src0_param.param_str);
2976 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2977 * If any of the first 3 components are < 0, discard this pixel */
2978 static void pshader_glsl_texkill(const struct wined3d_shader_instruction *ins)
2980 glsl_dst_param_t dst_param;
2982 /* The argument is a destination parameter, and no writemasks are allowed */
2983 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2984 if ((ins->ctx->reg_maps->shader_version >= WINED3DPS_VERSION(2,0)))
2986 /* 2.0 shaders compare all 4 components in texkill */
2987 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
2988 } else {
2989 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
2990 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
2991 * 4 components are defined, only the first 3 are used
2993 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
2997 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2998 * dst = dot2(src0, src1) + src2 */
2999 static void pshader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3001 glsl_src_param_t src0_param;
3002 glsl_src_param_t src1_param;
3003 glsl_src_param_t src2_param;
3004 DWORD write_mask;
3005 unsigned int mask_size;
3007 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3008 mask_size = shader_glsl_get_write_mask_size(write_mask);
3010 shader_glsl_add_src_param(ins, ins->src[0].token, ins->src[0].addr_token,
3011 WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3012 shader_glsl_add_src_param(ins, ins->src[1].token, ins->src[1].addr_token,
3013 WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3014 shader_glsl_add_src_param(ins, ins->src[2].token, ins->src[2].addr_token,
3015 WINED3DSP_WRITEMASK_0, &src2_param);
3017 if (mask_size > 1) {
3018 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3019 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3020 } else {
3021 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3022 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3026 static void pshader_glsl_input_pack(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer,
3027 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps,
3028 enum vertexprocessing_mode vertexprocessing)
3030 unsigned int i;
3031 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3033 for (i = 0; i < MAX_REG_INPUT; ++i)
3035 DWORD usage, usage_idx;
3036 char reg_mask[6];
3038 /* Unused */
3039 if (!reg_maps->packed_input[i]) continue;
3041 usage = semantics_in[i].usage;
3042 usage_idx = semantics_in[i].usage_idx;
3043 shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3045 switch (usage)
3047 case WINED3DDECLUSAGE_TEXCOORD:
3048 if (usage_idx < 8 && vertexprocessing == pretransformed)
3049 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3050 This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
3051 else
3052 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3053 This->input_reg_map[i], reg_mask, reg_mask);
3054 break;
3056 case WINED3DDECLUSAGE_COLOR:
3057 if (usage_idx == 0)
3058 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3059 This->input_reg_map[i], reg_mask, reg_mask);
3060 else if (usage_idx == 1)
3061 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3062 This->input_reg_map[i], reg_mask, reg_mask);
3063 else
3064 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3065 This->input_reg_map[i], reg_mask, reg_mask);
3066 break;
3068 default:
3069 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3070 This->input_reg_map[i], reg_mask, reg_mask);
3071 break;
3076 /*********************************************
3077 * Vertex Shader Specific Code begins here
3078 ********************************************/
3080 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3081 glsl_program_key_t *key;
3083 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3084 key->vshader = entry->vshader;
3085 key->pshader = entry->pshader;
3086 key->vs_args = entry->vs_args;
3087 key->ps_args = entry->ps_args;
3089 hash_table_put(priv->glsl_program_lookup, key, entry);
3092 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3093 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3094 struct ps_compile_args *ps_args) {
3095 glsl_program_key_t key;
3097 key.vshader = vshader;
3098 key.pshader = pshader;
3099 key.vs_args = *vs_args;
3100 key.ps_args = *ps_args;
3102 return hash_table_get(priv->glsl_program_lookup, &key);
3105 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
3106 struct glsl_shader_prog_link *entry)
3108 glsl_program_key_t *key;
3110 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3111 key->vshader = entry->vshader;
3112 key->pshader = entry->pshader;
3113 key->vs_args = entry->vs_args;
3114 key->ps_args = entry->ps_args;
3115 hash_table_remove(priv->glsl_program_lookup, key);
3117 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3118 if (entry->vshader) list_remove(&entry->vshader_entry);
3119 if (entry->pshader) list_remove(&entry->pshader_entry);
3120 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3121 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3122 HeapFree(GetProcessHeap(), 0, entry);
3125 static void handle_ps3_input(SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, const DWORD *map,
3126 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps_in,
3127 const struct wined3d_shader_semantic *semantics_out, const struct shader_reg_maps *reg_maps_out)
3129 unsigned int i, j;
3130 DWORD usage, usage_idx, usage_out, usage_idx_out;
3131 DWORD *set;
3132 DWORD in_idx;
3133 DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
3134 char reg_mask[6], reg_mask_out[6];
3135 char destination[50];
3137 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3139 if (!semantics_out) {
3140 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3141 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3142 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3145 for(i = 0; i < MAX_REG_INPUT; i++) {
3146 if (!reg_maps_in->packed_input[i]) continue;
3148 in_idx = map[i];
3149 if (in_idx >= (in_count + 2)) {
3150 FIXME("More input varyings declared than supported, expect issues\n");
3151 continue;
3153 else if (map[i] == ~0U)
3155 /* Declared, but not read register */
3156 continue;
3159 if (in_idx == in_count) {
3160 sprintf(destination, "gl_FrontColor");
3161 } else if (in_idx == in_count + 1) {
3162 sprintf(destination, "gl_FrontSecondaryColor");
3163 } else {
3164 sprintf(destination, "IN[%u]", in_idx);
3167 usage = semantics_in[i].usage;
3168 usage_idx = semantics_in[i].usage_idx;
3169 set[map[i]] = shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3171 if(!semantics_out) {
3172 switch(usage) {
3173 case WINED3DDECLUSAGE_COLOR:
3174 if (usage_idx == 0)
3175 shader_addline(buffer, "%s%s = front_color%s;\n",
3176 destination, reg_mask, reg_mask);
3177 else if (usage_idx == 1)
3178 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3179 destination, reg_mask, reg_mask);
3180 else
3181 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3182 destination, reg_mask, reg_mask);
3183 break;
3185 case WINED3DDECLUSAGE_TEXCOORD:
3186 if (usage_idx < 8) {
3187 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3188 destination, reg_mask, usage_idx, reg_mask);
3189 } else {
3190 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3191 destination, reg_mask, reg_mask);
3193 break;
3195 case WINED3DDECLUSAGE_FOG:
3196 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3197 destination, reg_mask, reg_mask);
3198 break;
3200 default:
3201 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3202 destination, reg_mask, reg_mask);
3204 } else {
3205 BOOL found = FALSE;
3206 for(j = 0; j < MAX_REG_OUTPUT; j++) {
3207 if (!reg_maps_out->packed_output[j]) continue;
3209 usage_out = semantics_out[j].usage;
3210 usage_idx_out = semantics_out[j].usage_idx;
3211 shader_glsl_get_write_mask(&semantics_out[j].reg, reg_mask_out);
3213 if(usage == usage_out &&
3214 usage_idx == usage_idx_out) {
3215 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3216 destination, reg_mask, j, reg_mask);
3217 found = TRUE;
3220 if(!found) {
3221 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3222 destination, reg_mask, reg_mask);
3227 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3228 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3229 * input varyings are assigned above, if the optimizer works properly.
3231 for(i = 0; i < in_count + 2; i++) {
3232 if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3233 unsigned int size = 0;
3234 memset(reg_mask, 0, sizeof(reg_mask));
3235 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3236 reg_mask[size] = 'x';
3237 size++;
3239 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3240 reg_mask[size] = 'y';
3241 size++;
3243 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3244 reg_mask[size] = 'z';
3245 size++;
3247 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3248 reg_mask[size] = 'w';
3249 size++;
3252 if (i == in_count) {
3253 sprintf(destination, "gl_FrontColor");
3254 } else if (i == in_count + 1) {
3255 sprintf(destination, "gl_FrontSecondaryColor");
3256 } else {
3257 sprintf(destination, "IN[%u]", i);
3260 if (size == 1) {
3261 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3262 } else {
3263 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3268 HeapFree(GetProcessHeap(), 0, set);
3271 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3272 IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3274 GLhandleARB ret = 0;
3275 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3276 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3277 IWineD3DDeviceImpl *device;
3278 DWORD vs_major = WINED3DSHADER_VERSION_MAJOR(vs->baseShader.reg_maps.shader_version);
3279 DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.reg_maps.shader_version) : 0;
3280 unsigned int i;
3281 SHADER_BUFFER buffer;
3282 DWORD usage, usage_idx, writemask;
3283 char reg_mask[6];
3284 const struct wined3d_shader_semantic *semantics_out;
3286 shader_buffer_init(&buffer);
3288 shader_addline(&buffer, "#version 120\n");
3290 if(vs_major < 3 && ps_major < 3) {
3291 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3292 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3294 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3295 if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3296 !device->frag_pipe->ffp_proj_control) {
3297 shader_addline(&buffer, "void order_ps_input() {\n");
3298 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3299 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3300 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3301 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3304 shader_addline(&buffer, "}\n");
3305 } else {
3306 shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3308 } else if(ps_major < 3 && vs_major >= 3) {
3309 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3310 semantics_out = vs->semantics_out;
3312 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3313 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3314 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3316 usage = semantics_out[i].usage;
3317 usage_idx = semantics_out[i].usage_idx;
3318 writemask = shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3320 switch(usage) {
3321 case WINED3DDECLUSAGE_COLOR:
3322 if (usage_idx == 0)
3323 shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3324 else if (usage_idx == 1)
3325 shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3326 break;
3328 case WINED3DDECLUSAGE_POSITION:
3329 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3330 break;
3332 case WINED3DDECLUSAGE_TEXCOORD:
3333 if (usage_idx < 8) {
3334 if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;
3336 shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3337 usage_idx, reg_mask, i, reg_mask);
3338 if(!(writemask & WINED3DSP_WRITEMASK_3)) {
3339 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
3342 break;
3344 case WINED3DDECLUSAGE_PSIZE:
3345 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3346 break;
3348 case WINED3DDECLUSAGE_FOG:
3349 shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3350 break;
3352 default:
3353 break;
3356 shader_addline(&buffer, "}\n");
3358 } else if(ps_major >= 3 && vs_major >= 3) {
3359 semantics_out = vs->semantics_out;
3361 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3362 shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3363 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3365 /* First, sort out position and point size. Those are not passed to the pixel shader */
3366 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3367 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3369 usage = semantics_out[i].usage;
3370 usage_idx = semantics_out[i].usage_idx;
3371 shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3373 switch(usage) {
3374 case WINED3DDECLUSAGE_POSITION:
3375 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3376 break;
3378 case WINED3DDECLUSAGE_PSIZE:
3379 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3380 break;
3382 default:
3383 break;
3387 /* Then, fix the pixel shader input */
3388 handle_ps3_input(&buffer, gl_info, ps->input_reg_map,
3389 ps->semantics_in, &ps->baseShader.reg_maps, semantics_out, &vs->baseShader.reg_maps);
3391 shader_addline(&buffer, "}\n");
3392 } else if(ps_major >= 3 && vs_major < 3) {
3393 shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3394 shader_addline(&buffer, "void order_ps_input() {\n");
3395 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3396 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3397 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3399 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->semantics_in, &ps->baseShader.reg_maps, NULL, NULL);
3400 shader_addline(&buffer, "}\n");
3401 } else {
3402 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3405 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3406 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3407 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3408 checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3409 GL_EXTCALL(glCompileShaderARB(ret));
3410 checkGLcall("glCompileShaderARB(ret)");
3412 shader_buffer_free(&buffer);
3413 return ret;
3416 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3417 GLhandleARB programId, char prefix)
3419 const local_constant *lconst;
3420 GLint tmp_loc;
3421 const float *value;
3422 char glsl_name[8];
3424 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3425 value = (const float *)lconst->value;
3426 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3427 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3428 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3430 checkGLcall("Hardcoding local constants\n");
3433 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3434 * It sets the programId on the current StateBlock (because it should be called
3435 * inside of the DrawPrimitive() part of the render loop).
3437 * If a program for the given combination does not exist, create one, and store
3438 * the program in the hash table. If it creates a program, it will link the
3439 * given objects, too.
3441 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3442 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3443 struct shader_glsl_priv *priv = This->shader_priv;
3444 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3445 IWineD3DPixelShader *pshader = This->stateBlock->pixelShader;
3446 IWineD3DVertexShader *vshader = This->stateBlock->vertexShader;
3447 struct glsl_shader_prog_link *entry = NULL;
3448 GLhandleARB programId = 0;
3449 GLhandleARB reorder_shader_id = 0;
3450 unsigned int i;
3451 char glsl_name[8];
3452 GLhandleARB vshader_id, pshader_id;
3453 struct ps_compile_args ps_compile_args;
3454 struct vs_compile_args vs_compile_args;
3456 if(use_vs) {
3457 find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3458 } else {
3459 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3460 memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3462 if(use_ps) {
3463 find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3464 } else {
3465 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3466 memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3468 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3469 if (entry) {
3470 priv->glsl_program = entry;
3471 return;
3474 /* If we get to this point, then no matching program exists, so we create one */
3475 programId = GL_EXTCALL(glCreateProgramObjectARB());
3476 TRACE("Created new GLSL shader program %u\n", programId);
3478 /* Create the entry */
3479 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3480 entry->programId = programId;
3481 entry->vshader = vshader;
3482 entry->pshader = pshader;
3483 entry->vs_args = vs_compile_args;
3484 entry->ps_args = ps_compile_args;
3485 entry->constant_version = 0;
3486 /* Add the hash table entry */
3487 add_glsl_program_entry(priv, entry);
3489 /* Set the current program */
3490 priv->glsl_program = entry;
3492 if(use_vs) {
3493 vshader_id = find_gl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
3494 } else {
3495 vshader_id = 0;
3498 /* Attach GLSL vshader */
3499 if (vshader_id) {
3500 const unsigned int max_attribs = 16; /* TODO: Will this always be the case? It is at the moment... */
3501 char tmp_name[10];
3503 reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
3504 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
3505 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
3506 checkGLcall("glAttachObjectARB");
3507 /* Flag the reorder function for deletion, then it will be freed automatically when the program
3508 * is destroyed
3510 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
3512 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
3513 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
3514 checkGLcall("glAttachObjectARB");
3516 /* Bind vertex attributes to a corresponding index number to match
3517 * the same index numbers as ARB_vertex_programs (makes loading
3518 * vertex attributes simpler). With this method, we can use the
3519 * exact same code to load the attributes later for both ARB and
3520 * GLSL shaders.
3522 * We have to do this here because we need to know the Program ID
3523 * in order to make the bindings work, and it has to be done prior
3524 * to linking the GLSL program. */
3525 for (i = 0; i < max_attribs; ++i) {
3526 if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
3527 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
3528 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
3531 checkGLcall("glBindAttribLocationARB");
3533 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3536 if(use_ps) {
3537 pshader_id = find_gl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
3538 } else {
3539 pshader_id = 0;
3542 /* Attach GLSL pshader */
3543 if (pshader_id) {
3544 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3545 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3546 checkGLcall("glAttachObjectARB");
3548 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3551 /* Link the program */
3552 TRACE("Linking GLSL shader program %u\n", programId);
3553 GL_EXTCALL(glLinkProgramARB(programId));
3554 print_glsl_info_log(&GLINFO_LOCATION, programId);
3556 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3557 for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3558 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3559 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3561 for (i = 0; i < MAX_CONST_I; ++i) {
3562 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
3563 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3565 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3566 for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3567 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3568 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3570 for (i = 0; i < MAX_CONST_I; ++i) {
3571 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
3572 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3575 if(pshader) {
3576 for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
3577 char name[32];
3578 sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
3579 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3580 sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3581 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3582 sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3583 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3587 if (use_ps && ps_compile_args.np2_fixup) {
3588 char name[32];
3589 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3590 if (ps_compile_args.np2_fixup & (1 << i)) {
3591 sprintf(name, "PsamplerNP2Fixup%u", i);
3592 entry->np2Fixup_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3593 } else {
3594 entry->np2Fixup_location[i] = -1;
3599 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
3600 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3601 checkGLcall("Find glsl program uniform locations");
3603 if (pshader
3604 && WINED3DSHADER_VERSION_MAJOR(((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version) >= 3
3605 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > GL_LIMITS(glsl_varyings) / 4)
3607 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
3608 entry->vertex_color_clamp = GL_FALSE;
3609 } else {
3610 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
3613 /* Set the shader to allow uniform loading on it */
3614 GL_EXTCALL(glUseProgramObjectARB(programId));
3615 checkGLcall("glUseProgramObjectARB(programId)");
3617 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
3618 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
3619 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
3620 * vertex shader with fixed function pixel processing is used we make sure that the card
3621 * supports enough samplers to allow the max number of vertex samplers with all possible
3622 * fixed function fragment processing setups. So once the program is linked these samplers
3623 * won't change.
3625 if(vshader_id) {
3626 /* Load vertex shader samplers */
3627 shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
3629 if(pshader_id) {
3630 /* Load pixel shader samplers */
3631 shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
3634 /* If the local constants do not have to be loaded with the environment constants,
3635 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
3636 * later
3638 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
3639 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
3641 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
3642 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
3646 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
3648 GLhandleARB program_id;
3649 GLhandleARB vshader_id, pshader_id;
3650 static const char *blt_vshader[] =
3652 "#version 120\n"
3653 "void main(void)\n"
3654 "{\n"
3655 " gl_Position = gl_Vertex;\n"
3656 " gl_FrontColor = vec4(1.0);\n"
3657 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
3658 "}\n"
3661 static const char *blt_pshaders[tex_type_count] =
3663 /* tex_1d */
3664 NULL,
3665 /* tex_2d */
3666 "#version 120\n"
3667 "uniform sampler2D sampler;\n"
3668 "void main(void)\n"
3669 "{\n"
3670 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3671 "}\n",
3672 /* tex_3d */
3673 NULL,
3674 /* tex_cube */
3675 "#version 120\n"
3676 "uniform samplerCube sampler;\n"
3677 "void main(void)\n"
3678 "{\n"
3679 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
3680 "}\n",
3681 /* tex_rect */
3682 "#version 120\n"
3683 "#extension GL_ARB_texture_rectangle : enable\n"
3684 "uniform sampler2DRect sampler;\n"
3685 "void main(void)\n"
3686 "{\n"
3687 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
3688 "}\n",
3691 if (!blt_pshaders[tex_type])
3693 FIXME("tex_type %#x not supported\n", tex_type);
3694 tex_type = tex_2d;
3697 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3698 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3699 GL_EXTCALL(glCompileShaderARB(vshader_id));
3701 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3702 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
3703 GL_EXTCALL(glCompileShaderARB(pshader_id));
3705 program_id = GL_EXTCALL(glCreateProgramObjectARB());
3706 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3707 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3708 GL_EXTCALL(glLinkProgramARB(program_id));
3710 print_glsl_info_log(&GLINFO_LOCATION, program_id);
3712 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
3713 * is destroyed
3715 GL_EXTCALL(glDeleteObjectARB(vshader_id));
3716 GL_EXTCALL(glDeleteObjectARB(pshader_id));
3717 return program_id;
3720 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3721 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3722 struct shader_glsl_priv *priv = This->shader_priv;
3723 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3724 GLhandleARB program_id = 0;
3725 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
3727 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3729 if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3730 else priv->glsl_program = NULL;
3732 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3734 if (old_vertex_color_clamp != current_vertex_color_clamp) {
3735 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
3736 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
3737 checkGLcall("glClampColorARB");
3738 } else {
3739 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
3743 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3744 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3745 GL_EXTCALL(glUseProgramObjectARB(program_id));
3746 checkGLcall("glUseProgramObjectARB");
3749 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
3750 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3751 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3752 struct shader_glsl_priv *priv = This->shader_priv;
3753 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
3755 if (!*blt_program) {
3756 GLint loc;
3757 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
3758 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
3759 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3760 GL_EXTCALL(glUniform1iARB(loc, 0));
3761 } else {
3762 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3766 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
3767 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3768 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3769 struct shader_glsl_priv *priv = This->shader_priv;
3770 GLhandleARB program_id;
3772 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3773 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3775 GL_EXTCALL(glUseProgramObjectARB(program_id));
3776 checkGLcall("glUseProgramObjectARB");
3779 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
3780 const struct list *linked_programs;
3781 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
3782 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3783 struct shader_glsl_priv *priv = device->shader_priv;
3784 const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
3785 IWineD3DPixelShaderImpl *ps = NULL;
3786 IWineD3DVertexShaderImpl *vs = NULL;
3788 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
3789 * can be called from IWineD3DBaseShader::Release
3791 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
3793 if(pshader) {
3794 ps = (IWineD3DPixelShaderImpl *) This;
3795 if(ps->num_gl_shaders == 0) return;
3796 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
3797 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3798 } else {
3799 vs = (IWineD3DVertexShaderImpl *) This;
3800 if(vs->num_gl_shaders == 0) return;
3801 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
3802 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3805 linked_programs = &This->baseShader.linked_programs;
3807 TRACE("Deleting linked programs\n");
3808 if (linked_programs->next) {
3809 struct glsl_shader_prog_link *entry, *entry2;
3811 if(pshader) {
3812 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
3813 delete_glsl_program_entry(priv, gl_info, entry);
3815 } else {
3816 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
3817 delete_glsl_program_entry(priv, gl_info, entry);
3822 if(pshader) {
3823 UINT i;
3825 ENTER_GL();
3826 for(i = 0; i < ps->num_gl_shaders; i++) {
3827 TRACE("deleting pshader %u\n", ps->gl_shaders[i].prgId);
3828 GL_EXTCALL(glDeleteObjectARB(ps->gl_shaders[i].prgId));
3829 checkGLcall("glDeleteObjectARB");
3831 LEAVE_GL();
3832 HeapFree(GetProcessHeap(), 0, ps->gl_shaders);
3833 ps->gl_shaders = NULL;
3834 ps->num_gl_shaders = 0;
3835 ps->shader_array_size = 0;
3836 } else {
3837 UINT i;
3839 ENTER_GL();
3840 for(i = 0; i < vs->num_gl_shaders; i++) {
3841 TRACE("deleting vshader %u\n", vs->gl_shaders[i].prgId);
3842 GL_EXTCALL(glDeleteObjectARB(vs->gl_shaders[i].prgId));
3843 checkGLcall("glDeleteObjectARB");
3845 LEAVE_GL();
3846 HeapFree(GetProcessHeap(), 0, vs->gl_shaders);
3847 vs->gl_shaders = NULL;
3848 vs->num_gl_shaders = 0;
3849 vs->shader_array_size = 0;
3853 static unsigned int glsl_program_key_hash(const void *key)
3855 const glsl_program_key_t *k = key;
3857 unsigned int hash = ((DWORD_PTR) k->vshader) | ((DWORD_PTR) k->pshader) << 16;
3858 hash += ~(hash << 15);
3859 hash ^= (hash >> 10);
3860 hash += (hash << 3);
3861 hash ^= (hash >> 6);
3862 hash += ~(hash << 11);
3863 hash ^= (hash >> 16);
3865 return hash;
3868 static BOOL glsl_program_key_compare(const void *keya, const void *keyb)
3870 const glsl_program_key_t *ka = keya;
3871 const glsl_program_key_t *kb = keyb;
3873 return ka->vshader == kb->vshader && ka->pshader == kb->pshader &&
3874 (memcmp(&ka->ps_args, &kb->ps_args, sizeof(kb->ps_args)) == 0) &&
3875 (memcmp(&ka->vs_args, &kb->vs_args, sizeof(kb->vs_args)) == 0);
3878 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
3880 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
3881 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
3883 if (!mem)
3885 ERR("Failed to allocate memory\n");
3886 return FALSE;
3889 heap->entries = mem;
3890 heap->entries[1].version = 0;
3891 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
3892 heap->size = 1;
3894 return TRUE;
3897 static void constant_heap_free(struct constant_heap *heap)
3899 HeapFree(GetProcessHeap(), 0, heap->entries);
3902 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
3903 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3904 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3905 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
3906 SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
3908 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
3909 if (!priv->stack)
3911 ERR("Failed to allocate memory.\n");
3912 HeapFree(GetProcessHeap(), 0, priv);
3913 return E_OUTOFMEMORY;
3916 if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
3918 ERR("Failed to initialize vertex shader constant heap\n");
3919 HeapFree(GetProcessHeap(), 0, priv->stack);
3920 HeapFree(GetProcessHeap(), 0, priv);
3921 return E_OUTOFMEMORY;
3924 if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
3926 ERR("Failed to initialize pixel shader constant heap\n");
3927 constant_heap_free(&priv->vconst_heap);
3928 HeapFree(GetProcessHeap(), 0, priv->stack);
3929 HeapFree(GetProcessHeap(), 0, priv);
3930 return E_OUTOFMEMORY;
3933 priv->glsl_program_lookup = hash_table_create(glsl_program_key_hash, glsl_program_key_compare);
3934 priv->next_constant_version = 1;
3936 This->shader_priv = priv;
3937 return WINED3D_OK;
3940 static void shader_glsl_free(IWineD3DDevice *iface) {
3941 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3942 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3943 struct shader_glsl_priv *priv = This->shader_priv;
3944 int i;
3946 for (i = 0; i < tex_type_count; ++i)
3948 if (priv->depth_blt_program[i])
3950 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
3954 hash_table_destroy(priv->glsl_program_lookup, NULL, NULL);
3955 constant_heap_free(&priv->pconst_heap);
3956 constant_heap_free(&priv->vconst_heap);
3958 HeapFree(GetProcessHeap(), 0, This->shader_priv);
3959 This->shader_priv = NULL;
3962 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
3963 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
3964 return FALSE;
3967 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer, const struct ps_compile_args *args) {
3968 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3969 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3970 CONST DWORD *function = This->baseShader.function;
3971 const char *fragcolor;
3972 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3974 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3975 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3977 shader_addline(buffer, "#version 120\n");
3979 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
3980 shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
3982 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3983 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3984 * drivers write a warning if we don't do so
3986 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3989 /* Base Declarations */
3990 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
3992 /* Pack 3.0 inputs */
3993 if (reg_maps->shader_version >= WINED3DPS_VERSION(3,0) && args->vp_mode != vertexshader) {
3994 pshader_glsl_input_pack(iface, buffer, This->semantics_in, reg_maps, args->vp_mode);
3997 /* Base Shader Body */
3998 shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
4000 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4001 if (reg_maps->shader_version < WINED3DPS_VERSION(2,0))
4003 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4004 if(GL_SUPPORT(ARB_DRAW_BUFFERS))
4005 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4006 else
4007 shader_addline(buffer, "gl_FragColor = R0;\n");
4010 if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
4011 fragcolor = "gl_FragData[0]";
4012 } else {
4013 fragcolor = "gl_FragColor";
4015 if(args->srgb_correction) {
4016 shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
4017 fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
4018 srgb_sub_high, srgb_sub_high, srgb_sub_high);
4019 shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
4020 shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
4021 shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
4022 shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
4023 shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
4025 /* Pixel shader < 3.0 do not replace the fog stage.
4026 * This implements linear fog computation and blending.
4027 * TODO: non linear fog
4028 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4029 * -1/(e-s) and e/(e-s) respectively.
4031 if(reg_maps->shader_version < WINED3DPS_VERSION(3,0)) {
4032 switch(args->fog) {
4033 case FOG_OFF: break;
4034 case FOG_LINEAR:
4035 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4036 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4037 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4038 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4039 break;
4040 case FOG_EXP:
4041 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4042 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4043 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4044 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4045 break;
4046 case FOG_EXP2:
4047 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4048 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4049 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4050 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4051 break;
4055 shader_addline(buffer, "}\n");
4057 TRACE("Compiling shader object %u\n", shader_obj);
4058 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4059 GL_EXTCALL(glCompileShaderARB(shader_obj));
4060 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4062 /* Store the shader object */
4063 return shader_obj;
4066 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer, const struct vs_compile_args *args) {
4067 IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
4068 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4069 CONST DWORD *function = This->baseShader.function;
4070 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
4072 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4073 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4075 shader_addline(buffer, "#version 120\n");
4077 /* Base Declarations */
4078 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
4080 /* Base Shader Body */
4081 shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
4083 /* Unpack 3.0 outputs */
4084 if (reg_maps->shader_version >= WINED3DVS_VERSION(3,0)) shader_addline(buffer, "order_ps_input(OUT);\n");
4085 else shader_addline(buffer, "order_ps_input();\n");
4087 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4088 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4089 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4090 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4092 if(args->fog_src == VS_FOG_Z) {
4093 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4094 } else if (!reg_maps->fog) {
4095 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4098 /* Write the final position.
4100 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4101 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4102 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4103 * contains 1.0 to allow a mad.
4105 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4106 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4108 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4110 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4111 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4112 * which is the same as z = z * 2 - w.
4114 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4116 shader_addline(buffer, "}\n");
4118 TRACE("Compiling shader object %u\n", shader_obj);
4119 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4120 GL_EXTCALL(glCompileShaderARB(shader_obj));
4121 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4123 return shader_obj;
4126 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4128 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4129 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4130 * vs_nv_version which is based on NV_vertex_program.
4131 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4132 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4133 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4134 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4136 if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4137 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4138 else
4139 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4140 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4141 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix) */
4142 pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF) - (MAX_CONST_B / 4) - MAX_CONST_I - 1;
4144 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4145 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4146 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4147 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4148 * in max native instructions. Intel and others also offer the info in this extension but they
4149 * don't support GLSL (at least on Windows).
4151 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4152 * of instructions is 512 or less we have to do with ps2.0 hardware.
4153 * 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.
4155 if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4156 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4157 else
4158 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4160 /* Subtract the other potential uniforms from the max available (bools & ints), and 2 states for fog.
4161 * In theory the texbem instruction may need one more shader constant too. But lets assume
4162 * that a sm <= 1.3 shader does not need all the uniforms provided by a glsl-capable card,
4163 * and lets not take away a uniform needlessly from all other shaders.
4165 pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF) - (MAX_CONST_B / 4) - MAX_CONST_I - 2;
4167 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4168 * Direct3D minimum requirement.
4170 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4171 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4173 * The problem is that the refrast clamps temporary results in the shader to
4174 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4175 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4176 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4177 * offer a way to query this.
4179 pCaps->PixelShader1xMaxValue = 8.0;
4180 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4183 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4185 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4187 TRACE("Checking support for fixup:\n");
4188 dump_color_fixup_desc(fixup);
4191 /* We support everything except YUV conversions. */
4192 if (!is_yuv_fixup(fixup))
4194 TRACE("[OK]\n");
4195 return TRUE;
4198 TRACE("[FAILED]\n");
4199 return FALSE;
4202 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4204 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4205 /* WINED3DSIH_ADD */ shader_glsl_arith,
4206 /* WINED3DSIH_BEM */ pshader_glsl_bem,
4207 /* WINED3DSIH_BREAK */ shader_glsl_break,
4208 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4209 /* WINED3DSIH_BREAKP */ NULL,
4210 /* WINED3DSIH_CALL */ shader_glsl_call,
4211 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4212 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4213 /* WINED3DSIH_CND */ shader_glsl_cnd,
4214 /* WINED3DSIH_CRS */ shader_glsl_cross,
4215 /* WINED3DSIH_DCL */ NULL,
4216 /* WINED3DSIH_DEF */ NULL,
4217 /* WINED3DSIH_DEFB */ NULL,
4218 /* WINED3DSIH_DEFI */ NULL,
4219 /* WINED3DSIH_DP2ADD */ pshader_glsl_dp2add,
4220 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4221 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4222 /* WINED3DSIH_DST */ shader_glsl_dst,
4223 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4224 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4225 /* WINED3DSIH_ELSE */ shader_glsl_else,
4226 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4227 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4228 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4229 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4230 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4231 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4232 /* WINED3DSIH_IF */ shader_glsl_if,
4233 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4234 /* WINED3DSIH_LABEL */ shader_glsl_label,
4235 /* WINED3DSIH_LIT */ shader_glsl_lit,
4236 /* WINED3DSIH_LOG */ shader_glsl_log,
4237 /* WINED3DSIH_LOGP */ shader_glsl_log,
4238 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4239 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4240 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4241 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4242 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4243 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4244 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4245 /* WINED3DSIH_MAD */ shader_glsl_mad,
4246 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4247 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4248 /* WINED3DSIH_MOV */ shader_glsl_mov,
4249 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4250 /* WINED3DSIH_MUL */ shader_glsl_arith,
4251 /* WINED3DSIH_NOP */ NULL,
4252 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4253 /* WINED3DSIH_PHASE */ NULL,
4254 /* WINED3DSIH_POW */ shader_glsl_pow,
4255 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4256 /* WINED3DSIH_REP */ shader_glsl_rep,
4257 /* WINED3DSIH_RET */ NULL,
4258 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4259 /* WINED3DSIH_SETP */ NULL,
4260 /* WINED3DSIH_SGE */ shader_glsl_compare,
4261 /* WINED3DSIH_SGN */ shader_glsl_map2gl,
4262 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4263 /* WINED3DSIH_SLT */ shader_glsl_compare,
4264 /* WINED3DSIH_SUB */ shader_glsl_arith,
4265 /* WINED3DSIH_TEX */ pshader_glsl_tex,
4266 /* WINED3DSIH_TEXBEM */ pshader_glsl_texbem,
4267 /* WINED3DSIH_TEXBEML */ pshader_glsl_texbem,
4268 /* WINED3DSIH_TEXCOORD */ pshader_glsl_texcoord,
4269 /* WINED3DSIH_TEXDEPTH */ pshader_glsl_texdepth,
4270 /* WINED3DSIH_TEXDP3 */ pshader_glsl_texdp3,
4271 /* WINED3DSIH_TEXDP3TEX */ pshader_glsl_texdp3tex,
4272 /* WINED3DSIH_TEXKILL */ pshader_glsl_texkill,
4273 /* WINED3DSIH_TEXLDD */ NULL,
4274 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4275 /* WINED3DSIH_TEXM3x2DEPTH */ pshader_glsl_texm3x2depth,
4276 /* WINED3DSIH_TEXM3x2PAD */ pshader_glsl_texm3x2pad,
4277 /* WINED3DSIH_TEXM3x2TEX */ pshader_glsl_texm3x2tex,
4278 /* WINED3DSIH_TEXM3x3 */ pshader_glsl_texm3x3,
4279 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4280 /* WINED3DSIH_TEXM3x3PAD */ pshader_glsl_texm3x3pad,
4281 /* WINED3DSIH_TEXM3x3SPEC */ pshader_glsl_texm3x3spec,
4282 /* WINED3DSIH_TEXM3x3TEX */ pshader_glsl_texm3x3tex,
4283 /* WINED3DSIH_TEXM3x3VSPEC */ pshader_glsl_texm3x3vspec,
4284 /* WINED3DSIH_TEXREG2AR */ pshader_glsl_texreg2ar,
4285 /* WINED3DSIH_TEXREG2GB */ pshader_glsl_texreg2gb,
4286 /* WINED3DSIH_TEXREG2RGB */ pshader_glsl_texreg2rgb,
4289 const shader_backend_t glsl_shader_backend = {
4290 shader_glsl_instruction_handler_table,
4291 shader_glsl_select,
4292 shader_glsl_select_depth_blt,
4293 shader_glsl_deselect_depth_blt,
4294 shader_glsl_update_float_vertex_constants,
4295 shader_glsl_update_float_pixel_constants,
4296 shader_glsl_load_constants,
4297 shader_glsl_load_np2fixup_constants,
4298 shader_glsl_destroy,
4299 shader_glsl_alloc,
4300 shader_glsl_free,
4301 shader_glsl_dirty_const,
4302 shader_glsl_generate_pshader,
4303 shader_glsl_generate_vshader,
4304 shader_glsl_get_caps,
4305 shader_glsl_color_fixup_supported,