VirtualBox

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

Last change on this file since 80515 was 80515, checked in by vboxsync, 6 years ago

Devices/Graphics/shaderlib: workaround for mac OS GL driver limits

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

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