wined3d: Emulate the 4 component address register in ARB.
[wine/hacks.git] / dlls / wined3d / glsl_shader.c
blobc978e5b0c5a3e5db82dcaaf34ca39aae06c8b1b4
1 /*
2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * D3D shader asm has swizzles on source parameters, and write masks for
26 * destination parameters. GLSL uses swizzles for both. The result of this is
27 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29 * mask for the destination parameter into account.
32 #include "config.h"
33 #include <limits.h>
34 #include <stdio.h>
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
42 #define GLINFO_LOCATION (*gl_info)
44 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
45 #define WINED3D_GLSL_SAMPLE_RECT 0x2
46 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
49 typedef struct {
50 char reg_name[150];
51 char mask_str[6];
52 } glsl_dst_param_t;
54 typedef struct {
55 char reg_name[150];
56 char param_str[200];
57 } glsl_src_param_t;
59 typedef struct {
60 const char *name;
61 DWORD coord_mask;
62 } glsl_sample_function_t;
64 enum heap_node_op
66 HEAP_NODE_TRAVERSE_LEFT,
67 HEAP_NODE_TRAVERSE_RIGHT,
68 HEAP_NODE_POP,
71 struct constant_entry
73 unsigned int idx;
74 unsigned int version;
77 struct constant_heap
79 struct constant_entry *entries;
80 unsigned int *positions;
81 unsigned int size;
84 /* GLSL shader private data */
85 struct shader_glsl_priv {
86 struct hash_table_t *glsl_program_lookup;
87 struct glsl_shader_prog_link *glsl_program;
88 struct constant_heap vconst_heap;
89 struct constant_heap pconst_heap;
90 unsigned char *stack;
91 GLhandleARB depth_blt_program[tex_type_count];
92 UINT next_constant_version;
95 /* Struct to maintain data about a linked GLSL program */
96 struct glsl_shader_prog_link {
97 struct list vshader_entry;
98 struct list pshader_entry;
99 GLhandleARB programId;
100 GLint *vuniformF_locations;
101 GLint *puniformF_locations;
102 GLint vuniformI_locations[MAX_CONST_I];
103 GLint puniformI_locations[MAX_CONST_I];
104 GLint posFixup_location;
105 GLint np2Fixup_location[MAX_FRAGMENT_SAMPLERS];
106 GLint bumpenvmat_location[MAX_TEXTURES];
107 GLint luminancescale_location[MAX_TEXTURES];
108 GLint luminanceoffset_location[MAX_TEXTURES];
109 GLint ycorrection_location;
110 GLenum vertex_color_clamp;
111 IWineD3DVertexShader *vshader;
112 IWineD3DPixelShader *pshader;
113 struct vs_compile_args vs_args;
114 struct ps_compile_args ps_args;
115 UINT constant_version;
118 typedef struct {
119 IWineD3DVertexShader *vshader;
120 IWineD3DPixelShader *pshader;
121 struct ps_compile_args ps_args;
122 struct vs_compile_args vs_args;
123 } glsl_program_key_t;
126 /** Prints the GLSL info log which will contain error messages if they exist */
127 /* GL locking is done by the caller */
128 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
130 int infologLength = 0;
131 char *infoLog;
132 unsigned int i;
133 BOOL is_spam;
135 static const char * const spam[] =
137 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
138 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx */
139 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
140 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
141 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
142 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
143 "Fragment shader was successfully compiled to run on hardware.\n"
144 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
145 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
146 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
147 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n" /* MacOS ati */
150 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
152 GL_EXTCALL(glGetObjectParameterivARB(obj,
153 GL_OBJECT_INFO_LOG_LENGTH_ARB,
154 &infologLength));
156 /* A size of 1 is just a null-terminated string, so the log should be bigger than
157 * that if there are errors. */
158 if (infologLength > 1)
160 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
161 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
163 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
164 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
165 is_spam = FALSE;
167 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
168 if(strcmp(infoLog, spam[i]) == 0) {
169 is_spam = TRUE;
170 break;
173 if(is_spam) {
174 TRACE("Spam received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
175 } else {
176 FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
178 HeapFree(GetProcessHeap(), 0, infoLog);
183 * Loads (pixel shader) samplers
185 /* GL locking is done by the caller */
186 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
188 GLint name_loc;
189 int i;
190 char sampler_name[20];
192 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
193 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
194 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
195 if (name_loc != -1) {
196 DWORD mapped_unit = tex_unit_map[i];
197 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(fragment_samplers))
199 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
200 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
201 checkGLcall("glUniform1iARB");
202 } else {
203 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
209 /* GL locking is done by the caller */
210 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
212 GLint name_loc;
213 char sampler_name[20];
214 int i;
216 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
217 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
218 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
219 if (name_loc != -1) {
220 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
221 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(combined_samplers))
223 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
224 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
225 checkGLcall("glUniform1iARB");
226 } else {
227 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
233 /* GL locking is done by the caller */
234 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
235 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
237 int stack_idx = 0;
238 unsigned int heap_idx = 1;
239 unsigned int idx;
241 if (heap->entries[heap_idx].version <= version) return;
243 idx = heap->entries[heap_idx].idx;
244 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
245 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
247 while (stack_idx >= 0)
249 /* Note that we fall through to the next case statement. */
250 switch(stack[stack_idx])
252 case HEAP_NODE_TRAVERSE_LEFT:
254 unsigned int left_idx = heap_idx << 1;
255 if (left_idx < heap->size && heap->entries[left_idx].version > version)
257 heap_idx = left_idx;
258 idx = heap->entries[heap_idx].idx;
259 if (constant_locations[idx] != -1)
260 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
262 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
263 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
264 break;
268 case HEAP_NODE_TRAVERSE_RIGHT:
270 unsigned int right_idx = (heap_idx << 1) + 1;
271 if (right_idx < heap->size && heap->entries[right_idx].version > version)
273 heap_idx = right_idx;
274 idx = heap->entries[heap_idx].idx;
275 if (constant_locations[idx] != -1)
276 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
278 stack[stack_idx++] = HEAP_NODE_POP;
279 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
280 break;
284 case HEAP_NODE_POP:
286 heap_idx >>= 1;
287 --stack_idx;
288 break;
292 checkGLcall("walk_constant_heap()");
295 /* GL locking is done by the caller */
296 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
298 GLfloat clamped_constant[4];
300 if (location == -1) return;
302 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
303 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
304 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
305 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
307 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
310 /* GL locking is done by the caller */
311 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
312 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
314 int stack_idx = 0;
315 unsigned int heap_idx = 1;
316 unsigned int idx;
318 if (heap->entries[heap_idx].version <= version) return;
320 idx = heap->entries[heap_idx].idx;
321 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
322 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
324 while (stack_idx >= 0)
326 /* Note that we fall through to the next case statement. */
327 switch(stack[stack_idx])
329 case HEAP_NODE_TRAVERSE_LEFT:
331 unsigned int left_idx = heap_idx << 1;
332 if (left_idx < heap->size && heap->entries[left_idx].version > version)
334 heap_idx = left_idx;
335 idx = heap->entries[heap_idx].idx;
336 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
338 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
339 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
340 break;
344 case HEAP_NODE_TRAVERSE_RIGHT:
346 unsigned int right_idx = (heap_idx << 1) + 1;
347 if (right_idx < heap->size && heap->entries[right_idx].version > version)
349 heap_idx = right_idx;
350 idx = heap->entries[heap_idx].idx;
351 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
353 stack[stack_idx++] = HEAP_NODE_POP;
354 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
355 break;
359 case HEAP_NODE_POP:
361 heap_idx >>= 1;
362 --stack_idx;
363 break;
367 checkGLcall("walk_constant_heap_clamped()");
370 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
371 /* GL locking is done by the caller */
372 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
373 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
374 unsigned char *stack, UINT version)
376 const local_constant *lconst;
378 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
379 if (This->baseShader.reg_maps.shader_version.major == 1
380 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
381 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
382 else
383 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
385 if (!This->baseShader.load_local_constsF)
387 TRACE("No need to load local float constants for this shader\n");
388 return;
391 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
392 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
394 GLint location = constant_locations[lconst->idx];
395 /* We found this uniform name in the program - go ahead and send the data */
396 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
398 checkGLcall("glUniform4fvARB()");
401 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
402 /* GL locking is done by the caller */
403 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
404 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
406 unsigned int i;
407 struct list* ptr;
409 for (i = 0; constants_set; constants_set >>= 1, ++i)
411 if (!(constants_set & 1)) continue;
413 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
414 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
416 /* We found this uniform name in the program - go ahead and send the data */
417 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
418 checkGLcall("glUniform4ivARB");
421 /* Load immediate constants */
422 ptr = list_head(&This->baseShader.constantsI);
423 while (ptr) {
424 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
425 unsigned int idx = lconst->idx;
426 const GLint *values = (const GLint *)lconst->value;
428 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
429 values[0], values[1], values[2], values[3]);
431 /* We found this uniform name in the program - go ahead and send the data */
432 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
433 checkGLcall("glUniform4ivARB");
434 ptr = list_next(&This->baseShader.constantsI, ptr);
438 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
439 /* GL locking is done by the caller */
440 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
441 GLhandleARB programId, const BOOL *constants, WORD constants_set)
443 GLint tmp_loc;
444 unsigned int i;
445 char tmp_name[8];
446 char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
447 const char* prefix = is_pshader? "PB":"VB";
448 struct list* ptr;
450 /* TODO: Benchmark and see if it would be beneficial to store the
451 * locations of the constants to avoid looking up each time */
452 for (i = 0; constants_set; constants_set >>= 1, ++i)
454 if (!(constants_set & 1)) continue;
456 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
458 /* TODO: Benchmark and see if it would be beneficial to store the
459 * locations of the constants to avoid looking up each time */
460 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
461 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
462 if (tmp_loc != -1)
464 /* We found this uniform name in the program - go ahead and send the data */
465 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
466 checkGLcall("glUniform1ivARB");
470 /* Load immediate constants */
471 ptr = list_head(&This->baseShader.constantsB);
472 while (ptr) {
473 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
474 unsigned int idx = lconst->idx;
475 const GLint *values = (const GLint *)lconst->value;
477 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
479 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
480 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
481 if (tmp_loc != -1) {
482 /* We found this uniform name in the program - go ahead and send the data */
483 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
484 checkGLcall("glUniform1ivARB");
486 ptr = list_next(&This->baseShader.constantsB, ptr);
490 static void reset_program_constant_version(void *value, void *context)
492 struct glsl_shader_prog_link *entry = value;
493 entry->constant_version = 0;
497 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
499 /* GL locking is done by the caller (state handler) */
500 static void shader_glsl_load_np2fixup_constants(
501 IWineD3DDevice* device,
502 char usePixelShader,
503 char useVertexShader) {
505 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
506 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
508 if (!prog) {
509 /* No GLSL program set - nothing to do. */
510 return;
513 if (!usePixelShader) {
514 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
515 return;
518 if (prog->ps_args.np2_fixup) {
519 UINT i;
520 UINT fixup = prog->ps_args.np2_fixup;
521 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
522 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
524 for (i = 0; fixup; fixup >>= 1, ++i) {
525 if (-1 != prog->np2Fixup_location[i]) {
526 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
527 if (!tex) {
528 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
529 continue;
530 } else {
531 const float tex_dim[2] = {tex->baseTexture.pow2Matrix[0], tex->baseTexture.pow2Matrix[5]};
532 GL_EXTCALL(glUniform2fvARB(prog->np2Fixup_location[i], 1, tex_dim));
540 * Loads the app-supplied constants into the currently set GLSL program.
542 /* GL locking is done by the caller (state handler) */
543 static void shader_glsl_load_constants(
544 IWineD3DDevice* device,
545 char usePixelShader,
546 char useVertexShader) {
548 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
549 struct shader_glsl_priv *priv = deviceImpl->shader_priv;
550 IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
551 const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
553 GLhandleARB programId;
554 struct glsl_shader_prog_link *prog = priv->glsl_program;
555 UINT constant_version;
556 int i;
558 if (!prog) {
559 /* No GLSL program set - nothing to do. */
560 return;
562 programId = prog->programId;
563 constant_version = prog->constant_version;
565 if (useVertexShader) {
566 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
568 /* Load DirectX 9 float constants/uniforms for vertex shader */
569 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
570 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
572 /* Load DirectX 9 integer constants/uniforms for vertex shader */
573 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
574 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
576 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
577 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
578 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
580 /* Upload the position fixup params */
581 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
582 checkGLcall("glUniform4fvARB");
585 if (usePixelShader) {
587 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
589 /* Load DirectX 9 float constants/uniforms for pixel shader */
590 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
591 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
593 /* Load DirectX 9 integer constants/uniforms for pixel shader */
594 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
595 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
597 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
598 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
599 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
601 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
602 * It can't be 0 for a valid texbem instruction.
604 for(i = 0; i < ((IWineD3DPixelShaderImpl *) pshader)->numbumpenvmatconsts; i++) {
605 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pshader;
606 int stage = ps->luminanceconst[i].texunit;
608 const float *data = (const float *)&stateBlock->textureState[(int)ps->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
609 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
610 checkGLcall("glUniformMatrix2fvARB");
612 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
613 * is set too, so we can check that in the needsbumpmat check
615 if(ps->baseShader.reg_maps.luminanceparams[stage]) {
616 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
617 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
619 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
620 checkGLcall("glUniform1fvARB");
621 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
622 checkGLcall("glUniform1fvARB");
626 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
627 float correction_params[4];
628 if(deviceImpl->render_offscreen) {
629 correction_params[0] = 0.0;
630 correction_params[1] = 1.0;
631 } else {
632 /* position is window relative, not viewport relative */
633 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
634 correction_params[1] = -1.0;
636 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
640 if (priv->next_constant_version == UINT_MAX)
642 TRACE("Max constant version reached, resetting to 0.\n");
643 hash_table_for_each_entry(priv->glsl_program_lookup, reset_program_constant_version, NULL);
644 priv->next_constant_version = 1;
646 else
648 prog->constant_version = priv->next_constant_version++;
652 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
653 unsigned int heap_idx, DWORD new_version)
655 struct constant_entry *entries = heap->entries;
656 unsigned int *positions = heap->positions;
657 unsigned int parent_idx;
659 while (heap_idx > 1)
661 parent_idx = heap_idx >> 1;
663 if (new_version <= entries[parent_idx].version) break;
665 entries[heap_idx] = entries[parent_idx];
666 positions[entries[parent_idx].idx] = heap_idx;
667 heap_idx = parent_idx;
670 entries[heap_idx].version = new_version;
671 entries[heap_idx].idx = idx;
672 positions[idx] = heap_idx;
675 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
677 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
678 struct shader_glsl_priv *priv = This->shader_priv;
679 struct constant_heap *heap = &priv->vconst_heap;
680 UINT i;
682 for (i = start; i < count + start; ++i)
684 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
685 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
686 else
687 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
691 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
693 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
694 struct shader_glsl_priv *priv = This->shader_priv;
695 struct constant_heap *heap = &priv->pconst_heap;
696 UINT i;
698 for (i = start; i < count + start; ++i)
700 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
701 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
702 else
703 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
707 static int vec4_varyings(DWORD shader_major, const WineD3D_GL_Info *gl_info)
709 int ret = GL_LIMITS(glsl_varyings) / 4;
710 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
711 if(shader_major > 3) return ret;
713 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
714 if(gl_info->glsl_clip_varying) ret -= 1;
715 return ret;
718 /** Generate the variable & register declarations for the GLSL output target */
719 static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
720 SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info,
721 const struct ps_compile_args *ps_args)
723 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
724 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
725 unsigned int i, extra_constants_needed = 0;
726 const local_constant *lconst;
728 /* There are some minor differences between pixel and vertex shaders */
729 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
730 char prefix = pshader ? 'P' : 'V';
732 /* Prototype the subroutines */
733 for (i = 0; i < This->baseShader.limits.label; i++) {
734 if (reg_maps->labels[i])
735 shader_addline(buffer, "void subroutine%u();\n", i);
738 /* Declare the constants (aka uniforms) */
739 if (This->baseShader.limits.constant_float > 0) {
740 unsigned max_constantsF;
741 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
742 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
743 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
744 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
745 * a dx9 card, as long as it doesn't also use all the other constants.
747 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
748 * declare only the amount that we're assured to have.
750 * Thus we run into problems in these two cases:
751 * 1) The shader really uses more uniforms than supported
752 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
754 if(pshader) {
755 /* No indirect addressing here */
756 max_constantsF = GL_LIMITS(pshader_constantsF);
757 } else {
758 if(This->baseShader.reg_maps.usesrelconstF) {
759 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
760 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
761 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
762 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
764 * Writing gl_ClipPos requires one uniform for each clipplane as well.
766 max_constantsF = GL_LIMITS(vshader_constantsF) - 3 - GL_LIMITS(clipplanes);
767 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
768 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
769 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
770 * for now take this into account when calculating the number of available constants
772 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
773 /* Set by driver quirks in directx.c */
774 max_constantsF -= GLINFO_LOCATION.reserved_glsl_constants;
775 } else {
776 max_constantsF = GL_LIMITS(vshader_constantsF);
779 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
780 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
783 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
784 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
786 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
787 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
789 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
790 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
792 if(!pshader) {
793 shader_addline(buffer, "uniform vec4 posFixup;\n");
794 /* Predeclaration; This function is added at link time based on the pixel shader.
795 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
796 * that. We know the input to the reorder function at vertex shader compile time, so
797 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
798 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
799 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
800 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
801 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
802 * inout.
804 if (reg_maps->shader_version.major >= 3)
806 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
807 } else {
808 shader_addline(buffer, "void order_ps_input();\n");
810 } else {
811 IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
813 ps_impl->numbumpenvmatconsts = 0;
814 for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
815 if(!reg_maps->bumpmat[i]) {
816 continue;
819 ps_impl->bumpenvmatconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
820 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
822 if(reg_maps->luminanceparams) {
823 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
824 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
825 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
826 extra_constants_needed++;
827 } else {
828 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = -1;
831 extra_constants_needed++;
832 ps_impl->numbumpenvmatconsts++;
835 if(ps_args->srgb_correction) {
836 shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
837 srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
838 shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
839 srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
841 if(reg_maps->vpos || reg_maps->usesdsy) {
842 if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
843 shader_addline(buffer, "uniform vec4 ycorrection;\n");
844 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
845 extra_constants_needed++;
846 } else {
847 /* This happens because we do not have proper tracking of the constant registers that are
848 * actually used, only the max limit of the shader version
850 FIXME("Cannot find a free uniform for vpos correction params\n");
851 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
852 device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
853 device->render_offscreen ? 1.0 : -1.0);
855 shader_addline(buffer, "vec4 vpos;\n");
859 /* Declare texture samplers */
860 for (i = 0; i < This->baseShader.limits.sampler; i++) {
861 if (reg_maps->sampler_type[i])
863 switch (reg_maps->sampler_type[i])
865 case WINED3DSTT_1D:
866 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
867 break;
868 case WINED3DSTT_2D:
869 if(device->stateBlock->textures[i] &&
870 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
871 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
872 } else {
873 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
876 if (pshader && ps_args->np2_fixup & (1 << i))
878 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
879 * while D3D has them in the (normalized) [0,1]x[0,1] range.
880 * samplerNP2Fixup stores texture dimensions and is updated through
881 * shader_glsl_load_np2fixup_constants when the sampler changes. */
882 shader_addline(buffer, "uniform vec2 %csamplerNP2Fixup%u;\n", prefix, i);
884 break;
885 case WINED3DSTT_CUBE:
886 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
887 break;
888 case WINED3DSTT_VOLUME:
889 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
890 break;
891 default:
892 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
893 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
894 break;
899 /* Declare address variables */
900 for (i = 0; i < This->baseShader.limits.address; i++) {
901 if (reg_maps->address[i])
902 shader_addline(buffer, "ivec4 A%d;\n", i);
905 /* Declare texture coordinate temporaries and initialize them */
906 for (i = 0; i < This->baseShader.limits.texcoord; i++) {
907 if (reg_maps->texcoord[i])
908 shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
911 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
912 * helper function shader that is linked in at link time
914 if (pshader && reg_maps->shader_version.major >= 3)
916 if (use_vs(device->stateBlock))
918 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
919 } else {
920 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
921 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
922 * pixel shader that reads the fixed function color into the packed input registers.
924 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
928 /* Declare output register temporaries */
929 if(This->baseShader.limits.packed_output) {
930 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
933 /* Declare temporary variables */
934 for(i = 0; i < This->baseShader.limits.temporary; i++) {
935 if (reg_maps->temporary[i])
936 shader_addline(buffer, "vec4 R%u;\n", i);
939 /* Declare attributes */
940 for (i = 0; i < This->baseShader.limits.attributes; i++) {
941 if (reg_maps->attributes[i])
942 shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
945 /* Declare loop registers aLx */
946 for (i = 0; i < reg_maps->loop_depth; i++) {
947 shader_addline(buffer, "int aL%u;\n", i);
948 shader_addline(buffer, "int tmpInt%u;\n", i);
951 /* Temporary variables for matrix operations */
952 shader_addline(buffer, "vec4 tmp0;\n");
953 shader_addline(buffer, "vec4 tmp1;\n");
955 /* Local constants use a different name so they can be loaded once at shader link time
956 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
957 * float -> string conversion can cause precision loss.
959 if(!This->baseShader.load_local_constsF) {
960 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
961 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
965 /* Start the main program */
966 shader_addline(buffer, "void main() {\n");
967 if(pshader && reg_maps->vpos) {
968 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
969 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
970 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
971 * precision troubles when we just substract 0.5.
973 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
975 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
977 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
978 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
979 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
980 * correctly on drivers that returns integer values.
982 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
986 /*****************************************************************************
987 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
989 * For more information, see http://wiki.winehq.org/DirectX-Shaders
990 ****************************************************************************/
992 /* Prototypes */
993 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
994 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
996 /** Used for opcode modifiers - They multiply the result by the specified amount */
997 static const char * const shift_glsl_tab[] = {
998 "", /* 0 (none) */
999 "2.0 * ", /* 1 (x2) */
1000 "4.0 * ", /* 2 (x4) */
1001 "8.0 * ", /* 3 (x8) */
1002 "16.0 * ", /* 4 (x16) */
1003 "32.0 * ", /* 5 (x32) */
1004 "", /* 6 (x64) */
1005 "", /* 7 (x128) */
1006 "", /* 8 (d256) */
1007 "", /* 9 (d128) */
1008 "", /* 10 (d64) */
1009 "", /* 11 (d32) */
1010 "0.0625 * ", /* 12 (d16) */
1011 "0.125 * ", /* 13 (d8) */
1012 "0.25 * ", /* 14 (d4) */
1013 "0.5 * " /* 15 (d2) */
1016 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1017 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1019 out_str[0] = 0;
1021 switch (src_modifier)
1023 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1024 case WINED3DSPSM_DW:
1025 case WINED3DSPSM_NONE:
1026 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1027 break;
1028 case WINED3DSPSM_NEG:
1029 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1030 break;
1031 case WINED3DSPSM_NOT:
1032 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1033 break;
1034 case WINED3DSPSM_BIAS:
1035 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1036 break;
1037 case WINED3DSPSM_BIASNEG:
1038 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1039 break;
1040 case WINED3DSPSM_SIGN:
1041 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1042 break;
1043 case WINED3DSPSM_SIGNNEG:
1044 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1045 break;
1046 case WINED3DSPSM_COMP:
1047 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1048 break;
1049 case WINED3DSPSM_X2:
1050 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1051 break;
1052 case WINED3DSPSM_X2NEG:
1053 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1054 break;
1055 case WINED3DSPSM_ABS:
1056 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1057 break;
1058 case WINED3DSPSM_ABSNEG:
1059 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1060 break;
1061 default:
1062 FIXME("Unhandled modifier %u\n", src_modifier);
1063 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1067 /** Writes the GLSL variable name that corresponds to the register that the
1068 * DX opcode parameter is trying to access */
1069 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1070 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1072 /* oPos, oFog and oPts in D3D */
1073 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1075 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1076 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1077 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
1078 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1080 *is_color = FALSE;
1082 switch (reg->type)
1084 case WINED3DSPR_TEMP:
1085 sprintf(register_name, "R%u", reg->idx);
1086 break;
1088 case WINED3DSPR_INPUT:
1089 /* vertex shaders */
1090 if (!pshader)
1092 if (((IWineD3DVertexShaderImpl *)This)->cur_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1093 sprintf(register_name, "attrib%u", reg->idx);
1094 break;
1097 /* pixel shaders >= 3.0 */
1098 if (This->baseShader.reg_maps.shader_version.major >= 3)
1100 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1101 DWORD in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1103 if (reg->rel_addr)
1105 glsl_src_param_t rel_param;
1107 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1109 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1110 * operation there */
1111 if (idx)
1113 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1115 sprintf(register_name,
1116 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1117 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1118 rel_param.param_str, idx);
1120 else
1122 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1125 else
1127 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1129 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1130 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1131 rel_param.param_str);
1133 else
1135 sprintf(register_name, "IN[%s]", rel_param.param_str);
1139 else
1141 if (idx == in_count) sprintf(register_name, "gl_Color");
1142 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1143 else sprintf(register_name, "IN[%u]", idx);
1146 else
1148 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1149 else strcpy(register_name, "gl_SecondaryColor");
1150 break;
1152 break;
1154 case WINED3DSPR_CONST:
1156 const char prefix = pshader ? 'P' : 'V';
1158 /* Relative addressing */
1159 if (reg->rel_addr)
1161 glsl_src_param_t rel_param;
1162 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1163 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1164 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1166 else
1168 if (shader_constant_is_local(This, reg->idx))
1169 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1170 else
1171 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1174 break;
1176 case WINED3DSPR_CONSTINT:
1177 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1178 else sprintf(register_name, "VI[%u]", reg->idx);
1179 break;
1181 case WINED3DSPR_CONSTBOOL:
1182 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1183 else sprintf(register_name, "VB[%u]", reg->idx);
1184 break;
1186 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1187 if (pshader) sprintf(register_name, "T%u", reg->idx);
1188 else sprintf(register_name, "A%u", reg->idx);
1189 break;
1191 case WINED3DSPR_LOOP:
1192 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1193 break;
1195 case WINED3DSPR_SAMPLER:
1196 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1197 else sprintf(register_name, "Vsampler%u", reg->idx);
1198 break;
1200 case WINED3DSPR_COLOROUT:
1201 if (reg->idx >= GL_LIMITS(buffers))
1202 WARN("Write to render target %u, only %d supported\n", reg->idx, GL_LIMITS(buffers));
1204 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) sprintf(register_name, "gl_FragData[%u]", reg->idx);
1205 /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
1206 else sprintf(register_name, "gl_FragColor");
1207 break;
1209 case WINED3DSPR_RASTOUT:
1210 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1211 break;
1213 case WINED3DSPR_DEPTHOUT:
1214 sprintf(register_name, "gl_FragDepth");
1215 break;
1217 case WINED3DSPR_ATTROUT:
1218 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1219 else sprintf(register_name, "gl_FrontSecondaryColor");
1220 break;
1222 case WINED3DSPR_TEXCRDOUT:
1223 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1224 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1225 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1226 break;
1228 case WINED3DSPR_MISCTYPE:
1229 if (reg->idx == 0)
1231 /* vPos */
1232 sprintf(register_name, "vpos");
1234 else if (reg->idx == 1)
1236 /* Note that gl_FrontFacing is a bool, while vFace is
1237 * a float for which the sign determines front/back */
1238 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1240 else
1242 FIXME("Unhandled misctype register %d\n", reg->idx);
1243 sprintf(register_name, "unrecognized_register");
1245 break;
1247 case WINED3DSPR_IMMCONST:
1248 switch (reg->immconst_type)
1250 case WINED3D_IMMCONST_FLOAT:
1251 sprintf(register_name, "%.8e", *(float *)reg->immconst_data);
1252 break;
1254 case WINED3D_IMMCONST_FLOAT4:
1255 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1256 *(float *)&reg->immconst_data[0], *(float *)&reg->immconst_data[1],
1257 *(float *)&reg->immconst_data[2], *(float *)&reg->immconst_data[3]);
1258 break;
1260 default:
1261 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1262 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1264 break;
1266 default:
1267 FIXME("Unhandled register name Type(%d)\n", reg->type);
1268 sprintf(register_name, "unrecognized_register");
1269 break;
1273 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1275 *str++ = '.';
1276 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1277 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1278 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1279 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1280 *str = '\0';
1283 /* Get the GLSL write mask for the destination register */
1284 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1286 DWORD mask = param->write_mask;
1288 if (shader_is_scalar(&param->reg))
1290 mask = WINED3DSP_WRITEMASK_0;
1291 *write_mask = '\0';
1293 else
1295 shader_glsl_write_mask_to_str(mask, write_mask);
1298 return mask;
1301 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1302 unsigned int size = 0;
1304 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1305 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1306 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1307 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1309 return size;
1312 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1314 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1315 * but addressed as "rgba". To fix this we need to swap the register's x
1316 * and z components. */
1317 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1319 *str++ = '.';
1320 /* swizzle bits fields: wwzzyyxx */
1321 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1322 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1323 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1324 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1325 *str = '\0';
1328 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1329 BOOL fixup, DWORD mask, char *swizzle_str)
1331 if (shader_is_scalar(&param->reg))
1332 *swizzle_str = '\0';
1333 else
1334 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1337 /* From a given parameter token, generate the corresponding GLSL string.
1338 * Also, return the actual register name and swizzle in case the
1339 * caller needs this information as well. */
1340 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1341 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1343 BOOL is_color = FALSE;
1344 char swizzle_str[6];
1346 glsl_src->reg_name[0] = '\0';
1347 glsl_src->param_str[0] = '\0';
1348 swizzle_str[0] = '\0';
1350 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1351 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1352 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1355 /* From a given parameter token, generate the corresponding GLSL string.
1356 * Also, return the actual register name and swizzle in case the
1357 * caller needs this information as well. */
1358 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1359 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1361 BOOL is_color = FALSE;
1363 glsl_dst->mask_str[0] = '\0';
1364 glsl_dst->reg_name[0] = '\0';
1366 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1367 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1370 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1371 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer,
1372 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1374 glsl_dst_param_t glsl_dst;
1375 DWORD mask;
1377 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1378 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1380 return mask;
1383 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1384 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, const struct wined3d_shader_instruction *ins)
1386 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1389 /** Process GLSL instruction modifiers */
1390 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1392 glsl_dst_param_t dst_param;
1393 DWORD modifiers;
1395 if (!ins->dst_count) return;
1397 modifiers = ins->dst[0].modifiers;
1398 if (!modifiers) return;
1400 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1402 if (modifiers & WINED3DSPDM_SATURATE)
1404 /* _SAT means to clamp the value of the register to between 0 and 1 */
1405 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1406 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1409 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1411 FIXME("_centroid modifier not handled\n");
1414 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1416 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1420 static inline const char *shader_get_comp_op(DWORD op)
1422 switch (op) {
1423 case COMPARISON_GT: return ">";
1424 case COMPARISON_EQ: return "==";
1425 case COMPARISON_GE: return ">=";
1426 case COMPARISON_LT: return "<";
1427 case COMPARISON_NE: return "!=";
1428 case COMPARISON_LE: return "<=";
1429 default:
1430 FIXME("Unrecognized comparison value: %u\n", op);
1431 return "(\?\?)";
1435 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1437 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1438 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1439 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1440 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1442 /* Note that there's no such thing as a projected cube texture. */
1443 switch(sampler_type) {
1444 case WINED3DSTT_1D:
1445 if(lod) {
1446 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1447 } else if(grad) {
1448 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1449 } else {
1450 sample_function->name = projected ? "texture1DProj" : "texture1D";
1452 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1453 break;
1454 case WINED3DSTT_2D:
1455 if(texrect) {
1456 if(lod) {
1457 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1458 } else if(grad) {
1459 /* What good are texrect grad functions? I don't know, but GL_EXT_gpu_shader4 defines them.
1460 * There is no GL_ARB_shader_texture_lod spec yet, so I don't know if they're defined there
1462 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1463 } else {
1464 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1466 } else {
1467 if(lod) {
1468 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1469 } else if(grad) {
1470 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1471 } else {
1472 sample_function->name = projected ? "texture2DProj" : "texture2D";
1475 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1476 break;
1477 case WINED3DSTT_CUBE:
1478 if(lod) {
1479 sample_function->name = "textureCubeLod";
1480 } else if(grad) {
1481 sample_function->name = "textureCubeGradARB";
1482 } else {
1483 sample_function->name = "textureCube";
1485 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1486 break;
1487 case WINED3DSTT_VOLUME:
1488 if(lod) {
1489 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1490 } else if(grad) {
1491 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1492 } else {
1493 sample_function->name = projected ? "texture3DProj" : "texture3D";
1495 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1496 break;
1497 default:
1498 sample_function->name = "";
1499 sample_function->coord_mask = 0;
1500 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1501 break;
1505 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1506 BOOL sign_fixup, enum fixup_channel_source channel_source)
1508 switch(channel_source)
1510 case CHANNEL_SOURCE_ZERO:
1511 strcat(arguments, "0.0");
1512 break;
1514 case CHANNEL_SOURCE_ONE:
1515 strcat(arguments, "1.0");
1516 break;
1518 case CHANNEL_SOURCE_X:
1519 strcat(arguments, reg_name);
1520 strcat(arguments, ".x");
1521 break;
1523 case CHANNEL_SOURCE_Y:
1524 strcat(arguments, reg_name);
1525 strcat(arguments, ".y");
1526 break;
1528 case CHANNEL_SOURCE_Z:
1529 strcat(arguments, reg_name);
1530 strcat(arguments, ".z");
1531 break;
1533 case CHANNEL_SOURCE_W:
1534 strcat(arguments, reg_name);
1535 strcat(arguments, ".w");
1536 break;
1538 default:
1539 FIXME("Unhandled channel source %#x\n", channel_source);
1540 strcat(arguments, "undefined");
1541 break;
1544 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1547 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1549 struct wined3d_shader_dst_param dst;
1550 unsigned int mask_size, remaining;
1551 glsl_dst_param_t dst_param;
1552 char arguments[256];
1553 DWORD mask;
1555 mask = 0;
1556 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1557 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1558 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1559 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1560 mask &= ins->dst[0].write_mask;
1562 if (!mask) return; /* Nothing to do */
1564 if (is_yuv_fixup(fixup))
1566 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1567 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1568 return;
1571 mask_size = shader_glsl_get_write_mask_size(mask);
1573 dst = ins->dst[0];
1574 dst.write_mask = mask;
1575 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1577 arguments[0] = '\0';
1578 remaining = mask_size;
1579 if (mask & WINED3DSP_WRITEMASK_0)
1581 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1582 if (--remaining) strcat(arguments, ", ");
1584 if (mask & WINED3DSP_WRITEMASK_1)
1586 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1587 if (--remaining) strcat(arguments, ", ");
1589 if (mask & WINED3DSP_WRITEMASK_2)
1591 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1592 if (--remaining) strcat(arguments, ", ");
1594 if (mask & WINED3DSP_WRITEMASK_3)
1596 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1597 if (--remaining) strcat(arguments, ", ");
1600 if (mask_size > 1)
1602 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1603 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1605 else
1607 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1611 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1612 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1613 const char *dx, const char *dy,
1614 const char *bias, const char *coord_reg_fmt, ...)
1616 const char *sampler_base;
1617 char dst_swizzle[6];
1618 struct color_fixup_desc fixup;
1619 BOOL np2_fixup = FALSE;
1620 va_list args;
1622 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1624 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1626 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1627 fixup = This->cur_args->color_fixup[sampler];
1628 sampler_base = "Psampler";
1630 if(This->cur_args->np2_fixup & (1 << sampler)) {
1631 if(bias) {
1632 FIXME("Biased sampling from NP2 textures is unsupported\n");
1633 } else {
1634 np2_fixup = TRUE;
1637 } else {
1638 sampler_base = "Vsampler";
1639 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1642 shader_glsl_append_dst(ins->ctx->buffer, ins);
1644 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1646 va_start(args, coord_reg_fmt);
1647 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1648 va_end(args);
1650 if(bias) {
1651 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1652 } else {
1653 if (np2_fixup) {
1654 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup%u)%s);\n", sampler, dst_swizzle);
1655 } else if(dx && dy) {
1656 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1657 } else {
1658 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1662 if(!is_identity_fixup(fixup)) {
1663 shader_glsl_color_correction(ins, fixup);
1667 /*****************************************************************************
1669 * Begin processing individual instruction opcodes
1671 ****************************************************************************/
1673 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1674 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1676 SHADER_BUFFER *buffer = ins->ctx->buffer;
1677 glsl_src_param_t src0_param;
1678 glsl_src_param_t src1_param;
1679 DWORD write_mask;
1680 char op;
1682 /* Determine the GLSL operator to use based on the opcode */
1683 switch (ins->handler_idx)
1685 case WINED3DSIH_MUL: op = '*'; break;
1686 case WINED3DSIH_ADD: op = '+'; break;
1687 case WINED3DSIH_SUB: op = '-'; break;
1688 default:
1689 op = ' ';
1690 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1691 break;
1694 write_mask = shader_glsl_append_dst(buffer, ins);
1695 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1696 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1697 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1700 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1701 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1703 SHADER_BUFFER *buffer = ins->ctx->buffer;
1704 glsl_src_param_t src0_param;
1705 DWORD write_mask;
1707 write_mask = shader_glsl_append_dst(buffer, ins);
1708 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1710 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1711 * shader versions WINED3DSIO_MOVA is used for this. */
1712 if (ins->ctx->reg_maps->shader_version.major == 1
1713 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1714 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1716 /* This is a simple floor() */
1717 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1718 if (mask_size > 1) {
1719 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1720 } else {
1721 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1724 else if(ins->handler_idx == WINED3DSIH_MOVA)
1726 /* We need to *round* to the nearest int here. */
1727 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1728 if (mask_size > 1) {
1729 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);
1730 } else {
1731 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1733 } else {
1734 shader_addline(buffer, "%s);\n", src0_param.param_str);
1738 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1739 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1741 SHADER_BUFFER *buffer = ins->ctx->buffer;
1742 glsl_src_param_t src0_param;
1743 glsl_src_param_t src1_param;
1744 DWORD dst_write_mask, src_write_mask;
1745 unsigned int dst_size = 0;
1747 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1748 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1750 /* dp3 works on vec3, dp4 on vec4 */
1751 if (ins->handler_idx == WINED3DSIH_DP4)
1753 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1754 } else {
1755 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1758 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
1759 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
1761 if (dst_size > 1) {
1762 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1763 } else {
1764 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1768 /* Note that this instruction has some restrictions. The destination write mask
1769 * can't contain the w component, and the source swizzles have to be .xyzw */
1770 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1772 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1773 glsl_src_param_t src0_param;
1774 glsl_src_param_t src1_param;
1775 char dst_mask[6];
1777 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1778 shader_glsl_append_dst(ins->ctx->buffer, ins);
1779 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
1780 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
1781 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1784 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1785 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1786 * GLSL uses the value as-is. */
1787 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1789 SHADER_BUFFER *buffer = ins->ctx->buffer;
1790 glsl_src_param_t src0_param;
1791 glsl_src_param_t src1_param;
1792 DWORD dst_write_mask;
1793 unsigned int dst_size;
1795 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1796 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1798 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1799 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
1801 if (dst_size > 1) {
1802 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1803 } else {
1804 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1808 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1809 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1810 * GLSL uses the value as-is. */
1811 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1813 SHADER_BUFFER *buffer = ins->ctx->buffer;
1814 glsl_src_param_t src0_param;
1815 DWORD dst_write_mask;
1816 unsigned int dst_size;
1818 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1819 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1821 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1823 if (dst_size > 1) {
1824 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1825 } else {
1826 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1830 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1831 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1833 SHADER_BUFFER *buffer = ins->ctx->buffer;
1834 glsl_src_param_t src_param;
1835 const char *instruction;
1836 DWORD write_mask;
1837 unsigned i;
1839 /* Determine the GLSL function to use based on the opcode */
1840 /* TODO: Possibly make this a table for faster lookups */
1841 switch (ins->handler_idx)
1843 case WINED3DSIH_MIN: instruction = "min"; break;
1844 case WINED3DSIH_MAX: instruction = "max"; break;
1845 case WINED3DSIH_ABS: instruction = "abs"; break;
1846 case WINED3DSIH_FRC: instruction = "fract"; break;
1847 case WINED3DSIH_NRM: instruction = "normalize"; break;
1848 case WINED3DSIH_EXP: instruction = "exp2"; break;
1849 case WINED3DSIH_SGN: instruction = "sign"; break;
1850 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1851 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1852 default: instruction = "";
1853 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1854 break;
1857 write_mask = shader_glsl_append_dst(buffer, ins);
1859 shader_addline(buffer, "%s(", instruction);
1861 if (ins->src_count)
1863 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
1864 shader_addline(buffer, "%s", src_param.param_str);
1865 for (i = 1; i < ins->src_count; ++i)
1867 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
1868 shader_addline(buffer, ", %s", src_param.param_str);
1872 shader_addline(buffer, "));\n");
1875 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1876 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1877 * dst.x = 2^(floor(src))
1878 * dst.y = src - floor(src)
1879 * dst.z = 2^src (partial precision is allowed, but optional)
1880 * dst.w = 1.0;
1881 * For 2.0 shaders, just do this (honoring writemask and swizzle):
1882 * dst = 2^src; (partial precision is allowed, but optional)
1884 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
1886 glsl_src_param_t src_param;
1888 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
1890 if (ins->ctx->reg_maps->shader_version.major < 2)
1892 char dst_mask[6];
1894 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1895 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1896 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1897 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
1899 shader_glsl_append_dst(ins->ctx->buffer, ins);
1900 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1901 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
1902 } else {
1903 DWORD write_mask;
1904 unsigned int mask_size;
1906 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1907 mask_size = shader_glsl_get_write_mask_size(write_mask);
1909 if (mask_size > 1) {
1910 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1911 } else {
1912 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
1917 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1918 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
1920 glsl_src_param_t src_param;
1921 DWORD write_mask;
1922 unsigned int mask_size;
1924 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1925 mask_size = shader_glsl_get_write_mask_size(write_mask);
1926 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
1928 if (mask_size > 1) {
1929 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1930 } else {
1931 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
1935 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
1937 SHADER_BUFFER *buffer = ins->ctx->buffer;
1938 glsl_src_param_t src_param;
1939 DWORD write_mask;
1940 unsigned int mask_size;
1942 write_mask = shader_glsl_append_dst(buffer, ins);
1943 mask_size = shader_glsl_get_write_mask_size(write_mask);
1945 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
1947 if (mask_size > 1) {
1948 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1949 } else {
1950 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1954 /** Process signed comparison opcodes in GLSL. */
1955 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
1957 glsl_src_param_t src0_param;
1958 glsl_src_param_t src1_param;
1959 DWORD write_mask;
1960 unsigned int mask_size;
1962 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1963 mask_size = shader_glsl_get_write_mask_size(write_mask);
1964 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1965 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1967 if (mask_size > 1) {
1968 const char *compare;
1970 switch(ins->handler_idx)
1972 case WINED3DSIH_SLT: compare = "lessThan"; break;
1973 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
1974 default: compare = "";
1975 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
1978 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1979 src0_param.param_str, src1_param.param_str);
1980 } else {
1981 switch(ins->handler_idx)
1983 case WINED3DSIH_SLT:
1984 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
1985 * to return 0.0 but step returns 1.0 because step is not < x
1986 * An alternative is a bvec compare padded with an unused second component.
1987 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
1988 * issue. Playing with not() is not possible either because not() does not accept
1989 * a scalar.
1991 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
1992 src0_param.param_str, src1_param.param_str);
1993 break;
1994 case WINED3DSIH_SGE:
1995 /* Here we can use the step() function and safe a conditional */
1996 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
1997 break;
1998 default:
1999 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2005 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2006 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2008 glsl_src_param_t src0_param;
2009 glsl_src_param_t src1_param;
2010 glsl_src_param_t src2_param;
2011 DWORD write_mask, cmp_channel = 0;
2012 unsigned int i, j;
2013 char mask_char[6];
2014 BOOL temp_destination = FALSE;
2016 if (shader_is_scalar(&ins->src[0].reg))
2018 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2020 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2021 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2022 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2024 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2025 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2026 } else {
2027 DWORD dst_mask = ins->dst[0].write_mask;
2028 struct wined3d_shader_dst_param dst = ins->dst[0];
2030 /* Cycle through all source0 channels */
2031 for (i=0; i<4; i++) {
2032 write_mask = 0;
2033 /* Find the destination channels which use the current source0 channel */
2034 for (j=0; j<4; j++) {
2035 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2037 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2038 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2041 dst.write_mask = dst_mask & write_mask;
2043 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2044 * The first lines may overwrite source parameters of the following lines.
2045 * Deal with that by using a temporary destination register if needed
2047 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2048 && ins->src[0].reg.type == ins->dst[0].reg.type)
2049 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2050 && ins->src[1].reg.type == ins->dst[0].reg.type)
2051 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2052 && ins->src[2].reg.type == ins->dst[0].reg.type))
2054 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2055 if (!write_mask) continue;
2056 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2057 temp_destination = TRUE;
2058 } else {
2059 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2060 if (!write_mask) continue;
2063 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2064 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2065 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2067 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2068 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2071 if(temp_destination) {
2072 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2073 shader_glsl_append_dst(ins->ctx->buffer, ins);
2074 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2080 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2081 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2082 * the compare is done per component of src0. */
2083 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2085 struct wined3d_shader_dst_param dst;
2086 glsl_src_param_t src0_param;
2087 glsl_src_param_t src1_param;
2088 glsl_src_param_t src2_param;
2089 DWORD write_mask, cmp_channel = 0;
2090 unsigned int i, j;
2091 DWORD dst_mask;
2092 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2093 ins->ctx->reg_maps->shader_version.minor);
2095 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2097 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2098 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2099 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2100 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2102 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2103 if (ins->coissue)
2105 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2106 } else {
2107 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2108 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2110 return;
2112 /* Cycle through all source0 channels */
2113 dst_mask = ins->dst[0].write_mask;
2114 dst = ins->dst[0];
2115 for (i=0; i<4; i++) {
2116 write_mask = 0;
2117 /* Find the destination channels which use the current source0 channel */
2118 for (j=0; j<4; j++) {
2119 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2121 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2122 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2126 dst.write_mask = dst_mask & write_mask;
2127 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2128 if (!write_mask) continue;
2130 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2131 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2132 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2134 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2135 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2139 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2140 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2142 glsl_src_param_t src0_param;
2143 glsl_src_param_t src1_param;
2144 glsl_src_param_t src2_param;
2145 DWORD write_mask;
2147 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2148 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2149 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2150 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2151 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2152 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2155 /** Handles transforming all WINED3DSIO_M?x? opcodes for
2156 Vertex shaders to GLSL codes */
2157 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2159 int i;
2160 int nComponents = 0;
2161 struct wined3d_shader_dst_param tmp_dst = {{0}};
2162 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2163 struct wined3d_shader_instruction tmp_ins;
2165 memset(&tmp_ins, 0, sizeof(tmp_ins));
2167 /* Set constants for the temporary argument */
2168 tmp_ins.ctx = ins->ctx;
2169 tmp_ins.dst_count = 1;
2170 tmp_ins.dst = &tmp_dst;
2171 tmp_ins.src_count = 2;
2172 tmp_ins.src = tmp_src;
2174 switch(ins->handler_idx)
2176 case WINED3DSIH_M4x4:
2177 nComponents = 4;
2178 tmp_ins.handler_idx = WINED3DSIH_DP4;
2179 break;
2180 case WINED3DSIH_M4x3:
2181 nComponents = 3;
2182 tmp_ins.handler_idx = WINED3DSIH_DP4;
2183 break;
2184 case WINED3DSIH_M3x4:
2185 nComponents = 4;
2186 tmp_ins.handler_idx = WINED3DSIH_DP3;
2187 break;
2188 case WINED3DSIH_M3x3:
2189 nComponents = 3;
2190 tmp_ins.handler_idx = WINED3DSIH_DP3;
2191 break;
2192 case WINED3DSIH_M3x2:
2193 nComponents = 2;
2194 tmp_ins.handler_idx = WINED3DSIH_DP3;
2195 break;
2196 default:
2197 break;
2200 tmp_dst = ins->dst[0];
2201 tmp_src[0] = ins->src[0];
2202 tmp_src[1] = ins->src[1];
2203 for (i = 0; i < nComponents; ++i)
2205 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2206 shader_glsl_dot(&tmp_ins);
2207 ++tmp_src[1].reg.idx;
2212 The LRP instruction performs a component-wise linear interpolation
2213 between the second and third operands using the first operand as the
2214 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2215 This is equivalent to mix(src2, src1, src0);
2217 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2219 glsl_src_param_t src0_param;
2220 glsl_src_param_t src1_param;
2221 glsl_src_param_t src2_param;
2222 DWORD write_mask;
2224 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2226 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2227 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2228 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2230 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2231 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2234 /** Process the WINED3DSIO_LIT instruction in GLSL:
2235 * dst.x = dst.w = 1.0
2236 * dst.y = (src0.x > 0) ? src0.x
2237 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2238 * where src.w is clamped at +- 128
2240 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2242 glsl_src_param_t src0_param;
2243 glsl_src_param_t src1_param;
2244 glsl_src_param_t src3_param;
2245 char dst_mask[6];
2247 shader_glsl_append_dst(ins->ctx->buffer, ins);
2248 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2250 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2251 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2252 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2254 /* The sdk specifies the instruction like this
2255 * dst.x = 1.0;
2256 * if(src.x > 0.0) dst.y = src.x
2257 * else dst.y = 0.0.
2258 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2259 * else dst.z = 0.0;
2260 * dst.w = 1.0;
2262 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2263 * dst.x = 1.0 ... No further explanation needed
2264 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2265 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2266 * dst.w = 1.0. ... Nothing fancy.
2268 * So we still have one conditional in there. So do this:
2269 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2271 * 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),
2272 * 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.
2273 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2275 shader_addline(ins->ctx->buffer,
2276 "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",
2277 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2280 /** Process the WINED3DSIO_DST instruction in GLSL:
2281 * dst.x = 1.0
2282 * dst.y = src0.x * src0.y
2283 * dst.z = src0.z
2284 * dst.w = src1.w
2286 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2288 glsl_src_param_t src0y_param;
2289 glsl_src_param_t src0z_param;
2290 glsl_src_param_t src1y_param;
2291 glsl_src_param_t src1w_param;
2292 char dst_mask[6];
2294 shader_glsl_append_dst(ins->ctx->buffer, ins);
2295 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2297 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2298 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2299 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2300 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2302 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2303 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2306 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2307 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2308 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2310 * dst.x = cos(src0.?)
2311 * dst.y = sin(src0.?)
2312 * dst.z = dst.z
2313 * dst.w = dst.w
2315 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2317 glsl_src_param_t src0_param;
2318 DWORD write_mask;
2320 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2321 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2323 switch (write_mask) {
2324 case WINED3DSP_WRITEMASK_0:
2325 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2326 break;
2328 case WINED3DSP_WRITEMASK_1:
2329 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2330 break;
2332 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2333 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2334 break;
2336 default:
2337 ERR("Write mask should be .x, .y or .xy\n");
2338 break;
2342 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2343 * Start a for() loop where src1.y is the initial value of aL,
2344 * increment aL by src1.z for a total of src1.x iterations.
2345 * Need to use a temporary variable for this operation.
2347 /* FIXME: I don't think nested loops will work correctly this way. */
2348 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2350 glsl_src_param_t src1_param;
2351 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2352 const DWORD *control_values = NULL;
2353 const local_constant *constant;
2355 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2357 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2358 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2359 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2360 * addressing.
2362 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2364 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2365 if (constant->idx == ins->src[1].reg.idx)
2367 control_values = constant->value;
2368 break;
2373 if(control_values) {
2374 if(control_values[2] > 0) {
2375 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
2376 shader->baseShader.cur_loop_depth, control_values[1],
2377 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2378 shader->baseShader.cur_loop_depth, control_values[2]);
2379 } else if(control_values[2] == 0) {
2380 shader_addline(ins->ctx->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
2381 shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
2382 shader->baseShader.cur_loop_depth, control_values[0],
2383 shader->baseShader.cur_loop_depth);
2384 } else {
2385 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
2386 shader->baseShader.cur_loop_depth, control_values[1],
2387 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2388 shader->baseShader.cur_loop_depth, control_values[2]);
2390 } else {
2391 shader_addline(ins->ctx->buffer,
2392 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2393 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2394 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2395 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2398 shader->baseShader.cur_loop_depth++;
2399 shader->baseShader.cur_loop_regno++;
2402 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2404 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2406 shader_addline(ins->ctx->buffer, "}\n");
2408 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2410 shader->baseShader.cur_loop_depth--;
2411 shader->baseShader.cur_loop_regno--;
2414 if (ins->handler_idx == WINED3DSIH_ENDREP)
2416 shader->baseShader.cur_loop_depth--;
2420 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2422 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2423 glsl_src_param_t src0_param;
2424 const DWORD *control_values = NULL;
2425 const local_constant *constant;
2427 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2428 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2430 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2432 if (constant->idx == ins->src[0].reg.idx)
2434 control_values = constant->value;
2435 break;
2440 if(control_values) {
2441 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2442 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2443 control_values[0], shader->baseShader.cur_loop_depth);
2444 } else {
2445 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2446 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2447 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2448 src0_param.param_str, shader->baseShader.cur_loop_depth);
2450 shader->baseShader.cur_loop_depth++;
2453 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2455 glsl_src_param_t src0_param;
2457 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2458 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2461 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2463 glsl_src_param_t src0_param;
2464 glsl_src_param_t src1_param;
2466 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2467 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2469 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2470 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2473 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2475 shader_addline(ins->ctx->buffer, "} else {\n");
2478 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2480 shader_addline(ins->ctx->buffer, "break;\n");
2483 /* FIXME: According to MSDN the compare is done per component. */
2484 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2486 glsl_src_param_t src0_param;
2487 glsl_src_param_t src1_param;
2489 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2490 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2492 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2493 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2496 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2498 shader_addline(ins->ctx->buffer, "}\n");
2499 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2502 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2504 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2507 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2509 glsl_src_param_t src1_param;
2511 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2512 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2515 /*********************************************
2516 * Pixel Shader Specific Code begins here
2517 ********************************************/
2518 static void pshader_glsl_tex(const struct wined3d_shader_instruction *ins)
2520 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2521 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2522 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2523 ins->ctx->reg_maps->shader_version.minor);
2524 glsl_sample_function_t sample_function;
2525 DWORD sample_flags = 0;
2526 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2527 DWORD sampler_idx;
2528 DWORD mask = 0, swizzle;
2530 /* 1.0-1.4: Use destination register as sampler source.
2531 * 2.0+: Use provided sampler source. */
2532 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2533 else sampler_idx = ins->src[1].reg.idx;
2534 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2536 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2538 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2540 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2541 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2542 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2543 switch (flags & ~WINED3DTTFF_PROJECTED) {
2544 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2545 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2546 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2547 case WINED3DTTFF_COUNT4:
2548 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2552 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2554 DWORD src_mod = ins->src[0].modifiers;
2556 if (src_mod == WINED3DSPSM_DZ) {
2557 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2558 mask = WINED3DSP_WRITEMASK_2;
2559 } else if (src_mod == WINED3DSPSM_DW) {
2560 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2561 mask = WINED3DSP_WRITEMASK_3;
2563 } else {
2564 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2566 /* ps 2.0 texldp instruction always divides by the fourth component. */
2567 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2568 mask = WINED3DSP_WRITEMASK_3;
2572 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2573 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2574 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2577 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2578 mask |= sample_function.coord_mask;
2580 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2581 else swizzle = ins->src[1].swizzle;
2583 /* 1.0-1.3: Use destination register as coordinate source.
2584 1.4+: Use provided coordinate source register. */
2585 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2587 char coord_mask[6];
2588 shader_glsl_write_mask_to_str(mask, coord_mask);
2589 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2590 "T%u%s", sampler_idx, coord_mask);
2591 } else {
2592 glsl_src_param_t coord_param;
2593 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2594 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2596 glsl_src_param_t bias;
2597 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2598 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2599 "%s", coord_param.param_str);
2600 } else {
2601 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2602 "%s", coord_param.param_str);
2607 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2609 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2610 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2611 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
2612 glsl_sample_function_t sample_function;
2613 glsl_src_param_t coord_param, dx_param, dy_param;
2614 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2615 DWORD sampler_type;
2616 DWORD sampler_idx;
2617 DWORD swizzle = ins->src[1].swizzle;
2619 if(!GL_SUPPORT(ARB_SHADER_TEXTURE_LOD)) {
2620 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2621 return pshader_glsl_tex(ins);
2624 sampler_idx = ins->src[1].reg.idx;
2625 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2626 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2627 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2628 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2631 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2632 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2633 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2634 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2636 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2637 "%s", coord_param.param_str);
2640 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2642 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2643 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2644 glsl_sample_function_t sample_function;
2645 glsl_src_param_t coord_param, lod_param;
2646 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2647 DWORD sampler_type;
2648 DWORD sampler_idx;
2649 DWORD swizzle = ins->src[1].swizzle;
2651 sampler_idx = ins->src[1].reg.idx;
2652 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2653 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2654 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2655 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2657 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2658 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2660 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2662 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2664 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2665 * However, they seem to work just fine in fragment shaders as well. */
2666 WARN("Using %s in fragment shader.\n", sample_function.name);
2668 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
2669 "%s", coord_param.param_str);
2672 static void pshader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2674 /* FIXME: Make this work for more than just 2D textures */
2675 SHADER_BUFFER *buffer = ins->ctx->buffer;
2676 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2678 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
2680 char dst_mask[6];
2682 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2683 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2684 ins->dst[0].reg.idx, dst_mask);
2685 } else {
2686 DWORD reg = ins->src[0].reg.idx;
2687 DWORD src_mod = ins->src[0].modifiers;
2688 char dst_swizzle[6];
2690 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
2692 if (src_mod == WINED3DSPSM_DZ) {
2693 glsl_src_param_t div_param;
2694 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2695 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
2697 if (mask_size > 1) {
2698 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2699 } else {
2700 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2702 } else if (src_mod == WINED3DSPSM_DW) {
2703 glsl_src_param_t div_param;
2704 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2705 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
2707 if (mask_size > 1) {
2708 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2709 } else {
2710 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2712 } else {
2713 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2718 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2719 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2720 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2721 static void pshader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2723 glsl_src_param_t src0_param;
2724 glsl_sample_function_t sample_function;
2725 DWORD sampler_idx = ins->dst[0].reg.idx;
2726 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2727 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2728 UINT mask_size;
2730 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2732 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2733 * scalar, and projected sampling would require 4.
2735 * It is a dependent read - not valid with conditional NP2 textures
2737 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2738 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2740 switch(mask_size)
2742 case 1:
2743 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2744 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2745 break;
2747 case 2:
2748 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2749 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2750 break;
2752 case 3:
2753 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2754 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2755 break;
2757 default:
2758 FIXME("Unexpected mask size %u\n", mask_size);
2759 break;
2763 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2764 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2765 static void pshader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2767 glsl_src_param_t src0_param;
2768 DWORD dstreg = ins->dst[0].reg.idx;
2769 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2770 DWORD dst_mask;
2771 unsigned int mask_size;
2773 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2774 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2775 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2777 if (mask_size > 1) {
2778 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2779 } else {
2780 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2784 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2785 * Calculate the depth as dst.x / dst.y */
2786 static void pshader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2788 glsl_dst_param_t dst_param;
2790 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2792 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2793 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2794 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2795 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2796 * >= 1.0 or < 0.0
2798 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2799 dst_param.reg_name, dst_param.reg_name);
2802 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2803 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2804 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2805 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2807 static void pshader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2809 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2810 DWORD dstreg = ins->dst[0].reg.idx;
2811 glsl_src_param_t src0_param;
2813 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2815 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2816 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2819 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2820 * Calculate the 1st of a 2-row matrix multiplication. */
2821 static void pshader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2823 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2824 DWORD reg = ins->dst[0].reg.idx;
2825 SHADER_BUFFER *buffer = ins->ctx->buffer;
2826 glsl_src_param_t src0_param;
2828 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2829 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2832 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2833 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2834 static void pshader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
2836 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2837 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2838 DWORD reg = ins->dst[0].reg.idx;
2839 SHADER_BUFFER *buffer = ins->ctx->buffer;
2840 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2841 glsl_src_param_t src0_param;
2843 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2844 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2845 current_state->texcoord_w[current_state->current_row++] = reg;
2848 static void pshader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
2850 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2851 DWORD reg = ins->dst[0].reg.idx;
2852 SHADER_BUFFER *buffer = ins->ctx->buffer;
2853 glsl_src_param_t src0_param;
2854 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2855 glsl_sample_function_t sample_function;
2857 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2858 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2860 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2862 /* Sample the texture using the calculated coordinates */
2863 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
2866 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2867 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2868 static void pshader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
2870 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2871 glsl_src_param_t src0_param;
2872 DWORD reg = ins->dst[0].reg.idx;
2873 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2874 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2875 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2876 glsl_sample_function_t sample_function;
2878 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2879 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2881 /* Dependent read, not valid with conditional NP2 */
2882 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2884 /* Sample the texture using the calculated coordinates */
2885 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
2887 current_state->current_row = 0;
2890 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2891 * Perform the 3rd row of a 3x3 matrix multiply */
2892 static void pshader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
2894 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2895 glsl_src_param_t src0_param;
2896 char dst_mask[6];
2897 DWORD reg = ins->dst[0].reg.idx;
2898 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2899 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2901 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2903 shader_glsl_append_dst(ins->ctx->buffer, ins);
2904 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2905 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2907 current_state->current_row = 0;
2910 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
2911 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2912 static void pshader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
2914 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2915 DWORD reg = ins->dst[0].reg.idx;
2916 glsl_src_param_t src0_param;
2917 glsl_src_param_t src1_param;
2918 SHADER_BUFFER *buffer = ins->ctx->buffer;
2919 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2920 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
2921 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2922 glsl_sample_function_t sample_function;
2924 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2925 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2927 /* Perform the last matrix multiply operation */
2928 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2929 /* Reflection calculation */
2930 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2932 /* Dependent read, not valid with conditional NP2 */
2933 shader_glsl_get_sample_function(stype, 0, &sample_function);
2935 /* Sample the texture */
2936 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
2938 current_state->current_row = 0;
2941 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
2942 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2943 static void pshader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
2945 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2946 DWORD reg = ins->dst[0].reg.idx;
2947 SHADER_BUFFER *buffer = ins->ctx->buffer;
2948 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2949 glsl_src_param_t src0_param;
2950 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2951 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2952 glsl_sample_function_t sample_function;
2954 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2956 /* Perform the last matrix multiply operation */
2957 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2959 /* Construct the eye-ray vector from w coordinates */
2960 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2961 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2962 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2964 /* Dependent read, not valid with conditional NP2 */
2965 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2967 /* Sample the texture using the calculated coordinates */
2968 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
2970 current_state->current_row = 0;
2973 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2974 * Apply a fake bump map transform.
2975 * texbem is pshader <= 1.3 only, this saves a few version checks
2977 static void pshader_glsl_texbem(const struct wined3d_shader_instruction *ins)
2979 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2980 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2981 glsl_sample_function_t sample_function;
2982 glsl_src_param_t coord_param;
2983 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2984 DWORD sampler_idx;
2985 DWORD mask;
2986 DWORD flags;
2987 char coord_mask[6];
2989 sampler_idx = ins->dst[0].reg.idx;
2990 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2992 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2993 /* Dependent read, not valid with conditional NP2 */
2994 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2995 mask = sample_function.coord_mask;
2997 shader_glsl_write_mask_to_str(mask, coord_mask);
2999 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3000 * so we can't let the GL handle this.
3002 if (flags & WINED3DTTFF_PROJECTED) {
3003 DWORD div_mask=0;
3004 char coord_div_mask[3];
3005 switch (flags & ~WINED3DTTFF_PROJECTED) {
3006 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3007 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3008 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3009 case WINED3DTTFF_COUNT4:
3010 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3012 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3013 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3016 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3018 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3019 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3020 coord_param.param_str, coord_mask);
3022 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3024 glsl_src_param_t luminance_param;
3025 glsl_dst_param_t dst_param;
3027 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3028 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3030 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3031 dst_param.reg_name, dst_param.mask_str,
3032 luminance_param.param_str, sampler_idx, sampler_idx);
3036 static void pshader_glsl_bem(const struct wined3d_shader_instruction *ins)
3038 glsl_src_param_t src0_param, src1_param;
3039 DWORD sampler_idx = ins->dst[0].reg.idx;
3041 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3042 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3044 shader_glsl_append_dst(ins->ctx->buffer, ins);
3045 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3046 src0_param.param_str, sampler_idx, src1_param.param_str);
3049 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3050 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3051 static void pshader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3053 glsl_src_param_t src0_param;
3054 DWORD sampler_idx = ins->dst[0].reg.idx;
3055 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3056 glsl_sample_function_t sample_function;
3058 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3060 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3061 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3062 "%s.wx", src0_param.reg_name);
3065 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3066 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3067 static void pshader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3069 glsl_src_param_t src0_param;
3070 DWORD sampler_idx = ins->dst[0].reg.idx;
3071 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3072 glsl_sample_function_t sample_function;
3074 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3076 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3077 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3078 "%s.yz", src0_param.reg_name);
3081 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3082 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3083 static void pshader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3085 glsl_src_param_t src0_param;
3086 DWORD sampler_idx = ins->dst[0].reg.idx;
3087 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3088 glsl_sample_function_t sample_function;
3090 /* Dependent read, not valid with conditional NP2 */
3091 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3092 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3094 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3095 "%s", src0_param.param_str);
3098 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3099 * If any of the first 3 components are < 0, discard this pixel */
3100 static void pshader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3102 glsl_dst_param_t dst_param;
3104 /* The argument is a destination parameter, and no writemasks are allowed */
3105 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3106 if (ins->ctx->reg_maps->shader_version.major >= 2)
3108 /* 2.0 shaders compare all 4 components in texkill */
3109 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3110 } else {
3111 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3112 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3113 * 4 components are defined, only the first 3 are used
3115 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3119 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3120 * dst = dot2(src0, src1) + src2 */
3121 static void pshader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3123 glsl_src_param_t src0_param;
3124 glsl_src_param_t src1_param;
3125 glsl_src_param_t src2_param;
3126 DWORD write_mask;
3127 unsigned int mask_size;
3129 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3130 mask_size = shader_glsl_get_write_mask_size(write_mask);
3132 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3133 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3134 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3136 if (mask_size > 1) {
3137 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3138 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3139 } else {
3140 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3141 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3145 static void pshader_glsl_input_pack(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer,
3146 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps,
3147 enum vertexprocessing_mode vertexprocessing)
3149 unsigned int i;
3150 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3152 for (i = 0; i < MAX_REG_INPUT; ++i)
3154 DWORD usage, usage_idx;
3155 char reg_mask[6];
3157 /* Unused */
3158 if (!reg_maps->packed_input[i]) continue;
3160 usage = semantics_in[i].usage;
3161 usage_idx = semantics_in[i].usage_idx;
3162 shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3164 switch (usage)
3166 case WINED3DDECLUSAGE_TEXCOORD:
3167 if (usage_idx < 8 && vertexprocessing == pretransformed)
3168 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3169 This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
3170 else
3171 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3172 This->input_reg_map[i], reg_mask, reg_mask);
3173 break;
3175 case WINED3DDECLUSAGE_COLOR:
3176 if (usage_idx == 0)
3177 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3178 This->input_reg_map[i], reg_mask, reg_mask);
3179 else if (usage_idx == 1)
3180 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3181 This->input_reg_map[i], reg_mask, reg_mask);
3182 else
3183 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3184 This->input_reg_map[i], reg_mask, reg_mask);
3185 break;
3187 default:
3188 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3189 This->input_reg_map[i], reg_mask, reg_mask);
3190 break;
3195 /*********************************************
3196 * Vertex Shader Specific Code begins here
3197 ********************************************/
3199 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3200 glsl_program_key_t *key;
3202 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3203 key->vshader = entry->vshader;
3204 key->pshader = entry->pshader;
3205 key->vs_args = entry->vs_args;
3206 key->ps_args = entry->ps_args;
3208 hash_table_put(priv->glsl_program_lookup, key, entry);
3211 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3212 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3213 struct ps_compile_args *ps_args) {
3214 glsl_program_key_t key;
3216 key.vshader = vshader;
3217 key.pshader = pshader;
3218 key.vs_args = *vs_args;
3219 key.ps_args = *ps_args;
3221 return hash_table_get(priv->glsl_program_lookup, &key);
3224 /* GL locking is done by the caller */
3225 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
3226 struct glsl_shader_prog_link *entry)
3228 glsl_program_key_t *key;
3230 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3231 key->vshader = entry->vshader;
3232 key->pshader = entry->pshader;
3233 key->vs_args = entry->vs_args;
3234 key->ps_args = entry->ps_args;
3235 hash_table_remove(priv->glsl_program_lookup, key);
3237 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3238 if (entry->vshader) list_remove(&entry->vshader_entry);
3239 if (entry->pshader) list_remove(&entry->pshader_entry);
3240 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3241 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3242 HeapFree(GetProcessHeap(), 0, entry);
3245 static void handle_ps3_input(SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, const DWORD *map,
3246 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps_in,
3247 const struct wined3d_shader_semantic *semantics_out, const struct shader_reg_maps *reg_maps_out)
3249 unsigned int i, j;
3250 DWORD usage, usage_idx, usage_out, usage_idx_out;
3251 DWORD *set;
3252 DWORD in_idx;
3253 DWORD in_count = vec4_varyings(3, gl_info);
3254 char reg_mask[6], reg_mask_out[6];
3255 char destination[50];
3257 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3259 if (!semantics_out) {
3260 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3261 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3262 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3265 for(i = 0; i < MAX_REG_INPUT; i++) {
3266 if (!reg_maps_in->packed_input[i]) continue;
3268 in_idx = map[i];
3269 if (in_idx >= (in_count + 2)) {
3270 FIXME("More input varyings declared than supported, expect issues\n");
3271 continue;
3273 else if (map[i] == ~0U)
3275 /* Declared, but not read register */
3276 continue;
3279 if (in_idx == in_count) {
3280 sprintf(destination, "gl_FrontColor");
3281 } else if (in_idx == in_count + 1) {
3282 sprintf(destination, "gl_FrontSecondaryColor");
3283 } else {
3284 sprintf(destination, "IN[%u]", in_idx);
3287 usage = semantics_in[i].usage;
3288 usage_idx = semantics_in[i].usage_idx;
3289 set[map[i]] = shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3291 if(!semantics_out) {
3292 switch(usage) {
3293 case WINED3DDECLUSAGE_COLOR:
3294 if (usage_idx == 0)
3295 shader_addline(buffer, "%s%s = front_color%s;\n",
3296 destination, reg_mask, reg_mask);
3297 else if (usage_idx == 1)
3298 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3299 destination, reg_mask, reg_mask);
3300 else
3301 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3302 destination, reg_mask, reg_mask);
3303 break;
3305 case WINED3DDECLUSAGE_TEXCOORD:
3306 if (usage_idx < 8) {
3307 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3308 destination, reg_mask, usage_idx, reg_mask);
3309 } else {
3310 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3311 destination, reg_mask, reg_mask);
3313 break;
3315 case WINED3DDECLUSAGE_FOG:
3316 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3317 destination, reg_mask, reg_mask);
3318 break;
3320 default:
3321 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3322 destination, reg_mask, reg_mask);
3324 } else {
3325 BOOL found = FALSE;
3326 for(j = 0; j < MAX_REG_OUTPUT; j++) {
3327 if (!reg_maps_out->packed_output[j]) continue;
3329 usage_out = semantics_out[j].usage;
3330 usage_idx_out = semantics_out[j].usage_idx;
3331 shader_glsl_get_write_mask(&semantics_out[j].reg, reg_mask_out);
3333 if(usage == usage_out &&
3334 usage_idx == usage_idx_out) {
3335 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3336 destination, reg_mask, j, reg_mask);
3337 found = TRUE;
3340 if(!found) {
3341 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3342 destination, reg_mask, reg_mask);
3347 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3348 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3349 * input varyings are assigned above, if the optimizer works properly.
3351 for(i = 0; i < in_count + 2; i++) {
3352 if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3353 unsigned int size = 0;
3354 memset(reg_mask, 0, sizeof(reg_mask));
3355 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3356 reg_mask[size] = 'x';
3357 size++;
3359 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3360 reg_mask[size] = 'y';
3361 size++;
3363 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3364 reg_mask[size] = 'z';
3365 size++;
3367 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3368 reg_mask[size] = 'w';
3369 size++;
3372 if (i == in_count) {
3373 sprintf(destination, "gl_FrontColor");
3374 } else if (i == in_count + 1) {
3375 sprintf(destination, "gl_FrontSecondaryColor");
3376 } else {
3377 sprintf(destination, "IN[%u]", i);
3380 if (size == 1) {
3381 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3382 } else {
3383 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3388 HeapFree(GetProcessHeap(), 0, set);
3391 /* GL locking is done by the caller */
3392 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3393 IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3395 GLhandleARB ret = 0;
3396 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3397 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3398 IWineD3DDeviceImpl *device;
3399 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3400 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3401 unsigned int i;
3402 SHADER_BUFFER buffer;
3403 DWORD usage, usage_idx, writemask;
3404 char reg_mask[6];
3405 const struct wined3d_shader_semantic *semantics_out;
3407 shader_buffer_init(&buffer);
3409 shader_addline(&buffer, "#version 120\n");
3411 if(vs_major < 3 && ps_major < 3) {
3412 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3413 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3415 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3416 if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3417 !device->frag_pipe->ffp_proj_control) {
3418 shader_addline(&buffer, "void order_ps_input() {\n");
3419 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3420 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3421 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3422 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3425 shader_addline(&buffer, "}\n");
3426 } else {
3427 shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3429 } else if(ps_major < 3 && vs_major >= 3) {
3430 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3431 semantics_out = vs->semantics_out;
3433 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3434 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3435 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3437 usage = semantics_out[i].usage;
3438 usage_idx = semantics_out[i].usage_idx;
3439 writemask = shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3441 switch(usage) {
3442 case WINED3DDECLUSAGE_COLOR:
3443 if (usage_idx == 0)
3444 shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3445 else if (usage_idx == 1)
3446 shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3447 break;
3449 case WINED3DDECLUSAGE_POSITION:
3450 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3451 break;
3453 case WINED3DDECLUSAGE_TEXCOORD:
3454 if (usage_idx < 8) {
3455 if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;
3457 shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3458 usage_idx, reg_mask, i, reg_mask);
3459 if(!(writemask & WINED3DSP_WRITEMASK_3)) {
3460 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
3463 break;
3465 case WINED3DDECLUSAGE_PSIZE:
3466 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3467 break;
3469 case WINED3DDECLUSAGE_FOG:
3470 shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3471 break;
3473 default:
3474 break;
3477 shader_addline(&buffer, "}\n");
3479 } else if(ps_major >= 3 && vs_major >= 3) {
3480 semantics_out = vs->semantics_out;
3482 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3483 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3484 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3486 /* First, sort out position and point size. Those are not passed to the pixel shader */
3487 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3488 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3490 usage = semantics_out[i].usage;
3491 usage_idx = semantics_out[i].usage_idx;
3492 shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3494 switch(usage) {
3495 case WINED3DDECLUSAGE_POSITION:
3496 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3497 break;
3499 case WINED3DDECLUSAGE_PSIZE:
3500 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3501 break;
3503 default:
3504 break;
3508 /* Then, fix the pixel shader input */
3509 handle_ps3_input(&buffer, gl_info, ps->input_reg_map,
3510 ps->semantics_in, &ps->baseShader.reg_maps, semantics_out, &vs->baseShader.reg_maps);
3512 shader_addline(&buffer, "}\n");
3513 } else if(ps_major >= 3 && vs_major < 3) {
3514 shader_addline(&buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3515 shader_addline(&buffer, "void order_ps_input() {\n");
3516 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3517 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3518 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3520 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->semantics_in, &ps->baseShader.reg_maps, NULL, NULL);
3521 shader_addline(&buffer, "}\n");
3522 } else {
3523 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3526 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3527 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3528 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3529 checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3530 GL_EXTCALL(glCompileShaderARB(ret));
3531 checkGLcall("glCompileShaderARB(ret)");
3533 shader_buffer_free(&buffer);
3534 return ret;
3537 /* GL locking is done by the caller */
3538 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3539 GLhandleARB programId, char prefix)
3541 const local_constant *lconst;
3542 GLint tmp_loc;
3543 const float *value;
3544 char glsl_name[8];
3546 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3547 value = (const float *)lconst->value;
3548 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3549 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3550 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3552 checkGLcall("Hardcoding local constants\n");
3555 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3556 * It sets the programId on the current StateBlock (because it should be called
3557 * inside of the DrawPrimitive() part of the render loop).
3559 * If a program for the given combination does not exist, create one, and store
3560 * the program in the hash table. If it creates a program, it will link the
3561 * given objects, too.
3564 /* GL locking is done by the caller */
3565 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3566 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3567 struct shader_glsl_priv *priv = This->shader_priv;
3568 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3569 IWineD3DPixelShader *pshader = This->stateBlock->pixelShader;
3570 IWineD3DVertexShader *vshader = This->stateBlock->vertexShader;
3571 struct glsl_shader_prog_link *entry = NULL;
3572 GLhandleARB programId = 0;
3573 GLhandleARB reorder_shader_id = 0;
3574 unsigned int i;
3575 char glsl_name[8];
3576 GLhandleARB vshader_id, pshader_id;
3577 struct ps_compile_args ps_compile_args;
3578 struct vs_compile_args vs_compile_args;
3580 if(use_vs) {
3581 find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3582 } else {
3583 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3584 memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3586 if(use_ps) {
3587 find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3588 } else {
3589 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3590 memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3592 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3593 if (entry) {
3594 priv->glsl_program = entry;
3595 return;
3598 /* If we get to this point, then no matching program exists, so we create one */
3599 programId = GL_EXTCALL(glCreateProgramObjectARB());
3600 TRACE("Created new GLSL shader program %u\n", programId);
3602 /* Create the entry */
3603 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3604 entry->programId = programId;
3605 entry->vshader = vshader;
3606 entry->pshader = pshader;
3607 entry->vs_args = vs_compile_args;
3608 entry->ps_args = ps_compile_args;
3609 entry->constant_version = 0;
3610 /* Add the hash table entry */
3611 add_glsl_program_entry(priv, entry);
3613 /* Set the current program */
3614 priv->glsl_program = entry;
3616 if(use_vs) {
3617 vshader_id = find_gl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
3618 } else {
3619 vshader_id = 0;
3622 /* Attach GLSL vshader */
3623 if (vshader_id) {
3624 const unsigned int max_attribs = 16; /* TODO: Will this always be the case? It is at the moment... */
3625 char tmp_name[10];
3627 reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
3628 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
3629 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
3630 checkGLcall("glAttachObjectARB");
3631 /* Flag the reorder function for deletion, then it will be freed automatically when the program
3632 * is destroyed
3634 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
3636 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
3637 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
3638 checkGLcall("glAttachObjectARB");
3640 /* Bind vertex attributes to a corresponding index number to match
3641 * the same index numbers as ARB_vertex_programs (makes loading
3642 * vertex attributes simpler). With this method, we can use the
3643 * exact same code to load the attributes later for both ARB and
3644 * GLSL shaders.
3646 * We have to do this here because we need to know the Program ID
3647 * in order to make the bindings work, and it has to be done prior
3648 * to linking the GLSL program. */
3649 for (i = 0; i < max_attribs; ++i) {
3650 if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
3651 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
3652 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
3655 checkGLcall("glBindAttribLocationARB");
3657 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3660 if(use_ps) {
3661 pshader_id = find_gl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
3662 } else {
3663 pshader_id = 0;
3666 /* Attach GLSL pshader */
3667 if (pshader_id) {
3668 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3669 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3670 checkGLcall("glAttachObjectARB");
3672 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3675 /* Link the program */
3676 TRACE("Linking GLSL shader program %u\n", programId);
3677 GL_EXTCALL(glLinkProgramARB(programId));
3678 print_glsl_info_log(&GLINFO_LOCATION, programId);
3680 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3681 for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3682 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3683 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3685 for (i = 0; i < MAX_CONST_I; ++i) {
3686 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
3687 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3689 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3690 for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3691 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3692 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3694 for (i = 0; i < MAX_CONST_I; ++i) {
3695 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
3696 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3699 if(pshader) {
3700 for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
3701 char name[32];
3702 sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
3703 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3704 sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3705 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3706 sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3707 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3711 if (use_ps && ps_compile_args.np2_fixup) {
3712 char name[32];
3713 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3714 if (ps_compile_args.np2_fixup & (1 << i)) {
3715 sprintf(name, "PsamplerNP2Fixup%u", i);
3716 entry->np2Fixup_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3717 } else {
3718 entry->np2Fixup_location[i] = -1;
3723 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
3724 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3725 checkGLcall("Find glsl program uniform locations");
3727 if (pshader
3728 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
3729 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
3731 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
3732 entry->vertex_color_clamp = GL_FALSE;
3733 } else {
3734 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
3737 /* Set the shader to allow uniform loading on it */
3738 GL_EXTCALL(glUseProgramObjectARB(programId));
3739 checkGLcall("glUseProgramObjectARB(programId)");
3741 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
3742 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
3743 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
3744 * vertex shader with fixed function pixel processing is used we make sure that the card
3745 * supports enough samplers to allow the max number of vertex samplers with all possible
3746 * fixed function fragment processing setups. So once the program is linked these samplers
3747 * won't change.
3749 if(vshader_id) {
3750 /* Load vertex shader samplers */
3751 shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
3753 if(pshader_id) {
3754 /* Load pixel shader samplers */
3755 shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
3758 /* If the local constants do not have to be loaded with the environment constants,
3759 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
3760 * later
3762 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
3763 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
3765 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
3766 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
3770 /* GL locking is done by the caller */
3771 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
3773 GLhandleARB program_id;
3774 GLhandleARB vshader_id, pshader_id;
3775 static const char *blt_vshader[] =
3777 "#version 120\n"
3778 "void main(void)\n"
3779 "{\n"
3780 " gl_Position = gl_Vertex;\n"
3781 " gl_FrontColor = vec4(1.0);\n"
3782 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
3783 "}\n"
3786 static const char *blt_pshaders[tex_type_count] =
3788 /* tex_1d */
3789 NULL,
3790 /* tex_2d */
3791 "#version 120\n"
3792 "uniform sampler2D sampler;\n"
3793 "void main(void)\n"
3794 "{\n"
3795 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3796 "}\n",
3797 /* tex_3d */
3798 NULL,
3799 /* tex_cube */
3800 "#version 120\n"
3801 "uniform samplerCube sampler;\n"
3802 "void main(void)\n"
3803 "{\n"
3804 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
3805 "}\n",
3806 /* tex_rect */
3807 "#version 120\n"
3808 "#extension GL_ARB_texture_rectangle : enable\n"
3809 "uniform sampler2DRect sampler;\n"
3810 "void main(void)\n"
3811 "{\n"
3812 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
3813 "}\n",
3816 if (!blt_pshaders[tex_type])
3818 FIXME("tex_type %#x not supported\n", tex_type);
3819 tex_type = tex_2d;
3822 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3823 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3824 GL_EXTCALL(glCompileShaderARB(vshader_id));
3826 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3827 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
3828 GL_EXTCALL(glCompileShaderARB(pshader_id));
3830 program_id = GL_EXTCALL(glCreateProgramObjectARB());
3831 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3832 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3833 GL_EXTCALL(glLinkProgramARB(program_id));
3835 print_glsl_info_log(&GLINFO_LOCATION, program_id);
3837 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
3838 * is destroyed
3840 GL_EXTCALL(glDeleteObjectARB(vshader_id));
3841 GL_EXTCALL(glDeleteObjectARB(pshader_id));
3842 return program_id;
3845 /* GL locking is done by the caller */
3846 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3847 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3848 struct shader_glsl_priv *priv = This->shader_priv;
3849 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3850 GLhandleARB program_id = 0;
3851 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
3853 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3855 if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3856 else priv->glsl_program = NULL;
3858 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3860 if (old_vertex_color_clamp != current_vertex_color_clamp) {
3861 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
3862 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
3863 checkGLcall("glClampColorARB");
3864 } else {
3865 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
3869 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3870 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3871 GL_EXTCALL(glUseProgramObjectARB(program_id));
3872 checkGLcall("glUseProgramObjectARB");
3875 /* GL locking is done by the caller */
3876 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
3877 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3878 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3879 struct shader_glsl_priv *priv = This->shader_priv;
3880 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
3882 if (!*blt_program) {
3883 GLint loc;
3884 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
3885 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
3886 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3887 GL_EXTCALL(glUniform1iARB(loc, 0));
3888 } else {
3889 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3893 /* GL locking is done by the caller */
3894 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
3895 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3896 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3897 struct shader_glsl_priv *priv = This->shader_priv;
3898 GLhandleARB program_id;
3900 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3901 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3903 GL_EXTCALL(glUseProgramObjectARB(program_id));
3904 checkGLcall("glUseProgramObjectARB");
3907 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
3908 const struct list *linked_programs;
3909 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
3910 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3911 struct shader_glsl_priv *priv = device->shader_priv;
3912 const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
3913 IWineD3DPixelShaderImpl *ps = NULL;
3914 IWineD3DVertexShaderImpl *vs = NULL;
3916 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
3917 * can be called from IWineD3DBaseShader::Release
3919 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
3921 if(pshader) {
3922 ps = (IWineD3DPixelShaderImpl *) This;
3923 if(ps->num_gl_shaders == 0) return;
3924 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
3926 ENTER_GL();
3927 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3928 LEAVE_GL();
3930 } else {
3931 vs = (IWineD3DVertexShaderImpl *) This;
3932 if(vs->num_gl_shaders == 0) return;
3933 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
3935 ENTER_GL();
3936 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3937 LEAVE_GL();
3941 linked_programs = &This->baseShader.linked_programs;
3943 TRACE("Deleting linked programs\n");
3944 if (linked_programs->next) {
3945 struct glsl_shader_prog_link *entry, *entry2;
3947 ENTER_GL();
3948 if(pshader) {
3949 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
3950 delete_glsl_program_entry(priv, gl_info, entry);
3952 } else {
3953 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
3954 delete_glsl_program_entry(priv, gl_info, entry);
3957 LEAVE_GL();
3960 if(pshader) {
3961 UINT i;
3963 ENTER_GL();
3964 for(i = 0; i < ps->num_gl_shaders; i++) {
3965 TRACE("deleting pshader %u\n", ps->gl_shaders[i].prgId);
3966 GL_EXTCALL(glDeleteObjectARB(ps->gl_shaders[i].prgId));
3967 checkGLcall("glDeleteObjectARB");
3969 LEAVE_GL();
3970 HeapFree(GetProcessHeap(), 0, ps->gl_shaders);
3971 ps->gl_shaders = NULL;
3972 ps->num_gl_shaders = 0;
3973 ps->shader_array_size = 0;
3974 } else {
3975 UINT i;
3977 ENTER_GL();
3978 for(i = 0; i < vs->num_gl_shaders; i++) {
3979 TRACE("deleting vshader %u\n", vs->gl_shaders[i].prgId);
3980 GL_EXTCALL(glDeleteObjectARB(vs->gl_shaders[i].prgId));
3981 checkGLcall("glDeleteObjectARB");
3983 LEAVE_GL();
3984 HeapFree(GetProcessHeap(), 0, vs->gl_shaders);
3985 vs->gl_shaders = NULL;
3986 vs->num_gl_shaders = 0;
3987 vs->shader_array_size = 0;
3991 static unsigned int glsl_program_key_hash(const void *key)
3993 const glsl_program_key_t *k = key;
3995 unsigned int hash = ((DWORD_PTR) k->vshader) | ((DWORD_PTR) k->pshader) << 16;
3996 hash += ~(hash << 15);
3997 hash ^= (hash >> 10);
3998 hash += (hash << 3);
3999 hash ^= (hash >> 6);
4000 hash += ~(hash << 11);
4001 hash ^= (hash >> 16);
4003 return hash;
4006 static BOOL glsl_program_key_compare(const void *keya, const void *keyb)
4008 const glsl_program_key_t *ka = keya;
4009 const glsl_program_key_t *kb = keyb;
4011 return ka->vshader == kb->vshader && ka->pshader == kb->pshader &&
4012 (memcmp(&ka->ps_args, &kb->ps_args, sizeof(kb->ps_args)) == 0) &&
4013 (memcmp(&ka->vs_args, &kb->vs_args, sizeof(kb->vs_args)) == 0);
4016 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4018 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4019 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4021 if (!mem)
4023 ERR("Failed to allocate memory\n");
4024 return FALSE;
4027 heap->entries = mem;
4028 heap->entries[1].version = 0;
4029 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4030 heap->size = 1;
4032 return TRUE;
4035 static void constant_heap_free(struct constant_heap *heap)
4037 HeapFree(GetProcessHeap(), 0, heap->entries);
4040 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4041 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4042 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4043 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4044 SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
4046 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4047 if (!priv->stack)
4049 ERR("Failed to allocate memory.\n");
4050 HeapFree(GetProcessHeap(), 0, priv);
4051 return E_OUTOFMEMORY;
4054 if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
4056 ERR("Failed to initialize vertex shader constant heap\n");
4057 HeapFree(GetProcessHeap(), 0, priv->stack);
4058 HeapFree(GetProcessHeap(), 0, priv);
4059 return E_OUTOFMEMORY;
4062 if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
4064 ERR("Failed to initialize pixel shader constant heap\n");
4065 constant_heap_free(&priv->vconst_heap);
4066 HeapFree(GetProcessHeap(), 0, priv->stack);
4067 HeapFree(GetProcessHeap(), 0, priv);
4068 return E_OUTOFMEMORY;
4071 priv->glsl_program_lookup = hash_table_create(glsl_program_key_hash, glsl_program_key_compare);
4072 priv->next_constant_version = 1;
4074 This->shader_priv = priv;
4075 return WINED3D_OK;
4078 static void shader_glsl_free(IWineD3DDevice *iface) {
4079 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4080 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
4081 struct shader_glsl_priv *priv = This->shader_priv;
4082 int i;
4084 ENTER_GL();
4085 for (i = 0; i < tex_type_count; ++i)
4087 if (priv->depth_blt_program[i])
4089 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4092 LEAVE_GL();
4094 hash_table_destroy(priv->glsl_program_lookup, NULL, NULL);
4095 constant_heap_free(&priv->pconst_heap);
4096 constant_heap_free(&priv->vconst_heap);
4098 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4099 This->shader_priv = NULL;
4102 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4103 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4104 return FALSE;
4107 /* GL locking is done by the caller */
4108 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShader *iface,
4109 SHADER_BUFFER *buffer, const struct ps_compile_args *args)
4111 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
4112 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4113 CONST DWORD *function = This->baseShader.function;
4114 const char *fragcolor;
4115 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
4117 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4118 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4120 shader_addline(buffer, "#version 120\n");
4122 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
4123 shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
4125 if(GL_SUPPORT(ARB_SHADER_TEXTURE_LOD) && reg_maps->usestexldd) {
4126 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4128 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
4129 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4130 * drivers write a warning if we don't do so
4132 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4135 /* Base Declarations */
4136 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
4138 /* Pack 3.0 inputs */
4139 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4141 pshader_glsl_input_pack(iface, buffer, This->semantics_in, reg_maps, args->vp_mode);
4144 /* Base Shader Body */
4145 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, NULL);
4147 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4148 if (reg_maps->shader_version.major < 2)
4150 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4151 if(GL_SUPPORT(ARB_DRAW_BUFFERS))
4152 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4153 else
4154 shader_addline(buffer, "gl_FragColor = R0;\n");
4157 if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
4158 fragcolor = "gl_FragData[0]";
4159 } else {
4160 fragcolor = "gl_FragColor";
4162 if(args->srgb_correction) {
4163 shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
4164 fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
4165 srgb_sub_high, srgb_sub_high, srgb_sub_high);
4166 shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
4167 shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
4168 shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
4169 shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
4170 shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
4172 /* Pixel shader < 3.0 do not replace the fog stage.
4173 * This implements linear fog computation and blending.
4174 * TODO: non linear fog
4175 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4176 * -1/(e-s) and e/(e-s) respectively.
4178 if (reg_maps->shader_version.major < 3)
4180 switch(args->fog) {
4181 case FOG_OFF: break;
4182 case FOG_LINEAR:
4183 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4184 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4185 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4186 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4187 break;
4188 case FOG_EXP:
4189 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4190 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4191 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4192 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4193 break;
4194 case FOG_EXP2:
4195 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4196 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4197 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4198 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4199 break;
4203 shader_addline(buffer, "}\n");
4205 TRACE("Compiling shader object %u\n", shader_obj);
4206 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4207 GL_EXTCALL(glCompileShaderARB(shader_obj));
4208 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4210 /* Store the shader object */
4211 return shader_obj;
4214 /* GL locking is done by the caller */
4215 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShader *iface,
4216 SHADER_BUFFER *buffer, const struct vs_compile_args *args)
4218 IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
4219 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4220 CONST DWORD *function = This->baseShader.function;
4221 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
4223 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4224 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4226 shader_addline(buffer, "#version 120\n");
4228 /* Base Declarations */
4229 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
4231 /* Base Shader Body */
4232 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, NULL);
4234 /* Unpack 3.0 outputs */
4235 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
4236 else shader_addline(buffer, "order_ps_input();\n");
4238 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4239 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4240 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4241 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4243 if(args->fog_src == VS_FOG_Z) {
4244 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4245 } else if (!reg_maps->fog) {
4246 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4249 /* Write the final position.
4251 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4252 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4253 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4254 * contains 1.0 to allow a mad.
4256 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4257 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4258 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4260 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4262 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4263 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4264 * which is the same as z = z * 2 - w.
4266 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4268 shader_addline(buffer, "}\n");
4270 TRACE("Compiling shader object %u\n", shader_obj);
4271 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4272 GL_EXTCALL(glCompileShaderARB(shader_obj));
4273 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4275 return shader_obj;
4278 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4280 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4281 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4282 * vs_nv_version which is based on NV_vertex_program.
4283 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4284 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4285 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4286 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4288 if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4289 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4290 else
4291 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4292 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4293 pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4295 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4296 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4297 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4298 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4299 * in max native instructions. Intel and others also offer the info in this extension but they
4300 * don't support GLSL (at least on Windows).
4302 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4303 * of instructions is 512 or less we have to do with ps2.0 hardware.
4304 * 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.
4306 if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4307 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4308 else
4309 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4311 pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
4313 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4314 * Direct3D minimum requirement.
4316 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4317 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4319 * The problem is that the refrast clamps temporary results in the shader to
4320 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4321 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4322 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4323 * offer a way to query this.
4325 pCaps->PixelShader1xMaxValue = 8.0;
4326 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4328 pCaps->VSClipping = TRUE;
4331 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4333 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4335 TRACE("Checking support for fixup:\n");
4336 dump_color_fixup_desc(fixup);
4339 /* We support everything except YUV conversions. */
4340 if (!is_yuv_fixup(fixup))
4342 TRACE("[OK]\n");
4343 return TRUE;
4346 TRACE("[FAILED]\n");
4347 return FALSE;
4350 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4352 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4353 /* WINED3DSIH_ADD */ shader_glsl_arith,
4354 /* WINED3DSIH_BEM */ pshader_glsl_bem,
4355 /* WINED3DSIH_BREAK */ shader_glsl_break,
4356 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4357 /* WINED3DSIH_BREAKP */ NULL,
4358 /* WINED3DSIH_CALL */ shader_glsl_call,
4359 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4360 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4361 /* WINED3DSIH_CND */ shader_glsl_cnd,
4362 /* WINED3DSIH_CRS */ shader_glsl_cross,
4363 /* WINED3DSIH_DCL */ NULL,
4364 /* WINED3DSIH_DEF */ NULL,
4365 /* WINED3DSIH_DEFB */ NULL,
4366 /* WINED3DSIH_DEFI */ NULL,
4367 /* WINED3DSIH_DP2ADD */ pshader_glsl_dp2add,
4368 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4369 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4370 /* WINED3DSIH_DST */ shader_glsl_dst,
4371 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4372 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4373 /* WINED3DSIH_ELSE */ shader_glsl_else,
4374 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4375 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4376 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4377 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4378 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4379 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4380 /* WINED3DSIH_IF */ shader_glsl_if,
4381 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4382 /* WINED3DSIH_LABEL */ shader_glsl_label,
4383 /* WINED3DSIH_LIT */ shader_glsl_lit,
4384 /* WINED3DSIH_LOG */ shader_glsl_log,
4385 /* WINED3DSIH_LOGP */ shader_glsl_log,
4386 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4387 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4388 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4389 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4390 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4391 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4392 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4393 /* WINED3DSIH_MAD */ shader_glsl_mad,
4394 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4395 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4396 /* WINED3DSIH_MOV */ shader_glsl_mov,
4397 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4398 /* WINED3DSIH_MUL */ shader_glsl_arith,
4399 /* WINED3DSIH_NOP */ NULL,
4400 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4401 /* WINED3DSIH_PHASE */ NULL,
4402 /* WINED3DSIH_POW */ shader_glsl_pow,
4403 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4404 /* WINED3DSIH_REP */ shader_glsl_rep,
4405 /* WINED3DSIH_RET */ NULL,
4406 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4407 /* WINED3DSIH_SETP */ NULL,
4408 /* WINED3DSIH_SGE */ shader_glsl_compare,
4409 /* WINED3DSIH_SGN */ shader_glsl_map2gl,
4410 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4411 /* WINED3DSIH_SLT */ shader_glsl_compare,
4412 /* WINED3DSIH_SUB */ shader_glsl_arith,
4413 /* WINED3DSIH_TEX */ pshader_glsl_tex,
4414 /* WINED3DSIH_TEXBEM */ pshader_glsl_texbem,
4415 /* WINED3DSIH_TEXBEML */ pshader_glsl_texbem,
4416 /* WINED3DSIH_TEXCOORD */ pshader_glsl_texcoord,
4417 /* WINED3DSIH_TEXDEPTH */ pshader_glsl_texdepth,
4418 /* WINED3DSIH_TEXDP3 */ pshader_glsl_texdp3,
4419 /* WINED3DSIH_TEXDP3TEX */ pshader_glsl_texdp3tex,
4420 /* WINED3DSIH_TEXKILL */ pshader_glsl_texkill,
4421 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4422 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4423 /* WINED3DSIH_TEXM3x2DEPTH */ pshader_glsl_texm3x2depth,
4424 /* WINED3DSIH_TEXM3x2PAD */ pshader_glsl_texm3x2pad,
4425 /* WINED3DSIH_TEXM3x2TEX */ pshader_glsl_texm3x2tex,
4426 /* WINED3DSIH_TEXM3x3 */ pshader_glsl_texm3x3,
4427 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4428 /* WINED3DSIH_TEXM3x3PAD */ pshader_glsl_texm3x3pad,
4429 /* WINED3DSIH_TEXM3x3SPEC */ pshader_glsl_texm3x3spec,
4430 /* WINED3DSIH_TEXM3x3TEX */ pshader_glsl_texm3x3tex,
4431 /* WINED3DSIH_TEXM3x3VSPEC */ pshader_glsl_texm3x3vspec,
4432 /* WINED3DSIH_TEXREG2AR */ pshader_glsl_texreg2ar,
4433 /* WINED3DSIH_TEXREG2GB */ pshader_glsl_texreg2gb,
4434 /* WINED3DSIH_TEXREG2RGB */ pshader_glsl_texreg2rgb,
4437 const shader_backend_t glsl_shader_backend = {
4438 shader_glsl_instruction_handler_table,
4439 shader_glsl_select,
4440 shader_glsl_select_depth_blt,
4441 shader_glsl_deselect_depth_blt,
4442 shader_glsl_update_float_vertex_constants,
4443 shader_glsl_update_float_pixel_constants,
4444 shader_glsl_load_constants,
4445 shader_glsl_load_np2fixup_constants,
4446 shader_glsl_destroy,
4447 shader_glsl_alloc,
4448 shader_glsl_free,
4449 shader_glsl_dirty_const,
4450 shader_glsl_generate_pshader,
4451 shader_glsl_generate_vshader,
4452 shader_glsl_get_caps,
4453 shader_glsl_color_fixup_supported,
4454 shader_glsl_add_instruction_modifiers,