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