VirtualBox

source: vbox/trunk/src/VBox/Devices/Graphics/shaderlib/glsl_shader.c@ 82972

最後變更 在這個檔案從82972是 82700,由 vboxsync 提交於 5 年 前

3D: Sampler index validation in ldl and ldd instructions, bugref:9613

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 219.2 KB
 
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 * Copyright 2009 Henri Verbeet for CodeWeavers
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24/*
25 * Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
26 * other than GPL or LGPL is available it will apply instead, Oracle elects to use only
27 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
28 * a choice of LGPL license versions is made available with the language indicating
29 * that LGPLv2 or any later version may be used, or where a choice of which version
30 * of the LGPL is applied is otherwise unspecified.
31 */
32
33/*
34 * D3D shader asm has swizzles on source parameters, and write masks for
35 * destination parameters. GLSL uses swizzles for both. The result of this is
36 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
37 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
38 * mask for the destination parameter into account.
39 */
40
41#include "config.h"
42#include "wine/port.h"
43#include <limits.h>
44#include <stdio.h>
45#include "wined3d_private.h"
46
47WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
48WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
49WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
50WINE_DECLARE_DEBUG_CHANNEL(d3d);
51
52#ifdef VBOX_WITH_VMSVGA
53#define LOG_GROUP LOG_GROUP_DEV_VMSVGA
54#include <VBox/log.h>
55#undef WDLOG
56#define WDLOG(_m) Log(_m)
57#undef CONST
58#define CONST const
59#endif
60
61#define GLINFO_LOCATION (*gl_info)
62
63#define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
64#define WINED3D_GLSL_SAMPLE_RECT 0x2
65#define WINED3D_GLSL_SAMPLE_LOD 0x4
66#define WINED3D_GLSL_SAMPLE_GRAD 0x8
67
68typedef struct {
69 char reg_name[150];
70 char mask_str[6];
71} glsl_dst_param_t;
72
73typedef struct {
74 char reg_name[150];
75 char param_str[200];
76} glsl_src_param_t;
77
78typedef struct {
79 const char *name;
80 DWORD coord_mask;
81} glsl_sample_function_t;
82
83enum heap_node_op
84{
85 HEAP_NODE_TRAVERSE_LEFT,
86 HEAP_NODE_TRAVERSE_RIGHT,
87 HEAP_NODE_POP,
88};
89
90struct constant_entry
91{
92 unsigned int idx;
93 unsigned int version;
94};
95
96struct constant_heap
97{
98 struct constant_entry *entries;
99 unsigned int *positions;
100 unsigned int size;
101};
102
103/* GLSL shader private data */
104struct shader_glsl_priv {
105 struct wined3d_shader_buffer shader_buffer;
106 struct wine_rb_tree program_lookup;
107 struct glsl_shader_prog_link *glsl_program;
108 struct constant_heap vconst_heap;
109 struct constant_heap pconst_heap;
110 unsigned char *stack;
111 GLhandleARB depth_blt_program[tex_type_count];
112 UINT next_constant_version;
113};
114
115/* Struct to maintain data about a linked GLSL program */
116struct glsl_shader_prog_link {
117 struct wine_rb_entry program_lookup_entry;
118 struct list vshader_entry;
119 struct list pshader_entry;
120 GLhandleARB programId;
121 GLint *vuniformF_locations;
122 GLint *puniformF_locations;
123 GLint vuniformI_locations[MAX_CONST_I];
124 GLint puniformI_locations[MAX_CONST_I];
125 GLint posFixup_location;
126 GLint np2Fixup_location;
127 GLint bumpenvmat_location[MAX_TEXTURES];
128 GLint luminancescale_location[MAX_TEXTURES];
129 GLint luminanceoffset_location[MAX_TEXTURES];
130 GLint ycorrection_location;
131 GLenum vertex_color_clamp;
132 IWineD3DVertexShader *vshader;
133 IWineD3DPixelShader *pshader;
134 struct vs_compile_args vs_args;
135 struct ps_compile_args ps_args;
136 UINT constant_version;
137 const struct wined3d_context *context;
138 UINT inp2Fixup_info;
139};
140
141#ifdef VBOX_WITH_VMSVGA
142# define WINEFIXUPINFO_NOINDEX (~0U)
143#else
144#define WINEFIXUPINFO_NOINDEX (~0UL)
145#endif
146#define WINEFIXUPINFO_GET(_p) get_fixup_info((const IWineD3DPixelShaderImpl*)(_p)->pshader, (_p)->inp2Fixup_info)
147#define WINEFIXUPINFO_ISVALID(_p) ((_p)->inp2Fixup_info != WINEFIXUPINFO_NOINDEX)
148#ifdef VBOX_WITH_VMSVGA
149# define WINEFIXUPINFO_INIT(_p) do { (_p)->inp2Fixup_info = WINEFIXUPINFO_NOINDEX; } while (0)
150#else
151#define WINEFIXUPINFO_INIT(_p) ((_p)->inp2Fixup_info == WINEFIXUPINFO_NOINDEX)
152#endif
153
154typedef struct {
155 IWineD3DVertexShader *vshader;
156 IWineD3DPixelShader *pshader;
157 struct ps_compile_args ps_args;
158 struct vs_compile_args vs_args;
159 const struct wined3d_context *context;
160} glsl_program_key_t;
161
162struct shader_glsl_ctx_priv {
163 const struct vs_compile_args *cur_vs_args;
164 const struct ps_compile_args *cur_ps_args;
165 struct ps_np2fixup_info *cur_np2fixup_info;
166};
167
168struct glsl_ps_compiled_shader
169{
170 struct ps_compile_args args;
171 struct ps_np2fixup_info np2fixup;
172 GLhandleARB prgId;
173 const struct wined3d_context *context;
174};
175
176struct glsl_pshader_private
177{
178 struct glsl_ps_compiled_shader *gl_shaders;
179 UINT num_gl_shaders, shader_array_size;
180};
181
182struct glsl_vs_compiled_shader
183{
184 struct vs_compile_args args;
185 GLhandleARB prgId;
186 const struct wined3d_context *context;
187};
188
189struct glsl_vshader_private
190{
191 struct glsl_vs_compiled_shader *gl_shaders;
192 UINT num_gl_shaders, shader_array_size;
193};
194
195static const char *debug_gl_shader_type(GLenum type)
196{
197 switch (type)
198 {
199#define WINED3D_TO_STR(u) case u: return #u
200 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
201 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
202 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
203#undef WINED3D_TO_STR
204 default:
205 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
206 }
207}
208
209/* Extract a line from the info log.
210 * Note that this modifies the source string. */
211static char *get_info_log_line(char **ptr, int *pcbStr)
212{
213 char *p, *q;
214 const int cbStr = *pcbStr;
215
216 if (!cbStr)
217 {
218 /* zero-length string */
219 return NULL;
220 }
221
222 if ((*ptr)[cbStr-1] != '\0')
223 {
224 ERR("string should be null-rerminated, forcing it!");
225 (*ptr)[cbStr-1] = '\0';
226 }
227 p = *ptr;
228 if (!*p)
229 {
230 *pcbStr = 0;
231 return NULL;
232 }
233
234 if (!(q = strstr(p, "\n")))
235 {
236 /* the string contains a single line! */
237 *ptr += strlen(p);
238 *pcbStr = 0;
239 return p;
240 }
241
242 *q = '\0';
243 *pcbStr = cbStr - (((uintptr_t)q) - ((uintptr_t)p)) - 1;
244 Assert((*pcbStr) >= 0);
245 Assert((*pcbStr) < cbStr);
246 *ptr = q + 1;
247
248 return p;
249}
250
251/** Prints the GLSL info log which will contain error messages if they exist */
252/* GL locking is done by the caller */
253static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
254{
255 int infologLength = 0;
256 char *infoLog;
257 unsigned int i;
258 BOOL is_spam;
259
260 static const char * const spam[] =
261 {
262 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
263 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
264 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
265 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
266 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
267 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
268 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
269 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
270 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
271 };
272
273#ifndef VBOXWINEDBG_SHADERS
274 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
275#endif
276
277 GL_EXTCALL(glGetObjectParameterivARB(obj,
278 GL_OBJECT_INFO_LOG_LENGTH_ARB,
279 &infologLength));
280
281 /* A size of 1 is just a null-terminated string, so the log should be bigger than
282 * that if there are errors. */
283 if (infologLength > 1)
284 {
285 char *ptr, *line;
286 int cbPtr;
287
288 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
289 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
290 */
291 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
292 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
293 is_spam = FALSE;
294
295 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
296 if(strcmp(infoLog, spam[i]) == 0) {
297 is_spam = TRUE;
298 break;
299 }
300 }
301
302 ptr = infoLog;
303 cbPtr = infologLength;
304 if (is_spam)
305 {
306 WDLOG(("Spam received from GLSL shader #%u:\n", obj));
307 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
308 }
309 else
310 {
311 WDLOG(("Error received from GLSL shader #%u:\n", obj));
312 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
313 }
314 HeapFree(GetProcessHeap(), 0, infoLog);
315 }
316}
317
318static void shader_glsl_dump_shader_source(const struct wined3d_gl_info *gl_info, GLhandleARB shader)
319{
320 char *ptr;
321 GLint tmp, source_size;
322 char *source = NULL;
323 int cbPtr;
324
325 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
326
327 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
328 if (!source)
329 {
330 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
331 return;
332 }
333
334 source_size = tmp;
335
336 WDLOG(("Object %u:\n", shader));
337 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_SUBTYPE_ARB, &tmp));
338 WDLOG((" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp)));
339 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
340 WDLOG((" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp));
341 WDLOG(("\n"));
342
343 if (tmp == 0)
344 {
345 /* Compilation error, print the compiler's error messages. */
346 print_glsl_info_log(gl_info, shader);
347 }
348
349 ptr = source;
350 cbPtr = source_size;
351 GL_EXTCALL(glGetShaderSourceARB(shader, source_size, NULL, source));
352#if 0
353 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
354#else
355 WDLOG(("*****shader source***\n"));
356 WDLOG((" %s\n", source));
357 WDLOG(("\n*****END shader source***\n\n"));
358#endif
359 WDLOG(("\n"));
360}
361
362/* GL locking is done by the caller. */
363static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
364{
365 GLint i, object_count;
366 GLhandleARB *objects;
367 char *source = NULL;
368
369 WDLOG(("\n***************************dumping program %d******************************\n", program));
370
371 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
372 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
373 if (!objects)
374 {
375 ERR("Failed to allocate object array memory.\n");
376 return;
377 }
378
379 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
380 for (i = 0; i < object_count; ++i)
381 {
382 shader_glsl_dump_shader_source(gl_info, objects[i]);
383 }
384
385 HeapFree(GetProcessHeap(), 0, source);
386 HeapFree(GetProcessHeap(), 0, objects);
387
388 WDLOG(("\n***************************END dumping program %d******************************\n\n", program));
389}
390
391/* GL locking is done by the caller. */
392static void shader_glsl_validate_compile_link(const struct wined3d_gl_info *gl_info, GLhandleARB program, GLboolean fIsProgram)
393{
394 GLint tmp = -1;
395
396#ifndef VBOXWINEDBG_SHADERS
397 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
398#endif
399
400 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
401 if (tmp == GL_PROGRAM_OBJECT_ARB)
402 {
403 if (!fIsProgram)
404 {
405 ERR("this is a program, but shader expected");
406 }
407 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
408 if (!tmp)
409 {
410 ERR("Program %p link status invalid.\n", (void *)(uintptr_t)program);
411#ifndef VBOXWINEDBG_SHADERS
412 shader_glsl_dump_program_source(gl_info, program);
413#endif
414 }
415#if defined(VBOX_WITH_VMSVGA) && defined(DEBUG)
416 shader_glsl_dump_program_source(gl_info, program);
417#endif
418 }
419 else if (tmp == GL_SHADER_OBJECT_ARB)
420 {
421 if (fIsProgram)
422 {
423 ERR("this is a shader, but program expected");
424 }
425
426 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
427 if (!tmp)
428 {
429 ERR("Shader %p compile status invalid.\n", (void *)(uintptr_t)program);
430 shader_glsl_dump_shader_source(gl_info, program);
431 }
432 }
433 else
434 {
435 ERR("unexpected oject type(%d)!", tmp);
436 }
437
438 print_glsl_info_log(gl_info, program);
439}
440
441/**
442 * Loads (pixel shader) samplers
443 */
444/* GL locking is done by the caller */
445static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
446 DWORD *tex_unit_map, GLhandleARB programId)
447{
448 GLint name_loc;
449 int i;
450 char sampler_name[20];
451
452 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
453 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
454 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
455 if (name_loc != -1) {
456 DWORD mapped_unit = tex_unit_map[i];
457 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
458 {
459 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
460 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
461 checkGLcall("glUniform1iARB");
462 } else {
463 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
464 }
465 }
466 }
467}
468
469/* GL locking is done by the caller */
470static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
471 DWORD *tex_unit_map, GLhandleARB programId)
472{
473 GLint name_loc;
474 char sampler_name[20];
475 int i;
476
477 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
478 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
479 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
480 if (name_loc != -1) {
481 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
482 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
483 {
484 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
485 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
486 checkGLcall("glUniform1iARB");
487 } else {
488 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
489 }
490 }
491 }
492}
493
494/* GL locking is done by the caller */
495static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
496 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
497{
498 int stack_idx = 0;
499 unsigned int heap_idx = 1;
500 unsigned int idx;
501
502 if (heap->entries[heap_idx].version <= version) return;
503
504 idx = heap->entries[heap_idx].idx;
505 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
506 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
507
508 while (stack_idx >= 0)
509 {
510 /* Note that we fall through to the next case statement. */
511 switch(stack[stack_idx])
512 {
513 case HEAP_NODE_TRAVERSE_LEFT:
514 {
515 unsigned int left_idx = heap_idx << 1;
516 if (left_idx < heap->size && heap->entries[left_idx].version > version)
517 {
518 heap_idx = left_idx;
519 idx = heap->entries[heap_idx].idx;
520 if (constant_locations[idx] != -1)
521 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
522
523 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
524 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
525 break;
526 }
527 } RT_FALL_THRU();
528
529 case HEAP_NODE_TRAVERSE_RIGHT:
530 {
531 unsigned int right_idx = (heap_idx << 1) + 1;
532 if (right_idx < heap->size && heap->entries[right_idx].version > version)
533 {
534 heap_idx = right_idx;
535 idx = heap->entries[heap_idx].idx;
536 if (constant_locations[idx] != -1)
537 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
538
539 stack[stack_idx++] = HEAP_NODE_POP;
540 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
541 break;
542 }
543 } RT_FALL_THRU();
544
545 case HEAP_NODE_POP:
546 {
547 heap_idx >>= 1;
548 --stack_idx;
549 break;
550 }
551 }
552 }
553 checkGLcall("walk_constant_heap()");
554}
555
556/* GL locking is done by the caller */
557static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
558{
559 GLfloat clamped_constant[4];
560
561 if (location == -1) return;
562
563 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
564 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
565 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
566 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
567
568 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
569}
570
571/* GL locking is done by the caller */
572static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
573 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
574{
575 int stack_idx = 0;
576 unsigned int heap_idx = 1;
577 unsigned int idx;
578
579 if (heap->entries[heap_idx].version <= version) return;
580
581 idx = heap->entries[heap_idx].idx;
582 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
583 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
584
585 while (stack_idx >= 0)
586 {
587 /* Note that we fall through to the next case statement. */
588 switch(stack[stack_idx])
589 {
590 case HEAP_NODE_TRAVERSE_LEFT:
591 {
592 unsigned int left_idx = heap_idx << 1;
593 if (left_idx < heap->size && heap->entries[left_idx].version > version)
594 {
595 heap_idx = left_idx;
596 idx = heap->entries[heap_idx].idx;
597 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
598
599 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
600 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
601 break;
602 }
603 } RT_FALL_THRU();
604
605 case HEAP_NODE_TRAVERSE_RIGHT:
606 {
607 unsigned int right_idx = (heap_idx << 1) + 1;
608 if (right_idx < heap->size && heap->entries[right_idx].version > version)
609 {
610 heap_idx = right_idx;
611 idx = heap->entries[heap_idx].idx;
612 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
613
614 stack[stack_idx++] = HEAP_NODE_POP;
615 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
616 break;
617 }
618 } RT_FALL_THRU();
619
620 case HEAP_NODE_POP:
621 {
622 heap_idx >>= 1;
623 --stack_idx;
624 break;
625 }
626 }
627 }
628 checkGLcall("walk_constant_heap_clamped()");
629}
630
631/* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
632/* GL locking is done by the caller */
633static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
634 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
635 unsigned char *stack, UINT version)
636{
637 const local_constant *lconst;
638
639 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
640 if (This->baseShader.reg_maps.shader_version.major == 1
641 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
642 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
643 else
644 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
645
646 if (!This->baseShader.load_local_constsF)
647 {
648 TRACE("No need to load local float constants for this shader\n");
649 return;
650 }
651
652 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
653 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
654 {
655 GLint location = constant_locations[lconst->idx];
656 /* We found this uniform name in the program - go ahead and send the data */
657 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
658 }
659 checkGLcall("glUniform4fvARB()");
660}
661
662/* Loads integer constants (aka uniforms) into the currently set GLSL program. */
663/* GL locking is done by the caller */
664static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
665 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
666{
667 unsigned int i;
668 struct list* ptr;
669
670 for (i = 0; constants_set; constants_set >>= 1, ++i)
671 {
672 if (!(constants_set & 1)) continue;
673
674 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
675 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
676
677 /* We found this uniform name in the program - go ahead and send the data */
678 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
679 checkGLcall("glUniform4ivARB");
680 }
681
682 /* Load immediate constants */
683 ptr = list_head(&This->baseShader.constantsI);
684 while (ptr) {
685 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
686 unsigned int idx = lconst->idx;
687 const GLint *values = (const GLint *)lconst->value;
688
689 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
690 values[0], values[1], values[2], values[3]);
691
692 /* We found this uniform name in the program - go ahead and send the data */
693 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
694 checkGLcall("glUniform4ivARB");
695 ptr = list_next(&This->baseShader.constantsI, ptr);
696 }
697}
698
699/* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
700/* GL locking is done by the caller */
701static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
702 GLhandleARB programId, const BOOL *constants, WORD constants_set)
703{
704 GLint tmp_loc;
705 unsigned int i;
706 char tmp_name[8];
707 const char *prefix;
708 struct list* ptr;
709
710 switch (This->baseShader.reg_maps.shader_version.type)
711 {
712 case WINED3D_SHADER_TYPE_VERTEX:
713 prefix = "VB";
714 break;
715
716 case WINED3D_SHADER_TYPE_GEOMETRY:
717 prefix = "GB";
718 break;
719
720 case WINED3D_SHADER_TYPE_PIXEL:
721 prefix = "PB";
722 break;
723
724 default:
725 FIXME("Unknown shader type %#x.\n",
726 This->baseShader.reg_maps.shader_version.type);
727 prefix = "UB";
728 break;
729 }
730
731 /* TODO: Benchmark and see if it would be beneficial to store the
732 * locations of the constants to avoid looking up each time */
733 for (i = 0; constants_set; constants_set >>= 1, ++i)
734 {
735 if (!(constants_set & 1)) continue;
736
737 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
738
739 /* TODO: Benchmark and see if it would be beneficial to store the
740 * locations of the constants to avoid looking up each time */
741 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
742 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
743 if (tmp_loc != -1)
744 {
745 /* We found this uniform name in the program - go ahead and send the data */
746 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
747 checkGLcall("glUniform1ivARB");
748 }
749 }
750
751 /* Load immediate constants */
752 ptr = list_head(&This->baseShader.constantsB);
753 while (ptr) {
754 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
755 unsigned int idx = lconst->idx;
756 const GLint *values = (const GLint *)lconst->value;
757
758 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
759
760 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
761 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
762 if (tmp_loc != -1) {
763 /* We found this uniform name in the program - go ahead and send the data */
764 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
765 checkGLcall("glUniform1ivARB");
766 }
767 ptr = list_next(&This->baseShader.constantsB, ptr);
768 }
769}
770
771static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
772{
773 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
774}
775
776static const struct ps_np2fixup_info * get_fixup_info(const IWineD3DPixelShaderImpl *shader, UINT inp2fixup_info)
777{
778 struct glsl_pshader_private *shader_data = shader->baseShader.backend_data;
779
780 if (inp2fixup_info == WINEFIXUPINFO_NOINDEX)
781 return NULL;
782
783 if (!shader->baseShader.backend_data)
784 {
785 ERR("no backend data\n");
786 return NULL;
787 }
788 shader_data = shader->baseShader.backend_data;
789
790 if (inp2fixup_info >= shader_data->num_gl_shaders)
791 {
792 ERR("invalid index\n");
793 return NULL;
794 }
795
796 return &shader_data->gl_shaders[inp2fixup_info].np2fixup;
797}
798
799/**
800 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
801 */
802/* GL locking is done by the caller (state handler) */
803static void shader_glsl_load_np2fixup_constants(
804 IWineD3DDevice* device,
805 char usePixelShader,
806 char useVertexShader) {
807
808 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
809 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
810
811 if (!prog) {
812 /* No GLSL program set - nothing to do. */
813 return;
814 }
815
816 if (!usePixelShader) {
817 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
818 return;
819 }
820
821 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
822 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
823 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
824 UINT i;
825 UINT fixup = prog->ps_args.np2_fixup;
826 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
827
828 const struct ps_np2fixup_info *np2Fixup_info = WINEFIXUPINFO_GET(prog);
829
830 for (i = 0; fixup; fixup >>= 1, ++i) {
831 const unsigned char idx = np2Fixup_info->idx[i];
832 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
833 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
834
835 if (!tex) {
836 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
837 continue;
838 }
839
840 if (idx % 2) {
841 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
842 } else {
843 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
844 }
845 }
846
847 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, np2Fixup_info->num_consts, np2fixup_constants));
848 }
849}
850
851/**
852 * Loads the app-supplied constants into the currently set GLSL program.
853 */
854/* GL locking is done by the caller (state handler) */
855static void shader_glsl_load_constants(const struct wined3d_context *context,
856 char usePixelShader, char useVertexShader)
857{
858 const struct wined3d_gl_info *gl_info = context->gl_info;
859 IWineD3DDeviceImpl *device = context_get_device(context);
860 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
861 struct shader_glsl_priv *priv = device->shader_priv;
862
863 GLhandleARB programId;
864 struct glsl_shader_prog_link *prog = priv->glsl_program;
865 UINT constant_version;
866 int i;
867
868 if (!prog) {
869 /* No GLSL program set - nothing to do. */
870 return;
871 }
872 programId = prog->programId;
873 constant_version = prog->constant_version;
874
875 if (useVertexShader) {
876 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
877
878 /* Load DirectX 9 float constants/uniforms for vertex shader */
879 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
880 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
881
882 /* Load DirectX 9 integer constants/uniforms for vertex shader */
883 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
884 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
885
886 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
887 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
888 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
889
890 /* Upload the position fixup params */
891 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
892 checkGLcall("glUniform4fvARB");
893 }
894
895 if (usePixelShader) {
896
897 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
898
899 /* Load DirectX 9 float constants/uniforms for pixel shader */
900 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
901 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
902
903 /* Load DirectX 9 integer constants/uniforms for pixel shader */
904 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
905 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
906
907 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
908 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
909 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
910
911 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
912 * It can't be 0 for a valid texbem instruction.
913 */
914 for(i = 0; i < MAX_TEXTURES; i++) {
915 const float *data;
916
917 if(prog->bumpenvmat_location[i] == -1) continue;
918
919 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
920 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
921 checkGLcall("glUniformMatrix2fvARB");
922
923 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
924 * is set too, so we can check that in the needsbumpmat check
925 */
926 if(prog->luminancescale_location[i] != -1) {
927 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
928 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
929
930 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
931 checkGLcall("glUniform1fvARB");
932 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
933 checkGLcall("glUniform1fvARB");
934 }
935 }
936
937 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
938 float correction_params[4];
939
940 if (context->render_offscreen)
941 {
942 correction_params[0] = 0.0f;
943 correction_params[1] = 1.0f;
944 } else {
945 /* position is window relative, not viewport relative */
946#ifdef VBOX_WITH_VMSVGA
947 correction_params[0] = device->rtHeight;
948#else
949 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
950#endif
951 correction_params[1] = -1.0f;
952 }
953 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
954 }
955 }
956
957 if (priv->next_constant_version == UINT_MAX)
958 {
959 TRACE("Max constant version reached, resetting to 0.\n");
960 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
961 priv->next_constant_version = 1;
962 }
963 else
964 {
965 prog->constant_version = priv->next_constant_version++;
966 }
967}
968
969static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
970 unsigned int heap_idx, DWORD new_version)
971{
972 struct constant_entry *entries = heap->entries;
973 unsigned int *positions = heap->positions;
974 unsigned int parent_idx;
975
976 while (heap_idx > 1)
977 {
978 parent_idx = heap_idx >> 1;
979
980 if (new_version <= entries[parent_idx].version) break;
981
982 entries[heap_idx] = entries[parent_idx];
983 positions[entries[parent_idx].idx] = heap_idx;
984 heap_idx = parent_idx;
985 }
986
987 entries[heap_idx].version = new_version;
988 entries[heap_idx].idx = idx;
989 positions[idx] = heap_idx;
990}
991
992static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
993{
994 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
995 struct shader_glsl_priv *priv = This->shader_priv;
996 struct constant_heap *heap = &priv->vconst_heap;
997 UINT i;
998
999 for (i = start; i < count + start; ++i)
1000 {
1001 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
1002 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
1003 else
1004 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
1005 }
1006}
1007
1008static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
1009{
1010 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1011 struct shader_glsl_priv *priv = This->shader_priv;
1012 struct constant_heap *heap = &priv->pconst_heap;
1013 UINT i;
1014
1015 for (i = start; i < count + start; ++i)
1016 {
1017 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
1018 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
1019 else
1020 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
1021 }
1022}
1023
1024static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
1025{
1026 unsigned int ret = gl_info->limits.glsl_varyings / 4;
1027 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
1028 if(shader_major > 3) return ret;
1029
1030 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
1031 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
1032 return ret;
1033}
1034
1035/** Generate the variable & register declarations for the GLSL output target */
1036static void shader_generate_glsl_declarations(const struct wined3d_context *context,
1037 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
1038 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
1039{
1040 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
1041 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
1042 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
1043 const struct wined3d_gl_info *gl_info = context->gl_info;
1044 unsigned int i, extra_constants_needed = 0;
1045 const local_constant *lconst;
1046 DWORD map;
1047
1048 /* There are some minor differences between pixel and vertex shaders */
1049 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1050 char prefix = pshader ? 'P' : 'V';
1051
1052 /* Prototype the subroutines */
1053 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
1054 {
1055 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
1056 }
1057
1058 /* Declare the constants (aka uniforms) */
1059 if (This->baseShader.limits.constant_float > 0) {
1060 unsigned max_constantsF;
1061 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
1062 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
1063 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
1064 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
1065 * a dx9 card, as long as it doesn't also use all the other constants.
1066 *
1067 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
1068 * declare only the amount that we're assured to have.
1069 *
1070 * Thus we run into problems in these two cases:
1071 * 1) The shader really uses more uniforms than supported
1072 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
1073 */
1074 if (pshader)
1075 {
1076 /* No indirect addressing here. */
1077 max_constantsF = gl_info->limits.glsl_ps_float_constants;
1078 }
1079 else
1080 {
1081#ifndef VBOX_WITH_VMSVGA
1082 if(This->baseShader.reg_maps.usesrelconstF) {
1083#else
1084 /* If GL supports only 256 constants (seen on macOS drivers for compatibility profile, which we use),
1085 * then ignore the need for potential uniforms and always declare VC[256].
1086 * This allows to compile Windows 10 shader which use hardcoded constants at 250+ index range.
1087 * Fixes drawing problems on Windows 10 desktop.
1088 *
1089 * This hack is normally active only on macOS, because Windows and Linux OpenGL drivers
1090 * have a more usable limit for GL compatibility context (1024+).
1091 */
1092 if (This->baseShader.reg_maps.usesrelconstF && gl_info->limits.glsl_vs_float_constants > 256) {
1093#endif
1094 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
1095 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
1096 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
1097 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
1098 *
1099 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
1100 */
1101#ifdef VBOX_WITH_WDDM
1102 if (gl_info->limits.glsl_vs_float_constants == 256)
1103 {
1104 DWORD dwVersion = GetVersion();
1105 DWORD dwMajor = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1106 DWORD dwMinor = (DWORD)(HIBYTE(LOWORD(dwVersion)));
1107 /* tmp workaround Win8 Aero requirement for 256 */
1108 if (dwMajor > 6 || dwMinor > 1)
1109 {
1110 /* tmp work-around to make Internet Explorer in win8 work with GPU supporting only with 256 shader uniform vars
1111 * @todo: make it more robust */
1112 max_constantsF = gl_info->limits.glsl_vs_float_constants - 1;
1113 }
1114 else
1115 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
1116 }
1117 else
1118#endif
1119 {
1120 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
1121 }
1122
1123 if(ctx_priv->cur_vs_args->clip_enabled)
1124 {
1125 max_constantsF -= gl_info->limits.clipplanes;
1126 }
1127 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
1128 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
1129 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
1130 * for now take this into account when calculating the number of available constants
1131 */
1132 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
1133 /* Set by driver quirks in directx.c */
1134 max_constantsF -= gl_info->reserved_glsl_constants;
1135 }
1136 else
1137 {
1138 max_constantsF = gl_info->limits.glsl_vs_float_constants;
1139 }
1140 }
1141 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
1142 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
1143 }
1144
1145 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
1146 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
1147 */
1148 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
1149 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
1150
1151 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
1152 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
1153
1154 if(!pshader) {
1155 shader_addline(buffer, "uniform vec4 posFixup;\n");
1156 /* Predeclaration; This function is added at link time based on the pixel shader.
1157 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
1158 * that. We know the input to the reorder function at vertex shader compile time, so
1159 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
1160 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
1161 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
1162 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
1163 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
1164 * inout.
1165 */
1166 if (reg_maps->shader_version.major >= 3)
1167 {
1168 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1169 } else {
1170 shader_addline(buffer, "void order_ps_input();\n");
1171 }
1172 } else {
1173 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1174 {
1175 if (!(map & 1)) continue;
1176
1177 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1178
1179 if (reg_maps->luminanceparams & (1 << i))
1180 {
1181 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1182 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1183 extra_constants_needed++;
1184 }
1185
1186 extra_constants_needed++;
1187 }
1188
1189 if (ps_args->srgb_correction)
1190 {
1191 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1192 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1193 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1194 srgb_cmp);
1195 }
1196 if (reg_maps->vpos || reg_maps->usesdsy)
1197 {
1198 if (This->baseShader.limits.constant_float + extra_constants_needed
1199 + 1 < gl_info->limits.glsl_ps_float_constants)
1200 {
1201 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1202 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1203 extra_constants_needed++;
1204 } else {
1205 /* This happens because we do not have proper tracking of the constant registers that are
1206 * actually used, only the max limit of the shader version
1207 */
1208 FIXME("Cannot find a free uniform for vpos correction params\n");
1209 AssertFailed();
1210 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1211 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
1212 context->render_offscreen ? 1.0f : -1.0f);
1213 }
1214 shader_addline(buffer, "vec4 vpos;\n");
1215 }
1216 }
1217
1218 /* Declare texture samplers */
1219 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1220 if (reg_maps->sampler_type[i])
1221 {
1222 switch (reg_maps->sampler_type[i])
1223 {
1224 case WINED3DSTT_1D:
1225 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1226 break;
1227 case WINED3DSTT_2D:
1228 if(device->stateBlock->textures[i] &&
1229 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
1230 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1231 } else {
1232 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1233 }
1234 break;
1235 case WINED3DSTT_CUBE:
1236 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1237 break;
1238 case WINED3DSTT_VOLUME:
1239 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1240 break;
1241 default:
1242 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1243 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1244 break;
1245 }
1246 }
1247 }
1248
1249 /* Declare uniforms for NP2 texcoord fixup:
1250 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1251 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1252 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1253 if (pshader && ps_args->np2_fixup) {
1254
1255 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1256 UINT cur = 0;
1257
1258 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1259 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1260 * samplerNP2Fixup stores texture dimensions and is updated through
1261 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1262
1263 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1264 if (reg_maps->sampler_type[i]) {
1265 if (!(ps_args->np2_fixup & (1 << i))) continue;
1266
1267 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1268 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1269 continue;
1270 }
1271
1272 fixup->idx[i] = cur++;
1273 }
1274 }
1275
1276 fixup->num_consts = (cur + 1) >> 1;
1277 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1278 }
1279
1280 /* Declare address variables */
1281 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1282 {
1283 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1284 }
1285
1286 /* Declare texture coordinate temporaries and initialize them */
1287 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1288 {
1289 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1290 }
1291
1292 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1293 * helper function shader that is linked in at link time
1294 */
1295 if (pshader && reg_maps->shader_version.major >= 3)
1296 {
1297 if (use_vs(device->stateBlock))
1298 {
1299 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1300 } else {
1301 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1302 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1303 * pixel shader that reads the fixed function color into the packed input registers.
1304 */
1305 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1306 }
1307 }
1308
1309 /* Declare output register temporaries */
1310 if(This->baseShader.limits.packed_output) {
1311 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1312 }
1313
1314 /* Declare temporary variables */
1315 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1316 {
1317 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1318 }
1319
1320 /* Declare attributes */
1321 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1322 {
1323 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1324 {
1325 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1326 }
1327 }
1328
1329 /* Declare loop registers aLx */
1330 for (i = 0; i < reg_maps->loop_depth; i++) {
1331 shader_addline(buffer, "int aL%u;\n", i);
1332 shader_addline(buffer, "int tmpInt%u;\n", i);
1333 }
1334
1335 /* Temporary variables for matrix operations */
1336 shader_addline(buffer, "vec4 tmp0;\n");
1337 shader_addline(buffer, "vec4 tmp1;\n");
1338#ifdef VBOX_WITH_VMSVGA
1339 shader_addline(buffer, "bool p0[4];\n");
1340#endif
1341
1342 /* Local constants use a different name so they can be loaded once at shader link time
1343 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1344 * float -> string conversion can cause precision loss.
1345 */
1346 if(!This->baseShader.load_local_constsF) {
1347 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1348 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1349 }
1350 }
1351
1352 shader_addline(buffer, "const float FLT_MAX = 1e38;\n");
1353
1354 /* Start the main program */
1355 shader_addline(buffer, "void main() {\n");
1356 if(pshader && reg_maps->vpos) {
1357 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1358 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1359 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1360 * precision troubles when we just substract 0.5.
1361 *
1362 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1363 *
1364 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1365 *
1366 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1367 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1368 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1369 * correctly on drivers that returns integer values.
1370 */
1371 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1372 }
1373}
1374
1375/*****************************************************************************
1376 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1377 *
1378 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1379 ****************************************************************************/
1380
1381/* Prototypes */
1382static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1383 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1384
1385/** Used for opcode modifiers - They multiply the result by the specified amount */
1386static const char * const shift_glsl_tab[] = {
1387 "", /* 0 (none) */
1388 "2.0 * ", /* 1 (x2) */
1389 "4.0 * ", /* 2 (x4) */
1390 "8.0 * ", /* 3 (x8) */
1391 "16.0 * ", /* 4 (x16) */
1392 "32.0 * ", /* 5 (x32) */
1393 "", /* 6 (x64) */
1394 "", /* 7 (x128) */
1395 "", /* 8 (d256) */
1396 "", /* 9 (d128) */
1397 "", /* 10 (d64) */
1398 "", /* 11 (d32) */
1399 "0.0625 * ", /* 12 (d16) */
1400 "0.125 * ", /* 13 (d8) */
1401 "0.25 * ", /* 14 (d4) */
1402 "0.5 * " /* 15 (d2) */
1403};
1404
1405/* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1406static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1407{
1408 out_str[0] = 0;
1409
1410 switch (src_modifier)
1411 {
1412 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1413 case WINED3DSPSM_DW:
1414 case WINED3DSPSM_NONE:
1415 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1416 break;
1417 case WINED3DSPSM_NEG:
1418 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1419 break;
1420 case WINED3DSPSM_NOT:
1421 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1422 break;
1423 case WINED3DSPSM_BIAS:
1424 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1425 break;
1426 case WINED3DSPSM_BIASNEG:
1427 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1428 break;
1429 case WINED3DSPSM_SIGN:
1430 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1431 break;
1432 case WINED3DSPSM_SIGNNEG:
1433 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1434 break;
1435 case WINED3DSPSM_COMP:
1436 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1437 break;
1438 case WINED3DSPSM_X2:
1439 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1440 break;
1441 case WINED3DSPSM_X2NEG:
1442 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1443 break;
1444 case WINED3DSPSM_ABS:
1445 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1446 break;
1447 case WINED3DSPSM_ABSNEG:
1448 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1449 break;
1450 default:
1451 FIXME("Unhandled modifier %u\n", src_modifier);
1452 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1453 }
1454}
1455
1456/** Writes the GLSL variable name that corresponds to the register that the
1457 * DX opcode parameter is trying to access */
1458static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1459 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1460{
1461 /* oPos, oFog and oPts in D3D */
1462 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1463
1464 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1465 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1466 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1467
1468 *is_color = FALSE;
1469
1470 switch (reg->type)
1471 {
1472 case WINED3DSPR_TEMP:
1473 sprintf(register_name, "R%u", reg->idx);
1474 break;
1475
1476 case WINED3DSPR_INPUT:
1477 /* vertex shaders */
1478 if (!pshader)
1479 {
1480 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1481 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1482 sprintf(register_name, "attrib%u", reg->idx);
1483 break;
1484 }
1485
1486 /* pixel shaders >= 3.0 */
1487 if (This->baseShader.reg_maps.shader_version.major >= 3)
1488 {
1489 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1490 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1491
1492 if (reg->rel_addr)
1493 {
1494 glsl_src_param_t rel_param;
1495
1496 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1497
1498 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1499 * operation there */
1500 if (idx)
1501 {
1502 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1503 {
1504 sprintf(register_name,
1505 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1506 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1507 rel_param.param_str, idx);
1508 }
1509 else
1510 {
1511 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1512 }
1513 }
1514 else
1515 {
1516 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1517 {
1518 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1519 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1520 rel_param.param_str);
1521 }
1522 else
1523 {
1524 sprintf(register_name, "IN[%s]", rel_param.param_str);
1525 }
1526 }
1527 }
1528 else
1529 {
1530 if (idx == in_count) sprintf(register_name, "gl_Color");
1531 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1532 else sprintf(register_name, "IN[%u]", idx);
1533 }
1534 }
1535 else
1536 {
1537 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1538 else strcpy(register_name, "gl_SecondaryColor");
1539 break;
1540 }
1541 break;
1542
1543 case WINED3DSPR_CONST:
1544 {
1545 const char prefix = pshader ? 'P' : 'V';
1546
1547 /* Relative addressing */
1548 if (reg->rel_addr)
1549 {
1550 glsl_src_param_t rel_param;
1551 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1552 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1553 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1554 }
1555 else
1556 {
1557 if (shader_constant_is_local(This, reg->idx))
1558 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1559 else
1560 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1561 }
1562 }
1563 break;
1564
1565 case WINED3DSPR_CONSTINT:
1566 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1567 else sprintf(register_name, "VI[%u]", reg->idx);
1568 break;
1569
1570 case WINED3DSPR_CONSTBOOL:
1571 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1572 else sprintf(register_name, "VB[%u]", reg->idx);
1573 break;
1574
1575 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1576 if (pshader) sprintf(register_name, "T%u", reg->idx);
1577 else sprintf(register_name, "A%u", reg->idx);
1578 break;
1579
1580 case WINED3DSPR_LOOP:
1581 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1582 break;
1583
1584 case WINED3DSPR_SAMPLER:
1585 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1586 else sprintf(register_name, "Vsampler%u", reg->idx);
1587 break;
1588
1589 case WINED3DSPR_COLOROUT:
1590 if (reg->idx >= gl_info->limits.buffers)
1591 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1592
1593 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1594 break;
1595
1596 case WINED3DSPR_RASTOUT:
1597 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1598 break;
1599
1600 case WINED3DSPR_DEPTHOUT:
1601 sprintf(register_name, "gl_FragDepth");
1602 break;
1603
1604 case WINED3DSPR_ATTROUT:
1605 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1606 else sprintf(register_name, "gl_FrontSecondaryColor");
1607 break;
1608
1609 case WINED3DSPR_TEXCRDOUT:
1610 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1611 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1612 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1613 break;
1614
1615 case WINED3DSPR_MISCTYPE:
1616 if (reg->idx == 0)
1617 {
1618 /* vPos */
1619 sprintf(register_name, "vpos");
1620 }
1621 else if (reg->idx == 1)
1622 {
1623 /* Note that gl_FrontFacing is a bool, while vFace is
1624 * a float for which the sign determines front/back */
1625 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1626 }
1627 else
1628 {
1629 FIXME("Unhandled misctype register %d\n", reg->idx);
1630 sprintf(register_name, "unrecognized_register");
1631 }
1632 break;
1633
1634 case WINED3DSPR_IMMCONST:
1635 switch (reg->immconst_type)
1636 {
1637 case WINED3D_IMMCONST_FLOAT:
1638 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1639 break;
1640
1641 case WINED3D_IMMCONST_FLOAT4:
1642 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1643 *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1644 *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1645 break;
1646
1647 default:
1648 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1649 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1650 }
1651 break;
1652
1653#ifdef VBOX_WITH_VMSVGA
1654 case WINED3DSPR_PREDICATE:
1655 sprintf(register_name, "p0");
1656 break;
1657#endif
1658
1659 default:
1660 FIXME("Unhandled register name Type(%d)\n", reg->type);
1661 sprintf(register_name, "unrecognized_register");
1662 break;
1663 }
1664}
1665
1666static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1667{
1668 *str++ = '.';
1669 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1670 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1671 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1672 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1673 *str = '\0';
1674}
1675
1676/* Get the GLSL write mask for the destination register */
1677static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1678{
1679 DWORD mask = param->write_mask;
1680
1681 if (shader_is_scalar(&param->reg))
1682 {
1683 mask = WINED3DSP_WRITEMASK_0;
1684 *write_mask = '\0';
1685 }
1686 else
1687 {
1688#ifdef VBOX_WITH_VMSVGA
1689 if (param->reg.type == WINED3DSPR_PREDICATE)
1690 {
1691 *write_mask++ = '[';
1692 if (mask & WINED3DSP_WRITEMASK_0) *write_mask++ = '0';
1693 else
1694 if (mask & WINED3DSP_WRITEMASK_1) *write_mask++ = '1';
1695 else
1696 if (mask & WINED3DSP_WRITEMASK_2) *write_mask++ = '2';
1697 else
1698 if (mask & WINED3DSP_WRITEMASK_3) *write_mask++ = '3';
1699 *write_mask++ = ']';
1700 *write_mask = '\0';
1701 }
1702 else
1703#endif
1704 shader_glsl_write_mask_to_str(mask, write_mask);
1705 }
1706
1707 return mask;
1708}
1709
1710static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1711 unsigned int size = 0;
1712
1713 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1714 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1715 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1716 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1717
1718 return size;
1719}
1720
1721static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1722{
1723 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1724 * but addressed as "rgba". To fix this we need to swap the register's x
1725 * and z components. */
1726 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1727
1728 *str++ = '.';
1729 /* swizzle bits fields: wwzzyyxx */
1730 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1731 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1732 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1733 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1734 *str = '\0';
1735}
1736
1737static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1738 BOOL fixup, DWORD mask, char *swizzle_str)
1739{
1740 if (shader_is_scalar(&param->reg))
1741 *swizzle_str = '\0';
1742 else
1743 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1744}
1745
1746/* From a given parameter token, generate the corresponding GLSL string.
1747 * Also, return the actual register name and swizzle in case the
1748 * caller needs this information as well. */
1749static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1750 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1751{
1752 BOOL is_color = FALSE;
1753 char swizzle_str[6];
1754
1755 glsl_src->reg_name[0] = '\0';
1756 glsl_src->param_str[0] = '\0';
1757 swizzle_str[0] = '\0';
1758
1759 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1760 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1761 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1762}
1763
1764/* From a given parameter token, generate the corresponding GLSL string.
1765 * Also, return the actual register name and swizzle in case the
1766 * caller needs this information as well. */
1767static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1768 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1769{
1770 BOOL is_color = FALSE;
1771
1772 glsl_dst->mask_str[0] = '\0';
1773 glsl_dst->reg_name[0] = '\0';
1774
1775 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1776 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1777}
1778
1779/* Append the destination part of the instruction to the buffer, return the effective write mask */
1780static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1781 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1782{
1783 glsl_dst_param_t glsl_dst;
1784 DWORD mask;
1785
1786 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1787 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1788
1789 return mask;
1790}
1791
1792/* Append the destination part of the instruction to the buffer, return the effective write mask */
1793static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1794{
1795 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1796}
1797
1798/** Process GLSL instruction modifiers */
1799static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1800{
1801 glsl_dst_param_t dst_param;
1802 DWORD modifiers;
1803
1804 if (!ins->dst_count) return;
1805
1806 modifiers = ins->dst[0].modifiers;
1807 if (!modifiers) return;
1808
1809 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1810
1811 if (modifiers & WINED3DSPDM_SATURATE)
1812 {
1813 /* _SAT means to clamp the value of the register to between 0 and 1 */
1814 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1815 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1816 }
1817
1818 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1819 {
1820 FIXME("_centroid modifier not handled\n");
1821 }
1822
1823 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1824 {
1825 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1826 }
1827}
1828
1829static inline const char *shader_get_comp_op(DWORD op)
1830{
1831 switch (op) {
1832 case COMPARISON_GT: return ">";
1833 case COMPARISON_EQ: return "==";
1834 case COMPARISON_GE: return ">=";
1835 case COMPARISON_LT: return "<";
1836 case COMPARISON_NE: return "!=";
1837 case COMPARISON_LE: return "<=";
1838 default:
1839 FIXME("Unrecognized comparison value: %u\n", op);
1840 return "(\?\?)";
1841 }
1842}
1843
1844static void shader_glsl_get_sample_function(const struct wined3d_gl_info *gl_info,
1845 DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1846{
1847 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1848 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1849 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1850 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1851
1852 /* Note that there's no such thing as a projected cube texture. */
1853 switch(sampler_type) {
1854 case WINED3DSTT_1D:
1855 if(lod) {
1856 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1857 }
1858 else if (grad)
1859 {
1860 if (gl_info->supported[EXT_GPU_SHADER4])
1861 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1862 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1863 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1864 else
1865 {
1866 FIXME("Unsupported 1D grad function.\n");
1867 sample_function->name = "unsupported1DGrad";
1868 }
1869 }
1870 else
1871 {
1872 sample_function->name = projected ? "texture1DProj" : "texture1D";
1873 }
1874 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1875 break;
1876 case WINED3DSTT_2D:
1877 if(texrect) {
1878 if(lod) {
1879 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1880 }
1881 else if (grad)
1882 {
1883 if (gl_info->supported[EXT_GPU_SHADER4])
1884 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1885 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1886 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1887 else
1888 {
1889 FIXME("Unsupported RECT grad function.\n");
1890 sample_function->name = "unsupported2DRectGrad";
1891 }
1892 }
1893 else
1894 {
1895 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1896 }
1897 } else {
1898 if(lod) {
1899 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1900 }
1901 else if (grad)
1902 {
1903 if (gl_info->supported[EXT_GPU_SHADER4])
1904 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1905 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1906 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1907 else
1908 {
1909 FIXME("Unsupported 2D grad function.\n");
1910 sample_function->name = "unsupported2DGrad";
1911 }
1912 }
1913 else
1914 {
1915 sample_function->name = projected ? "texture2DProj" : "texture2D";
1916 }
1917 }
1918 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1919 break;
1920 case WINED3DSTT_CUBE:
1921 if(lod) {
1922 sample_function->name = "textureCubeLod";
1923 }
1924 else if (grad)
1925 {
1926 if (gl_info->supported[EXT_GPU_SHADER4])
1927 sample_function->name = "textureCubeGrad";
1928 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1929 sample_function->name = "textureCubeGradARB";
1930 else
1931 {
1932 FIXME("Unsupported Cube grad function.\n");
1933 sample_function->name = "unsupportedCubeGrad";
1934 }
1935 }
1936 else
1937 {
1938 sample_function->name = "textureCube";
1939 }
1940 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1941 break;
1942 case WINED3DSTT_VOLUME:
1943 if(lod) {
1944 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1945 }
1946 else if (grad)
1947 {
1948 if (gl_info->supported[EXT_GPU_SHADER4])
1949 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1950 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1951 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1952 else
1953 {
1954 FIXME("Unsupported 3D grad function.\n");
1955 sample_function->name = "unsupported3DGrad";
1956 }
1957 }
1958 else
1959 {
1960 sample_function->name = projected ? "texture3DProj" : "texture3D";
1961 }
1962 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1963 break;
1964 default:
1965 sample_function->name = "";
1966 sample_function->coord_mask = 0;
1967 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1968 break;
1969 }
1970}
1971
1972static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1973 BOOL sign_fixup, enum fixup_channel_source channel_source)
1974{
1975 switch(channel_source)
1976 {
1977 case CHANNEL_SOURCE_ZERO:
1978 strcat(arguments, "0.0");
1979 break;
1980
1981 case CHANNEL_SOURCE_ONE:
1982 strcat(arguments, "1.0");
1983 break;
1984
1985 case CHANNEL_SOURCE_X:
1986 strcat(arguments, reg_name);
1987 strcat(arguments, ".x");
1988 break;
1989
1990 case CHANNEL_SOURCE_Y:
1991 strcat(arguments, reg_name);
1992 strcat(arguments, ".y");
1993 break;
1994
1995 case CHANNEL_SOURCE_Z:
1996 strcat(arguments, reg_name);
1997 strcat(arguments, ".z");
1998 break;
1999
2000 case CHANNEL_SOURCE_W:
2001 strcat(arguments, reg_name);
2002 strcat(arguments, ".w");
2003 break;
2004
2005 default:
2006 FIXME("Unhandled channel source %#x\n", channel_source);
2007 strcat(arguments, "undefined");
2008 break;
2009 }
2010
2011 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
2012}
2013
2014static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
2015{
2016 struct wined3d_shader_dst_param dst;
2017 unsigned int mask_size, remaining;
2018 glsl_dst_param_t dst_param;
2019 char arguments[256];
2020 DWORD mask;
2021
2022 mask = 0;
2023 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
2024 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
2025 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
2026 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
2027 mask &= ins->dst[0].write_mask;
2028
2029 if (!mask) return; /* Nothing to do */
2030
2031 if (is_complex_fixup(fixup))
2032 {
2033 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
2034 FIXME("Complex fixup (%#x) not supported\n",complex_fixup); (void)complex_fixup;
2035 return;
2036 }
2037
2038 mask_size = shader_glsl_get_write_mask_size(mask);
2039
2040 dst = ins->dst[0];
2041 dst.write_mask = mask;
2042 shader_glsl_add_dst_param(ins, &dst, &dst_param);
2043
2044 arguments[0] = '\0';
2045 remaining = mask_size;
2046 if (mask & WINED3DSP_WRITEMASK_0)
2047 {
2048 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
2049 if (--remaining) strcat(arguments, ", ");
2050 }
2051 if (mask & WINED3DSP_WRITEMASK_1)
2052 {
2053 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
2054 if (--remaining) strcat(arguments, ", ");
2055 }
2056 if (mask & WINED3DSP_WRITEMASK_2)
2057 {
2058 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
2059 if (--remaining) strcat(arguments, ", ");
2060 }
2061 if (mask & WINED3DSP_WRITEMASK_3)
2062 {
2063 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2064 if (--remaining) strcat(arguments, ", ");
2065 }
2066
2067 if (mask_size > 1)
2068 {
2069 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2070 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2071 }
2072 else
2073 {
2074 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2075 }
2076}
2077
2078static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2079 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
2080 const char *dx, const char *dy,
2081 const char *bias, const char *coord_reg_fmt, ...)
2082{
2083 const char *sampler_base;
2084 char dst_swizzle[6];
2085 struct color_fixup_desc fixup;
2086 BOOL np2_fixup = FALSE;
2087 BOOL tmirror_tmp_reg = FALSE;
2088 va_list args;
2089
2090 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2091
2092 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2093 {
2094 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2095 fixup = priv->cur_ps_args->color_fixup[sampler];
2096 sampler_base = "Psampler";
2097
2098 if (priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2099 if(bias) {
2100 FIXME("Biased sampling from NP2 textures is unsupported\n");
2101 } else {
2102 np2_fixup = TRUE;
2103 }
2104 }
2105
2106 if (priv->cur_ps_args->t_mirror & (1 << sampler))
2107 {
2108 if (ins->ctx->reg_maps->sampler_type[sampler]==WINED3DSTT_2D)
2109 {
2110 if (sample_function->coord_mask & WINED3DSP_WRITEMASK_1)
2111 {
2112 glsl_src_param_t coord_param;
2113 shader_glsl_add_src_param(ins, &ins->src[0], sample_function->coord_mask, &coord_param);
2114
2115 if (ins->src[0].reg.type != WINED3DSPR_INPUT)
2116 {
2117 shader_addline(ins->ctx->buffer, "%s.y=1.0-%s.y;\n",
2118 coord_param.reg_name, coord_param.reg_name);
2119 }
2120 else
2121 {
2122 tmirror_tmp_reg = TRUE;
2123 shader_addline(ins->ctx->buffer, "tmp0.xy=vec2(%s.x, 1.0-%s.y).xy;\n",
2124 coord_param.reg_name, coord_param.reg_name);
2125 }
2126 }
2127 else
2128 {
2129 DebugBreak();
2130 FIXME("Unexpected coord_mask with t_mirror\n");
2131 }
2132 }
2133 }
2134 } else {
2135 sampler_base = "Vsampler";
2136 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2137 }
2138
2139 shader_glsl_append_dst(ins->ctx->buffer, ins);
2140
2141 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2142
2143 if (tmirror_tmp_reg)
2144 {
2145 shader_addline(ins->ctx->buffer, "%s", "tmp0.xy");
2146 }
2147 else
2148 {
2149 va_start(args, coord_reg_fmt);
2150 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2151 va_end(args);
2152 }
2153
2154 if(bias) {
2155 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2156 } else {
2157 if (np2_fixup) {
2158 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2159 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2160
2161 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2162 (idx % 2) ? "zw" : "xy", dst_swizzle);
2163 } else if(dx && dy) {
2164 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2165 } else {
2166 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2167 }
2168 }
2169
2170 if(!is_identity_fixup(fixup)) {
2171 shader_glsl_color_correction(ins, fixup);
2172 }
2173}
2174
2175/*****************************************************************************
2176 * Begin processing individual instruction opcodes
2177 ****************************************************************************/
2178
2179/* Generate GLSL arithmetic functions (dst = src1 + src2) */
2180static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2181{
2182 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2183 glsl_src_param_t src0_param;
2184 glsl_src_param_t src1_param;
2185 DWORD write_mask;
2186 char op;
2187
2188 /* Determine the GLSL operator to use based on the opcode */
2189 switch (ins->handler_idx)
2190 {
2191 case WINED3DSIH_MUL: op = '*'; break;
2192 case WINED3DSIH_ADD: op = '+'; break;
2193 case WINED3DSIH_SUB: op = '-'; break;
2194 default:
2195 op = ' ';
2196 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2197 break;
2198 }
2199
2200 write_mask = shader_glsl_append_dst(buffer, ins);
2201 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2202 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2203 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2204}
2205
2206#ifdef VBOX_WITH_VMSVGA
2207static void shader_glsl_mov_impl(const struct wined3d_shader_instruction *ins, int p0_idx);
2208
2209/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2210static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2211{
2212 if (ins->predicate)
2213 {
2214 int i;
2215 DWORD dst_mask = ins->dst[0].write_mask;
2216 struct wined3d_shader_dst_param *dst = (struct wined3d_shader_dst_param *)&ins->dst[0];
2217
2218 for (i = 0; i < 4; i++)
2219 {
2220 if (dst_mask & RT_BIT(i))
2221 {
2222 dst->write_mask = RT_BIT(i);
2223
2224 shader_glsl_mov_impl(ins, i);
2225 }
2226 }
2227 dst->write_mask = dst_mask;
2228 }
2229 else
2230 shader_glsl_mov_impl(ins, 0);
2231}
2232
2233/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2234static void shader_glsl_mov_impl(const struct wined3d_shader_instruction *ins, int p0_idx)
2235
2236#else
2237/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2238static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2239#endif
2240{
2241 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2242 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2243 glsl_src_param_t src0_param;
2244 DWORD write_mask;
2245
2246#ifdef VBOX_WITH_VMSVGA
2247 if (ins->predicate)
2248 {
2249 shader_addline(buffer, "if (p0[%d]) {\n", p0_idx);
2250 }
2251#endif
2252
2253 write_mask = shader_glsl_append_dst(buffer, ins);
2254 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2255
2256 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2257 * shader versions WINED3DSIO_MOVA is used for this. */
2258 if (ins->ctx->reg_maps->shader_version.major == 1
2259 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2260 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2261 {
2262 /* This is a simple floor() */
2263 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2264 if (mask_size > 1) {
2265 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2266 } else {
2267 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2268 }
2269 }
2270 else if(ins->handler_idx == WINED3DSIH_MOVA)
2271 {
2272 /* We need to *round* to the nearest int here. */
2273 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2274
2275 if (gl_info->supported[EXT_GPU_SHADER4])
2276 {
2277 if (mask_size > 1)
2278 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2279 else
2280 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2281 }
2282 else
2283 {
2284 if (mask_size > 1)
2285 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2286 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2287 else
2288 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2289 src0_param.param_str, src0_param.param_str);
2290 }
2291 }
2292 else
2293 {
2294 shader_addline(buffer, "%s);\n", src0_param.param_str);
2295 }
2296#ifdef VBOX_WITH_VMSVGA
2297 if (ins->predicate)
2298 {
2299 shader_addline(buffer, "}\n");
2300 }
2301#endif
2302}
2303
2304/* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2305static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2306{
2307 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2308 glsl_src_param_t src0_param;
2309 glsl_src_param_t src1_param;
2310 DWORD dst_write_mask, src_write_mask;
2311 unsigned int dst_size = 0;
2312
2313 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2314 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2315
2316 /* dp3 works on vec3, dp4 on vec4 */
2317 if (ins->handler_idx == WINED3DSIH_DP4)
2318 {
2319 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2320 } else {
2321 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2322 }
2323
2324 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2325 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2326
2327 if (dst_size > 1) {
2328 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2329 } else {
2330 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2331 }
2332}
2333
2334/* Note that this instruction has some restrictions. The destination write mask
2335 * can't contain the w component, and the source swizzles have to be .xyzw */
2336static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2337{
2338 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2339 glsl_src_param_t src0_param;
2340 glsl_src_param_t src1_param;
2341 char dst_mask[6];
2342
2343 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2344 shader_glsl_append_dst(ins->ctx->buffer, ins);
2345 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2346 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2347 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2348}
2349
2350/* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2351 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2352 * GLSL uses the value as-is. */
2353static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2354{
2355 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2356 glsl_src_param_t src0_param;
2357 glsl_src_param_t src1_param;
2358 DWORD dst_write_mask;
2359 unsigned int dst_size;
2360
2361 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2362 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2363
2364 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2365 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2366
2367 if (dst_size > 1) {
2368 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2369 } else {
2370 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
2371 }
2372}
2373
2374/* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2375 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2376 * GLSL uses the value as-is. */
2377static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2378{
2379 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2380 glsl_src_param_t src0_param;
2381 DWORD dst_write_mask;
2382 unsigned int dst_size;
2383
2384 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2385 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2386
2387 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2388
2389 if (dst_size > 1)
2390 {
2391 shader_addline(buffer, "vec%d(%s == 0.0 ? -FLT_MAX : log2(abs(%s))));\n",
2392 dst_size, src0_param.param_str, src0_param.param_str);
2393 }
2394 else
2395 {
2396 shader_addline(buffer, "%s == 0.0 ? -FLT_MAX : log2(abs(%s)));\n",
2397 src0_param.param_str, src0_param.param_str);
2398 }
2399}
2400
2401/* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2402static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2403{
2404 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2405 glsl_src_param_t src_param;
2406 const char *instruction;
2407 DWORD write_mask;
2408 unsigned i;
2409
2410 /* Determine the GLSL function to use based on the opcode */
2411 /* TODO: Possibly make this a table for faster lookups */
2412 switch (ins->handler_idx)
2413 {
2414 case WINED3DSIH_MIN: instruction = "min"; break;
2415 case WINED3DSIH_MAX: instruction = "max"; break;
2416 case WINED3DSIH_ABS: instruction = "abs"; break;
2417 case WINED3DSIH_FRC: instruction = "fract"; break;
2418 case WINED3DSIH_EXP: instruction = "exp2"; break;
2419 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2420 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2421 default: instruction = "";
2422 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2423 break;
2424 }
2425
2426 write_mask = shader_glsl_append_dst(buffer, ins);
2427
2428 shader_addline(buffer, "%s(", instruction);
2429
2430 if (ins->src_count)
2431 {
2432 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2433 shader_addline(buffer, "%s", src_param.param_str);
2434 for (i = 1; i < ins->src_count; ++i)
2435 {
2436 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2437 shader_addline(buffer, ", %s", src_param.param_str);
2438 }
2439 }
2440
2441 shader_addline(buffer, "));\n");
2442}
2443
2444static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2445{
2446 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2447 glsl_src_param_t src_param;
2448 unsigned int mask_size;
2449 DWORD write_mask;
2450 char dst_mask[6];
2451
2452 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2453 mask_size = shader_glsl_get_write_mask_size(write_mask);
2454 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2455
2456 shader_addline(buffer, "tmp0.x = length(%s);\n", src_param.param_str);
2457 shader_glsl_append_dst(buffer, ins);
2458 if (mask_size > 1)
2459 {
2460 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s / tmp0.x));\n",
2461 mask_size, src_param.param_str);
2462 }
2463 else
2464 {
2465 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s / tmp0.x));\n",
2466 src_param.param_str);
2467 }
2468}
2469
2470/** Process the WINED3DSIO_EXPP instruction in GLSL:
2471 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2472 * dst.x = 2^(floor(src))
2473 * dst.y = src - floor(src)
2474 * dst.z = 2^src (partial precision is allowed, but optional)
2475 * dst.w = 1.0;
2476 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2477 * dst = 2^src; (partial precision is allowed, but optional)
2478 */
2479static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2480{
2481 glsl_src_param_t src_param;
2482
2483 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2484
2485 if (ins->ctx->reg_maps->shader_version.major < 2)
2486 {
2487 char dst_mask[6];
2488
2489 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2490 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2491 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2492 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2493
2494 shader_glsl_append_dst(ins->ctx->buffer, ins);
2495 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2496 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2497 } else {
2498 DWORD write_mask;
2499 unsigned int mask_size;
2500
2501 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2502 mask_size = shader_glsl_get_write_mask_size(write_mask);
2503
2504 if (mask_size > 1) {
2505 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2506 } else {
2507 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2508 }
2509 }
2510}
2511
2512/** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2513static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2514{
2515 glsl_src_param_t src_param;
2516 DWORD write_mask;
2517 unsigned int mask_size;
2518
2519 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2520 mask_size = shader_glsl_get_write_mask_size(write_mask);
2521 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2522
2523 if (mask_size > 1)
2524 {
2525 shader_addline(ins->ctx->buffer, "vec%d(%s == 0.0 ? FLT_MAX : 1.0 / %s));\n",
2526 mask_size, src_param.param_str, src_param.param_str);
2527 }
2528 else
2529 {
2530 shader_addline(ins->ctx->buffer, "%s == 0.0 ? FLT_MAX : 1.0 / %s);\n",
2531 src_param.param_str, src_param.param_str);
2532 }
2533}
2534
2535static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2536{
2537 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2538 glsl_src_param_t src_param;
2539 DWORD write_mask;
2540 unsigned int mask_size;
2541
2542 write_mask = shader_glsl_append_dst(buffer, ins);
2543 mask_size = shader_glsl_get_write_mask_size(write_mask);
2544
2545 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2546
2547 if (mask_size > 1)
2548 {
2549 shader_addline(buffer, "vec%d(%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s))));\n",
2550 mask_size, src_param.param_str, src_param.param_str);
2551 }
2552 else
2553 {
2554 shader_addline(buffer, "%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s)));\n",
2555 src_param.param_str, src_param.param_str);
2556 }
2557}
2558
2559#ifdef VBOX_WITH_VMSVGA
2560static void shader_glsl_setp(const struct wined3d_shader_instruction *ins)
2561{
2562 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2563 glsl_src_param_t src_param1, src_param2;
2564 DWORD write_mask;
2565
2566 int i;
2567 DWORD dst_mask = ins->dst[0].write_mask;
2568 struct wined3d_shader_dst_param dst = ins->dst[0];
2569
2570 /* Cycle through all source0 channels */
2571 for (i=0; i<4; i++) {
2572 if (dst_mask & RT_BIT(i))
2573 {
2574 write_mask = WINED3DSP_WRITEMASK_0 << i;
2575 dst.write_mask = dst_mask & write_mask;
2576
2577 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2578 Assert(write_mask);
2579
2580 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param1);
2581 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src_param2);
2582
2583 shader_addline(buffer, "%s %s %s);\n",
2584 src_param1.param_str, shader_get_comp_op(ins->flags), src_param2.param_str);
2585 }
2586 }
2587}
2588#endif
2589
2590/** Process signed comparison opcodes in GLSL. */
2591static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2592{
2593 glsl_src_param_t src0_param;
2594 glsl_src_param_t src1_param;
2595 DWORD write_mask;
2596 unsigned int mask_size;
2597
2598 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2599 mask_size = shader_glsl_get_write_mask_size(write_mask);
2600 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2601 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2602
2603 if (mask_size > 1) {
2604 const char *compare;
2605
2606 switch(ins->handler_idx)
2607 {
2608 case WINED3DSIH_SLT: compare = "lessThan"; break;
2609 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2610 default: compare = "";
2611 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2612 }
2613
2614 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2615 src0_param.param_str, src1_param.param_str);
2616 } else {
2617 switch(ins->handler_idx)
2618 {
2619 case WINED3DSIH_SLT:
2620 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2621 * to return 0.0 but step returns 1.0 because step is not < x
2622 * An alternative is a bvec compare padded with an unused second component.
2623 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2624 * issue. Playing with not() is not possible either because not() does not accept
2625 * a scalar.
2626 */
2627 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2628 src0_param.param_str, src1_param.param_str);
2629 break;
2630 case WINED3DSIH_SGE:
2631 /* Here we can use the step() function and safe a conditional */
2632 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2633 break;
2634 default:
2635 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2636 }
2637
2638 }
2639}
2640
2641/** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2642static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2643{
2644 glsl_src_param_t src0_param;
2645 glsl_src_param_t src1_param;
2646 glsl_src_param_t src2_param;
2647 DWORD write_mask, cmp_channel = 0;
2648 unsigned int i, j;
2649 char mask_char[6];
2650 BOOL temp_destination = FALSE;
2651
2652 if (shader_is_scalar(&ins->src[0].reg))
2653 {
2654 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2655
2656 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2657 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2658 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2659
2660 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2661 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2662 } else {
2663 DWORD dst_mask = ins->dst[0].write_mask;
2664 struct wined3d_shader_dst_param dst = ins->dst[0];
2665
2666 /* Cycle through all source0 channels */
2667 for (i=0; i<4; i++) {
2668 write_mask = 0;
2669 /* Find the destination channels which use the current source0 channel */
2670 for (j=0; j<4; j++) {
2671 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2672 {
2673 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2674 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2675 }
2676 }
2677 dst.write_mask = dst_mask & write_mask;
2678
2679 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2680 * The first lines may overwrite source parameters of the following lines.
2681 * Deal with that by using a temporary destination register if needed
2682 */
2683 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2684 && ins->src[0].reg.type == ins->dst[0].reg.type)
2685 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2686 && ins->src[1].reg.type == ins->dst[0].reg.type)
2687 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2688 && ins->src[2].reg.type == ins->dst[0].reg.type))
2689 {
2690 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2691 if (!write_mask) continue;
2692 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2693 temp_destination = TRUE;
2694 } else {
2695 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2696 if (!write_mask) continue;
2697 }
2698
2699 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2700 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2701 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2702
2703 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2704 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2705 }
2706
2707 if(temp_destination) {
2708 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2709 shader_glsl_append_dst(ins->ctx->buffer, ins);
2710 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2711 }
2712 }
2713
2714}
2715
2716/** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2717/* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2718 * the compare is done per component of src0. */
2719static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2720{
2721 struct wined3d_shader_dst_param dst;
2722 glsl_src_param_t src0_param;
2723 glsl_src_param_t src1_param;
2724 glsl_src_param_t src2_param;
2725 DWORD write_mask, cmp_channel = 0;
2726 unsigned int i, j;
2727 DWORD dst_mask;
2728 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2729 ins->ctx->reg_maps->shader_version.minor);
2730
2731 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2732 {
2733 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2734 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2735 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2736 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2737
2738 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2739 if (ins->coissue)
2740 {
2741 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2742 } else {
2743 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2744 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2745 }
2746 return;
2747 }
2748 /* Cycle through all source0 channels */
2749 dst_mask = ins->dst[0].write_mask;
2750 dst = ins->dst[0];
2751 for (i=0; i<4; i++) {
2752 write_mask = 0;
2753 /* Find the destination channels which use the current source0 channel */
2754 for (j=0; j<4; j++) {
2755 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2756 {
2757 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2758 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2759 }
2760 }
2761
2762 dst.write_mask = dst_mask & write_mask;
2763 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2764 if (!write_mask) continue;
2765
2766 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2767 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2768 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2769
2770 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2771 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2772 }
2773}
2774
2775/** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2776static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2777{
2778 glsl_src_param_t src0_param;
2779 glsl_src_param_t src1_param;
2780 glsl_src_param_t src2_param;
2781 DWORD write_mask;
2782
2783 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2784 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2785 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2786 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2787 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2788 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2789}
2790
2791/* Handles transforming all WINED3DSIO_M?x? opcodes for
2792 Vertex shaders to GLSL codes */
2793static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2794{
2795 int i;
2796 int nComponents = 0;
2797 struct wined3d_shader_dst_param tmp_dst = {{0}};
2798 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2799 struct wined3d_shader_instruction tmp_ins;
2800
2801 memset(&tmp_ins, 0, sizeof(tmp_ins));
2802
2803 /* Set constants for the temporary argument */
2804 tmp_ins.ctx = ins->ctx;
2805 tmp_ins.dst_count = 1;
2806 tmp_ins.dst = &tmp_dst;
2807 tmp_ins.src_count = 2;
2808 tmp_ins.src = tmp_src;
2809
2810 switch(ins->handler_idx)
2811 {
2812 case WINED3DSIH_M4x4:
2813 nComponents = 4;
2814 tmp_ins.handler_idx = WINED3DSIH_DP4;
2815 break;
2816 case WINED3DSIH_M4x3:
2817 nComponents = 3;
2818 tmp_ins.handler_idx = WINED3DSIH_DP4;
2819 break;
2820 case WINED3DSIH_M3x4:
2821 nComponents = 4;
2822 tmp_ins.handler_idx = WINED3DSIH_DP3;
2823 break;
2824 case WINED3DSIH_M3x3:
2825 nComponents = 3;
2826 tmp_ins.handler_idx = WINED3DSIH_DP3;
2827 break;
2828 case WINED3DSIH_M3x2:
2829 nComponents = 2;
2830 tmp_ins.handler_idx = WINED3DSIH_DP3;
2831 break;
2832 default:
2833 break;
2834 }
2835
2836 tmp_dst = ins->dst[0];
2837 tmp_src[0] = ins->src[0];
2838 tmp_src[1] = ins->src[1];
2839 for (i = 0; i < nComponents; ++i)
2840 {
2841 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2842 shader_glsl_dot(&tmp_ins);
2843 ++tmp_src[1].reg.idx;
2844 }
2845}
2846
2847/**
2848 The LRP instruction performs a component-wise linear interpolation
2849 between the second and third operands using the first operand as the
2850 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2851 This is equivalent to mix(src2, src1, src0);
2852*/
2853static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2854{
2855 glsl_src_param_t src0_param;
2856 glsl_src_param_t src1_param;
2857 glsl_src_param_t src2_param;
2858 DWORD write_mask;
2859
2860 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2861
2862 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2863 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2864 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2865
2866 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2867 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2868}
2869
2870/** Process the WINED3DSIO_LIT instruction in GLSL:
2871 * dst.x = dst.w = 1.0
2872 * dst.y = (src0.x > 0) ? src0.x
2873 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2874 * where src.w is clamped at +- 128
2875 */
2876static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2877{
2878 glsl_src_param_t src0_param;
2879 glsl_src_param_t src1_param;
2880 glsl_src_param_t src3_param;
2881 char dst_mask[6];
2882
2883 shader_glsl_append_dst(ins->ctx->buffer, ins);
2884 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2885
2886 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2887 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2888 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2889
2890 /* The sdk specifies the instruction like this
2891 * dst.x = 1.0;
2892 * if(src.x > 0.0) dst.y = src.x
2893 * else dst.y = 0.0.
2894 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2895 * else dst.z = 0.0;
2896 * dst.w = 1.0;
2897 *
2898 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2899 * dst.x = 1.0 ... No further explanation needed
2900 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2901 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2902 * dst.w = 1.0. ... Nothing fancy.
2903 *
2904 * So we still have one conditional in there. So do this:
2905 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2906 *
2907 * 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),
2908 * 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.
2909 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2910 */
2911 shader_addline(ins->ctx->buffer,
2912 "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",
2913 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2914}
2915
2916/** Process the WINED3DSIO_DST instruction in GLSL:
2917 * dst.x = 1.0
2918 * dst.y = src0.x * src0.y
2919 * dst.z = src0.z
2920 * dst.w = src1.w
2921 */
2922static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2923{
2924 glsl_src_param_t src0y_param;
2925 glsl_src_param_t src0z_param;
2926 glsl_src_param_t src1y_param;
2927 glsl_src_param_t src1w_param;
2928 char dst_mask[6];
2929
2930 shader_glsl_append_dst(ins->ctx->buffer, ins);
2931 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2932
2933 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2934 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2935 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2936 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2937
2938 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2939 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2940}
2941
2942/** Process the WINED3DSIO_SINCOS instruction in GLSL:
2943 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2944 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2945 *
2946 * dst.x = cos(src0.?)
2947 * dst.y = sin(src0.?)
2948 * dst.z = dst.z
2949 * dst.w = dst.w
2950 */
2951static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2952{
2953 glsl_src_param_t src0_param;
2954 DWORD write_mask;
2955
2956 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2957 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2958
2959 switch (write_mask) {
2960 case WINED3DSP_WRITEMASK_0:
2961 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2962 break;
2963
2964 case WINED3DSP_WRITEMASK_1:
2965 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2966 break;
2967
2968 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2969 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2970 break;
2971
2972 default:
2973 ERR("Write mask should be .x, .y or .xy\n");
2974 break;
2975 }
2976}
2977
2978/* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2979 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2980 * generate invalid code
2981 */
2982static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2983{
2984 glsl_src_param_t src0_param;
2985 DWORD write_mask;
2986
2987 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2988 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2989
2990 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2991}
2992
2993/** Process the WINED3DSIO_LOOP instruction in GLSL:
2994 * Start a for() loop where src1.y is the initial value of aL,
2995 * increment aL by src1.z for a total of src1.x iterations.
2996 * Need to use a temporary variable for this operation.
2997 */
2998/* FIXME: I don't think nested loops will work correctly this way. */
2999static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
3000{
3001 glsl_src_param_t src1_param;
3002 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3003 const DWORD *control_values = NULL;
3004 const local_constant *constant;
3005
3006 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
3007
3008 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
3009 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
3010 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
3011 * addressing.
3012 */
3013 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
3014 {
3015 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
3016 if (constant->idx == ins->src[1].reg.idx)
3017 {
3018 control_values = constant->value;
3019 break;
3020 }
3021 }
3022 }
3023
3024 if (control_values)
3025 {
3026 struct wined3d_shader_loop_control loop_control;
3027 loop_control.count = control_values[0];
3028 loop_control.start = control_values[1];
3029 loop_control.step = (int)control_values[2];
3030
3031 if (loop_control.step > 0)
3032 {
3033 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
3034 shader->baseShader.cur_loop_depth, loop_control.start,
3035 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
3036 shader->baseShader.cur_loop_depth, loop_control.step);
3037 }
3038 else if (loop_control.step < 0)
3039 {
3040 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
3041 shader->baseShader.cur_loop_depth, loop_control.start,
3042 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
3043 shader->baseShader.cur_loop_depth, loop_control.step);
3044 }
3045 else
3046 {
3047 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
3048 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
3049 shader->baseShader.cur_loop_depth, loop_control.count,
3050 shader->baseShader.cur_loop_depth);
3051 }
3052 } else {
3053 shader_addline(ins->ctx->buffer,
3054 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
3055 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
3056 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
3057 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
3058 }
3059
3060 shader->baseShader.cur_loop_depth++;
3061 shader->baseShader.cur_loop_regno++;
3062}
3063
3064static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
3065{
3066 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3067
3068 shader_addline(ins->ctx->buffer, "}\n");
3069
3070 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
3071 {
3072 shader->baseShader.cur_loop_depth--;
3073 shader->baseShader.cur_loop_regno--;
3074 }
3075
3076 if (ins->handler_idx == WINED3DSIH_ENDREP)
3077 {
3078 shader->baseShader.cur_loop_depth--;
3079 }
3080}
3081
3082static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
3083{
3084 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3085 glsl_src_param_t src0_param;
3086 const DWORD *control_values = NULL;
3087 const local_constant *constant;
3088
3089 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
3090 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
3091 {
3092 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
3093 {
3094 if (constant->idx == ins->src[0].reg.idx)
3095 {
3096 control_values = constant->value;
3097 break;
3098 }
3099 }
3100 }
3101
3102 if(control_values) {
3103 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
3104 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
3105 control_values[0], shader->baseShader.cur_loop_depth);
3106 } else {
3107 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3108 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
3109 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
3110 src0_param.param_str, shader->baseShader.cur_loop_depth);
3111 }
3112 shader->baseShader.cur_loop_depth++;
3113}
3114
3115static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
3116{
3117 glsl_src_param_t src0_param;
3118
3119 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3120 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
3121}
3122
3123static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
3124{
3125 glsl_src_param_t src0_param;
3126 glsl_src_param_t src1_param;
3127
3128 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3129 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3130
3131 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
3132 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
3133}
3134
3135static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
3136{
3137 shader_addline(ins->ctx->buffer, "} else {\n");
3138}
3139
3140static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
3141{
3142 shader_addline(ins->ctx->buffer, "break;\n");
3143}
3144
3145/* FIXME: According to MSDN the compare is done per component. */
3146static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
3147{
3148 glsl_src_param_t src0_param;
3149 glsl_src_param_t src1_param;
3150
3151 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3152 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3153
3154 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3155 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
3156}
3157
3158static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3159{
3160 shader_addline(ins->ctx->buffer, "}\n");
3161 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3162}
3163
3164static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3165{
3166 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3167}
3168
3169static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3170{
3171 glsl_src_param_t src1_param;
3172
3173 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3174 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3175}
3176
3177static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3178{
3179 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3180 * function only suppresses the unhandled instruction warning
3181 */
3182}
3183
3184/*********************************************
3185 * Pixel Shader Specific Code begins here
3186 ********************************************/
3187static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3188{
3189 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3190 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3191 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3192 ins->ctx->reg_maps->shader_version.minor);
3193 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3194 glsl_sample_function_t sample_function;
3195 DWORD sample_flags = 0;
3196 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3197 DWORD sampler_idx;
3198 DWORD mask = 0, swizzle;
3199
3200 /* 1.0-1.4: Use destination register as sampler source.
3201 * 2.0+: Use provided sampler source. */
3202 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3203 else sampler_idx = ins->src[1].reg.idx;
3204
3205 AssertReturnVoid(sampler_idx < RT_ELEMENTS(ins->ctx->reg_maps->sampler_type));
3206 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3207
3208 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3209 {
3210 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3211 DWORD flags = (priv->cur_ps_args->tex_transform >> (sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT))
3212 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3213
3214 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3215 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3216 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3217 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3218 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3219 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3220 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3221 case WINED3DTTFF_COUNT4:
3222 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3223 }
3224 }
3225 }
3226 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3227 {
3228 DWORD src_mod = ins->src[0].modifiers;
3229
3230 if (src_mod == WINED3DSPSM_DZ) {
3231 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3232 mask = WINED3DSP_WRITEMASK_2;
3233 } else if (src_mod == WINED3DSPSM_DW) {
3234 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3235 mask = WINED3DSP_WRITEMASK_3;
3236 }
3237 } else {
3238 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3239 {
3240 /* ps 2.0 texldp instruction always divides by the fourth component. */
3241 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3242 mask = WINED3DSP_WRITEMASK_3;
3243 }
3244 }
3245
3246 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3247 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3248 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3249 }
3250
3251 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3252 mask |= sample_function.coord_mask;
3253
3254 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3255 else swizzle = ins->src[1].swizzle;
3256
3257 /* 1.0-1.3: Use destination register as coordinate source.
3258 1.4+: Use provided coordinate source register. */
3259 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3260 {
3261 char coord_mask[6];
3262 shader_glsl_write_mask_to_str(mask, coord_mask);
3263 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3264 "T%u%s", sampler_idx, coord_mask);
3265 } else {
3266 glsl_src_param_t coord_param;
3267 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3268 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3269 {
3270 glsl_src_param_t bias;
3271 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3272 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3273 "%s", coord_param.param_str);
3274 } else {
3275 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3276 "%s", coord_param.param_str);
3277 }
3278 }
3279}
3280
3281static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3282{
3283 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3284 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3285 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3286 glsl_sample_function_t sample_function;
3287 glsl_src_param_t coord_param, dx_param, dy_param;
3288 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3289 DWORD sampler_type;
3290 DWORD sampler_idx;
3291 DWORD swizzle = ins->src[1].swizzle;
3292
3293 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3294 {
3295 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3296 shader_glsl_tex(ins);
3297 return;
3298 }
3299
3300 sampler_idx = ins->src[1].reg.idx;
3301 AssertReturnVoid(sampler_idx < RT_ELEMENTS(ins->ctx->reg_maps->sampler_type));
3302
3303 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3304 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3305 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3306 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3307 }
3308
3309 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3310 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3311 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3312 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3313
3314 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3315 "%s", coord_param.param_str);
3316}
3317
3318static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3319{
3320 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3321 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3322 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3323 glsl_sample_function_t sample_function;
3324 glsl_src_param_t coord_param, lod_param;
3325 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3326 DWORD sampler_type;
3327 DWORD sampler_idx;
3328 DWORD swizzle = ins->src[1].swizzle;
3329
3330 sampler_idx = ins->src[1].reg.idx;
3331 AssertReturnVoid(sampler_idx < RT_ELEMENTS(ins->ctx->reg_maps->sampler_type));
3332
3333 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3334 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3335 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3336 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3337 }
3338 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3339 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3340
3341 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3342
3343 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3344 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3345 {
3346 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
3347 * However, they seem to work just fine in fragment shaders as well. */
3348 WARN("Using %s in fragment shader.\n", sample_function.name);
3349 }
3350 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3351 "%s", coord_param.param_str);
3352}
3353
3354static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3355{
3356 /* FIXME: Make this work for more than just 2D textures */
3357 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3358 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3359
3360 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3361 {
3362 char dst_mask[6];
3363
3364 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3365 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3366 ins->dst[0].reg.idx, dst_mask);
3367 } else {
3368 DWORD reg = ins->src[0].reg.idx;
3369 DWORD src_mod = ins->src[0].modifiers;
3370 char dst_swizzle[6];
3371
3372 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3373
3374 if (src_mod == WINED3DSPSM_DZ) {
3375 glsl_src_param_t div_param;
3376 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3377 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3378
3379 if (mask_size > 1) {
3380 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3381 } else {
3382 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3383 }
3384 } else if (src_mod == WINED3DSPSM_DW) {
3385 glsl_src_param_t div_param;
3386 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3387 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3388
3389 if (mask_size > 1) {
3390 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3391 } else {
3392 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3393 }
3394 } else {
3395 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3396 }
3397 }
3398}
3399
3400/** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3401 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3402 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3403static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3404{
3405 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3406 glsl_src_param_t src0_param;
3407 glsl_sample_function_t sample_function;
3408 DWORD sampler_idx = ins->dst[0].reg.idx;
3409 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3410 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3411 UINT mask_size;
3412
3413 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3414
3415 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3416 * scalar, and projected sampling would require 4.
3417 *
3418 * It is a dependent read - not valid with conditional NP2 textures
3419 */
3420 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3421 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3422
3423 switch(mask_size)
3424 {
3425 case 1:
3426 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3427 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3428 break;
3429
3430 case 2:
3431 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3432 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3433 break;
3434
3435 case 3:
3436 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3437 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3438 break;
3439
3440 default:
3441 FIXME("Unexpected mask size %u\n", mask_size);
3442 break;
3443 }
3444}
3445
3446/** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3447 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3448static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3449{
3450 glsl_src_param_t src0_param;
3451 DWORD dstreg = ins->dst[0].reg.idx;
3452 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3453 DWORD dst_mask;
3454 unsigned int mask_size;
3455
3456 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3457 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3458 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3459
3460 if (mask_size > 1) {
3461 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3462 } else {
3463 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3464 }
3465}
3466
3467/** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3468 * Calculate the depth as dst.x / dst.y */
3469static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3470{
3471 glsl_dst_param_t dst_param;
3472
3473 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3474
3475 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3476 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3477 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3478 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3479 * >= 1.0 or < 0.0
3480 */
3481 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3482 dst_param.reg_name, dst_param.reg_name);
3483}
3484
3485/** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3486 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3487 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3488 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3489 */
3490static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3491{
3492 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3493 DWORD dstreg = ins->dst[0].reg.idx;
3494 glsl_src_param_t src0_param;
3495
3496 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3497
3498 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3499 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3500}
3501
3502/** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3503 * Calculate the 1st of a 2-row matrix multiplication. */
3504static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3505{
3506 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3507 DWORD reg = ins->dst[0].reg.idx;
3508 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3509 glsl_src_param_t src0_param;
3510
3511 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3512 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3513}
3514
3515/** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3516 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3517static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3518{
3519 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3520 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3521 DWORD reg = ins->dst[0].reg.idx;
3522 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3523 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3524 glsl_src_param_t src0_param;
3525
3526 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3527 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3528 current_state->texcoord_w[current_state->current_row++] = reg;
3529}
3530
3531static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3532{
3533 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3534 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3535 DWORD reg = ins->dst[0].reg.idx;
3536 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3537 glsl_src_param_t src0_param;
3538 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3539 glsl_sample_function_t sample_function;
3540
3541 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3542 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3543
3544 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3545
3546 /* Sample the texture using the calculated coordinates */
3547 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3548}
3549
3550/** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3551 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3552static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3553{
3554 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3555 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3556 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3557 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3558 glsl_src_param_t src0_param;
3559 DWORD reg = ins->dst[0].reg.idx;
3560 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3561 glsl_sample_function_t sample_function;
3562
3563 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3564 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3565
3566 /* Dependent read, not valid with conditional NP2 */
3567 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3568
3569 /* Sample the texture using the calculated coordinates */
3570 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3571
3572 current_state->current_row = 0;
3573}
3574
3575/** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3576 * Perform the 3rd row of a 3x3 matrix multiply */
3577static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3578{
3579 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3580 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3581 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3582 glsl_src_param_t src0_param;
3583 char dst_mask[6];
3584 DWORD reg = ins->dst[0].reg.idx;
3585
3586 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3587
3588 shader_glsl_append_dst(ins->ctx->buffer, ins);
3589 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3590 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3591
3592 current_state->current_row = 0;
3593}
3594
3595/* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3596 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3597static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3598{
3599 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3600 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3601 DWORD reg = ins->dst[0].reg.idx;
3602 glsl_src_param_t src0_param;
3603 glsl_src_param_t src1_param;
3604 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3605 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3606 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3607 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3608 glsl_sample_function_t sample_function;
3609
3610 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3611 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3612
3613 /* Perform the last matrix multiply operation */
3614 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3615 /* Reflection calculation */
3616 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3617
3618 /* Dependent read, not valid with conditional NP2 */
3619 shader_glsl_get_sample_function(gl_info, stype, 0, &sample_function);
3620
3621 /* Sample the texture */
3622 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3623
3624 current_state->current_row = 0;
3625}
3626
3627/* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3628 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3629static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3630{
3631 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3632 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3633 DWORD reg = ins->dst[0].reg.idx;
3634 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3635 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3636 glsl_src_param_t src0_param;
3637 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3638 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3639 glsl_sample_function_t sample_function;
3640
3641 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3642
3643 /* Perform the last matrix multiply operation */
3644 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3645
3646 /* Construct the eye-ray vector from w coordinates */
3647 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3648 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3649 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3650
3651 /* Dependent read, not valid with conditional NP2 */
3652 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3653
3654 /* Sample the texture using the calculated coordinates */
3655 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3656
3657 current_state->current_row = 0;
3658}
3659
3660/** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3661 * Apply a fake bump map transform.
3662 * texbem is pshader <= 1.3 only, this saves a few version checks
3663 */
3664static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3665{
3666 /*IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3667 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device; - unused */
3668 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3669 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3670 glsl_sample_function_t sample_function;
3671 glsl_src_param_t coord_param;
3672 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3673 DWORD sampler_idx;
3674 DWORD mask;
3675 DWORD flags;
3676 char coord_mask[6];
3677
3678 sampler_idx = ins->dst[0].reg.idx;
3679 flags = (priv->cur_ps_args->tex_transform >> (sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT))
3680 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3681
3682 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3683 /* Dependent read, not valid with conditional NP2 */
3684 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3685 mask = sample_function.coord_mask;
3686
3687 shader_glsl_write_mask_to_str(mask, coord_mask);
3688
3689 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3690 * so we can't let the GL handle this.
3691 */
3692 if (flags & WINED3D_PSARGS_PROJECTED) {
3693 DWORD div_mask=0;
3694 char coord_div_mask[3];
3695 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3696 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3697 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3698 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3699 case WINED3DTTFF_COUNT4:
3700 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3701 }
3702 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3703 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3704 }
3705
3706 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3707
3708 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3709 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3710 coord_param.param_str, coord_mask);
3711
3712 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3713 {
3714 glsl_src_param_t luminance_param;
3715 glsl_dst_param_t dst_param;
3716
3717 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3718 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3719
3720 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3721 dst_param.reg_name, dst_param.mask_str,
3722 luminance_param.param_str, sampler_idx, sampler_idx);
3723 }
3724}
3725
3726static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3727{
3728 glsl_src_param_t src0_param, src1_param;
3729 DWORD sampler_idx = ins->dst[0].reg.idx;
3730
3731 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3732 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3733
3734 shader_glsl_append_dst(ins->ctx->buffer, ins);
3735 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3736 src0_param.param_str, sampler_idx, src1_param.param_str);
3737}
3738
3739/** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3740 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3741static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3742{
3743 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3744 glsl_src_param_t src0_param;
3745 DWORD sampler_idx = ins->dst[0].reg.idx;
3746 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3747 glsl_sample_function_t sample_function;
3748
3749 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3750
3751 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3752 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3753 "%s.wx", src0_param.reg_name);
3754}
3755
3756/** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3757 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3758static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3759{
3760 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3761 glsl_src_param_t src0_param;
3762 DWORD sampler_idx = ins->dst[0].reg.idx;
3763 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3764 glsl_sample_function_t sample_function;
3765
3766 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3767
3768 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3769 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3770 "%s.yz", src0_param.reg_name);
3771}
3772
3773/** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3774 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3775static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3776{
3777 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3778 glsl_src_param_t src0_param;
3779 DWORD sampler_idx = ins->dst[0].reg.idx;
3780 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3781 glsl_sample_function_t sample_function;
3782
3783 /* Dependent read, not valid with conditional NP2 */
3784 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3785 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3786
3787 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3788 "%s", src0_param.param_str);
3789}
3790
3791/** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3792 * If any of the first 3 components are < 0, discard this pixel */
3793static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3794{
3795 glsl_dst_param_t dst_param;
3796
3797 /* The argument is a destination parameter, and no writemasks are allowed */
3798 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3799 if (ins->ctx->reg_maps->shader_version.major >= 2)
3800 {
3801 /* 2.0 shaders compare all 4 components in texkill */
3802 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3803 } else {
3804 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3805 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3806 * 4 components are defined, only the first 3 are used
3807 */
3808 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3809 }
3810}
3811
3812/** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3813 * dst = dot2(src0, src1) + src2 */
3814static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3815{
3816 glsl_src_param_t src0_param;
3817 glsl_src_param_t src1_param;
3818 glsl_src_param_t src2_param;
3819 DWORD write_mask;
3820 unsigned int mask_size;
3821
3822 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3823 mask_size = shader_glsl_get_write_mask_size(write_mask);
3824
3825 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3826 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3827 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3828
3829 if (mask_size > 1) {
3830 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3831 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3832 } else {
3833 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3834 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3835 }
3836}
3837
3838static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3839 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3840 enum vertexprocessing_mode vertexprocessing)
3841{
3842 unsigned int i;
3843 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3844 WORD map = reg_maps->input_registers;
3845
3846 for (i = 0; map; map >>= 1, ++i)
3847 {
3848 const char *semantic_name;
3849 UINT semantic_idx;
3850 char reg_mask[6];
3851
3852 /* Unused */
3853 if (!(map & 1)) continue;
3854
3855 semantic_name = input_signature[i].semantic_name;
3856 semantic_idx = input_signature[i].semantic_idx;
3857 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3858
3859 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3860 {
3861 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3862 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3863 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3864 else
3865 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3866 This->input_reg_map[i], reg_mask, reg_mask);
3867 }
3868 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3869 {
3870 if (semantic_idx == 0)
3871 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3872 This->input_reg_map[i], reg_mask, reg_mask);
3873 else if (semantic_idx == 1)
3874 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3875 This->input_reg_map[i], reg_mask, reg_mask);
3876 else
3877 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3878 This->input_reg_map[i], reg_mask, reg_mask);
3879 }
3880 else
3881 {
3882 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3883 This->input_reg_map[i], reg_mask, reg_mask);
3884 }
3885 }
3886}
3887
3888/*********************************************
3889 * Vertex Shader Specific Code begins here
3890 ********************************************/
3891
3892static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3893 glsl_program_key_t key;
3894
3895 key.vshader = entry->vshader;
3896 key.pshader = entry->pshader;
3897 key.vs_args = entry->vs_args;
3898 key.ps_args = entry->ps_args;
3899 key.context = entry->context;
3900
3901 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3902 {
3903 ERR("Failed to insert program entry.\n");
3904 }
3905}
3906
3907static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3908 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3909 struct ps_compile_args *ps_args, const struct wined3d_context *context) {
3910 struct wine_rb_entry *entry;
3911 glsl_program_key_t key;
3912
3913 key.vshader = vshader;
3914 key.pshader = pshader;
3915 key.vs_args = *vs_args;
3916 key.ps_args = *ps_args;
3917 key.context = context;
3918
3919 entry = wine_rb_get(&priv->program_lookup, &key);
3920 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3921}
3922
3923/* GL locking is done by the caller */
3924static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3925 struct glsl_shader_prog_link *entry)
3926{
3927 glsl_program_key_t key;
3928
3929 key.vshader = entry->vshader;
3930 key.pshader = entry->pshader;
3931 key.vs_args = entry->vs_args;
3932 key.ps_args = entry->ps_args;
3933 key.context = entry->context;
3934 wine_rb_remove(&priv->program_lookup, &key);
3935
3936 if (context_get_current() == entry->context)
3937 {
3938 TRACE("deleting program %p\n", (void *)(uintptr_t)entry->programId);
3939 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3940 checkGLcall("glDeleteObjectARB");
3941 }
3942 else
3943 {
3944 WARN("Attempting to delete program %p created in ctx %p from ctx %p\n", (void *)(uintptr_t)entry->programId, entry->context, context_get_current());
3945 }
3946
3947 if (entry->vshader) list_remove(&entry->vshader_entry);
3948 if (entry->pshader) list_remove(&entry->pshader_entry);
3949 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3950 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3951 HeapFree(GetProcessHeap(), 0, entry);
3952}
3953
3954static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3955 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3956 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3957{
3958 unsigned int i, j;
3959 const char *semantic_name_in, *semantic_name_out;
3960 UINT semantic_idx_in, semantic_idx_out;
3961 DWORD *set;
3962 DWORD in_idx;
3963 unsigned int in_count = vec4_varyings(3, gl_info);
3964 char reg_mask[6], reg_mask_out[6];
3965 char destination[50];
3966 WORD input_map, output_map;
3967
3968 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3969
3970 if (!output_signature)
3971 {
3972 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3973 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3974 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3975 }
3976
3977 input_map = reg_maps_in->input_registers;
3978 for (i = 0; input_map; input_map >>= 1, ++i)
3979 {
3980 if (!(input_map & 1)) continue;
3981
3982 in_idx = map[i];
3983 if (in_idx >= (in_count + 2)) {
3984 FIXME("More input varyings declared than supported, expect issues\n");
3985 continue;
3986 }
3987 else if (map[i] == ~0U)
3988 {
3989 /* Declared, but not read register */
3990 continue;
3991 }
3992
3993 if (in_idx == in_count) {
3994 sprintf(destination, "gl_FrontColor");
3995 } else if (in_idx == in_count + 1) {
3996 sprintf(destination, "gl_FrontSecondaryColor");
3997 } else {
3998 sprintf(destination, "IN[%u]", in_idx);
3999 }
4000
4001 semantic_name_in = input_signature[i].semantic_name;
4002 semantic_idx_in = input_signature[i].semantic_idx;
4003 set[map[i]] = input_signature[i].mask;
4004 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
4005
4006 if (!output_signature)
4007 {
4008 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
4009 {
4010 if (semantic_idx_in == 0)
4011 shader_addline(buffer, "%s%s = front_color%s;\n",
4012 destination, reg_mask, reg_mask);
4013 else if (semantic_idx_in == 1)
4014 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
4015 destination, reg_mask, reg_mask);
4016 else
4017 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4018 destination, reg_mask, reg_mask);
4019 }
4020 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
4021 {
4022 if (semantic_idx_in < 8)
4023 {
4024 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
4025 destination, reg_mask, semantic_idx_in, reg_mask);
4026 }
4027 else
4028 {
4029 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4030 destination, reg_mask, reg_mask);
4031 }
4032 }
4033 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
4034 {
4035 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
4036 destination, reg_mask, reg_mask);
4037 }
4038 else
4039 {
4040 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4041 destination, reg_mask, reg_mask);
4042 }
4043 } else {
4044 BOOL found = FALSE;
4045
4046 output_map = reg_maps_out->output_registers;
4047 for (j = 0; output_map; output_map >>= 1, ++j)
4048 {
4049 if (!(output_map & 1)) continue;
4050
4051 semantic_name_out = output_signature[j].semantic_name;
4052 semantic_idx_out = output_signature[j].semantic_idx;
4053 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
4054
4055 if (semantic_idx_in == semantic_idx_out
4056 && !strcmp(semantic_name_in, semantic_name_out))
4057 {
4058 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
4059 destination, reg_mask, j, reg_mask);
4060 found = TRUE;
4061 }
4062 }
4063 if(!found) {
4064 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4065 destination, reg_mask, reg_mask);
4066 }
4067 }
4068 }
4069
4070 /* This is solely to make the compiler / linker happy and avoid warning about undefined
4071 * varyings. It shouldn't result in any real code executed on the GPU, since all read
4072 * input varyings are assigned above, if the optimizer works properly.
4073 */
4074 for(i = 0; i < in_count + 2; i++) {
4075 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
4076 {
4077 unsigned int size = 0;
4078 memset(reg_mask, 0, sizeof(reg_mask));
4079 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
4080 reg_mask[size] = 'x';
4081 size++;
4082 }
4083 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
4084 reg_mask[size] = 'y';
4085 size++;
4086 }
4087 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
4088 reg_mask[size] = 'z';
4089 size++;
4090 }
4091 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
4092 reg_mask[size] = 'w';
4093 size++;
4094 }
4095
4096 if (i == in_count) {
4097 sprintf(destination, "gl_FrontColor");
4098 } else if (i == in_count + 1) {
4099 sprintf(destination, "gl_FrontSecondaryColor");
4100 } else {
4101 sprintf(destination, "IN[%u]", i);
4102 }
4103
4104 if (size == 1) {
4105 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
4106 } else {
4107 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
4108 }
4109 }
4110 }
4111
4112 HeapFree(GetProcessHeap(), 0, set);
4113}
4114
4115static void generate_texcoord_assignment(struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *vs, IWineD3DPixelShaderImpl *ps)
4116{
4117 DWORD map;
4118 unsigned int i;
4119 char reg_mask[6];
4120
4121 if (!ps)
4122 return;
4123
4124 for (i = 0, map = ps->baseShader.reg_maps.texcoord; map && i < min(8, MAX_REG_TEXCRD); map >>= 1, ++i)
4125 {
4126 if (!(map & 1))
4127 continue;
4128
4129 /* so far we assume that if texcoord_mask has any write flags, they are assigned appropriately with pixel shader */
4130 if ((vs->baseShader.reg_maps.texcoord_mask[i]) & WINED3DSP_WRITEMASK_ALL)
4131 continue;
4132
4133 shader_glsl_write_mask_to_str(WINED3DSP_WRITEMASK_ALL, reg_mask);
4134 shader_addline(buffer, "gl_TexCoord[%u]%s = gl_MultiTexCoord%u%s;\n", i, reg_mask, i, reg_mask);
4135 }
4136}
4137
4138/* GL locking is done by the caller */
4139static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
4140 IWineD3DVertexShader *a_vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
4141{
4142 GLhandleARB ret = 0;
4143 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) a_vertexshader;
4144 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
4145 IWineD3DDeviceImpl *device;
4146 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
4147 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
4148 unsigned int i;
4149 const char *semantic_name;
4150 UINT semantic_idx;
4151 char reg_mask[6];
4152 const struct wined3d_shader_signature_element *output_signature;
4153
4154 shader_buffer_clear(buffer);
4155
4156 shader_addline(buffer, "#version 120\n");
4157
4158 if(vs_major < 3 && ps_major < 3) {
4159 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
4160 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
4161 */
4162 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
4163 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
4164 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
4165 {
4166 shader_addline(buffer, "void order_ps_input() {\n");
4167 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
4168 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
4169 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
4170 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
4171 }
4172 }
4173 shader_addline(buffer, "}\n");
4174 } else {
4175 shader_addline(buffer, "void order_ps_input() {\n");
4176 generate_texcoord_assignment(buffer, vs, ps);
4177 shader_addline(buffer, "}\n");
4178 }
4179 } else if(ps_major < 3 && vs_major >= 3) {
4180 WORD map = vs->baseShader.reg_maps.output_registers;
4181
4182 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
4183 output_signature = vs->baseShader.output_signature;
4184
4185 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
4186 for (i = 0; map; map >>= 1, ++i)
4187 {
4188 DWORD write_mask;
4189
4190 if (!(map & 1)) continue;
4191
4192 semantic_name = output_signature[i].semantic_name;
4193 semantic_idx = output_signature[i].semantic_idx;
4194 write_mask = output_signature[i].mask;
4195 shader_glsl_write_mask_to_str(write_mask, reg_mask);
4196
4197 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
4198 {
4199 if (semantic_idx == 0)
4200 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4201 else if (semantic_idx == 1)
4202 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4203 }
4204 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
4205 {
4206 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4207 }
4208 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
4209 {
4210 if (semantic_idx < 8)
4211 {
4212 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
4213 write_mask |= WINED3DSP_WRITEMASK_3;
4214
4215 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
4216 semantic_idx, reg_mask, i, reg_mask);
4217 if (!(write_mask & WINED3DSP_WRITEMASK_3))
4218 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
4219 }
4220 }
4221 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
4222 {
4223 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
4224 }
4225 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
4226 {
4227 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
4228 }
4229 }
4230 shader_addline(buffer, "}\n");
4231
4232 } else if(ps_major >= 3 && vs_major >= 3) {
4233 WORD map = vs->baseShader.reg_maps.output_registers;
4234
4235 output_signature = vs->baseShader.output_signature;
4236
4237 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
4238 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
4239 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
4240
4241 /* First, sort out position and point size. Those are not passed to the pixel shader */
4242 for (i = 0; map; map >>= 1, ++i)
4243 {
4244 if (!(map & 1)) continue;
4245
4246 semantic_name = output_signature[i].semantic_name;
4247 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
4248
4249 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
4250 {
4251 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4252 }
4253 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
4254 {
4255 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
4256 }
4257 }
4258
4259 /* Then, fix the pixel shader input */
4260 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
4261 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
4262
4263 shader_addline(buffer, "}\n");
4264 } else if(ps_major >= 3 && vs_major < 3) {
4265 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
4266 shader_addline(buffer, "void order_ps_input() {\n");
4267 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
4268 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
4269 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
4270 */
4271 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
4272 &ps->baseShader.reg_maps, NULL, NULL);
4273 shader_addline(buffer, "}\n");
4274 } else {
4275 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
4276 }
4277
4278 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4279 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4280 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
4281 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
4282 GL_EXTCALL(glCompileShaderARB(ret));
4283 checkGLcall("glCompileShaderARB(ret)");
4284 shader_glsl_validate_compile_link(gl_info, ret, FALSE);
4285 return ret;
4286}
4287
4288#ifdef VBOX_WITH_VMSVGA
4289static GLhandleARB generate_passthrough_vshader(const struct wined3d_gl_info *gl_info)
4290{
4291 GLhandleARB ret = 0;
4292 static const char *passthrough_vshader[] =
4293 {
4294 "#version 120\n"
4295 "vec4 R0;\n"
4296 "void main(void)\n"
4297 "{\n"
4298 " R0 = gl_Vertex;\n"
4299 " R0.w = 1.0;\n"
4300 " R0.z = 0.0;\n"
4301 " gl_Position = gl_ModelViewProjectionMatrix * R0;\n"
4302 "}\n"
4303 };
4304
4305 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4306 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4307 GL_EXTCALL(glShaderSourceARB(ret, 1, passthrough_vshader, NULL));
4308 checkGLcall("glShaderSourceARB(ret, 1, passthrough_vshader, NULL)");
4309 GL_EXTCALL(glCompileShaderARB(ret));
4310 checkGLcall("glCompileShaderARB(ret)");
4311 shader_glsl_validate_compile_link(gl_info, ret, FALSE);
4312
4313 return ret;
4314}
4315
4316#endif
4317
4318/* GL locking is done by the caller */
4319static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
4320 GLhandleARB programId, char prefix)
4321{
4322 const local_constant *lconst;
4323 GLint tmp_loc;
4324 const float *value;
4325 char glsl_name[8];
4326
4327 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
4328 value = (const float *)lconst->value;
4329 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
4330 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4331 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4332 }
4333 checkGLcall("Hardcoding local constants");
4334}
4335
4336/* GL locking is done by the caller */
4337#ifdef VBOX_WITH_VMSVGA
4338static GLhandleARB shader_glsl_generate_pshader(const struct wined3d_context *context,
4339#else
4340static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4341#endif
4342 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
4343 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4344{
4345 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4346 const struct wined3d_gl_info *gl_info = context->gl_info;
4347 CONST DWORD *function = This->baseShader.function;
4348 struct shader_glsl_ctx_priv priv_ctx;
4349
4350 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4351 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4352
4353 memset(&priv_ctx, 0, sizeof(priv_ctx));
4354 priv_ctx.cur_ps_args = args;
4355 priv_ctx.cur_np2fixup_info = np2fixup_info;
4356
4357 shader_addline(buffer, "#version 120\n");
4358
4359 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
4360 {
4361 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4362 }
4363 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4364 {
4365 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4366 * drivers write a warning if we don't do so
4367 */
4368 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4369 }
4370 if (gl_info->supported[EXT_GPU_SHADER4])
4371 {
4372 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4373 }
4374
4375 /* Base Declarations */
4376 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4377
4378 /* Pack 3.0 inputs */
4379 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4380 {
4381 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
4382 This->baseShader.input_signature, reg_maps, args->vp_mode);
4383 }
4384
4385 /* Base Shader Body */
4386 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
4387
4388 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4389 if (reg_maps->shader_version.major < 2)
4390 {
4391 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4392 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4393 }
4394
4395 if (args->srgb_correction)
4396 {
4397 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4398 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4399 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4400 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4401 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4402 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4403 }
4404 /* Pixel shader < 3.0 do not replace the fog stage.
4405 * This implements linear fog computation and blending.
4406 * TODO: non linear fog
4407 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4408 * -1/(e-s) and e/(e-s) respectively.
4409 */
4410 if (reg_maps->shader_version.major < 3)
4411 {
4412 switch(args->fog) {
4413 case FOG_OFF: break;
4414 case FOG_LINEAR:
4415 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4416 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4417 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4418 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4419 break;
4420 case FOG_EXP:
4421 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4422 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4423 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4424 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4425 break;
4426 case FOG_EXP2:
4427 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4428 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4429 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4430 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4431 break;
4432 }
4433 }
4434
4435 shader_addline(buffer, "}\n");
4436
4437 TRACE("Compiling shader object %p\n", (void *)(uintptr_t)shader_obj);
4438 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4439 GL_EXTCALL(glCompileShaderARB(shader_obj));
4440 shader_glsl_validate_compile_link(gl_info, shader_obj, FALSE);
4441
4442 /* Store the shader object */
4443 return shader_obj;
4444}
4445
4446/* GL locking is done by the caller */
4447#ifdef VBOX_WITH_VMSVGA
4448static GLhandleARB shader_glsl_generate_vshader(const struct wined3d_context *context,
4449#else
4450static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4451#endif
4452 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4453 const struct vs_compile_args *args)
4454{
4455 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4456 const struct wined3d_gl_info *gl_info = context->gl_info;
4457 CONST DWORD *function = This->baseShader.function;
4458 struct shader_glsl_ctx_priv priv_ctx;
4459
4460 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4461 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4462
4463 shader_addline(buffer, "#version 120\n");
4464
4465 if (gl_info->supported[EXT_GPU_SHADER4])
4466 {
4467 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4468 }
4469
4470 memset(&priv_ctx, 0, sizeof(priv_ctx));
4471 priv_ctx.cur_vs_args = args;
4472
4473 /* Base Declarations */
4474 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4475
4476 /* Base Shader Body */
4477 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4478
4479 /* Unpack 3.0 outputs */
4480 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
4481 else shader_addline(buffer, "order_ps_input();\n");
4482
4483 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4484 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4485 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4486 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4487 */
4488 if(args->fog_src == VS_FOG_Z) {
4489 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4490 } else if (!reg_maps->fog) {
4491 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4492 }
4493
4494 /* Write the final position.
4495 *
4496 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4497 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4498 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4499 * contains 1.0 to allow a mad.
4500 */
4501 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4502 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4503 if(args->clip_enabled) {
4504 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4505 }
4506
4507 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4508 *
4509 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4510 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4511 * which is the same as z = z * 2 - w.
4512 */
4513 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4514
4515 shader_addline(buffer, "}\n");
4516
4517 TRACE("Compiling shader object %p\n", (void *)(uintptr_t)shader_obj);
4518 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4519 GL_EXTCALL(glCompileShaderARB(shader_obj));
4520 shader_glsl_validate_compile_link(gl_info, shader_obj, FALSE);
4521
4522 return shader_obj;
4523}
4524
4525static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4526 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4527 const struct ps_compile_args *args,
4528 UINT *inp2fixup_info
4529 )
4530{
4531 UINT i;
4532 DWORD new_size;
4533 struct glsl_ps_compiled_shader *new_array;
4534 struct glsl_pshader_private *shader_data;
4535 struct ps_np2fixup_info *np2fixup = NULL;
4536 GLhandleARB ret;
4537
4538 if (!shader->baseShader.backend_data)
4539 {
4540 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4541 if (!shader->baseShader.backend_data)
4542 {
4543 ERR("Failed to allocate backend data.\n");
4544 return 0;
4545 }
4546 }
4547 shader_data = shader->baseShader.backend_data;
4548
4549 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4550 * so a linear search is more performant than a hashmap or a binary search
4551 * (cache coherency etc)
4552 */
4553 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4554 if(shader_data->gl_shaders[i].context==context
4555 && memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4556 if(args->np2_fixup) {
4557 *inp2fixup_info = i;
4558 }
4559 return shader_data->gl_shaders[i].prgId;
4560 }
4561 }
4562
4563 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4564 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4565 if (shader_data->num_gl_shaders)
4566 {
4567 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4568 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4569 new_size * sizeof(*shader_data->gl_shaders));
4570 } else {
4571 new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4572 new_size = 1;
4573 }
4574
4575 if(!new_array) {
4576 ERR("Out of memory\n");
4577 return 0;
4578 }
4579 shader_data->gl_shaders = new_array;
4580 shader_data->shader_array_size = new_size;
4581 }
4582
4583 shader_data->gl_shaders[shader_data->num_gl_shaders].context = context;
4584 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4585
4586 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4587 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4588
4589 pixelshader_update_samplers(&shader->baseShader.reg_maps,
4590 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4591
4592 shader_buffer_clear(buffer);
4593 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4594 *inp2fixup_info = shader_data->num_gl_shaders;
4595 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4596
4597 return ret;
4598}
4599
4600static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4601 const DWORD use_map) {
4602 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4603 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4604 return stored->fog_src == new->fog_src;
4605}
4606
4607static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4608 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4609 const struct vs_compile_args *args)
4610{
4611 UINT i;
4612 DWORD new_size;
4613 struct glsl_vs_compiled_shader *new_array;
4614 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4615 struct glsl_vshader_private *shader_data;
4616 GLhandleARB ret;
4617
4618 if (!shader->baseShader.backend_data)
4619 {
4620 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4621 if (!shader->baseShader.backend_data)
4622 {
4623 ERR("Failed to allocate backend data.\n");
4624 return 0;
4625 }
4626 }
4627 shader_data = shader->baseShader.backend_data;
4628
4629 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4630 * so a linear search is more performant than a hashmap or a binary search
4631 * (cache coherency etc)
4632 */
4633 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4634 if(shader_data->gl_shaders[i].context==context
4635 && vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4636 return shader_data->gl_shaders[i].prgId;
4637 }
4638 }
4639
4640 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4641
4642 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4643 if (shader_data->num_gl_shaders)
4644 {
4645 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4646 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4647 new_size * sizeof(*shader_data->gl_shaders));
4648 } else {
4649 new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4650 new_size = 1;
4651 }
4652
4653 if(!new_array) {
4654 ERR("Out of memory\n");
4655 return 0;
4656 }
4657 shader_data->gl_shaders = new_array;
4658 shader_data->shader_array_size = new_size;
4659 }
4660
4661 shader_data->gl_shaders[shader_data->num_gl_shaders].context = context;
4662 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4663
4664 shader_buffer_clear(buffer);
4665 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4666 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4667
4668 return ret;
4669}
4670
4671/** Sets the GLSL program ID for the given pixel and vertex shader combination.
4672 * It sets the programId on the current StateBlock (because it should be called
4673 * inside of the DrawPrimitive() part of the render loop).
4674 *
4675 * If a program for the given combination does not exist, create one, and store
4676 * the program in the hash table. If it creates a program, it will link the
4677 * given objects, too.
4678 */
4679
4680/* GL locking is done by the caller */
4681static void set_glsl_shader_program(const struct wined3d_context *context,
4682 IWineD3DDeviceImpl *device, BOOL a_use_ps, BOOL a_use_vs)
4683{
4684 IWineD3DVertexShader *vshader = a_use_vs ? device->stateBlock->vertexShader : NULL;
4685 IWineD3DPixelShader *pshader = a_use_ps ? device->stateBlock->pixelShader : NULL;
4686 const struct wined3d_gl_info *gl_info = context->gl_info;
4687 struct shader_glsl_priv *priv = device->shader_priv;
4688 struct glsl_shader_prog_link *entry = NULL;
4689 GLhandleARB programId = 0;
4690 GLhandleARB reorder_shader_id = 0;
4691 unsigned int i;
4692 char glsl_name[8];
4693 struct ps_compile_args ps_compile_args;
4694 struct vs_compile_args vs_compile_args;
4695
4696 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4697 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4698
4699 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args, context);
4700 if (entry) {
4701 priv->glsl_program = entry;
4702 return;
4703 }
4704
4705 /* If we get to this point, then no matching program exists, so we create one */
4706 programId = GL_EXTCALL(glCreateProgramObjectARB());
4707 TRACE("Created new GLSL shader program %p\n", (void *)(uintptr_t)programId);
4708
4709 /* Create the entry */
4710 entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct glsl_shader_prog_link));
4711 entry->context = context;
4712 entry->programId = programId;
4713 entry->vshader = vshader;
4714 entry->pshader = pshader;
4715 entry->vs_args = vs_compile_args;
4716 entry->ps_args = ps_compile_args;
4717 entry->constant_version = 0;
4718 WINEFIXUPINFO_INIT(entry);
4719 /* Add the hash table entry */
4720 add_glsl_program_entry(priv, entry);
4721
4722 /* Set the current program */
4723 priv->glsl_program = entry;
4724
4725 /* Attach GLSL vshader */
4726 if (vshader)
4727 {
4728 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4729 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4730 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4731 char tmp_name[10];
4732
4733 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4734 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)reorder_shader_id, (void *)(uintptr_t)programId);
4735 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4736 checkGLcall("glAttachObjectARB");
4737 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4738 * is destroyed
4739 */
4740 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4741
4742 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)vshader_id, (void *)(uintptr_t)programId);
4743 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4744 checkGLcall("glAttachObjectARB");
4745
4746 /* Bind vertex attributes to a corresponding index number to match
4747 * the same index numbers as ARB_vertex_programs (makes loading
4748 * vertex attributes simpler). With this method, we can use the
4749 * exact same code to load the attributes later for both ARB and
4750 * GLSL shaders.
4751 *
4752 * We have to do this here because we need to know the Program ID
4753 * in order to make the bindings work, and it has to be done prior
4754 * to linking the GLSL program. */
4755 for (i = 0; map; map >>= 1, ++i)
4756 {
4757 if (!(map & 1)) continue;
4758
4759 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4760 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4761 }
4762 checkGLcall("glBindAttribLocationARB");
4763
4764 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4765 }
4766#ifdef VBOX_WITH_VMSVGA
4767 else
4768 if (device->strided_streams.position_transformed)
4769 {
4770 GLhandleARB passthrough_vshader_id;
4771
4772 passthrough_vshader_id = generate_passthrough_vshader(gl_info);
4773 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)passthrough_vshader_id, (void *)(uintptr_t)programId);
4774 GL_EXTCALL(glAttachObjectARB(programId, passthrough_vshader_id));
4775 checkGLcall("glAttachObjectARB");
4776 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4777 * is destroyed
4778 */
4779 GL_EXTCALL(glDeleteObjectARB(passthrough_vshader_id));
4780 }
4781#endif
4782
4783
4784 /* Attach GLSL pshader */
4785 if (pshader)
4786 {
4787 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4788 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args,
4789 &entry->inp2Fixup_info
4790 );
4791 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)pshader_id, (void *)(uintptr_t)programId);
4792 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4793 checkGLcall("glAttachObjectARB");
4794
4795 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4796 }
4797
4798 /* Link the program */
4799 TRACE("Linking GLSL shader program %p\n", (void *)(uintptr_t)programId);
4800 GL_EXTCALL(glLinkProgramARB(programId));
4801 shader_glsl_validate_compile_link(gl_info, programId, TRUE);
4802
4803 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4804 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4805 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4806 {
4807 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4808 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4809 }
4810 for (i = 0; i < MAX_CONST_I; ++i)
4811 {
4812 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4813 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4814 }
4815 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4816 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4817 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4818 {
4819 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4820 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4821 }
4822 for (i = 0; i < MAX_CONST_I; ++i)
4823 {
4824 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4825 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4826 }
4827
4828 if(pshader) {
4829 char name[32];
4830
4831 for(i = 0; i < MAX_TEXTURES; i++) {
4832 sprintf(name, "bumpenvmat%u", i);
4833 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4834 sprintf(name, "luminancescale%u", i);
4835 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4836 sprintf(name, "luminanceoffset%u", i);
4837 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4838 }
4839
4840 if (ps_compile_args.np2_fixup) {
4841 if (WINEFIXUPINFO_ISVALID(entry)) {
4842 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4843 } else {
4844 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4845 }
4846 }
4847 }
4848
4849 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4850 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4851 checkGLcall("Find glsl program uniform locations");
4852
4853 if (pshader
4854 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4855 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4856 {
4857 TRACE("Shader %p needs vertex color clamping disabled\n", (void *)(uintptr_t)programId);
4858 entry->vertex_color_clamp = GL_FALSE;
4859 } else {
4860 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4861 }
4862
4863 /* Set the shader to allow uniform loading on it */
4864 GL_EXTCALL(glUseProgramObjectARB(programId));
4865 checkGLcall("glUseProgramObjectARB(programId)");
4866
4867#ifdef DEBUG_misha
4868 {
4869 GLint programIdTest = -1;
4870 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
4871 Assert(programIdTest == programId);
4872 }
4873#endif
4874
4875 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4876 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4877 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4878 * vertex shader with fixed function pixel processing is used we make sure that the card
4879 * supports enough samplers to allow the max number of vertex samplers with all possible
4880 * fixed function fragment processing setups. So once the program is linked these samplers
4881 * won't change.
4882 */
4883 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4884 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4885
4886 /* If the local constants do not have to be loaded with the environment constants,
4887 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4888 * later
4889 */
4890 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4891 {
4892 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4893 }
4894 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4895 {
4896 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4897 }
4898}
4899
4900/* GL locking is done by the caller */
4901static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4902{
4903 GLhandleARB program_id;
4904 GLhandleARB vshader_id, pshader_id;
4905 static const char *blt_vshader[] =
4906 {
4907 "#version 120\n"
4908 "void main(void)\n"
4909 "{\n"
4910 " gl_Position = gl_Vertex;\n"
4911 " gl_FrontColor = vec4(1.0);\n"
4912 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4913 "}\n"
4914 };
4915
4916 static const char *blt_pshaders[tex_type_count] =
4917 {
4918 /* tex_1d */
4919 NULL,
4920 /* tex_2d */
4921 "#version 120\n"
4922 "uniform sampler2D sampler;\n"
4923 "void main(void)\n"
4924 "{\n"
4925 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4926 "}\n",
4927 /* tex_3d */
4928 NULL,
4929 /* tex_cube */
4930 "#version 120\n"
4931 "uniform samplerCube sampler;\n"
4932 "void main(void)\n"
4933 "{\n"
4934 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4935 "}\n",
4936 /* tex_rect */
4937 "#version 120\n"
4938 "#extension GL_ARB_texture_rectangle : enable\n"
4939 "uniform sampler2DRect sampler;\n"
4940 "void main(void)\n"
4941 "{\n"
4942 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4943 "}\n",
4944 };
4945
4946 if (!blt_pshaders[tex_type])
4947 {
4948 FIXME("tex_type %#x not supported\n", tex_type);
4949 tex_type = tex_2d;
4950 }
4951
4952 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4953 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4954 GL_EXTCALL(glCompileShaderARB(vshader_id));
4955 shader_glsl_validate_compile_link(gl_info, vshader_id, FALSE);
4956
4957 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4958 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4959 GL_EXTCALL(glCompileShaderARB(pshader_id));
4960
4961 shader_glsl_validate_compile_link(gl_info, vshader_id, FALSE);
4962
4963 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4964 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4965 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4966 GL_EXTCALL(glLinkProgramARB(program_id));
4967 shader_glsl_validate_compile_link(gl_info, program_id, TRUE);
4968
4969 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4970 * is destroyed
4971 */
4972 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4973 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4974 return program_id;
4975}
4976
4977/* GL locking is done by the caller */
4978static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4979{
4980 const struct wined3d_gl_info *gl_info = context->gl_info;
4981 IWineD3DDeviceImpl *device = context_get_device(context);
4982 struct shader_glsl_priv *priv = device->shader_priv;
4983 GLhandleARB program_id = 0;
4984 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4985
4986 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4987
4988 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4989 else priv->glsl_program = NULL;
4990
4991 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4992
4993 if (old_vertex_color_clamp != current_vertex_color_clamp)
4994 {
4995 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4996 {
4997 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4998 checkGLcall("glClampColorARB");
4999 }
5000 else
5001 {
5002 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
5003 }
5004 }
5005
5006 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5007 if (program_id) TRACE("Using GLSL program %p\n", (void *)(uintptr_t)program_id);
5008 GL_EXTCALL(glUseProgramObjectARB(program_id));
5009 checkGLcall("glUseProgramObjectARB");
5010#ifdef DEBUG_misha
5011 {
5012 GLint programIdTest = -1;
5013 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5014 Assert(programIdTest == program_id);
5015 }
5016#endif
5017
5018 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
5019 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
5020 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
5021 if (priv->glsl_program && WINEFIXUPINFO_ISVALID(priv->glsl_program))
5022 {
5023 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
5024 }
5025}
5026
5027/* GL locking is done by the caller */
5028static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
5029 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5030 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5031 struct shader_glsl_priv *priv = This->shader_priv;
5032 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
5033
5034 if (!*blt_program) {
5035 GLint loc;
5036 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
5037 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
5038 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5039#ifdef DEBUG_misha
5040 {
5041 GLint programIdTest = -1;
5042 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5043 Assert(programIdTest == *blt_program);
5044 }
5045#endif
5046 GL_EXTCALL(glUniform1iARB(loc, 0));
5047 } else {
5048 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5049#ifdef DEBUG_misha
5050 {
5051 GLint programIdTest = -1;
5052 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5053 Assert(programIdTest == *blt_program);
5054 }
5055#endif
5056 }
5057}
5058
5059/* GL locking is done by the caller */
5060static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
5061 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5062 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5063 struct shader_glsl_priv *priv = This->shader_priv;
5064 GLhandleARB program_id;
5065
5066 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5067 if (program_id) TRACE("Using GLSL program %p\n", (void *)(uintptr_t)program_id);
5068
5069 GL_EXTCALL(glUseProgramObjectARB(program_id));
5070 checkGLcall("glUseProgramObjectARB");
5071#ifdef DEBUG_misha
5072 {
5073 GLint programIdTest = -1;
5074 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5075 Assert(programIdTest == program_id);
5076 }
5077#endif
5078}
5079
5080static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
5081 const struct list *linked_programs;
5082 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
5083 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
5084 struct shader_glsl_priv *priv = device->shader_priv;
5085 const struct wined3d_gl_info *gl_info;
5086 struct wined3d_context *context;
5087
5088 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
5089 * can be called from IWineD3DBaseShader::Release
5090 */
5091 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
5092
5093 if(pshader) {
5094 struct glsl_pshader_private *shader_data;
5095 shader_data = This->baseShader.backend_data;
5096 if(!shader_data || shader_data->num_gl_shaders == 0)
5097 {
5098 HeapFree(GetProcessHeap(), 0, shader_data);
5099 This->baseShader.backend_data = NULL;
5100 return;
5101 }
5102
5103 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
5104 gl_info = context->gl_info;
5105
5106 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
5107 {
5108 ENTER_GL();
5109 shader_glsl_select(context, FALSE, FALSE);
5110 LEAVE_GL();
5111 }
5112 } else {
5113 struct glsl_vshader_private *shader_data;
5114 shader_data = This->baseShader.backend_data;
5115 if(!shader_data || shader_data->num_gl_shaders == 0)
5116 {
5117 HeapFree(GetProcessHeap(), 0, shader_data);
5118 This->baseShader.backend_data = NULL;
5119 return;
5120 }
5121
5122 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
5123 gl_info = context->gl_info;
5124
5125 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
5126 {
5127 ENTER_GL();
5128 shader_glsl_select(context, FALSE, FALSE);
5129 LEAVE_GL();
5130 }
5131 }
5132
5133 linked_programs = &This->baseShader.linked_programs;
5134
5135 TRACE("Deleting linked programs\n");
5136 if (linked_programs->next) {
5137 struct glsl_shader_prog_link *entry, *entry2;
5138
5139 ENTER_GL();
5140 if(pshader) {
5141 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
5142 delete_glsl_program_entry(priv, gl_info, entry);
5143 }
5144 } else {
5145 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
5146 delete_glsl_program_entry(priv, gl_info, entry);
5147 }
5148 }
5149 LEAVE_GL();
5150 }
5151
5152 if(pshader) {
5153 UINT i;
5154 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
5155
5156 ENTER_GL();
5157 for(i = 0; i < shader_data->num_gl_shaders; i++) {
5158 if (shader_data->gl_shaders[i].context==context_get_current())
5159 {
5160 TRACE("deleting pshader %p\n", (void *)(uintptr_t)shader_data->gl_shaders[i].prgId);
5161 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
5162 checkGLcall("glDeleteObjectARB");
5163 }
5164 else
5165 {
5166 WARN("Attempting to delete pshader %p created in ctx %p from ctx %p\n",
5167 (void *)(uintptr_t)shader_data->gl_shaders[i].prgId, shader_data->gl_shaders[i].context, context_get_current());
5168 }
5169 }
5170 LEAVE_GL();
5171 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
5172 }
5173 else
5174 {
5175 UINT i;
5176 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
5177
5178 ENTER_GL();
5179 for(i = 0; i < shader_data->num_gl_shaders; i++) {
5180 if (shader_data->gl_shaders[i].context==context_get_current())
5181 {
5182 TRACE("deleting vshader %p\n", (void *)(uintptr_t)shader_data->gl_shaders[i].prgId);
5183 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
5184 checkGLcall("glDeleteObjectARB");
5185 }
5186 else
5187 {
5188 WARN("Attempting to delete vshader %p created in ctx %p from ctx %p\n",
5189 (void *)(uintptr_t)shader_data->gl_shaders[i].prgId, shader_data->gl_shaders[i].context, context_get_current());
5190 }
5191 }
5192 LEAVE_GL();
5193 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
5194 }
5195
5196 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
5197 This->baseShader.backend_data = NULL;
5198
5199 context_release(context);
5200}
5201
5202static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
5203{
5204 const glsl_program_key_t *k = key;
5205 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
5206 const struct glsl_shader_prog_link, program_lookup_entry);
5207 int cmp;
5208
5209 if (k->context > prog->context) return 1;
5210 else if (k->context < prog->context) return -1;
5211
5212 if (k->vshader > prog->vshader) return 1;
5213 else if (k->vshader < prog->vshader) return -1;
5214
5215 if (k->pshader > prog->pshader) return 1;
5216 else if (k->pshader < prog->pshader) return -1;
5217
5218 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
5219 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
5220
5221 return 0;
5222}
5223
5224static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
5225{
5226#ifndef VBOX
5227 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5228 void *mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
5229#else
5230 SIZE_T size;
5231 void *mem;
5232
5233 /* Don't trash the heap if the input is bogus. */
5234 if (constant_count == 0)
5235 constant_count = 1;
5236
5237 size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5238 mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
5239#endif
5240
5241 if (!mem)
5242 {
5243 ERR("Failed to allocate memory\n");
5244 return FALSE;
5245 }
5246
5247 heap->entries = mem;
5248 heap->entries[1].version = 0;
5249 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
5250 heap->size = 1;
5251
5252 return TRUE;
5253}
5254
5255static void constant_heap_free(struct constant_heap *heap)
5256{
5257 HeapFree(GetProcessHeap(), 0, heap->entries);
5258}
5259
5260static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
5261{
5262 wined3d_rb_alloc,
5263 wined3d_rb_realloc,
5264 wined3d_rb_free,
5265 glsl_program_key_compare,
5266};
5267
5268static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
5269 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5270 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5271 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
5272 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
5273 gl_info->limits.glsl_ps_float_constants)) + 1;
5274
5275 if (!shader_buffer_init(&priv->shader_buffer))
5276 {
5277 ERR("Failed to initialize shader buffer.\n");
5278 goto fail;
5279 }
5280
5281 priv->stack = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, stack_size * sizeof(*priv->stack));
5282 if (!priv->stack)
5283 {
5284 ERR("Failed to allocate memory.\n");
5285 goto fail;
5286 }
5287 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
5288 {
5289 ERR("Failed to initialize vertex shader constant heap\n");
5290 goto fail;
5291 }
5292 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
5293 {
5294 ERR("Failed to initialize pixel shader constant heap\n");
5295 goto fail;
5296 }
5297
5298 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
5299 {
5300 ERR("Failed to initialize rbtree.\n");
5301 goto fail;
5302 }
5303
5304 priv->next_constant_version = 1;
5305
5306 This->shader_priv = priv;
5307 return WINED3D_OK;
5308
5309fail:
5310 constant_heap_free(&priv->pconst_heap);
5311 constant_heap_free(&priv->vconst_heap);
5312 HeapFree(GetProcessHeap(), 0, priv->stack);
5313 shader_buffer_free(&priv->shader_buffer);
5314 HeapFree(GetProcessHeap(), 0, priv);
5315 return E_OUTOFMEMORY;
5316}
5317
5318/* Context activation is done by the caller. */
5319static void shader_glsl_free(IWineD3DDevice *iface) {
5320 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5321 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5322 struct shader_glsl_priv *priv = This->shader_priv;
5323 int i;
5324
5325 ENTER_GL();
5326 for (i = 0; i < tex_type_count; ++i)
5327 {
5328 if (priv->depth_blt_program[i])
5329 {
5330 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
5331 }
5332 }
5333 LEAVE_GL();
5334
5335 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
5336 constant_heap_free(&priv->pconst_heap);
5337 constant_heap_free(&priv->vconst_heap);
5338 HeapFree(GetProcessHeap(), 0, priv->stack);
5339 shader_buffer_free(&priv->shader_buffer);
5340
5341 HeapFree(GetProcessHeap(), 0, This->shader_priv);
5342 This->shader_priv = NULL;
5343}
5344
5345static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
5346 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
5347 return FALSE;
5348}
5349
5350static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
5351{
5352 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
5353 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
5354 * on the version of NV_vertex_program.
5355 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
5356 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
5357 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
5358 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
5359 */
5360 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
5361 || gl_info->limits.arb_ps_instructions <= 512
5362 || gl_info->limits.glsl_vs_float_constants < 256)
5363 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
5364 else
5365 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
5366 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
5367 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
5368
5369 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
5370 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
5371 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
5372 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
5373 * in max native instructions. Intel and others also offer the info in this extension but they
5374 * don't support GLSL (at least on Windows).
5375 *
5376 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
5377 * of instructions is 512 or less we have to do with ps2.0 hardware.
5378 * 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.
5379 */
5380 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
5381 || gl_info->limits.arb_ps_instructions <= 512
5382 || gl_info->limits.glsl_vs_float_constants < 256)
5383 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
5384 else
5385 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
5386
5387 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
5388
5389 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
5390 * Direct3D minimum requirement.
5391 *
5392 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
5393 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
5394 *
5395 * The problem is that the refrast clamps temporary results in the shader to
5396 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
5397 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
5398 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
5399 * offer a way to query this.
5400 */
5401 pCaps->PixelShader1xMaxValue = 8.0;
5402 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
5403
5404 pCaps->VSClipping = TRUE;
5405}
5406
5407static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5408{
5409 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5410 {
5411 TRACE("Checking support for fixup:\n");
5412 dump_color_fixup_desc(fixup);
5413 }
5414
5415 /* We support everything except YUV conversions. */
5416 if (!is_complex_fixup(fixup))
5417 {
5418 TRACE("[OK]\n");
5419 return TRUE;
5420 }
5421
5422 TRACE("[FAILED]\n");
5423 return FALSE;
5424}
5425
5426static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5427{
5428 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5429 /* WINED3DSIH_ADD */ shader_glsl_arith,
5430 /* WINED3DSIH_BEM */ shader_glsl_bem,
5431 /* WINED3DSIH_BREAK */ shader_glsl_break,
5432 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5433 /* WINED3DSIH_BREAKP */ NULL,
5434 /* WINED3DSIH_CALL */ shader_glsl_call,
5435 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5436 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5437 /* WINED3DSIH_CND */ shader_glsl_cnd,
5438 /* WINED3DSIH_CRS */ shader_glsl_cross,
5439 /* WINED3DSIH_CUT */ NULL,
5440 /* WINED3DSIH_DCL */ NULL,
5441 /* WINED3DSIH_DEF */ NULL,
5442 /* WINED3DSIH_DEFB */ NULL,
5443 /* WINED3DSIH_DEFI */ NULL,
5444 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5445 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5446 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5447 /* WINED3DSIH_DST */ shader_glsl_dst,
5448 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5449 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5450 /* WINED3DSIH_ELSE */ shader_glsl_else,
5451 /* WINED3DSIH_EMIT */ NULL,
5452 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5453 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5454 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5455 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5456 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5457 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5458 /* WINED3DSIH_IADD */ NULL,
5459 /* WINED3DSIH_IF */ shader_glsl_if,
5460 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5461 /* WINED3DSIH_IGE */ NULL,
5462 /* WINED3DSIH_LABEL */ shader_glsl_label,
5463 /* WINED3DSIH_LIT */ shader_glsl_lit,
5464 /* WINED3DSIH_LOG */ shader_glsl_log,
5465 /* WINED3DSIH_LOGP */ shader_glsl_log,
5466 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5467 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5468 /* WINED3DSIH_LT */ NULL,
5469 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5470 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5471 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5472 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5473 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5474 /* WINED3DSIH_MAD */ shader_glsl_mad,
5475 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5476 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5477 /* WINED3DSIH_MOV */ shader_glsl_mov,
5478 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5479 /* WINED3DSIH_MUL */ shader_glsl_arith,
5480 /* WINED3DSIH_NOP */ NULL,
5481 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5482 /* WINED3DSIH_PHASE */ NULL,
5483 /* WINED3DSIH_POW */ shader_glsl_pow,
5484 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5485 /* WINED3DSIH_REP */ shader_glsl_rep,
5486 /* WINED3DSIH_RET */ shader_glsl_ret,
5487 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5488#ifdef VBOX_WITH_VMSVGA
5489 /* WINED3DSIH_SETP */ shader_glsl_setp,
5490#else
5491 /* WINED3DSIH_SETP */ NULL,
5492#endif
5493 /* WINED3DSIH_SGE */ shader_glsl_compare,
5494 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5495 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5496 /* WINED3DSIH_SLT */ shader_glsl_compare,
5497 /* WINED3DSIH_SUB */ shader_glsl_arith,
5498 /* WINED3DSIH_TEX */ shader_glsl_tex,
5499 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5500 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5501 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5502 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5503 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5504 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5505 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5506 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5507 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5508 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5509 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5510 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5511 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5512 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5513 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5514 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5515 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5516 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5517 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5518 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5519 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5520};
5521
5522static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5523 SHADER_HANDLER hw_fct;
5524
5525 /* Select handler */
5526 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5527
5528 /* Unhandled opcode */
5529 if (!hw_fct)
5530 {
5531 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5532 return;
5533 }
5534 hw_fct(ins);
5535
5536 shader_glsl_add_instruction_modifiers(ins);
5537}
5538
5539const shader_backend_t glsl_shader_backend = {
5540 shader_glsl_handle_instruction,
5541 shader_glsl_select,
5542 shader_glsl_select_depth_blt,
5543 shader_glsl_deselect_depth_blt,
5544 shader_glsl_update_float_vertex_constants,
5545 shader_glsl_update_float_pixel_constants,
5546 shader_glsl_load_constants,
5547 shader_glsl_load_np2fixup_constants,
5548 shader_glsl_destroy,
5549 shader_glsl_alloc,
5550 shader_glsl_free,
5551 shader_glsl_dirty_const,
5552 shader_glsl_get_caps,
5553 shader_glsl_color_fixup_supported,
5554};
5555
5556#if defined(VBOXWINEDBG_SHADERS) || defined(VBOX_WINE_WITH_PROFILE)
5557void vboxWDbgPrintF(char * szString, ...)
5558{
5559 char szBuffer[4096*2] = {0};
5560 va_list pArgList;
5561 va_start(pArgList, szString);
5562 _vsnprintf(szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]), szString, pArgList);
5563 va_end(pArgList);
5564
5565 OutputDebugStringA(szBuffer);
5566}
5567#endif
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette