VirtualBox

source: vbox/trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-ogl.cpp@ 84742

Last change on this file since 84742 was 84742, checked in by vboxsync, 4 years ago

Devices/Graphics: experimental GLX graphics output

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 293.0 KB
Line 
1/* $Id: DevVGA-SVGA3d-ogl.cpp 84742 2020-06-09 17:49:09Z vboxsync $ */
2/** @file
3 * DevVMWare - VMWare SVGA device
4 */
5
6/*
7 * Copyright (C) 2013-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22/* Enable to disassemble defined shaders. (Windows host only) */
23#if defined(RT_OS_WINDOWS) && defined(DEBUG) && 0 /* Disabled as we don't have the DirectX SDK avaible atm. */
24# define DUMP_SHADER_DISASSEMBLY
25#endif
26#ifdef DEBUG_bird
27//# define RTMEM_WRAP_TO_EF_APIS
28#endif
29#define LOG_GROUP LOG_GROUP_DEV_VMSVGA
30#include <VBox/vmm/pdmdev.h>
31#include <VBox/version.h>
32#include <VBox/err.h>
33#include <VBox/log.h>
34#include <VBox/vmm/pgm.h>
35#include <VBox/AssertGuest.h>
36
37#include <iprt/assert.h>
38#include <iprt/semaphore.h>
39#include <iprt/uuid.h>
40#include <iprt/mem.h>
41
42#include <VBoxVideo.h> /* required by DevVGA.h */
43#include <VBoxVideo3D.h>
44
45/* should go BEFORE any other DevVGA include to make all DevVGA.h config defines be visible */
46#include "DevVGA.h"
47
48#include "DevVGA-SVGA.h"
49#include "DevVGA-SVGA3d.h"
50#include "DevVGA-SVGA3d-internal.h"
51
52#ifdef DUMP_SHADER_DISASSEMBLY
53# include <d3dx9shader.h>
54#endif
55
56#include <stdlib.h>
57#include <math.h>
58#include <float.h> /* FLT_MIN */
59
60
61/*********************************************************************************************************************************
62* Defined Constants And Macros *
63*********************************************************************************************************************************/
64#ifndef VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE
65# define VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE 1.0
66#endif
67
68#ifdef VMSVGA3D_DYNAMIC_LOAD
69# define OGLGETPROCADDRESS glLdrGetProcAddress
70#else
71#ifdef RT_OS_WINDOWS
72# define OGLGETPROCADDRESS MyWinGetProcAddress
73DECLINLINE(PROC) MyWinGetProcAddress(const char *pszSymbol)
74{
75 /* Khronos: [on failure] "some implementations will return other values. 1, 2, and 3 are used, as well as -1". */
76 PROC p = wglGetProcAddress(pszSymbol);
77 if (RT_VALID_PTR(p))
78 return p;
79 return 0;
80}
81#elif defined(RT_OS_DARWIN)
82# include <dlfcn.h>
83# define OGLGETPROCADDRESS MyNSGLGetProcAddress
84/** Resolves an OpenGL symbol. */
85static void *MyNSGLGetProcAddress(const char *pszSymbol)
86{
87 /* Another copy in shaderapi.c. */
88 static void *s_pvImage = NULL;
89 if (s_pvImage == NULL)
90 s_pvImage = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
91 return s_pvImage ? dlsym(s_pvImage, pszSymbol) : NULL;
92}
93
94#else
95# define OGLGETPROCADDRESS(x) glXGetProcAddress((const GLubyte *)x)
96#endif
97#endif
98
99/* Invert y-coordinate for OpenGL's bottom left origin. */
100#define D3D_TO_OGL_Y_COORD(ptrSurface, y_coordinate) (ptrSurface->paMipmapLevels[0].mipmapSize.height - (y_coordinate))
101#define D3D_TO_OGL_Y_COORD_MIPLEVEL(ptrMipLevel, y_coordinate) (ptrMipLevel->size.height - (y_coordinate))
102
103/**
104 * Macro for doing something and then checking for errors during initialization.
105 * Uses AssertLogRelMsg.
106 */
107#define VMSVGA3D_INIT_CHECKED(a_Expr) \
108 do \
109 { \
110 a_Expr; \
111 GLenum iGlError = glGetError(); \
112 AssertLogRelMsg(iGlError == GL_NO_ERROR, ("VMSVGA3d: %s -> %#x\n", #a_Expr, iGlError)); \
113 } while (0)
114
115/**
116 * Macro for doing something and then checking for errors during initialization,
117 * doing the same in the other context when enabled.
118 *
119 * This will try both profiles in dual profile builds. Caller must be in the
120 * default context.
121 *
122 * Uses AssertLogRelMsg to indicate trouble.
123 */
124#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
125# define VMSVGA3D_INIT_CHECKED_BOTH(a_pState, a_pContext, a_pOtherCtx, a_Expr) \
126 do \
127 { \
128 for (uint32_t i = 0; i < 64; i++) if (glGetError() == GL_NO_ERROR) break; Assert(glGetError() == GL_NO_ERROR); \
129 a_Expr; \
130 GLenum iGlError = glGetError(); \
131 if (iGlError != GL_NO_ERROR) \
132 { \
133 VMSVGA3D_SET_CURRENT_CONTEXT(a_pState, a_pOtherCtx); \
134 for (uint32_t i = 0; i < 64; i++) if (glGetError() == GL_NO_ERROR) break; Assert(glGetError() == GL_NO_ERROR); \
135 a_Expr; \
136 GLenum iGlError2 = glGetError(); \
137 AssertLogRelMsg(iGlError2 == GL_NO_ERROR, ("VMSVGA3d: %s -> %#x / %#x\n", #a_Expr, iGlError, iGlError2)); \
138 VMSVGA3D_SET_CURRENT_CONTEXT(a_pState, a_pContext); \
139 } \
140 } while (0)
141#else
142# define VMSVGA3D_INIT_CHECKED_BOTH(a_pState, a_pContext, a_pOtherCtx, a_Expr) VMSVGA3D_INIT_CHECKED(a_Expr)
143#endif
144
145
146/*********************************************************************************************************************************
147* Global Variables *
148*********************************************************************************************************************************/
149/* Define the default light parameters as specified by MSDN. */
150/** @todo move out; fetched from Wine */
151const SVGA3dLightData vmsvga3d_default_light =
152{
153 SVGA3D_LIGHTTYPE_DIRECTIONAL, /* type */
154 false, /* inWorldSpace */
155 { 1.0f, 1.0f, 1.0f, 0.0f }, /* diffuse r,g,b,a */
156 { 0.0f, 0.0f, 0.0f, 0.0f }, /* specular r,g,b,a */
157 { 0.0f, 0.0f, 0.0f, 0.0f }, /* ambient r,g,b,a, */
158 { 0.0f, 0.0f, 0.0f }, /* position x,y,z */
159 { 0.0f, 0.0f, 1.0f }, /* direction x,y,z */
160 0.0f, /* range */
161 0.0f, /* falloff */
162 0.0f, 0.0f, 0.0f, /* attenuation 0,1,2 */
163 0.0f, /* theta */
164 0.0f /* phi */
165};
166
167
168/*********************************************************************************************************************************
169* Internal Functions *
170*********************************************************************************************************************************/
171static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid);
172static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha);
173
174/* Generated by VBoxDef2LazyLoad from the VBoxSVGA3D.def and VBoxSVGA3DObjC.def files. */
175extern "C" int ExplicitlyLoadVBoxSVGA3D(bool fResolveAllImports, PRTERRINFO pErrInfo);
176
177
178/**
179 * Checks if the given OpenGL extension is supported.
180 *
181 * @returns true if supported, false if not.
182 * @param pState The VMSVGA3d state.
183 * @param rsMinGLVersion The OpenGL version that introduced this feature
184 * into the core.
185 * @param pszWantedExtension The name of the OpenGL extension we want padded
186 * with one space at each end.
187 * @remarks Init time only.
188 */
189static bool vmsvga3dCheckGLExtension(PVMSVGA3DSTATE pState, float rsMinGLVersion, const char *pszWantedExtension)
190{
191 RT_NOREF(rsMinGLVersion);
192 /* check padding. */
193 Assert(pszWantedExtension[0] == ' ');
194 Assert(pszWantedExtension[1] != ' ');
195 Assert(strchr(&pszWantedExtension[1], ' ') + 1 == strchr(pszWantedExtension, '\0'));
196
197 /* Look it up. */
198 bool fRet = false;
199 if (strstr(pState->pszExtensions, pszWantedExtension))
200 fRet = true;
201
202 /* Temporarily. Later start if (rsMinGLVersion != 0.0 && fActualGLVersion >= rsMinGLVersion) return true; */
203#ifdef RT_OS_DARWIN
204 AssertMsg( rsMinGLVersion == 0.0
205 || fRet == (pState->rsGLVersion >= rsMinGLVersion)
206 || VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE == 2.1,
207 ("%s actual:%d min:%d fRet=%d\n",
208 pszWantedExtension, (int)(pState->rsGLVersion * 10), (int)(rsMinGLVersion * 10), fRet));
209#else
210 AssertMsg(rsMinGLVersion == 0.0 || fRet == (pState->rsGLVersion >= rsMinGLVersion),
211 ("%s actual:%d min:%d fRet=%d\n",
212 pszWantedExtension, (int)(pState->rsGLVersion * 10), (int)(rsMinGLVersion * 10), fRet));
213#endif
214 return fRet;
215}
216
217
218/**
219 * Outputs GL_EXTENSIONS list to the release log.
220 */
221static void vmsvga3dLogRelExtensions(const char *pszPrefix, const char *pszExtensions)
222{
223 /* OpenGL 3.0 interface (glGetString(GL_EXTENSIONS) return NULL). */
224 bool fBuffered = RTLogRelSetBuffering(true);
225
226 /*
227 * Determin the column widths first.
228 */
229 size_t acchWidths[4] = { 1, 1, 1, 1 };
230 uint32_t i;
231 const char *psz = pszExtensions;
232 for (i = 0; ; i++)
233 {
234 while (*psz == ' ')
235 psz++;
236 if (!*psz)
237 break;
238
239 const char *pszEnd = strchr(psz, ' ');
240 AssertBreak(pszEnd);
241 size_t cch = pszEnd - psz;
242
243 uint32_t iColumn = i % RT_ELEMENTS(acchWidths);
244 if (acchWidths[iColumn] < cch)
245 acchWidths[iColumn] = cch;
246
247 psz = pszEnd;
248 }
249
250 /*
251 * Output it.
252 */
253 LogRel(("VMSVGA3d: %sOpenGL extensions (%d):", pszPrefix, i));
254 psz = pszExtensions;
255 for (i = 0; ; i++)
256 {
257 while (*psz == ' ')
258 psz++;
259 if (!*psz)
260 break;
261
262 const char *pszEnd = strchr(psz, ' ');
263 AssertBreak(pszEnd);
264 size_t cch = pszEnd - psz;
265
266 uint32_t iColumn = i % RT_ELEMENTS(acchWidths);
267 if (iColumn == 0)
268 LogRel(("\nVMSVGA3d: %-*.*s", acchWidths[iColumn], cch, psz));
269 else if (iColumn != RT_ELEMENTS(acchWidths) - 1)
270 LogRel((" %-*.*s", acchWidths[iColumn], cch, psz));
271 else
272 LogRel((" %.*s", cch, psz));
273
274 psz = pszEnd;
275 }
276
277 RTLogRelSetBuffering(fBuffered);
278 LogRel(("\n"));
279}
280
281/**
282 * Gathers the GL_EXTENSIONS list, storing it as a space padded list at
283 * @a ppszExtensions.
284 *
285 * @returns VINF_SUCCESS or VERR_NO_STR_MEMORY
286 * @param ppszExtensions Pointer to the string pointer. Free with RTStrFree.
287 * @param fGLProfileVersion The OpenGL profile version.
288 */
289static int vmsvga3dGatherExtensions(char **ppszExtensions, float fGLProfileVersion)
290{
291 int rc;
292 *ppszExtensions = NULL;
293
294 /*
295 * Try the old glGetString interface first.
296 */
297 const char *pszExtensions = (const char *)glGetString(GL_EXTENSIONS);
298 if (pszExtensions)
299 {
300 rc = RTStrAAppendExN(ppszExtensions, 3, " ", (size_t)1, pszExtensions, RTSTR_MAX, " ", (size_t)1);
301 AssertLogRelRCReturn(rc, rc);
302 }
303 else
304 {
305 /*
306 * The new interface where each extension string is retrieved separately.
307 * Note! Cannot use VMSVGA3D_INIT_CHECKED_GL_GET_INTEGER_VALUE here because
308 * the above GL_EXTENSIONS error lingers on darwin. sucks.
309 */
310#ifndef GL_NUM_EXTENSIONS
311# define GL_NUM_EXTENSIONS 0x821D
312#endif
313 GLint cExtensions = 1024;
314 glGetIntegerv(GL_NUM_EXTENSIONS, &cExtensions);
315 Assert(cExtensions != 1024);
316
317 PFNGLGETSTRINGIPROC pfnGlGetStringi = (PFNGLGETSTRINGIPROC)OGLGETPROCADDRESS("glGetStringi");
318 AssertLogRelReturn(pfnGlGetStringi, VERR_NOT_SUPPORTED);
319
320 rc = RTStrAAppend(ppszExtensions, " ");
321 for (GLint i = 0; RT_SUCCESS(rc) && i < cExtensions; i++)
322 {
323 const char *pszExt = (const char *)pfnGlGetStringi(GL_EXTENSIONS, i);
324 if (pszExt)
325 rc = RTStrAAppendExN(ppszExtensions, 2, pfnGlGetStringi(GL_EXTENSIONS, i), RTSTR_MAX, " ", (size_t)1);
326 }
327 AssertRCReturn(rc, rc);
328 }
329
330#if 1
331 /*
332 * Add extensions promoted into the core OpenGL profile.
333 */
334 static const struct
335 {
336 float fGLVersion;
337 const char *pszzExtensions;
338 } s_aPromotedExtensions[] =
339 {
340 {
341 1.1f,
342 " GL_EXT_vertex_array \0"
343 " GL_EXT_polygon_offset \0"
344 " GL_EXT_blend_logic_op \0"
345 " GL_EXT_texture \0"
346 " GL_EXT_copy_texture \0"
347 " GL_EXT_subtexture \0"
348 " GL_EXT_texture_object \0"
349 " GL_ARB_framebuffer_object \0"
350 " GL_ARB_map_buffer_range \0"
351 " GL_ARB_vertex_array_object \0"
352 "\0"
353 },
354 {
355 1.2f,
356 " EXT_texture3D \0"
357 " EXT_bgra \0"
358 " EXT_packed_pixels \0"
359 " EXT_rescale_normal \0"
360 " EXT_separate_specular_color \0"
361 " SGIS_texture_edge_clamp \0"
362 " SGIS_texture_lod \0"
363 " EXT_draw_range_elements \0"
364 "\0"
365 },
366 {
367 1.3f,
368 " GL_ARB_texture_compression \0"
369 " GL_ARB_texture_cube_map \0"
370 " GL_ARB_multisample \0"
371 " GL_ARB_multitexture \0"
372 " GL_ARB_texture_env_add \0"
373 " GL_ARB_texture_env_combine \0"
374 " GL_ARB_texture_env_dot3 \0"
375 " GL_ARB_texture_border_clamp \0"
376 " GL_ARB_transpose_matrix \0"
377 "\0"
378 },
379 {
380 1.5f,
381 " GL_SGIS_generate_mipmap \0"
382 /*" GL_NV_blend_equare \0"*/
383 " GL_ARB_depth_texture \0"
384 " GL_ARB_shadow \0"
385 " GL_EXT_fog_coord \0"
386 " GL_EXT_multi_draw_arrays \0"
387 " GL_ARB_point_parameters \0"
388 " GL_EXT_secondary_color \0"
389 " GL_EXT_blend_func_separate \0"
390 " GL_EXT_stencil_wrap \0"
391 " GL_ARB_texture_env_crossbar \0"
392 " GL_EXT_texture_lod_bias \0"
393 " GL_ARB_texture_mirrored_repeat \0"
394 " GL_ARB_window_pos \0"
395 "\0"
396 },
397 {
398 1.6f,
399 " GL_ARB_vertex_buffer_object \0"
400 " GL_ARB_occlusion_query \0"
401 " GL_EXT_shadow_funcs \0"
402 },
403 {
404 2.0f,
405 " GL_ARB_shader_objects \0" /*??*/
406 " GL_ARB_vertex_shader \0" /*??*/
407 " GL_ARB_fragment_shader \0" /*??*/
408 " GL_ARB_shading_language_100 \0" /*??*/
409 " GL_ARB_draw_buffers \0"
410 " GL_ARB_texture_non_power_of_two \0"
411 " GL_ARB_point_sprite \0"
412 " GL_ATI_separate_stencil \0"
413 " GL_EXT_stencil_two_side \0"
414 "\0"
415 },
416 {
417 2.1f,
418 " GL_ARB_pixel_buffer_object \0"
419 " GL_EXT_texture_sRGB \0"
420 "\0"
421 },
422 {
423 3.0f,
424 " GL_ARB_framebuffer_object \0"
425 " GL_ARB_map_buffer_range \0"
426 " GL_ARB_vertex_array_object \0"
427 "\0"
428 },
429 {
430 3.1f,
431 " GL_ARB_copy_buffer \0"
432 " GL_ARB_uniform_buffer_object \0"
433 "\0"
434 },
435 {
436 3.2f,
437 " GL_ARB_vertex_array_bgra \0"
438 " GL_ARB_draw_elements_base_vertex \0"
439 " GL_ARB_fragment_coord_conventions \0"
440 " GL_ARB_provoking_vertex \0"
441 " GL_ARB_seamless_cube_map \0"
442 " GL_ARB_texture_multisample \0"
443 " GL_ARB_depth_clamp \0"
444 " GL_ARB_sync \0"
445 " GL_ARB_geometry_shader4 \0" /*??*/
446 "\0"
447 },
448 {
449 3.3f,
450 " GL_ARB_blend_func_extended \0"
451 " GL_ARB_sampler_objects \0"
452 " GL_ARB_explicit_attrib_location \0"
453 " GL_ARB_occlusion_query2 \0"
454 " GL_ARB_shader_bit_encoding \0"
455 " GL_ARB_texture_rgb10_a2ui \0"
456 " GL_ARB_texture_swizzle \0"
457 " GL_ARB_timer_query \0"
458 " GL_ARB_vertex_type_2_10_10_10_rev \0"
459 "\0"
460 },
461 {
462 4.0f,
463 " GL_ARB_texture_query_lod \0"
464 " GL_ARB_draw_indirect \0"
465 " GL_ARB_gpu_shader5 \0"
466 " GL_ARB_gpu_shader_fp64 \0"
467 " GL_ARB_shader_subroutine \0"
468 " GL_ARB_tessellation_shader \0"
469 " GL_ARB_texture_buffer_object_rgb32 \0"
470 " GL_ARB_texture_cube_map_array \0"
471 " GL_ARB_texture_gather \0"
472 " GL_ARB_transform_feedback2 \0"
473 " GL_ARB_transform_feedback3 \0"
474 "\0"
475 },
476 {
477 4.1f,
478 " GL_ARB_ES2_compatibility \0"
479 " GL_ARB_get_program_binary \0"
480 " GL_ARB_separate_shader_objects \0"
481 " GL_ARB_shader_precision \0"
482 " GL_ARB_vertex_attrib_64bit \0"
483 " GL_ARB_viewport_array \0"
484 "\0"
485 }
486 };
487
488 uint32_t cPromoted = 0;
489 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPromotedExtensions) && s_aPromotedExtensions[i].fGLVersion <= fGLProfileVersion; i++)
490 {
491 const char *pszExt = s_aPromotedExtensions[i].pszzExtensions;
492 while (*pszExt)
493 {
494# ifdef VBOX_STRICT
495 size_t cchExt = strlen(pszExt);
496 Assert(cchExt > 3);
497 Assert(pszExt[0] == ' ');
498 Assert(pszExt[1] != ' ');
499 Assert(pszExt[cchExt - 2] != ' ');
500 Assert(pszExt[cchExt - 1] == ' ');
501# endif
502
503 if (strstr(*ppszExtensions, pszExt) == NULL)
504 {
505 if (cPromoted++ == 0)
506 {
507 rc = RTStrAAppend(ppszExtensions, " <promoted-extensions:> <promoted-extensions:> <promoted-extensions:> ");
508 AssertRCReturn(rc, rc);
509 }
510
511 rc = RTStrAAppend(ppszExtensions, pszExt);
512 AssertRCReturn(rc, rc);
513 }
514
515 pszExt = strchr(pszExt, '\0') + 1;
516 }
517 }
518#endif
519
520 return VINF_SUCCESS;
521}
522
523/** Check whether this is an Intel GL driver.
524 *
525 * @returns true if this seems to be some Intel graphics.
526 */
527static bool vmsvga3dIsVendorIntel(void)
528{
529 return RTStrNICmp((char *)glGetString(GL_VENDOR), "Intel", 5) == 0;
530}
531
532/**
533 * @interface_method_impl{VBOXVMSVGASHADERIF,pfnSwitchInitProfile}
534 */
535static DECLCALLBACK(void) vmsvga3dShaderIfSwitchInitProfile(PVBOXVMSVGASHADERIF pThis, bool fOtherProfile)
536{
537#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
538 PVMSVGA3DSTATE pState = RT_FROM_MEMBER(pThis, VMSVGA3DSTATE, ShaderIf);
539 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pState->papContexts[fOtherProfile ? 2 : 1]);
540#else
541 NOREF(pThis);
542 NOREF(fOtherProfile);
543#endif
544}
545
546
547/**
548 * @interface_method_impl{VBOXVMSVGASHADERIF,pfnGetNextExtension}
549 */
550static DECLCALLBACK(bool) vmsvga3dShaderIfGetNextExtension(PVBOXVMSVGASHADERIF pThis, void **ppvEnumCtx,
551 char *pszBuf, size_t cbBuf, bool fOtherProfile)
552{
553 PVMSVGA3DSTATE pState = RT_FROM_MEMBER(pThis, VMSVGA3DSTATE, ShaderIf);
554 const char *pszCur = *ppvEnumCtx ? (const char *)*ppvEnumCtx
555 : fOtherProfile ? pState->pszOtherExtensions : pState->pszExtensions;
556 while (*pszCur == ' ')
557 pszCur++;
558 if (!*pszCur)
559 return false;
560
561 const char *pszEnd = strchr(pszCur, ' ');
562 AssertReturn(pszEnd, false);
563 size_t cch = pszEnd - pszCur;
564 if (cch < cbBuf)
565 {
566 memcpy(pszBuf, pszCur, cch);
567 pszBuf[cch] = '\0';
568 }
569 else if (cbBuf > 0)
570 {
571 memcpy(pszBuf, "<overflow>", RT_MIN(sizeof("<overflow>"), cbBuf));
572 pszBuf[cbBuf - 1] = '\0';
573 }
574
575 *ppvEnumCtx = (void *)pszEnd;
576 return true;
577}
578
579
580/**
581 * Initializes the VMSVGA3D state during VGA device construction.
582 *
583 * Failure are generally not fatal, 3D support will just be disabled.
584 *
585 * @returns VBox status code.
586 * @param pDevIns The device instance.
587 * @param pThis The shared VGA/VMSVGA state where svga.p3dState will be
588 * modified.
589 * @param pThisCC The VGA/VMSVGA state for ring-3.
590 */
591int vmsvga3dInit(PPDMDEVINS pDevIns, PVGASTATE pThis, PVGASTATECC pThisCC)
592{
593 int rc;
594 RT_NOREF(pDevIns, pThis);
595
596 AssertCompile(GL_TRUE == 1);
597 AssertCompile(GL_FALSE == 0);
598
599#ifdef VMSVGA3D_DYNAMIC_LOAD
600 rc = glLdrInit(pDevIns);
601 if (RT_FAILURE(rc))
602 {
603 LogRel(("VMSVGA3d: Error loading OpenGL library and resolving necessary functions: %Rrc\n", rc));
604 return rc;
605 }
606#endif
607
608 /*
609 * Load and resolve imports from the external shared libraries.
610 */
611 RTERRINFOSTATIC ErrInfo;
612 rc = ExplicitlyLoadVBoxSVGA3D(true /*fResolveAllImports*/, RTErrInfoInitStatic(&ErrInfo));
613 if (RT_FAILURE(rc))
614 {
615 LogRel(("VMSVGA3d: Error loading VBoxSVGA3D and resolving necessary functions: %Rrc - %s\n", rc, ErrInfo.Core.pszMsg));
616 return rc;
617 }
618#ifdef RT_OS_DARWIN
619 rc = ExplicitlyLoadVBoxSVGA3DObjC(true /*fResolveAllImports*/, RTErrInfoInitStatic(&ErrInfo));
620 if (RT_FAILURE(rc))
621 {
622 LogRel(("VMSVGA3d: Error loading VBoxSVGA3DObjC and resolving necessary functions: %Rrc - %s\n", rc, ErrInfo.Core.pszMsg));
623 return rc;
624 }
625#endif
626
627 /*
628 * Allocate the state.
629 */
630 pThisCC->svga.p3dState = (PVMSVGA3DSTATE)RTMemAllocZ(sizeof(VMSVGA3DSTATE));
631 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
632
633#ifdef RT_OS_WINDOWS
634 /* Create event semaphore and async IO thread. */
635 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
636 rc = RTSemEventCreate(&pState->WndRequestSem);
637 if (RT_SUCCESS(rc))
638 {
639 rc = RTThreadCreate(&pState->pWindowThread, vmsvga3dWindowThread, pState->WndRequestSem, 0, RTTHREADTYPE_GUI, 0,
640 "VMSVGA3DWND");
641 if (RT_SUCCESS(rc))
642 return VINF_SUCCESS;
643
644 /* bail out. */
645 LogRel(("VMSVGA3d: RTThreadCreate failed: %Rrc\n", rc));
646 RTSemEventDestroy(pState->WndRequestSem);
647 }
648 else
649 LogRel(("VMSVGA3d: RTSemEventCreate failed: %Rrc\n", rc));
650 RTMemFree(pThisCC->svga.p3dState);
651 pThisCC->svga.p3dState = NULL;
652 return rc;
653#else
654 return VINF_SUCCESS;
655#endif
656}
657
658static int vmsvga3dLoadGLFunctions(PVMSVGA3DSTATE pState)
659{
660 /* A strict approach to get a proc address as recommended by Khronos:
661 * - "If the function is a core OpenGL function, then we need to check the OpenGL version".
662 * - "If the function is an extension, we need to check to see if the extension is supported."
663 */
664
665/* Get a function address, return VERR_NOT_IMPLEMENTED on failure. */
666#define GLGETPROC_(ProcType, ProcName, NameSuffix) do { \
667 pState->ext.ProcName = (ProcType)OGLGETPROCADDRESS(#ProcName NameSuffix); \
668 AssertLogRelMsgReturn(pState->ext.ProcName, (#ProcName NameSuffix " missing"), VERR_NOT_IMPLEMENTED); \
669} while(0)
670
671/* Get an optional function address. LogRel on failure. */
672#define GLGETPROCOPT_(ProcType, ProcName, NameSuffix) do { \
673 pState->ext.ProcName = (ProcType)OGLGETPROCADDRESS(#ProcName NameSuffix); \
674 if (!pState->ext.ProcName) \
675 { \
676 LogRel(("VMSVGA3d: missing optional %s\n", #ProcName NameSuffix)); \
677 AssertFailed(); \
678 } \
679} while(0)
680
681 /* OpenGL 2.0 or earlier core. Do not bother with extensions. */
682 GLGETPROC_(PFNGLGENQUERIESPROC , glGenQueries, "");
683 GLGETPROC_(PFNGLDELETEQUERIESPROC , glDeleteQueries, "");
684 GLGETPROC_(PFNGLBEGINQUERYPROC , glBeginQuery, "");
685 GLGETPROC_(PFNGLENDQUERYPROC , glEndQuery, "");
686 GLGETPROC_(PFNGLGETQUERYOBJECTUIVPROC , glGetQueryObjectuiv, "");
687 GLGETPROC_(PFNGLTEXIMAGE3DPROC , glTexImage3D, "");
688 GLGETPROC_(PFNGLTEXSUBIMAGE3DPROC , glTexSubImage3D, "");
689 GLGETPROC_(PFNGLGETCOMPRESSEDTEXIMAGEPROC , glGetCompressedTexImage, "");
690 GLGETPROC_(PFNGLCOMPRESSEDTEXIMAGE2DPROC , glCompressedTexImage2D, "");
691 GLGETPROC_(PFNGLCOMPRESSEDTEXIMAGE3DPROC , glCompressedTexImage3D, "");
692 GLGETPROC_(PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC , glCompressedTexSubImage2D, "");
693 GLGETPROC_(PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC , glCompressedTexSubImage3D, "");
694 GLGETPROC_(PFNGLPOINTPARAMETERFPROC , glPointParameterf, "");
695 GLGETPROC_(PFNGLBLENDEQUATIONSEPARATEPROC , glBlendEquationSeparate, "");
696 GLGETPROC_(PFNGLBLENDFUNCSEPARATEPROC , glBlendFuncSeparate, "");
697 GLGETPROC_(PFNGLSTENCILOPSEPARATEPROC , glStencilOpSeparate, "");
698 GLGETPROC_(PFNGLSTENCILFUNCSEPARATEPROC , glStencilFuncSeparate, "");
699 GLGETPROC_(PFNGLBINDBUFFERPROC , glBindBuffer, "");
700 GLGETPROC_(PFNGLDELETEBUFFERSPROC , glDeleteBuffers, "");
701 GLGETPROC_(PFNGLGENBUFFERSPROC , glGenBuffers, "");
702 GLGETPROC_(PFNGLBUFFERDATAPROC , glBufferData, "");
703 GLGETPROC_(PFNGLMAPBUFFERPROC , glMapBuffer, "");
704 GLGETPROC_(PFNGLUNMAPBUFFERPROC , glUnmapBuffer, "");
705 GLGETPROC_(PFNGLENABLEVERTEXATTRIBARRAYPROC , glEnableVertexAttribArray, "");
706 GLGETPROC_(PFNGLDISABLEVERTEXATTRIBARRAYPROC , glDisableVertexAttribArray, "");
707 GLGETPROC_(PFNGLVERTEXATTRIBPOINTERPROC , glVertexAttribPointer, "");
708 GLGETPROC_(PFNGLACTIVETEXTUREPROC , glActiveTexture, "");
709 /* glGetProgramivARB determines implementation limits for the program
710 * target (GL_FRAGMENT_PROGRAM_ARB, GL_VERTEX_PROGRAM_ARB).
711 * It differs from glGetProgramiv, which returns a parameter from a program object.
712 */
713 GLGETPROC_(PFNGLGETPROGRAMIVARBPROC , glGetProgramivARB, "");
714 GLGETPROC_(PFNGLFOGCOORDPOINTERPROC , glFogCoordPointer, "");
715#if VBOX_VMSVGA3D_GL_HACK_LEVEL < 0x102
716 GLGETPROC_(PFNGLBLENDCOLORPROC , glBlendColor, "");
717 GLGETPROC_(PFNGLBLENDEQUATIONPROC , glBlendEquation, "");
718#endif
719#if VBOX_VMSVGA3D_GL_HACK_LEVEL < 0x103
720 GLGETPROC_(PFNGLCLIENTACTIVETEXTUREPROC , glClientActiveTexture, "");
721#endif
722 GLGETPROC_(PFNGLDRAWBUFFERSPROC , glDrawBuffers, "");
723 GLGETPROC_(PFNGLCREATESHADERPROC , glCreateShader, "");
724 GLGETPROC_(PFNGLSHADERSOURCEPROC , glShaderSource, "");
725 GLGETPROC_(PFNGLCOMPILESHADERPROC , glCompileShader, "");
726 GLGETPROC_(PFNGLGETSHADERIVPROC , glGetShaderiv, "");
727 GLGETPROC_(PFNGLGETSHADERINFOLOGPROC , glGetShaderInfoLog, "");
728 GLGETPROC_(PFNGLCREATEPROGRAMPROC , glCreateProgram, "");
729 GLGETPROC_(PFNGLATTACHSHADERPROC , glAttachShader, "");
730 GLGETPROC_(PFNGLLINKPROGRAMPROC , glLinkProgram, "");
731 GLGETPROC_(PFNGLGETPROGRAMIVPROC , glGetProgramiv, "");
732 GLGETPROC_(PFNGLGETPROGRAMINFOLOGPROC , glGetProgramInfoLog, "");
733 GLGETPROC_(PFNGLUSEPROGRAMPROC , glUseProgram, "");
734 GLGETPROC_(PFNGLGETUNIFORMLOCATIONPROC , glGetUniformLocation, "");
735 GLGETPROC_(PFNGLUNIFORM1IPROC , glUniform1i, "");
736 GLGETPROC_(PFNGLUNIFORM4FVPROC , glUniform4fv, "");
737 GLGETPROC_(PFNGLDETACHSHADERPROC , glDetachShader, "");
738 GLGETPROC_(PFNGLDELETESHADERPROC , glDeleteShader, "");
739 GLGETPROC_(PFNGLDELETEPROGRAMPROC , glDeleteProgram, "");
740
741 GLGETPROC_(PFNGLVERTEXATTRIB4FVPROC , glVertexAttrib4fv, "");
742 GLGETPROC_(PFNGLVERTEXATTRIB4UBVPROC , glVertexAttrib4ubv, "");
743 GLGETPROC_(PFNGLVERTEXATTRIB4NUBVPROC , glVertexAttrib4Nubv, "");
744 GLGETPROC_(PFNGLVERTEXATTRIB4SVPROC , glVertexAttrib4sv, "");
745 GLGETPROC_(PFNGLVERTEXATTRIB4NSVPROC , glVertexAttrib4Nsv, "");
746 GLGETPROC_(PFNGLVERTEXATTRIB4NUSVPROC , glVertexAttrib4Nusv, "");
747
748 /* OpenGL 3.0 core, GL_ARB_instanced_arrays. Same functions names in the ARB and core specs. */
749 if ( pState->rsGLVersion >= 3.0f
750 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_framebuffer_object "))
751 {
752 GLGETPROC_(PFNGLISRENDERBUFFERPROC , glIsRenderbuffer, "");
753 GLGETPROC_(PFNGLBINDRENDERBUFFERPROC , glBindRenderbuffer, "");
754 GLGETPROC_(PFNGLDELETERENDERBUFFERSPROC , glDeleteRenderbuffers, "");
755 GLGETPROC_(PFNGLGENRENDERBUFFERSPROC , glGenRenderbuffers, "");
756 GLGETPROC_(PFNGLRENDERBUFFERSTORAGEPROC , glRenderbufferStorage, "");
757 GLGETPROC_(PFNGLGETRENDERBUFFERPARAMETERIVPROC , glGetRenderbufferParameteriv, "");
758 GLGETPROC_(PFNGLISFRAMEBUFFERPROC , glIsFramebuffer, "");
759 GLGETPROC_(PFNGLBINDFRAMEBUFFERPROC , glBindFramebuffer, "");
760 GLGETPROC_(PFNGLDELETEFRAMEBUFFERSPROC , glDeleteFramebuffers, "");
761 GLGETPROC_(PFNGLGENFRAMEBUFFERSPROC , glGenFramebuffers, "");
762 GLGETPROC_(PFNGLCHECKFRAMEBUFFERSTATUSPROC , glCheckFramebufferStatus, "");
763 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE1DPROC , glFramebufferTexture1D, "");
764 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE2DPROC , glFramebufferTexture2D, "");
765 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE3DPROC , glFramebufferTexture3D, "");
766 GLGETPROC_(PFNGLFRAMEBUFFERRENDERBUFFERPROC , glFramebufferRenderbuffer, "");
767 GLGETPROC_(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC , glGetFramebufferAttachmentParameteriv, "");
768 GLGETPROC_(PFNGLGENERATEMIPMAPPROC , glGenerateMipmap, "");
769 GLGETPROC_(PFNGLBLITFRAMEBUFFERPROC , glBlitFramebuffer, "");
770 GLGETPROC_(PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC , glRenderbufferStorageMultisample, "");
771 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURELAYERPROC , glFramebufferTextureLayer, "");
772 }
773
774 /* OpenGL 3.1 core, GL_ARB_draw_instanced, GL_EXT_draw_instanced. */
775 if (pState->rsGLVersion >= 3.1f)
776 {
777 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "");
778 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "");
779 }
780 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_draw_instanced "))
781 {
782 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "ARB");
783 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "ARB");
784 }
785 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_draw_instanced "))
786 {
787 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "EXT");
788 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "EXT");
789 }
790
791 /* OpenGL 3.2 core, GL_ARB_draw_elements_base_vertex. Same functions names in the ARB and core specs. */
792 if ( pState->rsGLVersion >= 3.2f
793 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_draw_elements_base_vertex "))
794 {
795 GLGETPROC_(PFNGLDRAWELEMENTSBASEVERTEXPROC , glDrawElementsBaseVertex, "");
796 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC , glDrawElementsInstancedBaseVertex, "");
797 }
798
799 /* Optional. OpenGL 3.2 core, GL_ARB_provoking_vertex. Same functions names in the ARB and core specs. */
800 if ( pState->rsGLVersion >= 3.2f
801 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_provoking_vertex "))
802 {
803 GLGETPROCOPT_(PFNGLPROVOKINGVERTEXPROC , glProvokingVertex, "");
804 }
805
806 /* OpenGL 3.3 core, GL_ARB_instanced_arrays. */
807 if (pState->rsGLVersion >= 3.3f)
808 {
809 GLGETPROC_(PFNGLVERTEXATTRIBDIVISORPROC , glVertexAttribDivisor, "");
810 }
811 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_instanced_arrays "))
812 {
813 GLGETPROC_(PFNGLVERTEXATTRIBDIVISORARBPROC , glVertexAttribDivisor, "ARB");
814 }
815
816#undef GLGETPROCOPT_
817#undef GLGETPROC_
818
819 return VINF_SUCCESS;
820}
821
822
823/* We must delay window creation until the PowerOn phase. Init is too early and will cause failures. */
824int vmsvga3dPowerOn(PPDMDEVINS pDevIns, PVGASTATE pThis, PVGASTATECC pThisCC)
825{
826 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
827 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
828 PVMSVGA3DCONTEXT pContext;
829#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
830 PVMSVGA3DCONTEXT pOtherCtx;
831#endif
832 int rc;
833 RT_NOREF(pDevIns, pThis);
834
835 if (pState->rsGLVersion != 0.0)
836 return VINF_SUCCESS; /* already initialized (load state) */
837
838 /*
839 * OpenGL function calls aren't possible without a valid current context, so create a fake one here.
840 */
841 rc = vmsvga3dContextDefineOgl(pThisCC, 1, VMSVGA3D_DEF_CTX_F_INIT);
842 AssertRCReturn(rc, rc);
843
844 pContext = pState->papContexts[1];
845 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
846
847#ifdef VMSVGA3D_DYNAMIC_LOAD
848 /* Context is set and it is possible now to resolve extension functions. */
849 rc = glLdrGetExtFunctions(pDevIns);
850 if (RT_FAILURE(rc))
851 {
852 LogRel(("VMSVGA3d: Error resolving extension functions: %Rrc\n", rc));
853 return rc;
854 }
855#endif
856
857 LogRel(("VMSVGA3d: OpenGL version: %s\n"
858 "VMSVGA3d: OpenGL Vendor: %s\n"
859 "VMSVGA3d: OpenGL Renderer: %s\n"
860 "VMSVGA3d: OpenGL shader language version: %s\n",
861 glGetString(GL_VERSION), glGetString(GL_VENDOR), glGetString(GL_RENDERER),
862 glGetString(GL_SHADING_LANGUAGE_VERSION)));
863
864 rc = vmsvga3dGatherExtensions(&pState->pszExtensions, VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE);
865 AssertRCReturn(rc, rc);
866 vmsvga3dLogRelExtensions("", pState->pszExtensions);
867
868 pState->rsGLVersion = atof((const char *)glGetString(GL_VERSION));
869
870
871#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
872 /*
873 * Get the extension list for the alternative profile so we can better
874 * figure out the shader model and stuff.
875 */
876 rc = vmsvga3dContextDefineOgl(pThisCC, 2, VMSVGA3D_DEF_CTX_F_INIT | VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
877 AssertLogRelRCReturn(rc, rc);
878 pContext = pState->papContexts[1]; /* Array may have been reallocated. */
879
880 pOtherCtx = pState->papContexts[2];
881 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
882
883 LogRel(("VMSVGA3d: Alternative OpenGL version: %s\n"
884 "VMSVGA3d: Alternative OpenGL Vendor: %s\n"
885 "VMSVGA3d: Alternative OpenGL Renderer: %s\n"
886 "VMSVGA3d: Alternative OpenGL shader language version: %s\n",
887 glGetString(GL_VERSION), glGetString(GL_VENDOR), glGetString(GL_RENDERER),
888 glGetString(GL_SHADING_LANGUAGE_VERSION)));
889
890 rc = vmsvga3dGatherExtensions(&pState->pszOtherExtensions, VBOX_VMSVGA3D_OTHER_OGL_PROFILE);
891 AssertRCReturn(rc, rc);
892 vmsvga3dLogRelExtensions("Alternative ", pState->pszOtherExtensions);
893
894 pState->rsOtherGLVersion = atof((const char *)glGetString(GL_VERSION));
895
896 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
897#else
898 pState->pszOtherExtensions = (char *)"";
899 pState->rsOtherGLVersion = pState->rsGLVersion;
900#endif
901
902 /*
903 * Resolve GL function pointers and store them in pState->ext.
904 */
905 rc = vmsvga3dLoadGLFunctions(pState);
906 if (RT_FAILURE(rc))
907 {
908 LogRel(("VMSVGA3d: missing required OpenGL function or extension; aborting\n"));
909 return rc;
910 }
911
912 /*
913 * Initialize the capabilities with sensible defaults.
914 */
915 pState->caps.maxActiveLights = 1;
916 pState->caps.maxTextures = 1;
917 pState->caps.maxClipDistances = 4;
918 pState->caps.maxColorAttachments = 1;
919 pState->caps.maxRectangleTextureSize = 2048;
920 pState->caps.maxTextureAnisotropy = 1;
921 pState->caps.maxVertexShaderInstructions = 1024;
922 pState->caps.maxFragmentShaderInstructions = 1024;
923 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_NONE;
924 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_NONE;
925 pState->caps.flPointSize[0] = 1;
926 pState->caps.flPointSize[1] = 1;
927
928 /*
929 * Query capabilities
930 */
931 pState->caps.fS3TCSupported = vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_texture_compression_s3tc ");
932 pState->caps.fTextureFilterAnisotropicSupported = vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_texture_filter_anisotropic ");
933
934 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetIntegerv(GL_MAX_LIGHTS, &pState->caps.maxActiveLights));
935 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &pState->caps.maxTextures));
936#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE /* The alternative profile has a higher number here (ati/darwin). */
937 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
938 VMSVGA3D_INIT_CHECKED_BOTH(pState, pOtherCtx, pContext, glGetIntegerv(GL_MAX_CLIP_DISTANCES, &pState->caps.maxClipDistances));
939 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
940#else
941 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_CLIP_DISTANCES, &pState->caps.maxClipDistances));
942#endif
943 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &pState->caps.maxColorAttachments));
944 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE, &pState->caps.maxRectangleTextureSize));
945 if (pState->caps.fTextureFilterAnisotropicSupported)
946 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &pState->caps.maxTextureAnisotropy));
947 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, pState->caps.flPointSize));
948
949 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
950 pState->ext.glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB,
951 &pState->caps.maxFragmentShaderTemps));
952 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
953 pState->ext.glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB,
954 &pState->caps.maxFragmentShaderInstructions));
955 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
956 pState->ext.glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB,
957 &pState->caps.maxVertexShaderTemps));
958 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
959 pState->ext.glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB,
960 &pState->caps.maxVertexShaderInstructions));
961
962 /* http://http://www.opengl.org/wiki/Detecting_the_Shader_Model
963 * ARB Assembly Language
964 * These are done through testing the presence of extensions. You should test them in this order:
965 * GL_NV_gpu_program4: SM 4.0 or better.
966 * GL_NV_vertex_program3: SM 3.0 or better.
967 * GL_ARB_fragment_program: SM 2.0 or better.
968 * ATI does not support higher than SM 2.0 functionality in assembly shaders.
969 *
970 */
971 /** @todo distinguish between vertex and pixel shaders??? */
972#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE /* The alternative profile has a higher number here (ati/darwin). */
973 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
974 const char *pszShadingLanguageVersion = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION);
975 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
976#else
977 const char *pszShadingLanguageVersion = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION);
978#endif
979 float v = pszShadingLanguageVersion ? atof(pszShadingLanguageVersion) : 0.0f;
980 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_NV_gpu_program4 ")
981 || strstr(pState->pszOtherExtensions, " GL_NV_gpu_program4 "))
982 {
983 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_40;
984 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_40;
985 }
986 else
987 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_NV_vertex_program3 ")
988 || strstr(pState->pszOtherExtensions, " GL_NV_vertex_program3 ")
989 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_shader_texture_lod ") /* Wine claims this suggests SM 3.0 support */
990 || strstr(pState->pszOtherExtensions, " GL_ARB_shader_texture_lod ")
991 )
992 {
993 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_30;
994 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_30;
995 }
996 else
997 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_fragment_program ")
998 || strstr(pState->pszOtherExtensions, " GL_ARB_fragment_program "))
999 {
1000 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_20;
1001 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_20;
1002 }
1003 else
1004 {
1005 LogRel(("VMSVGA3D: WARNING: unknown support for assembly shaders!!\n"));
1006 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_11;
1007 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_11;
1008 }
1009
1010 /* Now check the shading language version, in case it indicates a higher supported version. */
1011 if (v >= 3.30f)
1012 {
1013 pState->caps.vertexShaderVersion = RT_MAX(pState->caps.vertexShaderVersion, SVGA3DVSVERSION_40);
1014 pState->caps.fragmentShaderVersion = RT_MAX(pState->caps.fragmentShaderVersion, SVGA3DPSVERSION_40);
1015 }
1016 else
1017 if (v >= 1.20f)
1018 {
1019 pState->caps.vertexShaderVersion = RT_MAX(pState->caps.vertexShaderVersion, SVGA3DVSVERSION_20);
1020 pState->caps.fragmentShaderVersion = RT_MAX(pState->caps.fragmentShaderVersion, SVGA3DPSVERSION_20);
1021 }
1022
1023 if ( !vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_vertex_array_bgra ")
1024 && !vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_vertex_array_bgra "))
1025 {
1026 LogRel(("VMSVGA3D: WARNING: Missing required extension GL_ARB_vertex_array_bgra (d3dcolor)!!!\n"));
1027 }
1028
1029 /*
1030 * Tweak capabilities.
1031 */
1032 /* Intel Windows drivers return 31, while the guest expects 32 at least. */
1033 if ( pState->caps.maxVertexShaderTemps < 32
1034 && vmsvga3dIsVendorIntel())
1035 pState->caps.maxVertexShaderTemps = 32;
1036
1037#if 0
1038 SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND = 11,
1039 SVGA3D_DEVCAP_QUERY_TYPES = 15,
1040 SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING = 16,
1041 SVGA3D_DEVCAP_MAX_POINT_SIZE = 17,
1042 SVGA3D_DEVCAP_MAX_SHADER_TEXTURES = 18,
1043 SVGA3D_DEVCAP_MAX_VOLUME_EXTENT = 21,
1044 SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT = 22,
1045 SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO = 23,
1046 SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY = 24,
1047 SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT = 25,
1048 SVGA3D_DEVCAP_MAX_VERTEX_INDEX = 26,
1049 SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS = 28,
1050 SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS = 29,
1051 SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS = 30,
1052 SVGA3D_DEVCAP_TEXTURE_OPS = 31,
1053 SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8 = 32,
1054 SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8 = 33,
1055 SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10 = 34,
1056 SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5 = 35,
1057 SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5 = 36,
1058 SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4 = 37,
1059 SVGA3D_DEVCAP_SURFACEFMT_R5G6B5 = 38,
1060 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16 = 39,
1061 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8 = 40,
1062 SVGA3D_DEVCAP_SURFACEFMT_ALPHA8 = 41,
1063 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8 = 42,
1064 SVGA3D_DEVCAP_SURFACEFMT_Z_D16 = 43,
1065 SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8 = 44,
1066 SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8 = 45,
1067 SVGA3D_DEVCAP_SURFACEFMT_DXT1 = 46,
1068 SVGA3D_DEVCAP_SURFACEFMT_DXT2 = 47,
1069 SVGA3D_DEVCAP_SURFACEFMT_DXT3 = 48,
1070 SVGA3D_DEVCAP_SURFACEFMT_DXT4 = 49,
1071 SVGA3D_DEVCAP_SURFACEFMT_DXT5 = 50,
1072 SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8 = 51,
1073 SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10 = 52,
1074 SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8 = 53,
1075 SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8 = 54,
1076 SVGA3D_DEVCAP_SURFACEFMT_CxV8U8 = 55,
1077 SVGA3D_DEVCAP_SURFACEFMT_R_S10E5 = 56,
1078 SVGA3D_DEVCAP_SURFACEFMT_R_S23E8 = 57,
1079 SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5 = 58,
1080 SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8 = 59,
1081 SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5 = 60,
1082 SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8 = 61,
1083 SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES = 63,
1084 SVGA3D_DEVCAP_SURFACEFMT_V16U16 = 65,
1085 SVGA3D_DEVCAP_SURFACEFMT_G16R16 = 66,
1086 SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16 = 67,
1087 SVGA3D_DEVCAP_SURFACEFMT_UYVY = 68,
1088 SVGA3D_DEVCAP_SURFACEFMT_YUY2 = 69,
1089 SVGA3D_DEVCAP_MULTISAMPLE_NONMASKABLESAMPLES = 70,
1090 SVGA3D_DEVCAP_MULTISAMPLE_MASKABLESAMPLES = 71,
1091 SVGA3D_DEVCAP_ALPHATOCOVERAGE = 72,
1092 SVGA3D_DEVCAP_SUPERSAMPLE = 73,
1093 SVGA3D_DEVCAP_AUTOGENMIPMAPS = 74,
1094 SVGA3D_DEVCAP_SURFACEFMT_NV12 = 75,
1095 SVGA3D_DEVCAP_SURFACEFMT_AYUV = 76,
1096 SVGA3D_DEVCAP_SURFACEFMT_Z_DF16 = 79,
1097 SVGA3D_DEVCAP_SURFACEFMT_Z_DF24 = 80,
1098 SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT = 81,
1099 SVGA3D_DEVCAP_SURFACEFMT_BC4_UNORM = 82,
1100 SVGA3D_DEVCAP_SURFACEFMT_BC5_UNORM = 83,
1101#endif
1102
1103 LogRel(("VMSVGA3d: Capabilities:\n"));
1104 LogRel(("VMSVGA3d: maxActiveLights=%-2d maxTextures=%-2d\n",
1105 pState->caps.maxActiveLights, pState->caps.maxTextures));
1106 LogRel(("VMSVGA3d: maxClipDistances=%-2d maxColorAttachments=%-2d maxClipDistances=%d\n",
1107 pState->caps.maxClipDistances, pState->caps.maxColorAttachments, pState->caps.maxClipDistances));
1108 LogRel(("VMSVGA3d: maxColorAttachments=%-2d maxTextureAnisotropy=%-2d maxRectangleTextureSize=%d\n",
1109 pState->caps.maxColorAttachments, pState->caps.maxTextureAnisotropy, pState->caps.maxRectangleTextureSize));
1110 LogRel(("VMSVGA3d: maxVertexShaderTemps=%-2d maxVertexShaderInstructions=%d maxFragmentShaderInstructions=%d\n",
1111 pState->caps.maxVertexShaderTemps, pState->caps.maxVertexShaderInstructions, pState->caps.maxFragmentShaderInstructions));
1112 LogRel(("VMSVGA3d: maxFragmentShaderTemps=%d flPointSize={%d.%02u, %d.%02u}\n",
1113 pState->caps.maxFragmentShaderTemps,
1114 (int)pState->caps.flPointSize[0], (int)(pState->caps.flPointSize[0] * 100) % 100,
1115 (int)pState->caps.flPointSize[1], (int)(pState->caps.flPointSize[1] * 100) % 100));
1116 LogRel(("VMSVGA3d: fragmentShaderVersion=%-2d vertexShaderVersion=%-2d\n",
1117 pState->caps.fragmentShaderVersion, pState->caps.vertexShaderVersion));
1118 LogRel(("VMSVGA3d: fS3TCSupported=%-2d fTextureFilterAnisotropicSupported=%d\n",
1119 pState->caps.fS3TCSupported, pState->caps.fTextureFilterAnisotropicSupported));
1120
1121
1122 /* Initialize the shader library. */
1123 pState->ShaderIf.pfnSwitchInitProfile = vmsvga3dShaderIfSwitchInitProfile;
1124 pState->ShaderIf.pfnGetNextExtension = vmsvga3dShaderIfGetNextExtension;
1125 rc = ShaderInitLib(&pState->ShaderIf);
1126 AssertRC(rc);
1127
1128 /* Cleanup */
1129 rc = vmsvga3dContextDestroy(pThisCC, 1);
1130 AssertRC(rc);
1131#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
1132 rc = vmsvga3dContextDestroy(pThisCC, 2);
1133 AssertRC(rc);
1134#endif
1135
1136 if ( pState->rsGLVersion < 3.0
1137 && pState->rsOtherGLVersion < 3.0 /* darwin: legacy profile hack */)
1138 {
1139 LogRel(("VMSVGA3d: unsupported OpenGL version; minimum is 3.0\n"));
1140 return VERR_NOT_IMPLEMENTED;
1141 }
1142
1143 return VINF_SUCCESS;
1144}
1145
1146int vmsvga3dReset(PVGASTATECC pThisCC)
1147{
1148 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1149 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
1150
1151 /* Destroy all leftover surfaces. */
1152 for (uint32_t i = 0; i < pState->cSurfaces; i++)
1153 {
1154 if (pState->papSurfaces[i]->id != SVGA3D_INVALID_ID)
1155 vmsvga3dSurfaceDestroy(pThisCC, pState->papSurfaces[i]->id);
1156 }
1157
1158 /* Destroy all leftover contexts. */
1159 for (uint32_t i = 0; i < pState->cContexts; i++)
1160 {
1161 if (pState->papContexts[i]->id != SVGA3D_INVALID_ID)
1162 vmsvga3dContextDestroy(pThisCC, pState->papContexts[i]->id);
1163 }
1164
1165 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
1166 vmsvga3dContextDestroyOgl(pThisCC, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID);
1167
1168 return VINF_SUCCESS;
1169}
1170
1171int vmsvga3dTerminate(PVGASTATECC pThisCC)
1172{
1173 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1174 AssertReturn(pState, VERR_WRONG_ORDER);
1175 int rc;
1176
1177 rc = vmsvga3dReset(pThisCC);
1178 AssertRCReturn(rc, rc);
1179
1180 /* Terminate the shader library. */
1181 rc = ShaderDestroyLib();
1182 AssertRC(rc);
1183
1184#ifdef RT_OS_WINDOWS
1185 /* Terminate the window creation thread. */
1186 rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_EXIT, 0, 0);
1187 AssertRCReturn(rc, rc);
1188
1189 RTSemEventDestroy(pState->WndRequestSem);
1190#elif defined(RT_OS_DARWIN)
1191
1192#elif defined(RT_OS_LINUX)
1193 /* signal to the thread that it is supposed to exit */
1194 pState->bTerminate = true;
1195 /* wait for it to terminate */
1196 rc = RTThreadWait(pState->pWindowThread, 10000, NULL);
1197 AssertRC(rc);
1198 XCloseDisplay(pState->display);
1199#endif
1200
1201 RTStrFree(pState->pszExtensions);
1202 pState->pszExtensions = NULL;
1203#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
1204 RTStrFree(pState->pszOtherExtensions);
1205#endif
1206 pState->pszOtherExtensions = NULL;
1207
1208 return VINF_SUCCESS;
1209}
1210
1211
1212void vmsvga3dUpdateHostScreenViewport(PVGASTATECC pThisCC, uint32_t idScreen, VMSVGAVIEWPORT const *pOldViewport)
1213{
1214 /** @todo Move the visible framebuffer content here, don't wait for the guest to
1215 * redraw it. */
1216
1217#ifdef RT_OS_DARWIN
1218 RT_NOREF(pOldViewport);
1219 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1220 if ( pState
1221 && idScreen == 0
1222 && pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
1223 {
1224 vmsvga3dCocoaViewUpdateViewport(pState->SharedCtx.cocoaView);
1225 }
1226#else
1227 RT_NOREF(pThisCC, idScreen, pOldViewport);
1228#endif
1229}
1230
1231
1232/**
1233 * Worker for vmsvga3dQueryCaps that figures out supported operations for a
1234 * given surface format capability.
1235 *
1236 * @returns Supported/indented operations (SVGA3DFORMAT_OP_XXX).
1237 * @param idx3dCaps The SVGA3D_CAPS_XXX value of the surface format.
1238 *
1239 * @remarks See fromat_cap_table in svga_format.c (mesa/gallium) for a reference
1240 * of implicit guest expectations:
1241 * http://cgit.freedesktop.org/mesa/mesa/tree/src/gallium/drivers/svga/svga_format.c
1242 */
1243static uint32_t vmsvga3dGetSurfaceFormatSupport(uint32_t idx3dCaps)
1244{
1245 uint32_t result = 0;
1246
1247 /** @todo missing:
1248 *
1249 * SVGA3DFORMAT_OP_PIXELSIZE
1250 */
1251
1252 switch (idx3dCaps)
1253 {
1254 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1255 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1256 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1257 result |= SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB
1258 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1259 | SVGA3DFORMAT_OP_DISPLAYMODE /* Should not be set for alpha formats. */
1260 | SVGA3DFORMAT_OP_3DACCELERATION; /* implies OP_DISPLAYMODE */
1261 break;
1262
1263 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1264 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1265 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1266 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1267 result |= SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB
1268 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1269 | SVGA3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET;
1270 break;
1271 }
1272
1273 /** @todo check hardware caps! */
1274 switch (idx3dCaps)
1275 {
1276 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1277 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1278 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1279 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1280 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1281 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1282 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1283 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16:
1284 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8:
1285 case SVGA3D_DEVCAP_SURFACEFMT_ALPHA8:
1286 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8:
1287 result |= SVGA3DFORMAT_OP_TEXTURE
1288 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET
1289 | SVGA3DFORMAT_OP_OFFSCREENPLAIN
1290 | SVGA3DFORMAT_OP_SAME_FORMAT_RENDERTARGET
1291 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1292 | SVGA3DFORMAT_OP_CUBETEXTURE
1293 | SVGA3DFORMAT_OP_SRGBREAD
1294 | SVGA3DFORMAT_OP_SRGBWRITE;
1295 break;
1296
1297 case SVGA3D_DEVCAP_SURFACEFMT_Z_D16:
1298 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8:
1299 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8:
1300 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF16:
1301 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF24:
1302 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT:
1303 result |= SVGA3DFORMAT_OP_ZSTENCIL
1304 | SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH
1305 | SVGA3DFORMAT_OP_TEXTURE /* Necessary for Ubuntu Unity */;
1306 break;
1307
1308 case SVGA3D_DEVCAP_SURFACEFMT_DXT1:
1309 case SVGA3D_DEVCAP_SURFACEFMT_DXT2:
1310 case SVGA3D_DEVCAP_SURFACEFMT_DXT3:
1311 case SVGA3D_DEVCAP_SURFACEFMT_DXT4:
1312 case SVGA3D_DEVCAP_SURFACEFMT_DXT5:
1313 result |= SVGA3DFORMAT_OP_TEXTURE
1314 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1315 | SVGA3DFORMAT_OP_CUBETEXTURE
1316 | SVGA3DFORMAT_OP_SRGBREAD;
1317 break;
1318
1319 case SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8:
1320 case SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10:
1321 case SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8:
1322 case SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8:
1323 case SVGA3D_DEVCAP_SURFACEFMT_CxV8U8:
1324 break;
1325
1326 case SVGA3D_DEVCAP_SURFACEFMT_R_S10E5:
1327 case SVGA3D_DEVCAP_SURFACEFMT_R_S23E8:
1328 case SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5:
1329 case SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8:
1330 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5:
1331 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8:
1332 result |= SVGA3DFORMAT_OP_TEXTURE
1333 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1334 | SVGA3DFORMAT_OP_CUBETEXTURE
1335 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET;
1336 break;
1337
1338 case SVGA3D_DEVCAP_SURFACEFMT_V16U16:
1339 case SVGA3D_DEVCAP_SURFACEFMT_G16R16:
1340 case SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16:
1341 result |= SVGA3DFORMAT_OP_TEXTURE
1342 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1343 | SVGA3DFORMAT_OP_CUBETEXTURE
1344 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET;
1345 break;
1346
1347 case SVGA3D_DEVCAP_SURFACEFMT_UYVY:
1348 case SVGA3D_DEVCAP_SURFACEFMT_YUY2:
1349 result |= SVGA3DFORMAT_OP_OFFSCREENPLAIN
1350 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1351 | SVGA3DFORMAT_OP_TEXTURE;
1352 break;
1353
1354 case SVGA3D_DEVCAP_SURFACEFMT_NV12:
1355 case SVGA3D_DEVCAP_SURFACEFMT_AYUV:
1356 break;
1357 }
1358 Log(("CAPS: %s =\n%s\n", vmsvga3dGetCapString(idx3dCaps), vmsvga3dGet3dFormatString(result)));
1359
1360 return result;
1361}
1362
1363#if 0 /* unused */
1364static uint32_t vmsvga3dGetDepthFormatSupport(PVMSVGA3DSTATE pState3D, uint32_t idx3dCaps)
1365{
1366 RT_NOREF(pState3D, idx3dCaps);
1367
1368 /** @todo test this somehow */
1369 uint32_t result = SVGA3DFORMAT_OP_ZSTENCIL | SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH;
1370
1371 Log(("CAPS: %s =\n%s\n", vmsvga3dGetCapString(idx3dCaps), vmsvga3dGet3dFormatString(result)));
1372 return result;
1373}
1374#endif
1375
1376
1377int vmsvga3dQueryCaps(PVGASTATECC pThisCC, uint32_t idx3dCaps, uint32_t *pu32Val)
1378{
1379 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1380 AssertReturn(pState, VERR_NO_MEMORY);
1381 int rc = VINF_SUCCESS;
1382
1383 *pu32Val = 0;
1384
1385 /*
1386 * The capabilities access by current (2015-03-01) linux sources (gallium,
1387 * vmwgfx, xorg-video-vmware) are annotated, caps without xref annotations
1388 * aren't access.
1389 */
1390
1391 switch (idx3dCaps)
1392 {
1393 /* Linux: vmwgfx_fifo.c in kmod; only used with SVGA_CAP_GBOBJECTS. */
1394 case SVGA3D_DEVCAP_3D:
1395 *pu32Val = 1; /* boolean? */
1396 break;
1397
1398 case SVGA3D_DEVCAP_MAX_LIGHTS:
1399 *pu32Val = pState->caps.maxActiveLights;
1400 break;
1401
1402 case SVGA3D_DEVCAP_MAX_TEXTURES:
1403 *pu32Val = pState->caps.maxTextures;
1404 break;
1405
1406 case SVGA3D_DEVCAP_MAX_CLIP_PLANES:
1407 *pu32Val = pState->caps.maxClipDistances;
1408 break;
1409
1410 /* Linux: svga_screen.c in gallium; 3.0 or later required. */
1411 case SVGA3D_DEVCAP_VERTEX_SHADER_VERSION:
1412 *pu32Val = pState->caps.vertexShaderVersion;
1413 break;
1414
1415 case SVGA3D_DEVCAP_VERTEX_SHADER:
1416 /* boolean? */
1417 *pu32Val = (pState->caps.vertexShaderVersion != SVGA3DVSVERSION_NONE);
1418 break;
1419
1420 /* Linux: svga_screen.c in gallium; 3.0 or later required. */
1421 case SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION:
1422 *pu32Val = pState->caps.fragmentShaderVersion;
1423 break;
1424
1425 case SVGA3D_DEVCAP_FRAGMENT_SHADER:
1426 /* boolean? */
1427 *pu32Val = (pState->caps.fragmentShaderVersion != SVGA3DPSVERSION_NONE);
1428 break;
1429
1430 case SVGA3D_DEVCAP_S23E8_TEXTURES:
1431 case SVGA3D_DEVCAP_S10E5_TEXTURES:
1432 /* Must be obsolete by now; surface format caps specify the same thing. */
1433 rc = VERR_INVALID_PARAMETER;
1434 break;
1435
1436 case SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND:
1437 break;
1438
1439 /*
1440 * 2. The BUFFER_FORMAT capabilities are deprecated, and they always
1441 * return TRUE. Even on physical hardware that does not support
1442 * these formats natively, the SVGA3D device will provide an emulation
1443 * which should be invisible to the guest OS.
1444 */
1445 case SVGA3D_DEVCAP_D16_BUFFER_FORMAT:
1446 case SVGA3D_DEVCAP_D24S8_BUFFER_FORMAT:
1447 case SVGA3D_DEVCAP_D24X8_BUFFER_FORMAT:
1448 *pu32Val = 1;
1449 break;
1450
1451 case SVGA3D_DEVCAP_QUERY_TYPES:
1452 break;
1453
1454 case SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING:
1455 break;
1456
1457 /* Linux: svga_screen.c in gallium; capped at 80.0, default 1.0. */
1458 case SVGA3D_DEVCAP_MAX_POINT_SIZE:
1459 AssertCompile(sizeof(uint32_t) == sizeof(float));
1460 *(float *)pu32Val = pState->caps.flPointSize[1];
1461 break;
1462
1463 case SVGA3D_DEVCAP_MAX_SHADER_TEXTURES:
1464 /** @todo ?? */
1465 rc = VERR_INVALID_PARAMETER;
1466 break;
1467
1468 /* Linux: svga_screen.c in gallium (for PIPE_CAP_MAX_TEXTURE_2D_LEVELS); have default if missing. */
1469 case SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH:
1470 case SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT:
1471 *pu32Val = pState->caps.maxRectangleTextureSize;
1472 break;
1473
1474 /* Linux: svga_screen.c in gallium (for PIPE_CAP_MAX_TEXTURE_3D_LEVELS); have default if missing. */
1475 case SVGA3D_DEVCAP_MAX_VOLUME_EXTENT:
1476 //*pu32Val = pCaps->MaxVolumeExtent;
1477 *pu32Val = 256;
1478 break;
1479
1480 case SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT:
1481 *pu32Val = 32768; /* hardcoded in Wine */
1482 break;
1483
1484 case SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO:
1485 //*pu32Val = pCaps->MaxTextureAspectRatio;
1486 break;
1487
1488 /* Linux: svga_screen.c in gallium (for PIPE_CAPF_MAX_TEXTURE_ANISOTROPY); defaults to 4.0. */
1489 case SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY:
1490 *pu32Val = pState->caps.maxTextureAnisotropy;
1491 break;
1492
1493 case SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT:
1494 case SVGA3D_DEVCAP_MAX_VERTEX_INDEX:
1495 *pu32Val = 0xFFFFF; /* hardcoded in Wine */
1496 break;
1497
1498 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_VERTEX/PIPE_SHADER_CAP_MAX_INSTRUCTIONS); defaults to 512. */
1499 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_INSTRUCTIONS:
1500 *pu32Val = pState->caps.maxVertexShaderInstructions;
1501 break;
1502
1503 case SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS:
1504 *pu32Val = pState->caps.maxFragmentShaderInstructions;
1505 break;
1506
1507 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_VERTEX/PIPE_SHADER_CAP_MAX_TEMPS); defaults to 32. */
1508 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS:
1509 *pu32Val = pState->caps.maxVertexShaderTemps;
1510 break;
1511
1512 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_FRAGMENT/PIPE_SHADER_CAP_MAX_TEMPS); defaults to 32. */
1513 case SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS:
1514 *pu32Val = pState->caps.maxFragmentShaderTemps;
1515 break;
1516
1517 case SVGA3D_DEVCAP_TEXTURE_OPS:
1518 break;
1519
1520 case SVGA3D_DEVCAP_MULTISAMPLE_NONMASKABLESAMPLES:
1521 break;
1522
1523 case SVGA3D_DEVCAP_MULTISAMPLE_MASKABLESAMPLES:
1524 break;
1525
1526 case SVGA3D_DEVCAP_ALPHATOCOVERAGE:
1527 break;
1528
1529 case SVGA3D_DEVCAP_SUPERSAMPLE:
1530 break;
1531
1532 case SVGA3D_DEVCAP_AUTOGENMIPMAPS:
1533 //*pu32Val = !!(pCaps->Caps2 & D3DCAPS2_CANAUTOGENMIPMAP);
1534 break;
1535
1536 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES:
1537 break;
1538
1539 case SVGA3D_DEVCAP_MAX_RENDER_TARGETS: /** @todo same thing? */
1540 case SVGA3D_DEVCAP_MAX_SIMULTANEOUS_RENDER_TARGETS:
1541 *pu32Val = pState->caps.maxColorAttachments;
1542 break;
1543
1544 /*
1545 * This is the maximum number of SVGA context IDs that the guest
1546 * can define using SVGA_3D_CMD_CONTEXT_DEFINE.
1547 */
1548 case SVGA3D_DEVCAP_MAX_CONTEXT_IDS:
1549 *pu32Val = SVGA3D_MAX_CONTEXT_IDS;
1550 break;
1551
1552 /*
1553 * This is the maximum number of SVGA surface IDs that the guest
1554 * can define using SVGA_3D_CMD_SURFACE_DEFINE*.
1555 */
1556 case SVGA3D_DEVCAP_MAX_SURFACE_IDS:
1557 *pu32Val = SVGA3D_MAX_SURFACE_IDS;
1558 break;
1559
1560#if 0 /* Appeared more recently, not yet implemented. */
1561 /* Linux: svga_screen.c in gallium; defaults to FALSE. */
1562 case SVGA3D_DEVCAP_LINE_AA:
1563 break;
1564 /* Linux: svga_screen.c in gallium; defaults to FALSE. */
1565 case SVGA3D_DEVCAP_LINE_STIPPLE:
1566 break;
1567 /* Linux: svga_screen.c in gallium; defaults to 1.0. */
1568 case SVGA3D_DEVCAP_MAX_LINE_WIDTH:
1569 break;
1570 /* Linux: svga_screen.c in gallium; defaults to 1.0. */
1571 case SVGA3D_DEVCAP_MAX_AA_LINE_WIDTH:
1572 break;
1573#endif
1574
1575 /*
1576 * Supported surface formats.
1577 * Linux: svga_format.c in gallium, format_cap_table defines implicit expectations.
1578 */
1579 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1580 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1581 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1582 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1583 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1584 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1585 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1586 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16:
1587 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8:
1588 case SVGA3D_DEVCAP_SURFACEFMT_ALPHA8:
1589 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8:
1590 case SVGA3D_DEVCAP_SURFACEFMT_Z_D16:
1591 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8:
1592 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8:
1593 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF16:
1594 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF24:
1595 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT:
1596 case SVGA3D_DEVCAP_SURFACEFMT_DXT1:
1597 *pu32Val = vmsvga3dGetSurfaceFormatSupport(idx3dCaps);
1598 break;
1599
1600 case SVGA3D_DEVCAP_SURFACEFMT_DXT2:
1601 case SVGA3D_DEVCAP_SURFACEFMT_DXT3:
1602 case SVGA3D_DEVCAP_SURFACEFMT_DXT4:
1603 case SVGA3D_DEVCAP_SURFACEFMT_DXT5:
1604 case SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8:
1605 case SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10:
1606 case SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8:
1607 case SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8:
1608 case SVGA3D_DEVCAP_SURFACEFMT_CxV8U8:
1609 case SVGA3D_DEVCAP_SURFACEFMT_R_S10E5:
1610 case SVGA3D_DEVCAP_SURFACEFMT_R_S23E8:
1611 case SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5:
1612 case SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8:
1613 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5:
1614 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8:
1615 case SVGA3D_DEVCAP_SURFACEFMT_V16U16:
1616 case SVGA3D_DEVCAP_SURFACEFMT_G16R16:
1617 case SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16:
1618 case SVGA3D_DEVCAP_SURFACEFMT_UYVY:
1619 case SVGA3D_DEVCAP_SURFACEFMT_YUY2:
1620 case SVGA3D_DEVCAP_SURFACEFMT_NV12:
1621 case SVGA3D_DEVCAP_SURFACEFMT_AYUV:
1622 *pu32Val = vmsvga3dGetSurfaceFormatSupport(idx3dCaps);
1623 break;
1624
1625 /* Linux: Not referenced in current sources. */
1626 case SVGA3D_DEVCAP_SURFACEFMT_BC4_UNORM:
1627 case SVGA3D_DEVCAP_SURFACEFMT_BC5_UNORM:
1628 Log(("CAPS: Unknown CAP %s\n", vmsvga3dGetCapString(idx3dCaps)));
1629 rc = VERR_INVALID_PARAMETER;
1630 *pu32Val = 0;
1631 break;
1632
1633 default:
1634 Log(("CAPS: Unexpected CAP %d\n", idx3dCaps));
1635 rc = VERR_INVALID_PARAMETER;
1636 break;
1637 }
1638
1639 Log(("CAPS: %s - %x\n", vmsvga3dGetCapString(idx3dCaps), *pu32Val));
1640 return rc;
1641}
1642
1643/**
1644 * Convert SVGA format value to its OpenGL equivalent
1645 *
1646 * @remarks Clues to be had in format_texture_info table (wined3d/utils.c) with
1647 * help from wined3dformat_from_d3dformat().
1648 */
1649void vmsvga3dSurfaceFormat2OGL(PVMSVGA3DSURFACE pSurface, SVGA3dSurfaceFormat format)
1650{
1651#if 0
1652#define AssertTestFmt(f) AssertMsgFailed(("Test me - " #f "\n"))
1653#else
1654#define AssertTestFmt(f) do {} while(0)
1655#endif
1656 /* Init cbBlockGL for non-emulated formats. */
1657 pSurface->cbBlockGL = pSurface->cbBlock;
1658
1659 switch (format)
1660 {
1661 case SVGA3D_X8R8G8B8: /* D3DFMT_X8R8G8B8 - WINED3DFMT_B8G8R8X8_UNORM */
1662 pSurface->internalFormatGL = GL_RGB8;
1663 pSurface->formatGL = GL_BGRA;
1664 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1665 break;
1666 case SVGA3D_A8R8G8B8: /* D3DFMT_A8R8G8B8 - WINED3DFMT_B8G8R8A8_UNORM */
1667 pSurface->internalFormatGL = GL_RGBA8;
1668 pSurface->formatGL = GL_BGRA;
1669 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1670 break;
1671 case SVGA3D_R5G6B5: /* D3DFMT_R5G6B5 - WINED3DFMT_B5G6R5_UNORM */
1672 pSurface->internalFormatGL = GL_RGB5;
1673 pSurface->formatGL = GL_RGB;
1674 pSurface->typeGL = GL_UNSIGNED_SHORT_5_6_5;
1675 AssertTestFmt(SVGA3D_R5G6B5);
1676 break;
1677 case SVGA3D_X1R5G5B5: /* D3DFMT_X1R5G5B5 - WINED3DFMT_B5G5R5X1_UNORM */
1678 pSurface->internalFormatGL = GL_RGB5;
1679 pSurface->formatGL = GL_BGRA;
1680 pSurface->typeGL = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1681 AssertTestFmt(SVGA3D_X1R5G5B5);
1682 break;
1683 case SVGA3D_A1R5G5B5: /* D3DFMT_A1R5G5B5 - WINED3DFMT_B5G5R5A1_UNORM */
1684 pSurface->internalFormatGL = GL_RGB5_A1;
1685 pSurface->formatGL = GL_BGRA;
1686 pSurface->typeGL = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1687 AssertTestFmt(SVGA3D_A1R5G5B5);
1688 break;
1689 case SVGA3D_A4R4G4B4: /* D3DFMT_A4R4G4B4 - WINED3DFMT_B4G4R4A4_UNORM */
1690 pSurface->internalFormatGL = GL_RGBA4;
1691 pSurface->formatGL = GL_BGRA;
1692 pSurface->typeGL = GL_UNSIGNED_SHORT_4_4_4_4_REV;
1693 AssertTestFmt(SVGA3D_A4R4G4B4);
1694 break;
1695
1696 case SVGA3D_R8G8B8A8_UNORM:
1697 pSurface->internalFormatGL = GL_RGBA8;
1698 pSurface->formatGL = GL_RGBA;
1699 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1700 break;
1701
1702 case SVGA3D_Z_D32: /* D3DFMT_D32 - WINED3DFMT_D32_UNORM */
1703 pSurface->internalFormatGL = GL_DEPTH_COMPONENT32;
1704 pSurface->formatGL = GL_DEPTH_COMPONENT;
1705 pSurface->typeGL = GL_UNSIGNED_INT;
1706 break;
1707 case SVGA3D_Z_D16: /* D3DFMT_D16 - WINED3DFMT_D16_UNORM */
1708 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16; /** @todo Wine suggests GL_DEPTH_COMPONENT24. */
1709 pSurface->formatGL = GL_DEPTH_COMPONENT;
1710 pSurface->typeGL = GL_UNSIGNED_SHORT;
1711 AssertTestFmt(SVGA3D_Z_D16);
1712 break;
1713 case SVGA3D_Z_D24S8: /* D3DFMT_D24S8 - WINED3DFMT_D24_UNORM_S8_UINT */
1714 pSurface->internalFormatGL = GL_DEPTH24_STENCIL8;
1715 pSurface->formatGL = GL_DEPTH_STENCIL;
1716 pSurface->typeGL = GL_UNSIGNED_INT_24_8;
1717 break;
1718 case SVGA3D_Z_D15S1: /* D3DFMT_D15S1 - WINED3DFMT_S1_UINT_D15_UNORM */
1719 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16; /** @todo ??? */
1720 pSurface->formatGL = GL_DEPTH_STENCIL;
1721 pSurface->typeGL = GL_UNSIGNED_SHORT;
1722 /** @todo Wine sources hints at no hw support for this, so test this one! */
1723 AssertTestFmt(SVGA3D_Z_D15S1);
1724 break;
1725 case SVGA3D_Z_D24X8: /* D3DFMT_D24X8 - WINED3DFMT_X8D24_UNORM */
1726 pSurface->internalFormatGL = GL_DEPTH_COMPONENT24;
1727 pSurface->formatGL = GL_DEPTH_COMPONENT;
1728 pSurface->typeGL = GL_UNSIGNED_INT;
1729 AssertTestFmt(SVGA3D_Z_D24X8);
1730 break;
1731
1732 /* Advanced D3D9 depth formats. */
1733 case SVGA3D_Z_DF16: /* D3DFMT_DF16? - not supported */
1734 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16;
1735 pSurface->formatGL = GL_DEPTH_COMPONENT;
1736 pSurface->typeGL = GL_HALF_FLOAT;
1737 break;
1738
1739 case SVGA3D_Z_DF24: /* D3DFMT_DF24? - not supported */
1740 pSurface->internalFormatGL = GL_DEPTH_COMPONENT24;
1741 pSurface->formatGL = GL_DEPTH_COMPONENT;
1742 pSurface->typeGL = GL_FLOAT; /* ??? */
1743 break;
1744
1745 case SVGA3D_Z_D24S8_INT: /* D3DFMT_D24S8 */
1746 pSurface->internalFormatGL = GL_DEPTH24_STENCIL8;
1747 pSurface->formatGL = GL_DEPTH_STENCIL;
1748 pSurface->typeGL = GL_UNSIGNED_INT_24_8;
1749 break;
1750
1751 case SVGA3D_DXT1: /* D3DFMT_DXT1 - WINED3DFMT_DXT1 */
1752 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1753 pSurface->formatGL = GL_RGBA; /* not used */
1754 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1755 break;
1756
1757 case SVGA3D_DXT2: /* D3DFMT_DXT2 */
1758 /* "DXT2 and DXT3 are the same from an API perspective." */
1759 RT_FALL_THRU();
1760 case SVGA3D_DXT3: /* D3DFMT_DXT3 - WINED3DFMT_DXT3 */
1761 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
1762 pSurface->formatGL = GL_RGBA; /* not used */
1763 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1764 break;
1765
1766 case SVGA3D_DXT4: /* D3DFMT_DXT4 */
1767 /* "DXT4 and DXT5 are the same from an API perspective." */
1768 RT_FALL_THRU();
1769 case SVGA3D_DXT5: /* D3DFMT_DXT5 - WINED3DFMT_DXT5 */
1770 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
1771 pSurface->formatGL = GL_RGBA; /* not used */
1772 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1773 break;
1774
1775 case SVGA3D_LUMINANCE8: /* D3DFMT_? - ? */
1776 pSurface->internalFormatGL = GL_LUMINANCE8_EXT;
1777 pSurface->formatGL = GL_LUMINANCE;
1778 pSurface->typeGL = GL_UNSIGNED_BYTE;
1779 break;
1780
1781 case SVGA3D_LUMINANCE16: /* D3DFMT_? - ? */
1782 pSurface->internalFormatGL = GL_LUMINANCE16_EXT;
1783 pSurface->formatGL = GL_LUMINANCE;
1784 pSurface->typeGL = GL_UNSIGNED_SHORT;
1785 break;
1786
1787 case SVGA3D_LUMINANCE4_ALPHA4: /* D3DFMT_? - ? */
1788 pSurface->internalFormatGL = GL_LUMINANCE4_ALPHA4_EXT;
1789 pSurface->formatGL = GL_LUMINANCE_ALPHA;
1790 pSurface->typeGL = GL_UNSIGNED_BYTE;
1791 break;
1792
1793 case SVGA3D_LUMINANCE8_ALPHA8: /* D3DFMT_? - ? */
1794 pSurface->internalFormatGL = GL_LUMINANCE8_ALPHA8_EXT;
1795 pSurface->formatGL = GL_LUMINANCE_ALPHA;
1796 pSurface->typeGL = GL_UNSIGNED_BYTE; /* unsigned_short causes issues even though this type should be 16-bit */
1797 break;
1798
1799 case SVGA3D_ALPHA8: /* D3DFMT_A8? - WINED3DFMT_A8_UNORM? */
1800 pSurface->internalFormatGL = GL_ALPHA8_EXT;
1801 pSurface->formatGL = GL_ALPHA;
1802 pSurface->typeGL = GL_UNSIGNED_BYTE;
1803 break;
1804
1805#if 0
1806
1807 /* Bump-map formats */
1808 case SVGA3D_BUMPU8V8:
1809 return D3DFMT_V8U8;
1810 case SVGA3D_BUMPL6V5U5:
1811 return D3DFMT_L6V5U5;
1812 case SVGA3D_BUMPX8L8V8U8:
1813 return D3DFMT_X8L8V8U8;
1814 case SVGA3D_BUMPL8V8U8:
1815 /* No corresponding D3D9 equivalent. */
1816 AssertFailedReturn(D3DFMT_UNKNOWN);
1817 /* signed bump-map formats */
1818 case SVGA3D_V8U8:
1819 return D3DFMT_V8U8;
1820 case SVGA3D_Q8W8V8U8:
1821 return D3DFMT_Q8W8V8U8;
1822 case SVGA3D_CxV8U8:
1823 return D3DFMT_CxV8U8;
1824 /* mixed bump-map formats */
1825 case SVGA3D_X8L8V8U8:
1826 return D3DFMT_X8L8V8U8;
1827 case SVGA3D_A2W10V10U10:
1828 return D3DFMT_A2W10V10U10;
1829#endif
1830
1831 case SVGA3D_ARGB_S10E5: /* 16-bit floating-point ARGB */ /* D3DFMT_A16B16G16R16F - WINED3DFMT_R16G16B16A16_FLOAT */
1832 pSurface->internalFormatGL = GL_RGBA16F;
1833 pSurface->formatGL = GL_RGBA;
1834#if 0 /* bird: wine uses half float, sounds correct to me... */
1835 pSurface->typeGL = GL_FLOAT;
1836#else
1837 pSurface->typeGL = GL_HALF_FLOAT;
1838 AssertTestFmt(SVGA3D_ARGB_S10E5);
1839#endif
1840 break;
1841
1842 case SVGA3D_ARGB_S23E8: /* 32-bit floating-point ARGB */ /* D3DFMT_A32B32G32R32F - WINED3DFMT_R32G32B32A32_FLOAT */
1843 pSurface->internalFormatGL = GL_RGBA32F;
1844 pSurface->formatGL = GL_RGBA;
1845 pSurface->typeGL = GL_FLOAT; /* ?? - same as wine, so probably correct */
1846 break;
1847
1848 case SVGA3D_A2R10G10B10: /* D3DFMT_A2R10G10B10 - WINED3DFMT_B10G10R10A2_UNORM */
1849 pSurface->internalFormatGL = GL_RGB10_A2; /* ?? - same as wine, so probably correct */
1850#if 0 /* bird: Wine uses GL_BGRA instead of GL_RGBA. */
1851 pSurface->formatGL = GL_RGBA;
1852#else
1853 pSurface->formatGL = GL_BGRA;
1854#endif
1855 pSurface->typeGL = GL_UNSIGNED_INT;
1856 AssertTestFmt(SVGA3D_A2R10G10B10);
1857 break;
1858
1859
1860 /* Single- and dual-component floating point formats */
1861 case SVGA3D_R_S10E5: /* D3DFMT_R16F - WINED3DFMT_R16_FLOAT */
1862 pSurface->internalFormatGL = GL_R16F;
1863 pSurface->formatGL = GL_RED;
1864#if 0 /* bird: wine uses half float, sounds correct to me... */
1865 pSurface->typeGL = GL_FLOAT;
1866#else
1867 pSurface->typeGL = GL_HALF_FLOAT;
1868 AssertTestFmt(SVGA3D_R_S10E5);
1869#endif
1870 break;
1871 case SVGA3D_R_S23E8: /* D3DFMT_R32F - WINED3DFMT_R32_FLOAT */
1872 pSurface->internalFormatGL = GL_R32F;
1873 pSurface->formatGL = GL_RED;
1874 pSurface->typeGL = GL_FLOAT;
1875 break;
1876 case SVGA3D_RG_S10E5: /* D3DFMT_G16R16F - WINED3DFMT_R16G16_FLOAT */
1877 pSurface->internalFormatGL = GL_RG16F;
1878 pSurface->formatGL = GL_RG;
1879#if 0 /* bird: wine uses half float, sounds correct to me... */
1880 pSurface->typeGL = GL_FLOAT;
1881#else
1882 pSurface->typeGL = GL_HALF_FLOAT;
1883 AssertTestFmt(SVGA3D_RG_S10E5);
1884#endif
1885 break;
1886 case SVGA3D_RG_S23E8: /* D3DFMT_G32R32F - WINED3DFMT_R32G32_FLOAT */
1887 pSurface->internalFormatGL = GL_RG32F;
1888 pSurface->formatGL = GL_RG;
1889 pSurface->typeGL = GL_FLOAT;
1890 break;
1891
1892 /*
1893 * Any surface can be used as a buffer object, but SVGA3D_BUFFER is
1894 * the most efficient format to use when creating new surfaces
1895 * expressly for index or vertex data.
1896 */
1897 case SVGA3D_BUFFER:
1898 pSurface->internalFormatGL = -1;
1899 pSurface->formatGL = -1;
1900 pSurface->typeGL = -1;
1901 break;
1902
1903#if 0
1904 return D3DFMT_UNKNOWN;
1905
1906 case SVGA3D_V16U16:
1907 return D3DFMT_V16U16;
1908#endif
1909
1910 case SVGA3D_G16R16: /* D3DFMT_G16R16 - WINED3DFMT_R16G16_UNORM */
1911 pSurface->internalFormatGL = GL_RG16;
1912 pSurface->formatGL = GL_RG;
1913#if 0 /* bird: Wine uses GL_UNSIGNED_SHORT here. */
1914 pSurface->typeGL = GL_UNSIGNED_INT;
1915#else
1916 pSurface->typeGL = GL_UNSIGNED_SHORT;
1917 AssertTestFmt(SVGA3D_G16R16);
1918#endif
1919 break;
1920
1921 case SVGA3D_A16B16G16R16: /* D3DFMT_A16B16G16R16 - WINED3DFMT_R16G16B16A16_UNORM */
1922 pSurface->internalFormatGL = GL_RGBA16;
1923 pSurface->formatGL = GL_RGBA;
1924#if 0 /* bird: Wine uses GL_UNSIGNED_SHORT here. */
1925 pSurface->typeGL = GL_UNSIGNED_INT; /* ??? */
1926#else
1927 pSurface->typeGL = GL_UNSIGNED_SHORT;
1928 AssertTestFmt(SVGA3D_A16B16G16R16);
1929#endif
1930 break;
1931
1932 case SVGA3D_R8G8B8A8_SNORM:
1933 pSurface->internalFormatGL = GL_RGB8;
1934 pSurface->formatGL = GL_BGRA;
1935 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1936 AssertTestFmt(SVGA3D_R8G8B8A8_SNORM);
1937 break;
1938 case SVGA3D_R16G16_UNORM:
1939 pSurface->internalFormatGL = GL_RG16;
1940 pSurface->formatGL = GL_RG;
1941 pSurface->typeGL = GL_UNSIGNED_SHORT;
1942 AssertTestFmt(SVGA3D_R16G16_UNORM);
1943 break;
1944
1945 /* Packed Video formats */
1946 case SVGA3D_UYVY:
1947 case SVGA3D_YUY2:
1948 /* Use a BRGA texture to hold the data and convert it to an actual BGRA. */
1949 pSurface->fEmulated = true;
1950 pSurface->internalFormatGL = GL_RGBA8;
1951 pSurface->formatGL = GL_BGRA;
1952 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1953 pSurface->cbBlockGL = 4 * pSurface->cxBlock * pSurface->cyBlock;
1954 break;
1955
1956#if 0
1957 /* Planar video formats */
1958 case SVGA3D_NV12:
1959 return (D3DFORMAT)MAKEFOURCC('N', 'V', '1', '2');
1960
1961 /* Video format with alpha */
1962 case SVGA3D_AYUV:
1963 return (D3DFORMAT)MAKEFOURCC('A', 'Y', 'U', 'V');
1964
1965 case SVGA3D_BC4_UNORM:
1966 case SVGA3D_BC5_UNORM:
1967 /* Unknown; only in DX10 & 11 */
1968 break;
1969#endif
1970 default:
1971 AssertMsgFailed(("Unsupported format %d\n", format));
1972 break;
1973 }
1974#undef AssertTestFmt
1975}
1976
1977
1978#if 0
1979/**
1980 * Convert SVGA multi sample count value to its D3D equivalent
1981 */
1982D3DMULTISAMPLE_TYPE vmsvga3dMultipeSampleCount2D3D(uint32_t multisampleCount)
1983{
1984 AssertCompile(D3DMULTISAMPLE_2_SAMPLES == 2);
1985 AssertCompile(D3DMULTISAMPLE_16_SAMPLES == 16);
1986
1987 if (multisampleCount > 16)
1988 return D3DMULTISAMPLE_NONE;
1989
1990 /** @todo exact same mapping as d3d? */
1991 return (D3DMULTISAMPLE_TYPE)multisampleCount;
1992}
1993#endif
1994
1995/**
1996 * Destroy backend specific surface bits (part of SVGA_3D_CMD_SURFACE_DESTROY).
1997 *
1998 * @param pState The VMSVGA3d state.
1999 * @param pSurface The surface being destroyed.
2000 */
2001void vmsvga3dBackSurfaceDestroy(PVMSVGA3DSTATE pState, PVMSVGA3DSURFACE pSurface)
2002{
2003 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2004 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2005
2006 switch (pSurface->enmOGLResType)
2007 {
2008 case VMSVGA3D_OGLRESTYPE_BUFFER:
2009 Assert(pSurface->oglId.buffer != OPENGL_INVALID_ID);
2010 pState->ext.glDeleteBuffers(1, &pSurface->oglId.buffer);
2011 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2012 break;
2013
2014 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2015 Assert(pSurface->oglId.texture != OPENGL_INVALID_ID);
2016 glDeleteTextures(1, &pSurface->oglId.texture);
2017 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2018 if (pSurface->fEmulated)
2019 {
2020 if (pSurface->idEmulated)
2021 {
2022 glDeleteTextures(1, &pSurface->idEmulated);
2023 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2024 }
2025 }
2026 else
2027 {
2028 Assert(!pSurface->idEmulated);
2029 }
2030 break;
2031
2032 case VMSVGA3D_OGLRESTYPE_RENDERBUFFER:
2033 Assert(pSurface->oglId.renderbuffer != OPENGL_INVALID_ID);
2034 pState->ext.glDeleteRenderbuffers(1, &pSurface->oglId.renderbuffer);
2035 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2036 break;
2037
2038 default:
2039 AssertMsg(!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface),
2040 ("hint=%#x, type=%d\n",
2041 (pSurface->surfaceFlags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK), pSurface->enmOGLResType));
2042 break;
2043 }
2044}
2045
2046
2047int vmsvga3dSurfaceCopy(PVGASTATECC pThisCC, SVGA3dSurfaceImageId dest, SVGA3dSurfaceImageId src,
2048 uint32_t cCopyBoxes, SVGA3dCopyBox *pBox)
2049{
2050 int rc;
2051
2052 LogFunc(("Copy %d boxes from sid=%u face=%u mipmap=%u to sid=%u face=%u mipmap=%u\n",
2053 cCopyBoxes, src.sid, src.face, src.mipmap, dest.sid, dest.face, dest.mipmap));
2054
2055 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2056 AssertReturn(pState, VERR_INVALID_STATE);
2057
2058 PVMSVGA3DSURFACE pSurfaceSrc;
2059 rc = vmsvga3dSurfaceFromSid(pState, src.sid, &pSurfaceSrc);
2060 AssertRCReturn(rc, rc);
2061
2062 PVMSVGA3DSURFACE pSurfaceDst;
2063 rc = vmsvga3dSurfaceFromSid(pState, dest.sid, &pSurfaceDst);
2064 AssertRCReturn(rc, rc);
2065
2066 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceSrc))
2067 {
2068 /* The source surface is still in memory. */
2069 PVMSVGA3DMIPMAPLEVEL pMipmapLevelSrc;
2070 rc = vmsvga3dMipmapLevel(pSurfaceSrc, src.face, src.mipmap, &pMipmapLevelSrc);
2071 AssertRCReturn(rc, rc);
2072
2073 PVMSVGA3DMIPMAPLEVEL pMipmapLevelDst;
2074 rc = vmsvga3dMipmapLevel(pSurfaceDst, dest.face, dest.mipmap, &pMipmapLevelDst);
2075 AssertRCReturn(rc, rc);
2076
2077 /* The copy operation is performed on the shared context. */
2078 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2079 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2080
2081 /* Use glTexSubImage to upload the data to the destination texture.
2082 * The latter must be an OpenGL texture.
2083 */
2084 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceDst))
2085 {
2086 LogFunc(("dest sid=%u type=0x%x format=%d -> create texture\n", dest.sid, pSurfaceDst->surfaceFlags, pSurfaceDst->format));
2087 rc = vmsvga3dBackCreateTexture(pState, pContext, pContext->id, pSurfaceDst);
2088 AssertRCReturn(rc, rc);
2089 }
2090
2091 GLenum target;
2092 if (pSurfaceDst->targetGL == GL_TEXTURE_CUBE_MAP)
2093 target = vmsvga3dCubemapFaceFromIndex(dest.face);
2094 else
2095 {
2096 AssertMsg(pSurfaceDst->targetGL == GL_TEXTURE_2D, ("Test %#x\n", pSurfaceDst->targetGL));
2097 target = pSurfaceDst->targetGL;
2098 }
2099
2100 /* Save the unpacking parameters and set what we need here. */
2101 VMSVGAPACKPARAMS SavedParams;
2102 vmsvga3dOglSetUnpackParams(pState, pContext,
2103 pMipmapLevelSrc->mipmapSize.width,
2104 target == GL_TEXTURE_3D ? pMipmapLevelSrc->mipmapSize.height : 0,
2105 &SavedParams);
2106
2107 glBindTexture(pSurfaceDst->targetGL, pSurfaceDst->oglId.texture);
2108 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2109
2110 for (uint32_t i = 0; i < cCopyBoxes; ++i)
2111 {
2112 SVGA3dCopyBox clipBox = pBox[i];
2113 vmsvgaR3ClipCopyBox(&pMipmapLevelSrc->mipmapSize, &pMipmapLevelDst->mipmapSize, &clipBox);
2114 if ( !clipBox.w
2115 || !clipBox.h
2116 || !clipBox.d)
2117 {
2118 LogFunc(("Skipped empty box.\n"));
2119 continue;
2120 }
2121
2122 LogFunc(("copy box %d,%d,%d %dx%d to %d,%d,%d\n",
2123 clipBox.srcx, clipBox.srcy, clipBox.srcz, clipBox.w, clipBox.h, clipBox.x, clipBox.y, clipBox.z));
2124
2125 uint32_t const u32BlockX = clipBox.srcx / pSurfaceSrc->cxBlock;
2126 uint32_t const u32BlockY = clipBox.srcy / pSurfaceSrc->cyBlock;
2127 uint32_t const u32BlockZ = clipBox.srcz;
2128 Assert(u32BlockX * pSurfaceSrc->cxBlock == clipBox.srcx);
2129 Assert(u32BlockY * pSurfaceSrc->cyBlock == clipBox.srcy);
2130
2131 uint8_t const *pSrcBits = (uint8_t *)pMipmapLevelSrc->pSurfaceData
2132 + pMipmapLevelSrc->cbSurfacePlane * u32BlockZ
2133 + pMipmapLevelSrc->cbSurfacePitch * u32BlockY
2134 + pSurfaceSrc->cbBlock * u32BlockX;
2135
2136 if (target == GL_TEXTURE_3D)
2137 {
2138 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2139 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2140 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2141 {
2142 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2143 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2144 uint32_t const imageSize = cBlocksX * cBlocksY * clipBox.d * pSurfaceSrc->cbBlock;
2145 pState->ext.glCompressedTexSubImage3D(target, dest.mipmap,
2146 clipBox.x, clipBox.y, clipBox.z,
2147 clipBox.w, clipBox.h, clipBox.d,
2148 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2149 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2150 }
2151 else
2152 {
2153 pState->ext.glTexSubImage3D(target, dest.mipmap,
2154 clipBox.x, clipBox.y, clipBox.z,
2155 clipBox.w, clipBox.h, clipBox.d,
2156 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2157 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2158 }
2159 }
2160 else
2161 {
2162 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2163 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2164 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2165 {
2166 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2167 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2168 uint32_t const imageSize = cBlocksX * cBlocksY * pSurfaceSrc->cbBlock;
2169 pState->ext.glCompressedTexSubImage2D(target, dest.mipmap,
2170 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2171 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2172 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2173 }
2174 else
2175 {
2176 glTexSubImage2D(target, dest.mipmap,
2177 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2178 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2179 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2180 }
2181 }
2182 }
2183
2184 glBindTexture(pSurfaceDst->targetGL, 0);
2185 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2186
2187 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2188
2189 return VINF_SUCCESS;
2190 }
2191
2192 PVGASTATE pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVGASTATE);
2193 for (uint32_t i = 0; i < cCopyBoxes; i++)
2194 {
2195 SVGA3dBox destBox, srcBox;
2196
2197 srcBox.x = pBox[i].srcx;
2198 srcBox.y = pBox[i].srcy;
2199 srcBox.z = pBox[i].srcz;
2200 srcBox.w = pBox[i].w;
2201 srcBox.h = pBox[i].h;
2202 srcBox.d = pBox[i].d;
2203
2204 destBox.x = pBox[i].x;
2205 destBox.y = pBox[i].y;
2206 destBox.z = pBox[i].z;
2207 destBox.w = pBox[i].w;
2208 destBox.h = pBox[i].h;
2209 destBox.d = pBox[i].d;
2210
2211 /* No stretching is required, therefore use SVGA3D_STRETCH_BLT_POINT which translated to GL_NEAREST. */
2212 rc = vmsvga3dSurfaceStretchBlt(pThis, pThisCC, &dest, &destBox, &src, &srcBox, SVGA3D_STRETCH_BLT_POINT);
2213 AssertRCReturn(rc, rc);
2214 }
2215 return VINF_SUCCESS;
2216}
2217
2218
2219/**
2220 * Saves texture unpacking parameters and loads the specified ones.
2221 *
2222 * @param pState The VMSVGA3D state structure.
2223 * @param pContext The active context.
2224 * @param cxRow The number of pixels in a row. 0 for the entire width.
2225 * @param cyImage The height of the image in pixels. 0 for the entire height.
2226 * @param pSave Where to save stuff.
2227 */
2228void vmsvga3dOglSetUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, GLint cxRow, GLint cyImage,
2229 PVMSVGAPACKPARAMS pSave)
2230{
2231 RT_NOREF(pState);
2232
2233 /*
2234 * Save (ignore errors, setting the defaults we want and avoids restore).
2235 */
2236 pSave->iAlignment = 1;
2237 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2238 pSave->cxRow = 0;
2239 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2240 pSave->cyImage = 0;
2241 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &pSave->cyImage), pState, pContext);
2242
2243#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2244 pSave->fSwapBytes = GL_FALSE;
2245 glGetBooleanv(GL_UNPACK_SWAP_BYTES, &pSave->fSwapBytes);
2246 Assert(pSave->fSwapBytes == GL_FALSE);
2247
2248 pSave->fLsbFirst = GL_FALSE;
2249 glGetBooleanv(GL_UNPACK_LSB_FIRST, &pSave->fLsbFirst);
2250 Assert(pSave->fLsbFirst == GL_FALSE);
2251
2252 pSave->cSkipRows = 0;
2253 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &pSave->cSkipRows);
2254 Assert(pSave->cSkipRows == 0);
2255
2256 pSave->cSkipPixels = 0;
2257 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &pSave->cSkipPixels);
2258 Assert(pSave->cSkipPixels == 0);
2259
2260 pSave->cSkipImages = 0;
2261 glGetIntegerv(GL_UNPACK_SKIP_IMAGES, &pSave->cSkipImages);
2262 Assert(pSave->cSkipImages == 0);
2263
2264 VMSVGA3D_CLEAR_GL_ERRORS();
2265#endif
2266
2267 /*
2268 * Setup unpack.
2269 *
2270 * Note! We use 1 as alignment here because we currently don't do any
2271 * aligning of line pitches anywhere.
2272 */
2273 pSave->fChanged = 0;
2274 if (pSave->iAlignment != 1)
2275 {
2276 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1), pState, pContext);
2277 pSave->fChanged |= VMSVGAPACKPARAMS_ALIGNMENT;
2278 }
2279 if (pSave->cxRow != cxRow)
2280 {
2281 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, cxRow), pState, pContext);
2282 pSave->fChanged |= VMSVGAPACKPARAMS_ROW_LENGTH;
2283 }
2284 if (pSave->cyImage != cyImage)
2285 {
2286 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, cyImage), pState, pContext);
2287 pSave->fChanged |= VMSVGAPACKPARAMS_IMAGE_HEIGHT;
2288 }
2289#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2290 if (pSave->fSwapBytes != 0)
2291 {
2292 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2293 pSave->fChanged |= VMSVGAPACKPARAMS_SWAP_BYTES;
2294 }
2295 if (pSave->fLsbFirst != 0)
2296 {
2297 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE), pState, pContext);
2298 pSave->fChanged |= VMSVGAPACKPARAMS_LSB_FIRST;
2299 }
2300 if (pSave->cSkipRows != 0)
2301 {
2302 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, 0), pState, pContext);
2303 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_ROWS;
2304 }
2305 if (pSave->cSkipPixels != 0)
2306 {
2307 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0), pState, pContext);
2308 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_PIXELS;
2309 }
2310 if (pSave->cSkipImages != 0)
2311 {
2312 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0), pState, pContext);
2313 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_IMAGES;
2314 }
2315#endif
2316}
2317
2318
2319/**
2320 * Restores texture unpacking parameters.
2321 *
2322 * @param pState The VMSVGA3D state structure.
2323 * @param pContext The active context.
2324 * @param pSave Where stuff was saved.
2325 */
2326void vmsvga3dOglRestoreUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext,
2327 PCVMSVGAPACKPARAMS pSave)
2328{
2329 RT_NOREF(pState);
2330
2331 if (pSave->fChanged & VMSVGAPACKPARAMS_ALIGNMENT)
2332 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2333 if (pSave->fChanged & VMSVGAPACKPARAMS_ROW_LENGTH)
2334 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2335 if (pSave->fChanged & VMSVGAPACKPARAMS_IMAGE_HEIGHT)
2336 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2337#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2338 if (pSave->fChanged & VMSVGAPACKPARAMS_SWAP_BYTES)
2339 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2340 if (pSave->fChanged & VMSVGAPACKPARAMS_LSB_FIRST)
2341 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2342 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_ROWS)
2343 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2344 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_PIXELS)
2345 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2346 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_IMAGES)
2347 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2348#endif
2349}
2350
2351/**
2352 * Create D3D/OpenGL texture object for the specified surface.
2353 *
2354 * Surfaces are created when needed.
2355 *
2356 * @param pState The VMSVGA3d state.
2357 * @param pContext The context.
2358 * @param idAssociatedContext Probably the same as pContext->id.
2359 * @param pSurface The surface to create the texture for.
2360 */
2361int vmsvga3dBackCreateTexture(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, uint32_t idAssociatedContext,
2362 PVMSVGA3DSURFACE pSurface)
2363{
2364 RT_NOREF(idAssociatedContext);
2365
2366 LogFunc(("sid=%u\n", pSurface->id));
2367
2368 uint32_t const numMipLevels = pSurface->faces[0].numMipLevels;
2369
2370 /* Fugure out what kind of texture we are creating. */
2371 GLenum binding;
2372 GLenum target;
2373 if (pSurface->surfaceFlags & SVGA3D_SURFACE_CUBEMAP)
2374 {
2375 Assert(pSurface->cFaces == 6);
2376
2377 binding = GL_TEXTURE_BINDING_CUBE_MAP;
2378 target = GL_TEXTURE_CUBE_MAP;
2379 }
2380 else
2381 {
2382 if (pSurface->paMipmapLevels[0].mipmapSize.depth > 1)
2383 {
2384 binding = GL_TEXTURE_BINDING_3D;
2385 target = GL_TEXTURE_3D;
2386 }
2387 else
2388 {
2389 Assert(pSurface->cFaces == 1);
2390
2391 binding = GL_TEXTURE_BINDING_2D;
2392 target = GL_TEXTURE_2D;
2393 }
2394 }
2395
2396 /* All textures are created in the SharedCtx. */
2397 uint32_t idPrevCtx = pState->idActiveContext;
2398 pContext = &pState->SharedCtx;
2399 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2400
2401 glGenTextures(1, &pSurface->oglId.texture);
2402 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2403 if (pSurface->fEmulated)
2404 {
2405 glGenTextures(1, &pSurface->idEmulated);
2406 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2407 }
2408 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_TEXTURE;
2409
2410 GLint activeTexture = 0;
2411 glGetIntegerv(binding, &activeTexture);
2412 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2413
2414 /* Must bind texture to the current context in order to change it. */
2415 glBindTexture(target, pSurface->oglId.texture);
2416 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2417
2418 /* Set the unpacking parameters. */
2419 VMSVGAPACKPARAMS SavedParams;
2420 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
2421
2422 /** @todo Set the mip map generation filter settings. */
2423
2424 /* Set the mipmap base and max level parameters. */
2425 glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0);
2426 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2427 glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, pSurface->faces[0].numMipLevels - 1);
2428 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2429
2430 if (pSurface->fDirty)
2431 LogFunc(("sync dirty texture\n"));
2432
2433 /* Always allocate and initialize all mipmap levels; non-initialized mipmap levels used as render targets cause failures. */
2434 if (target == GL_TEXTURE_3D)
2435 {
2436 for (uint32_t i = 0; i < numMipLevels; ++i)
2437 {
2438 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2439 * exposing random host memory to the guest and helps a with the fedora 21 surface
2440 * corruption issues (launchpad, background, search field, login).
2441 */
2442 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2443
2444 LogFunc(("sync dirty 3D texture mipmap level %d (pitch %x) (dirty %d)\n",
2445 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2446
2447 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2448 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2449 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2450 {
2451 pState->ext.glCompressedTexImage3D(GL_TEXTURE_3D,
2452 i,
2453 pSurface->internalFormatGL,
2454 pMipLevel->mipmapSize.width,
2455 pMipLevel->mipmapSize.height,
2456 pMipLevel->mipmapSize.depth,
2457 0,
2458 pMipLevel->cbSurface,
2459 pMipLevel->pSurfaceData);
2460 }
2461 else
2462 {
2463 pState->ext.glTexImage3D(GL_TEXTURE_3D,
2464 i,
2465 pSurface->internalFormatGL,
2466 pMipLevel->mipmapSize.width,
2467 pMipLevel->mipmapSize.height,
2468 pMipLevel->mipmapSize.depth,
2469 0, /* border */
2470 pSurface->formatGL,
2471 pSurface->typeGL,
2472 pMipLevel->pSurfaceData);
2473 }
2474 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2475
2476 pMipLevel->fDirty = false;
2477 }
2478 }
2479 else if (target == GL_TEXTURE_CUBE_MAP)
2480 {
2481 for (uint32_t iFace = 0; iFace < 6; ++iFace)
2482 {
2483 GLenum const Face = vmsvga3dCubemapFaceFromIndex(iFace);
2484
2485 for (uint32_t i = 0; i < numMipLevels; ++i)
2486 {
2487 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[iFace * numMipLevels + i];
2488 Assert(pMipLevel->mipmapSize.width == pMipLevel->mipmapSize.height);
2489 Assert(pMipLevel->mipmapSize.depth == 1);
2490
2491 LogFunc(("sync cube texture face %d mipmap level %d (dirty %d)\n",
2492 iFace, i, pMipLevel->fDirty));
2493
2494 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2495 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2496 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2497 {
2498 pState->ext.glCompressedTexImage2D(Face,
2499 i,
2500 pSurface->internalFormatGL,
2501 pMipLevel->mipmapSize.width,
2502 pMipLevel->mipmapSize.height,
2503 0,
2504 pMipLevel->cbSurface,
2505 pMipLevel->pSurfaceData);
2506 }
2507 else
2508 {
2509 glTexImage2D(Face,
2510 i,
2511 pSurface->internalFormatGL,
2512 pMipLevel->mipmapSize.width,
2513 pMipLevel->mipmapSize.height,
2514 0,
2515 pSurface->formatGL,
2516 pSurface->typeGL,
2517 pMipLevel->pSurfaceData);
2518 }
2519 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2520
2521 pMipLevel->fDirty = false;
2522 }
2523 }
2524 }
2525 else if (target == GL_TEXTURE_2D)
2526 {
2527 for (uint32_t i = 0; i < numMipLevels; ++i)
2528 {
2529 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2530 * exposing random host memory to the guest and helps a with the fedora 21 surface
2531 * corruption issues (launchpad, background, search field, login).
2532 */
2533 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2534 Assert(pMipLevel->mipmapSize.depth == 1);
2535
2536 LogFunc(("sync dirty texture mipmap level %d (pitch %x) (dirty %d)\n",
2537 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2538
2539 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2540 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2541 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2542 {
2543 pState->ext.glCompressedTexImage2D(GL_TEXTURE_2D,
2544 i,
2545 pSurface->internalFormatGL,
2546 pMipLevel->mipmapSize.width,
2547 pMipLevel->mipmapSize.height,
2548 0,
2549 pMipLevel->cbSurface,
2550 pMipLevel->pSurfaceData);
2551 }
2552 else
2553 {
2554 glTexImage2D(GL_TEXTURE_2D,
2555 i,
2556 pSurface->internalFormatGL,
2557 pMipLevel->mipmapSize.width,
2558 pMipLevel->mipmapSize.height,
2559 0,
2560 pSurface->formatGL,
2561 pSurface->typeGL,
2562 NULL);
2563 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2564
2565 if (pSurface->fEmulated)
2566 {
2567 /* Bind the emulated texture and init it. */
2568 glBindTexture(GL_TEXTURE_2D, pSurface->idEmulated);
2569 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2570
2571 glTexImage2D(GL_TEXTURE_2D,
2572 i,
2573 pSurface->internalFormatGL,
2574 pMipLevel->mipmapSize.width,
2575 pMipLevel->mipmapSize.height,
2576 0,
2577 pSurface->formatGL,
2578 pSurface->typeGL,
2579 NULL);
2580 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2581 }
2582
2583 /* Fetch texture data: either to the actual or to the emulated texture.
2584 * The pSurfaceData buffer may be smaller than the entire texture
2585 * for emulated formats, in which case only part of the texture is synched.
2586 */
2587 uint32_t cBlocksX = pMipLevel->mipmapSize.width / pSurface->cxBlock;
2588 uint32_t cBlocksY = pMipLevel->mipmapSize.height / pSurface->cyBlock;
2589 glTexSubImage2D(GL_TEXTURE_2D,
2590 i,
2591 0,
2592 0,
2593 cBlocksX,
2594 cBlocksY,
2595 pSurface->formatGL,
2596 pSurface->typeGL,
2597 pMipLevel->pSurfaceData);
2598 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2599
2600 if (pSurface->fEmulated)
2601 {
2602 /* Update the actual texture using the format converter. */
2603 FormatConvUpdateTexture(pState, pContext, pSurface, i);
2604
2605 /* Rebind the actual texture. */
2606 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture);
2607 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2608 }
2609 }
2610 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2611
2612 pMipLevel->fDirty = false;
2613 }
2614 }
2615
2616 pSurface->fDirty = false;
2617
2618 /* Restore unpacking parameters. */
2619 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2620
2621 /* Restore the old active texture. */
2622 glBindTexture(target, activeTexture);
2623 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2624
2625 pSurface->surfaceFlags |= SVGA3D_SURFACE_HINT_TEXTURE;
2626 pSurface->targetGL = target;
2627 pSurface->bindingGL = binding;
2628
2629 if (idPrevCtx < pState->cContexts && pState->papContexts[idPrevCtx]->id == idPrevCtx)
2630 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pState->papContexts[idPrevCtx]);
2631 return VINF_SUCCESS;
2632}
2633
2634
2635/**
2636 * Backend worker for implementing SVGA_3D_CMD_SURFACE_STRETCHBLT.
2637 *
2638 * @returns VBox status code.
2639 * @param pThis The VGA device instance.
2640 * @param pState The VMSVGA3d state.
2641 * @param pDstSurface The destination host surface.
2642 * @param uDstFace The destination face (valid).
2643 * @param uDstMipmap The destination mipmap level (valid).
2644 * @param pDstBox The destination box.
2645 * @param pSrcSurface The source host surface.
2646 * @param uSrcFace The destination face (valid).
2647 * @param uSrcMipmap The source mimap level (valid).
2648 * @param pSrcBox The source box.
2649 * @param enmMode The strecht blt mode .
2650 * @param pContext The VMSVGA3d context (already current for OGL).
2651 */
2652int vmsvga3dBackSurfaceStretchBlt(PVGASTATE pThis, PVMSVGA3DSTATE pState,
2653 PVMSVGA3DSURFACE pDstSurface, uint32_t uDstFace, uint32_t uDstMipmap, SVGA3dBox const *pDstBox,
2654 PVMSVGA3DSURFACE pSrcSurface, uint32_t uSrcFace, uint32_t uSrcMipmap, SVGA3dBox const *pSrcBox,
2655 SVGA3dStretchBltMode enmMode, PVMSVGA3DCONTEXT pContext)
2656{
2657 RT_NOREF(pThis);
2658
2659 AssertReturn( RT_BOOL(pSrcSurface->surfaceFlags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2660 == RT_BOOL(pDstSurface->surfaceFlags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL), VERR_NOT_IMPLEMENTED);
2661
2662 GLenum glAttachment = GL_COLOR_ATTACHMENT0;
2663 GLbitfield glMask = GL_COLOR_BUFFER_BIT;
2664 if (pDstSurface->surfaceFlags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2665 {
2666 /** @todo Need GL_DEPTH_STENCIL_ATTACHMENT for depth/stencil formats? */
2667 glAttachment = GL_DEPTH_ATTACHMENT;
2668 glMask = GL_DEPTH_BUFFER_BIT;
2669 }
2670
2671 /* Activate the read and draw framebuffer objects. */
2672 pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, pContext->idReadFramebuffer);
2673 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2674 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, pContext->idDrawFramebuffer);
2675 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2676
2677 /* Bind the source and destination objects to the right place. */
2678 GLenum textarget;
2679 if (pSrcSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2680 textarget = vmsvga3dCubemapFaceFromIndex(uSrcFace);
2681 else
2682 {
2683 /// @todo later AssertMsg(pSrcSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSrcSurface->targetGL));
2684 textarget = GL_TEXTURE_2D;
2685 }
2686 pState->ext.glFramebufferTexture2D(GL_READ_FRAMEBUFFER, glAttachment, textarget,
2687 pSrcSurface->oglId.texture, uSrcMipmap);
2688 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2689
2690 if (pDstSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2691 textarget = vmsvga3dCubemapFaceFromIndex(uDstFace);
2692 else
2693 {
2694 /// @todo later AssertMsg(pDstSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pDstSurface->targetGL));
2695 textarget = GL_TEXTURE_2D;
2696 }
2697 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, textarget,
2698 pDstSurface->oglId.texture, uDstMipmap);
2699 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2700
2701 Log(("src conv. (%d,%d)(%d,%d); dest conv (%d,%d)(%d,%d)\n",
2702 pSrcBox->x, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y + pSrcBox->h),
2703 pSrcBox->x + pSrcBox->w, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y),
2704 pDstBox->x, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y + pDstBox->h),
2705 pDstBox->x + pDstBox->w, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y)));
2706
2707 pState->ext.glBlitFramebuffer(pSrcBox->x,
2708 pSrcBox->y,
2709 pSrcBox->x + pSrcBox->w, /* exclusive. */
2710 pSrcBox->y + pSrcBox->h,
2711 pDstBox->x,
2712 pDstBox->y,
2713 pDstBox->x + pDstBox->w, /* exclusive. */
2714 pDstBox->y + pDstBox->h,
2715 glMask,
2716 (enmMode == SVGA3D_STRETCH_BLT_POINT) ? GL_NEAREST : GL_LINEAR);
2717 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2718
2719 /* Reset the frame buffer association */
2720 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
2721 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2722
2723 return VINF_SUCCESS;
2724}
2725
2726/**
2727 * Save texture packing parameters and loads those appropriate for the given
2728 * surface.
2729 *
2730 * @param pState The VMSVGA3D state structure.
2731 * @param pContext The active context.
2732 * @param pSurface The surface.
2733 * @param pSave Where to save stuff.
2734 */
2735void vmsvga3dOglSetPackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2736 PVMSVGAPACKPARAMS pSave)
2737{
2738 RT_NOREF(pState);
2739 /*
2740 * Save (ignore errors, setting the defaults we want and avoids restore).
2741 */
2742 pSave->iAlignment = 1;
2743 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2744 pSave->cxRow = 0;
2745 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2746
2747#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2748 pSave->cyImage = 0;
2749 glGetIntegerv(GL_PACK_IMAGE_HEIGHT, &pSave->cyImage);
2750 Assert(pSave->cyImage == 0);
2751
2752 pSave->fSwapBytes = GL_FALSE;
2753 glGetBooleanv(GL_PACK_SWAP_BYTES, &pSave->fSwapBytes);
2754 Assert(pSave->fSwapBytes == GL_FALSE);
2755
2756 pSave->fLsbFirst = GL_FALSE;
2757 glGetBooleanv(GL_PACK_LSB_FIRST, &pSave->fLsbFirst);
2758 Assert(pSave->fLsbFirst == GL_FALSE);
2759
2760 pSave->cSkipRows = 0;
2761 glGetIntegerv(GL_PACK_SKIP_ROWS, &pSave->cSkipRows);
2762 Assert(pSave->cSkipRows == 0);
2763
2764 pSave->cSkipPixels = 0;
2765 glGetIntegerv(GL_PACK_SKIP_PIXELS, &pSave->cSkipPixels);
2766 Assert(pSave->cSkipPixels == 0);
2767
2768 pSave->cSkipImages = 0;
2769 glGetIntegerv(GL_PACK_SKIP_IMAGES, &pSave->cSkipImages);
2770 Assert(pSave->cSkipImages == 0);
2771
2772 VMSVGA3D_CLEAR_GL_ERRORS();
2773#endif
2774
2775 /*
2776 * Setup unpack.
2777 *
2778 * Note! We use 1 as alignment here because we currently don't do any
2779 * aligning of line pitches anywhere.
2780 */
2781 NOREF(pSurface);
2782 if (pSave->iAlignment != 1)
2783 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, 1), pState, pContext);
2784 if (pSave->cxRow != 0)
2785 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, 0), pState, pContext);
2786#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2787 if (pSave->cyImage != 0)
2788 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0), pState, pContext);
2789 if (pSave->fSwapBytes != 0)
2790 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2791 if (pSave->fLsbFirst != 0)
2792 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE), pState, pContext);
2793 if (pSave->cSkipRows != 0)
2794 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, 0), pState, pContext);
2795 if (pSave->cSkipPixels != 0)
2796 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, 0), pState, pContext);
2797 if (pSave->cSkipImages != 0)
2798 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, 0), pState, pContext);
2799#endif
2800}
2801
2802
2803/**
2804 * Restores texture packing parameters.
2805 *
2806 * @param pState The VMSVGA3D state structure.
2807 * @param pContext The active context.
2808 * @param pSurface The surface.
2809 * @param pSave Where stuff was saved.
2810 */
2811void vmsvga3dOglRestorePackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2812 PCVMSVGAPACKPARAMS pSave)
2813{
2814 RT_NOREF(pState, pSurface);
2815 if (pSave->iAlignment != 1)
2816 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2817 if (pSave->cxRow != 0)
2818 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2819#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2820 if (pSave->cyImage != 0)
2821 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2822 if (pSave->fSwapBytes != 0)
2823 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2824 if (pSave->fLsbFirst != 0)
2825 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2826 if (pSave->cSkipRows != 0)
2827 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2828 if (pSave->cSkipPixels != 0)
2829 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2830 if (pSave->cSkipImages != 0)
2831 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2832#endif
2833}
2834
2835
2836/**
2837 * Backend worker for implementing SVGA_3D_CMD_SURFACE_DMA that copies one box.
2838 *
2839 * @returns Failure status code or @a rc.
2840 * @param pThis The shared VGA/VMSVGA instance data.
2841 * @param pThisCC The VGA/VMSVGA state for ring-3.
2842 * @param pState The VMSVGA3d state.
2843 * @param pSurface The host surface.
2844 * @param pMipLevel Mipmap level. The caller knows it already.
2845 * @param uHostFace The host face (valid).
2846 * @param uHostMipmap The host mipmap level (valid).
2847 * @param GuestPtr The guest pointer.
2848 * @param cbGuestPitch The guest pitch.
2849 * @param transfer The transfer direction.
2850 * @param pBox The box to copy (clipped, valid, except for guest's srcx, srcy, srcz).
2851 * @param pContext The context (for OpenGL).
2852 * @param rc The current rc for all boxes.
2853 * @param iBox The current box number (for Direct 3D).
2854 */
2855int vmsvga3dBackSurfaceDMACopyBox(PVGASTATE pThis, PVGASTATECC pThisCC, PVMSVGA3DSTATE pState, PVMSVGA3DSURFACE pSurface,
2856 PVMSVGA3DMIPMAPLEVEL pMipLevel, uint32_t uHostFace, uint32_t uHostMipmap,
2857 SVGAGuestPtr GuestPtr, uint32_t cbGuestPitch, SVGA3dTransferType transfer,
2858 SVGA3dCopyBox const *pBox, PVMSVGA3DCONTEXT pContext, int rc, int iBox)
2859{
2860 RT_NOREF(iBox);
2861
2862 switch (pSurface->enmOGLResType)
2863 {
2864 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2865 {
2866 uint32_t cbSurfacePitch;
2867 uint8_t *pDoubleBuffer;
2868 uint64_t offHst;
2869
2870 uint32_t const u32HostBlockX = pBox->x / pSurface->cxBlock;
2871 uint32_t const u32HostBlockY = pBox->y / pSurface->cyBlock;
2872 uint32_t const u32HostZ = pBox->z;
2873 Assert(u32HostBlockX * pSurface->cxBlock == pBox->x);
2874 Assert(u32HostBlockY * pSurface->cyBlock == pBox->y);
2875
2876 uint32_t const u32GuestBlockX = pBox->srcx / pSurface->cxBlock;
2877 uint32_t const u32GuestBlockY = pBox->srcy / pSurface->cyBlock;
2878 uint32_t const u32GuestZ = pBox->srcz / pSurface->cyBlock;
2879 Assert(u32GuestBlockX * pSurface->cxBlock == pBox->srcx);
2880 Assert(u32GuestBlockY * pSurface->cyBlock == pBox->srcy);
2881
2882 uint32_t const cBlocksX = (pBox->w + pSurface->cxBlock - 1) / pSurface->cxBlock;
2883 uint32_t const cBlocksY = (pBox->h + pSurface->cyBlock - 1) / pSurface->cyBlock;
2884 AssertMsgReturn(cBlocksX && cBlocksY, ("Empty box %dx%d\n", pBox->w, pBox->h), VERR_INTERNAL_ERROR);
2885
2886 GLenum texImageTarget;
2887 if (pSurface->targetGL == GL_TEXTURE_3D)
2888 {
2889 texImageTarget = GL_TEXTURE_3D;
2890 }
2891 else if (pSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2892 {
2893 texImageTarget = vmsvga3dCubemapFaceFromIndex(uHostFace);
2894 }
2895 else
2896 {
2897 AssertMsg(pSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSurface->targetGL));
2898 texImageTarget = GL_TEXTURE_2D;
2899 }
2900
2901 /* The buffer must be large enough to hold entire texture in the OpenGL format. */
2902 pDoubleBuffer = (uint8_t *)RTMemAlloc(pSurface->cbBlockGL * pMipLevel->cBlocks);
2903 AssertReturn(pDoubleBuffer, VERR_NO_MEMORY);
2904
2905 if (transfer == SVGA3D_READ_HOST_VRAM)
2906 {
2907 /* Read the entire texture to the double buffer. */
2908 GLint activeTexture;
2909
2910 /* Must bind texture to the current context in order to read it. */
2911 glGetIntegerv(pSurface->bindingGL, &activeTexture);
2912 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2913
2914 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
2915 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2916
2917 if (pSurface->fEmulated)
2918 {
2919 FormatConvReadTexture(pState, pContext, pSurface, uHostMipmap);
2920 }
2921
2922 /* Set row length and alignment of the input data. */
2923 VMSVGAPACKPARAMS SavedParams;
2924 vmsvga3dOglSetPackParams(pState, pContext, pSurface, &SavedParams);
2925
2926 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2927 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2928 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2929 {
2930 pState->ext.glGetCompressedTexImage(texImageTarget, uHostMipmap, pDoubleBuffer);
2931 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2932 }
2933 else
2934 {
2935 glGetTexImage(texImageTarget, uHostMipmap, pSurface->formatGL, pSurface->typeGL, pDoubleBuffer);
2936 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2937 }
2938
2939 vmsvga3dOglRestorePackParams(pState, pContext, pSurface, &SavedParams);
2940
2941 /* Restore the old active texture. */
2942 glBindTexture(pSurface->targetGL, activeTexture);
2943 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2944
2945 offHst = u32HostBlockX * pSurface->cbBlock + u32HostBlockY * pMipLevel->cbSurfacePitch + u32HostZ * pMipLevel->cbSurfacePlane;
2946 cbSurfacePitch = pMipLevel->cbSurfacePitch;
2947 }
2948 else
2949 {
2950 /* The buffer will contain only the copied rectangle. */
2951 offHst = 0;
2952 cbSurfacePitch = cBlocksX * pSurface->cbBlock;
2953 }
2954
2955 uint64_t offGst = u32GuestBlockX * pSurface->cbBlock + u32GuestBlockY * cbGuestPitch + u32GuestZ * cbGuestPitch * pMipLevel->mipmapSize.height;
2956
2957 for (uint32_t iPlane = 0; iPlane < pBox->d; ++iPlane)
2958 {
2959 AssertBreak(offHst < UINT32_MAX);
2960 AssertBreak(offGst < UINT32_MAX);
2961
2962 rc = vmsvgaR3GmrTransfer(pThis,
2963 pThisCC,
2964 transfer,
2965 pDoubleBuffer,
2966 pMipLevel->cbSurface,
2967 (uint32_t)offHst,
2968 cbSurfacePitch,
2969 GuestPtr,
2970 (uint32_t)offGst,
2971 cbGuestPitch,
2972 cBlocksX * pSurface->cbBlock,
2973 cBlocksY);
2974 AssertRC(rc);
2975
2976 offHst += pMipLevel->cbSurfacePlane;
2977 offGst += pMipLevel->mipmapSize.height * cbGuestPitch;
2978 }
2979
2980 /* Update the opengl surface data. */
2981 if (transfer == SVGA3D_WRITE_HOST_VRAM)
2982 {
2983 GLint activeTexture = 0;
2984 glGetIntegerv(pSurface->bindingGL, &activeTexture);
2985 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2986
2987 /* Must bind texture to the current context in order to change it. */
2988 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
2989 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2990
2991 LogFunc(("copy texture mipmap level %d (pitch %x)\n", uHostMipmap, pMipLevel->cbSurfacePitch));
2992
2993 /* Set row length and alignment of the input data. */
2994 /* We do not need to set ROW_LENGTH to w here, because the image in pDoubleBuffer is tightly packed. */
2995 VMSVGAPACKPARAMS SavedParams;
2996 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
2997
2998 if (texImageTarget == GL_TEXTURE_3D)
2999 {
3000 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3001 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3002 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3003 {
3004 pState->ext.glCompressedTexSubImage3D(texImageTarget,
3005 uHostMipmap,
3006 pBox->x,
3007 pBox->y,
3008 pBox->z,
3009 pBox->w,
3010 pBox->h,
3011 pBox->d,
3012 pSurface->internalFormatGL,
3013 cbSurfacePitch * cBlocksY * pBox->d,
3014 pDoubleBuffer);
3015 }
3016 else
3017 {
3018 pState->ext.glTexSubImage3D(texImageTarget,
3019 uHostMipmap,
3020 u32HostBlockX,
3021 u32HostBlockY,
3022 pBox->z,
3023 cBlocksX,
3024 cBlocksY,
3025 pBox->d,
3026 pSurface->formatGL,
3027 pSurface->typeGL,
3028 pDoubleBuffer);
3029 }
3030 }
3031 else
3032 {
3033 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3034 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3035 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3036 {
3037 pState->ext.glCompressedTexSubImage2D(texImageTarget,
3038 uHostMipmap,
3039 pBox->x,
3040 pBox->y,
3041 pBox->w,
3042 pBox->h,
3043 pSurface->internalFormatGL,
3044 cbSurfacePitch * cBlocksY,
3045 pDoubleBuffer);
3046 }
3047 else
3048 {
3049 glTexSubImage2D(texImageTarget,
3050 uHostMipmap,
3051 u32HostBlockX,
3052 u32HostBlockY,
3053 cBlocksX,
3054 cBlocksY,
3055 pSurface->formatGL,
3056 pSurface->typeGL,
3057 pDoubleBuffer);
3058 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3059
3060 if (pSurface->fEmulated)
3061 {
3062 /* Convert the texture to the actual texture if necessary */
3063 FormatConvUpdateTexture(pState, pContext, pSurface, uHostMipmap);
3064 }
3065 }
3066 }
3067 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3068
3069 /* Restore old values. */
3070 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
3071
3072 /* Restore the old active texture. */
3073 glBindTexture(pSurface->targetGL, activeTexture);
3074 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3075 }
3076
3077 Log4(("first line:\n%.*Rhxd\n", cBlocksX * pSurface->cbBlock, pDoubleBuffer));
3078
3079 /* Free the double buffer. */
3080 RTMemFree(pDoubleBuffer);
3081 break;
3082 }
3083
3084 case VMSVGA3D_OGLRESTYPE_BUFFER:
3085 {
3086 /* Buffers are uncompressed. */
3087 AssertReturn(pSurface->cxBlock == 1 && pSurface->cyBlock == 1, VERR_INTERNAL_ERROR);
3088
3089 /* Caller already clipped pBox and buffers are 1-dimensional. */
3090 Assert(pBox->y == 0 && pBox->h == 1 && pBox->z == 0 && pBox->d == 1);
3091
3092 VMSVGA3D_CLEAR_GL_ERRORS();
3093 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pSurface->oglId.buffer);
3094 if (VMSVGA3D_GL_IS_SUCCESS(pContext))
3095 {
3096 GLenum enmGlTransfer = (transfer == SVGA3D_READ_HOST_VRAM) ? GL_READ_ONLY : GL_WRITE_ONLY;
3097 uint8_t *pbData = (uint8_t *)pState->ext.glMapBuffer(GL_ARRAY_BUFFER, enmGlTransfer);
3098 if (RT_LIKELY(pbData != NULL))
3099 {
3100#if defined(VBOX_STRICT) && defined(RT_OS_DARWIN)
3101 GLint cbStrictBufSize;
3102 glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &cbStrictBufSize);
3103 Assert(VMSVGA3D_GL_IS_SUCCESS(pContext));
3104 AssertMsg(cbStrictBufSize >= (int32_t)pMipLevel->cbSurface,
3105 ("cbStrictBufSize=%#x cbSurface=%#x pContext->id=%#x\n", (uint32_t)cbStrictBufSize, pMipLevel->cbSurface, pContext->id));
3106#endif
3107 Log(("Lock %s memory for rectangle (%d,%d)(%d,%d)\n",
3108 (pSurface->surfaceFlags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_VERTEXBUFFER ? "vertex" :
3109 (pSurface->surfaceFlags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_INDEXBUFFER ? "index" : "buffer",
3110 pBox->x, pBox->y, pBox->x + pBox->w, pBox->y + pBox->h));
3111
3112 /* The caller already copied the data to the pMipLevel->pSurfaceData buffer, see VMSVGA3DSURFACE_NEEDS_DATA. */
3113 uint32_t const offHst = pBox->x * pSurface->cbBlock;
3114 uint32_t const cbWidth = pBox->w * pSurface->cbBlock;
3115
3116 memcpy(pbData + offHst, (uint8_t *)pMipLevel->pSurfaceData + offHst, cbWidth);
3117
3118 Log4(("Buffer updated at [0x%x;0x%x):\n%.*Rhxd\n", offHst, offHst + cbWidth, cbWidth, (uint8_t *)pbData + offHst));
3119
3120 pState->ext.glUnmapBuffer(GL_ARRAY_BUFFER);
3121 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3122 }
3123 else
3124 VMSVGA3D_GL_GET_AND_COMPLAIN(pState, pContext, ("glMapBuffer(GL_ARRAY_BUFFER, %#x) -> NULL\n", enmGlTransfer));
3125 }
3126 else
3127 VMSVGA3D_GL_COMPLAIN(pState, pContext, ("glBindBuffer(GL_ARRAY_BUFFER, %#x)\n", pSurface->oglId.buffer));
3128 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
3129 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3130 break;
3131 }
3132
3133 default:
3134 AssertFailed();
3135 break;
3136 }
3137
3138 return rc;
3139}
3140
3141int vmsvga3dGenerateMipmaps(PVGASTATECC pThisCC, uint32_t sid, SVGA3dTextureFilter filter)
3142{
3143 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3144 PVMSVGA3DSURFACE pSurface;
3145 int rc = VINF_SUCCESS;
3146 PVMSVGA3DCONTEXT pContext;
3147 uint32_t cid;
3148 GLint activeTexture = 0;
3149
3150 AssertReturn(pState, VERR_NO_MEMORY);
3151
3152 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
3153 AssertRCReturn(rc, rc);
3154
3155 Assert(filter != SVGA3D_TEX_FILTER_FLATCUBIC);
3156 Assert(filter != SVGA3D_TEX_FILTER_GAUSSIANCUBIC);
3157 pSurface->autogenFilter = filter;
3158
3159 LogFunc(("sid=%u filter=%d\n", sid, filter));
3160
3161 cid = SVGA3D_INVALID_ID;
3162 pContext = &pState->SharedCtx;
3163 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3164
3165 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
3166 {
3167 /* Unknown surface type; turn it into a texture. */
3168 LogFunc(("unknown src surface id=%x type=%d format=%d -> create texture\n", sid, pSurface->surfaceFlags, pSurface->format));
3169 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pSurface);
3170 AssertRCReturn(rc, rc);
3171 }
3172 else
3173 {
3174 /** @todo new filter */
3175 AssertFailed();
3176 }
3177
3178 glGetIntegerv(pSurface->bindingGL, &activeTexture);
3179 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3180
3181 /* Must bind texture to the current context in order to change it. */
3182 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
3183 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3184
3185 /* Generate the mip maps. */
3186 pState->ext.glGenerateMipmap(pSurface->targetGL);
3187 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3188
3189 /* Restore the old texture. */
3190 glBindTexture(pSurface->targetGL, activeTexture);
3191 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3192
3193 return VINF_SUCCESS;
3194}
3195
3196
3197#ifdef RT_OS_LINUX
3198/**
3199 * X11 event handling thread.
3200 *
3201 * @returns VINF_SUCCESS (ignored)
3202 * @param hThreadSelf thread handle
3203 * @param pvUser pointer to pState structure
3204 */
3205DECLCALLBACK(int) vmsvga3dXEventThread(RTTHREAD hThreadSelf, void *pvUser)
3206{
3207 RT_NOREF(hThreadSelf);
3208 PVMSVGA3DSTATE pState = (PVMSVGA3DSTATE)pvUser;
3209 while (!pState->bTerminate)
3210 {
3211 while (XPending(pState->display) > 0)
3212 {
3213 XEvent event;
3214 XNextEvent(pState->display, &event);
3215
3216 switch (event.type)
3217 {
3218 default:
3219 break;
3220 }
3221 }
3222 /* sleep for 16ms to not burn too many cycles */
3223 RTThreadSleep(16);
3224 }
3225 return VINF_SUCCESS;
3226}
3227#endif // RT_OS_LINUX
3228
3229
3230/**
3231 * Create a new 3d context
3232 *
3233 * @returns VBox status code.
3234 * @param pThisCC The VGA/VMSVGA state for ring-3.
3235 * @param cid Context id
3236 * @param fFlags VMSVGA3D_DEF_CTX_F_XXX.
3237 */
3238int vmsvga3dContextDefineOgl(PVGASTATECC pThisCC, uint32_t cid, uint32_t fFlags)
3239{
3240 int rc;
3241 PVMSVGA3DCONTEXT pContext;
3242 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3243
3244 AssertReturn(pState, VERR_NO_MEMORY);
3245 AssertReturn( cid < SVGA3D_MAX_CONTEXT_IDS
3246 || (cid == VMSVGA3D_SHARED_CTX_ID && (fFlags & VMSVGA3D_DEF_CTX_F_SHARED_CTX)), VERR_INVALID_PARAMETER);
3247#if !defined(VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE) || !(defined(RT_OS_DARWIN))
3248 AssertReturn(!(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE), VERR_INTERNAL_ERROR_3);
3249#endif
3250
3251 Log(("vmsvga3dContextDefine id %x\n", cid));
3252
3253 if (cid == VMSVGA3D_SHARED_CTX_ID)
3254 pContext = &pState->SharedCtx;
3255 else
3256 {
3257 if (cid >= pState->cContexts)
3258 {
3259 /* Grow the array. */
3260 uint32_t cNew = RT_ALIGN(cid + 15, 16);
3261 void *pvNew = RTMemRealloc(pState->papContexts, sizeof(pState->papContexts[0]) * cNew);
3262 AssertReturn(pvNew, VERR_NO_MEMORY);
3263 pState->papContexts = (PVMSVGA3DCONTEXT *)pvNew;
3264 while (pState->cContexts < cNew)
3265 {
3266 pContext = (PVMSVGA3DCONTEXT)RTMemAllocZ(sizeof(*pContext));
3267 AssertReturn(pContext, VERR_NO_MEMORY);
3268 pContext->id = SVGA3D_INVALID_ID;
3269 pState->papContexts[pState->cContexts++] = pContext;
3270 }
3271 }
3272 /* If one already exists with this id, then destroy it now. */
3273 if (pState->papContexts[cid]->id != SVGA3D_INVALID_ID)
3274 vmsvga3dContextDestroy(pThisCC, cid);
3275
3276 pContext = pState->papContexts[cid];
3277 }
3278
3279 /*
3280 * Find or create the shared context if needed (necessary for sharing e.g. textures between contexts).
3281 */
3282 PVMSVGA3DCONTEXT pSharedCtx = NULL;
3283 if (!(fFlags & (VMSVGA3D_DEF_CTX_F_INIT | VMSVGA3D_DEF_CTX_F_SHARED_CTX)))
3284 {
3285 pSharedCtx = &pState->SharedCtx;
3286 if (pSharedCtx->id != VMSVGA3D_SHARED_CTX_ID)
3287 {
3288 rc = vmsvga3dContextDefineOgl(pThisCC, VMSVGA3D_SHARED_CTX_ID, VMSVGA3D_DEF_CTX_F_SHARED_CTX);
3289 AssertLogRelRCReturn(rc, rc);
3290
3291 /* Create resources which use the shared context. */
3292 vmsvga3dOnSharedContextDefine(pState);
3293 }
3294 }
3295
3296 /*
3297 * Initialize the context.
3298 */
3299 memset(pContext, 0, sizeof(*pContext));
3300 pContext->id = cid;
3301 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); i++)
3302 pContext->aSidActiveTextures[i] = SVGA3D_INVALID_ID;
3303
3304 pContext->state.shidVertex = SVGA3D_INVALID_ID;
3305 pContext->state.shidPixel = SVGA3D_INVALID_ID;
3306 pContext->idFramebuffer = OPENGL_INVALID_ID;
3307 pContext->idReadFramebuffer = OPENGL_INVALID_ID;
3308 pContext->idDrawFramebuffer = OPENGL_INVALID_ID;
3309
3310 rc = ShaderContextCreate(&pContext->pShaderContext);
3311 AssertRCReturn(rc, rc);
3312
3313 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->state.aRenderTargets); i++)
3314 pContext->state.aRenderTargets[i] = SVGA3D_INVALID_ID;
3315
3316#ifdef RT_OS_WINDOWS
3317 /* Create a context window with minimal 4x4 size. We will never use the swapchain
3318 * to present the rendered image. Rendered images from the guest will be copied to
3319 * the VMSVGA SCREEN object, which can be either an offscreen render target or
3320 * system memory in the guest VRAM.
3321 */
3322 rc = vmsvga3dContextWindowCreate(pState->hInstance, pState->pWindowThread, pState->WndRequestSem, &pContext->hwnd);
3323 AssertRCReturn(rc, rc);
3324
3325 pContext->hdc = GetDC(pContext->hwnd);
3326 AssertMsgReturn(pContext->hdc, ("GetDC %x failed with %d\n", pContext->hwnd, GetLastError()), VERR_INTERNAL_ERROR);
3327
3328 PIXELFORMATDESCRIPTOR pfd = {
3329 sizeof(PIXELFORMATDESCRIPTOR), /* size of this pfd */
3330 1, /* version number */
3331 PFD_DRAW_TO_WINDOW | /* support window */
3332 PFD_SUPPORT_OPENGL, /* support OpenGL */
3333 PFD_TYPE_RGBA, /* RGBA type */
3334 24, /* 24-bit color depth */
3335 0, 0, 0, 0, 0, 0, /* color bits ignored */
3336 8, /* alpha buffer */
3337 0, /* shift bit ignored */
3338 0, /* no accumulation buffer */
3339 0, 0, 0, 0, /* accum bits ignored */
3340 16, /* set depth buffer */
3341 16, /* set stencil buffer */
3342 0, /* no auxiliary buffer */
3343 PFD_MAIN_PLANE, /* main layer */
3344 0, /* reserved */
3345 0, 0, 0 /* layer masks ignored */
3346 };
3347 int pixelFormat;
3348 BOOL ret;
3349
3350 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3351 /** @todo is this really necessary?? */
3352 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3353 AssertMsgReturn(pixelFormat != 0, ("ChoosePixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3354
3355 ret = SetPixelFormat(pContext->hdc, pixelFormat, &pfd);
3356 AssertMsgReturn(ret == TRUE, ("SetPixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3357
3358 pContext->hglrc = wglCreateContext(pContext->hdc);
3359 AssertMsgReturn(pContext->hglrc, ("wglCreateContext %x failed with %d\n", pContext->hdc, GetLastError()), VERR_INTERNAL_ERROR);
3360
3361 if (pSharedCtx)
3362 {
3363 ret = wglShareLists(pSharedCtx->hglrc, pContext->hglrc);
3364 AssertMsg(ret == TRUE, ("wglShareLists(%p, %p) failed with %d\n", pSharedCtx->hglrc, pContext->hglrc, GetLastError()));
3365 }
3366
3367#elif defined(RT_OS_DARWIN)
3368 pContext->fOtherProfile = RT_BOOL(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
3369
3370 NativeNSOpenGLContextRef pShareContext = pSharedCtx ? pSharedCtx->cocoaContext : NULL;
3371 vmsvga3dCocoaCreateViewAndContext(&pContext->cocoaView, &pContext->cocoaContext,
3372 NULL,
3373 4, 4,
3374 pShareContext, pContext->fOtherProfile);
3375
3376#else
3377 if (pState->display == NULL)
3378 {
3379 /* get an X display and make sure we have glX 1.3 */
3380 pState->display = XOpenDisplay(0);
3381 AssertLogRelMsgReturn(pState->display, ("XOpenDisplay failed"), VERR_INTERNAL_ERROR);
3382 int glxMajor, glxMinor;
3383 Bool ret = glXQueryVersion(pState->display, &glxMajor, &glxMinor);
3384 AssertLogRelMsgReturn(ret && glxMajor == 1 && glxMinor >= 3, ("glX >=1.3 not present"), VERR_INTERNAL_ERROR);
3385 /* start our X event handling thread */
3386 rc = RTThreadCreate(&pState->pWindowThread, vmsvga3dXEventThread, pState, 0, RTTHREADTYPE_GUI, RTTHREADFLAGS_WAITABLE, "VMSVGA3DXEVENT");
3387 AssertLogRelMsgReturn(RT_SUCCESS(rc), ("Async IO Thread creation for 3d window handling failed rc=%Rrc\n", rc), rc);
3388 }
3389
3390 Window defaultRootWindow = XDefaultRootWindow(pState->display);
3391 /* Create a small 4x4 window required for GL context. */
3392 int attrib[] =
3393 {
3394 GLX_RGBA,
3395 GLX_RED_SIZE, 1,
3396 GLX_GREEN_SIZE, 1,
3397 GLX_BLUE_SIZE, 1,
3398 //GLX_ALPHA_SIZE, 1, this flips the bbos screen
3399 GLX_DOUBLEBUFFER,
3400 None
3401 };
3402 XVisualInfo *vi = glXChooseVisual(pState->display, DefaultScreen(pState->display), attrib);
3403 AssertLogRelMsgReturn(vi, ("glXChooseVisual failed"), VERR_INTERNAL_ERROR);
3404 XSetWindowAttributes swa;
3405 swa.colormap = XCreateColormap(pState->display, defaultRootWindow, vi->visual, AllocNone);
3406 AssertLogRelMsgReturn(swa.colormap, ("XCreateColormap failed"), VERR_INTERNAL_ERROR);
3407 swa.border_pixel = 0;
3408 swa.background_pixel = 0;
3409 swa.event_mask = StructureNotifyMask;
3410 unsigned long flags = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask;
3411 pContext->window = XCreateWindow(pState->display, defaultRootWindow,
3412 0, 0, 4, 4,
3413 0, vi->depth, InputOutput,
3414 vi->visual, flags, &swa);
3415 AssertLogRelMsgReturn(pContext->window, ("XCreateWindow failed"), VERR_INTERNAL_ERROR);
3416
3417 /* The window is hidden by default and never mapped, because we only render offscreen and never present to it. */
3418
3419 GLXContext shareContext = pSharedCtx ? pSharedCtx->glxContext : NULL;
3420 pContext->glxContext = glXCreateContext(pState->display, vi, shareContext, GL_TRUE);
3421 AssertLogRelMsgReturn(pContext->glxContext, ("glXCreateContext failed"), VERR_INTERNAL_ERROR);
3422#endif
3423
3424 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3425
3426 /* NULL during the first PowerOn call. */
3427 if (pState->ext.glGenFramebuffers)
3428 {
3429 /* Create a framebuffer object for this context. */
3430 pState->ext.glGenFramebuffers(1, &pContext->idFramebuffer);
3431 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3432
3433 /* Bind the object to the framebuffer target. */
3434 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
3435 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3436
3437 /* Create read and draw framebuffer objects for this context. */
3438 pState->ext.glGenFramebuffers(1, &pContext->idReadFramebuffer);
3439 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3440
3441 pState->ext.glGenFramebuffers(1, &pContext->idDrawFramebuffer);
3442 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3443
3444 }
3445#if 0
3446 /** @todo move to shader lib!!! */
3447 /* Clear the screen */
3448 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3449
3450 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
3451 glClearIndex(0);
3452 glClearDepth(1);
3453 glClearStencil(0xffff);
3454 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
3455 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
3456 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
3457 if (pState->ext.glProvokingVertex)
3458 pState->ext.glProvokingVertex(GL_FIRST_VERTEX_CONVENTION);
3459 /** @todo move to shader lib!!! */
3460#endif
3461 return VINF_SUCCESS;
3462}
3463
3464#if defined(RT_OS_LINUX)
3465/*
3466 * HW accelerated graphics output.
3467 */
3468
3469/* Send a notification to the UI. */
3470static int vmsvga3dDrvNotifyHwScreen(PVGASTATECC pThisCC, VBOX3D_NOTIFY_TYPE enmNotification,
3471 uint32_t idScreen, Pixmap pixmap, void *pvData, size_t cbData)
3472{
3473#if 0
3474 /* Emulates no support from frontend. */
3475 RT_NOREF(pThisCC, enmNotification, idScreen, pixmap, pvData, cbData);
3476 return VERR_NOT_SUPPORTED;
3477#else
3478 uint8_t au8Buffer[128];
3479 AssertLogRelMsgReturn(cbData <= sizeof(au8Buffer) - sizeof(VBOX3DNOTIFY),
3480 ("cbData %zu", cbData),
3481 VERR_INVALID_PARAMETER);
3482
3483 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3484 p->enmNotification = enmNotification;
3485 p->iDisplay = idScreen;
3486 p->u32Reserved = 0;
3487 p->cbData = cbData + sizeof(uint64_t);
3488 /* au8Data consists of a 64 bit pixmap handle followed by notification specific data. */
3489 AssertCompile(sizeof(pixmap) <= sizeof(uint64_t));
3490 *(uint64_t *)&p->au8Data[0] = (uint64_t)pixmap;
3491 memcpy(&p->au8Data[sizeof(uint64_t)], pvData, cbData);
3492
3493 int rc = pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3494 return rc;
3495#endif
3496}
3497
3498static int ctxErrorHandler(Display *dpy, XErrorEvent *ev)
3499{
3500 RT_NOREF(dpy);
3501 LogRel4(("VMSVGA: XError %d\n", (int)ev->error_code));
3502 return 0;
3503}
3504
3505/* Create a GLX pixmap as a HW accelerated screen. */
3506static int vmsvga3dHwScreenCreate(PVMSVGA3DSTATE pState, unsigned int cWidth, unsigned int cHeight, VMSVGAHWSCREEN *p)
3507{
3508 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3509
3510 int rc = VINF_SUCCESS;
3511
3512 /*
3513 * Create a new GL context, which will be used for copying to the screen pixmap.
3514 */
3515
3516 /* FBConfig attributes. */
3517 static int const aConfigAttribList[] =
3518 {
3519 // GLX_RENDER_TYPE, GLX_RGBA_BIT,
3520 // GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
3521 // GLX_X_RENDERABLE, True, // Render to GLX pixmaps
3522 GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT, // Must support GLX pixmaps
3523 GLX_BIND_TO_TEXTURE_RGBA_EXT, True, // Must support GLX_EXT_texture_from_pixmap
3524 GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_RECTANGLE_BIT_EXT, // Must support GL_TEXTURE_RECTANGLE for the frontend code
3525 GLX_DOUBLEBUFFER, False, // No need for double buffering for a pixmap.
3526 GLX_RED_SIZE, 8, // True color RGB with 8 bits per channel.
3527 GLX_GREEN_SIZE, 8,
3528 GLX_BLUE_SIZE, 8,
3529 GLX_ALPHA_SIZE, 8,
3530 GLX_STENCIL_SIZE, 0, // No stencil buffer
3531 GLX_DEPTH_SIZE, 0, // No depth buffer
3532 GLX_CONFIG_CAVEAT, GLX_NONE,
3533 None
3534 };
3535
3536 /* Find a suitable FB config. */
3537 int cConfigs = 0;
3538 GLXFBConfig *paConfigs = glXChooseFBConfig(pState->display, 0, aConfigAttribList, &cConfigs);
3539 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: paConfigs %p cConfigs %d\n", (void *)paConfigs, cConfigs));
3540 if (paConfigs)
3541 {
3542 XVisualInfo *vi = NULL;
3543 int i = 0;
3544 for (; i < cConfigs; ++i)
3545 {
3546 /* Use XFree to free the data returned in the previous iteration of this loop. */
3547 if (vi)
3548 XFree(vi);
3549
3550 vi = glXGetVisualFromFBConfig(pState->display, paConfigs[i]);
3551 if (!vi)
3552 continue;
3553
3554 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: %p vid %lu screen %d depth %d r %lu g %lu b %lu clrmap %d bitsperrgb %d\n",
3555 (void *)vi->visual, vi->visualid, vi->screen, vi->depth,
3556 vi->red_mask, vi->green_mask, vi->blue_mask, vi->colormap_size, vi->bits_per_rgb));
3557
3558 /* Search for 32 bits per pixel. */
3559 if (vi->depth != 32)
3560 continue;
3561
3562 /* 8 bits per color component is enough. */
3563 if (vi->bits_per_rgb != 8)
3564 continue;
3565
3566 /* Render to pixmap. */
3567 int value = 0;
3568 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_DRAWABLE_TYPE, &value);
3569 if (!(value & GLX_PIXMAP_BIT))
3570 continue;
3571
3572 /* Pixmap will be used as TEXTURE_RECTANGLE. */
3573 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_TARGETS_EXT, &value);
3574 if (!(value & GLX_TEXTURE_RECTANGLE_BIT_EXT))
3575 continue;
3576
3577 /* Need to bind to a texture using GLX_EXT_texture_from_pixmap. */
3578 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &value);
3579 if (value == 0)
3580 {
3581 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &value);
3582 if (value == 0)
3583 continue;
3584 }
3585
3586 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_Y_INVERTED_EXT, &value);
3587 p->fYInverted = (value == 1);
3588
3589 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_MIPMAP_TEXTURE_EXT, &value);
3590 p->fMipmap = (value > 0);
3591
3592 /* This FB config can be used. */
3593 break;
3594 }
3595
3596 if (i < cConfigs)
3597 {
3598 /* Found a suitable config with index i. */
3599 p->visualid = vi->visualid;
3600
3601 Window const rootWindow = RootWindow(pState->display, vi->screen);
3602 p->pixmap = XCreatePixmap(pState->display, rootWindow, cWidth, cHeight, vi->depth);
3603 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->pixmap %ld\n", p->pixmap));
3604
3605 static int const aPixmapAttribList[] =
3606 {
3607 GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_RECTANGLE_EXT,
3608 GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT,
3609 GLX_MIPMAP_TEXTURE_EXT, p->fMipmap,
3610 None
3611 };
3612 p->glxpixmap = glXCreatePixmap(pState->display, paConfigs[i], p->pixmap, aPixmapAttribList);
3613 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxpixmap %ld\n", p->glxpixmap));
3614
3615 p->glxctx = glXCreateContext(pState->display, vi, pState->SharedCtx.glxContext, GL_TRUE);
3616 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxctx %p\n", (void *)p->glxctx));
3617
3618 XSync(pState->display, False);
3619 }
3620 else
3621 {
3622 /* A suitable config is not found. */
3623 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: no FBConfig\n"));
3624 rc = VERR_NOT_SUPPORTED;
3625 }
3626
3627 if (vi)
3628 XFree(vi);
3629
3630 /* "Use XFree to free the memory returned by glXChooseFBConfig." */
3631 XFree(paConfigs);
3632 }
3633 else
3634 {
3635 /* glXChooseFBConfig failed. */
3636 rc = VERR_NOT_SUPPORTED;
3637 }
3638
3639 XSetErrorHandler(oldHandler);
3640 return rc;
3641}
3642
3643/* Destroy a HW accelerated screen. */
3644static void vmsvga3dHwScreenDestroy(PVMSVGA3DSTATE pState, VMSVGAHWSCREEN *p)
3645{
3646 if (p)
3647 {
3648 LogRel4(("VMSVGA: vmsvga3dHwScreenDestroy: p->glxpixmap %ld, ctx %p\n", p->glxpixmap, (void *)p->glxctx));
3649 if (p->glxctx)
3650 {
3651 /* GLX context is changed here, so other code has to set the appropriate context again. */
3652 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3653 glXMakeCurrent(pState->display, None, NULL);
3654 glXDestroyContext(pState->display, p->glxctx);
3655 }
3656
3657 if (p->glxpixmap)
3658 glXDestroyPixmap(pState->display, p->glxpixmap);
3659
3660 if (p->pixmap)
3661 XFreePixmap(pState->display, p->pixmap);
3662
3663 RT_ZERO(*p);
3664 }
3665}
3666
3667#define GLCHECK() \
3668 do { \
3669 int glErr = glGetError(); \
3670 if (glErr != GL_NO_ERROR) LogRel4(("VMSVGA: GL error 0x%x @%d\n", glErr, __LINE__)); \
3671 } while(0)
3672
3673int vmsvga3dBackDefineScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3674{
3675 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: screen %u\n", pScreen->idScreen));
3676
3677 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3678 AssertReturn(pState, VERR_NOT_SUPPORTED);
3679
3680 Assert(pScreen->pHwScreen == NULL);
3681
3682 VMSVGAHWSCREEN *p = (VMSVGAHWSCREEN *)RTMemAllocZ(sizeof(VMSVGAHWSCREEN));
3683 AssertPtrReturn(p, VERR_NO_MEMORY);
3684
3685 int rc = vmsvga3dHwScreenCreate(pState, pScreen->cWidth, pScreen->cHeight, p);
3686 if (RT_SUCCESS(rc))
3687 {
3688 /*
3689 * Setup the OpenGL context of the screen.
3690 */
3691
3692 /* GLX context is changed here, so other code has to set the appropriate context again. */
3693 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3694
3695 Bool const fSuccess = glXMakeCurrent(pState->display, p->glxpixmap, p->glxctx);
3696 if (fSuccess)
3697 {
3698 /* Work in screen coordinates. */
3699 glMatrixMode(GL_MODELVIEW);
3700 glLoadIdentity();
3701 glOrtho(0, pScreen->cWidth, 0, pScreen->cHeight, -1, 1);
3702 glMatrixMode(GL_PROJECTION);
3703 glLoadIdentity();
3704
3705 /* Set GL state. */
3706 glClearColor(0, 0, 0, 1);
3707 glEnable(GL_TEXTURE_2D);
3708 glDisable(GL_DEPTH_TEST);
3709 glDisable(GL_CULL_FACE);
3710
3711 /* Clear the pixmap. */
3712 glClear(GL_COLOR_BUFFER_BIT);
3713 glFinish();
3714
3715 glXMakeCurrent(pState->display, None, NULL);
3716
3717 rc = vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_CREATED,
3718 pScreen->idScreen, p->pixmap, &p->visualid, sizeof(p->visualid));
3719 }
3720 else
3721 {
3722 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: failed to set current context\n"));
3723 rc = VERR_NOT_SUPPORTED;
3724 }
3725 }
3726
3727 if (RT_SUCCESS(rc))
3728 {
3729 pScreen->pHwScreen = p;
3730 }
3731 else
3732 {
3733 vmsvga3dHwScreenDestroy(pState, p);
3734 RTMemFree(p);
3735 }
3736
3737 return rc;
3738}
3739
3740int vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3741{
3742 LogRel4(("VMSVGA: vmsvga3dBackDestroyScreen: screen %u\n", pScreen->idScreen));
3743
3744 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3745 AssertReturn(pState, VERR_NOT_SUPPORTED);
3746
3747 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3748
3749 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3750 if (p)
3751 {
3752 pScreen->pHwScreen = NULL;
3753
3754 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_DESTROYED,
3755 pScreen->idScreen, p->pixmap, NULL, 0);
3756
3757 vmsvga3dHwScreenDestroy(pState, p);
3758 RTMemFree(p);
3759 }
3760
3761 XSetErrorHandler(oldHandler);
3762
3763 return VINF_SUCCESS;
3764}
3765
3766/* Blit a surface to the GLX pixmap. */
3767int vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3768 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3769 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3770{
3771 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3772 AssertReturn(pState, VERR_NOT_SUPPORTED);
3773
3774 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3775 AssertReturn(p, VERR_NOT_SUPPORTED);
3776
3777 PVMSVGA3DSURFACE pSurface;
3778 int rc = vmsvga3dSurfaceFromSid(pState, srcImage.sid, &pSurface);
3779 AssertRCReturn(rc, rc);
3780
3781 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
3782 {
3783 LogFunc(("src sid=%u flags=0x%x format=%d -> create texture\n", srcImage.sid, pSurface->surfaceFlags, pSurface->format));
3784 rc = vmsvga3dBackCreateTexture(pState, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID, pSurface);
3785 AssertRCReturn(rc, rc);
3786 }
3787
3788 AssertReturn(pSurface->enmOGLResType == VMSVGA3D_OGLRESTYPE_TEXTURE, VERR_NOT_SUPPORTED);
3789
3790 PVMSVGA3DMIPMAPLEVEL pMipLevel;
3791 rc = vmsvga3dMipmapLevel(pSurface, srcImage.face, srcImage.mipmap, &pMipLevel);
3792 AssertRCReturn(rc, rc);
3793
3794 /** @todo Implement. */
3795 RT_NOREF(destRect, cRects, paRects);
3796
3797 /* GLX context is changed here, so other code has to set appropriate context again. */
3798 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3799
3800 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3801
3802 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_UPDATE_BEGIN, pScreen->idScreen, p->pixmap, NULL, 0);
3803
3804 GLint const w = pScreen->cWidth;
3805 GLint const h = pScreen->cHeight;
3806
3807 GLfloat const wSurf = (GLfloat)pMipLevel->mipmapSize.width;
3808 GLfloat const hSurf = (GLfloat)pMipLevel->mipmapSize.height;
3809 GLfloat const x1 = (GLfloat)srcRect.left / wSurf;
3810 GLfloat const y1 = (GLfloat)srcRect.top / hSurf;
3811 GLfloat const x2 = (GLfloat)srcRect.right / wSurf;
3812 GLfloat const y2 = (GLfloat)srcRect.bottom / hSurf;
3813
3814 //printf("blit to screen src %fx%f %u,%u %u,%u (%f,%f %f,%f) dest %dx%d %u,%u %u,%u\n",
3815 // wSurf, hSurf, srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, x1, y1, x2, y2,
3816 // w, h, destRect.left, destRect.top, destRect.right, destRect.bottom);
3817
3818 Bool fSuccess = glXMakeCurrent(pState->display, p->glxpixmap, p->glxctx);
3819 if (fSuccess)
3820 {
3821 glClear(GL_COLOR_BUFFER_BIT);
3822
3823 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture); GLCHECK();
3824
3825 glBegin(GL_QUADS);
3826 /** @todo Y inversion. */
3827 glTexCoord2f(x1, y1); glVertex2i(0, h);
3828 glTexCoord2f(x1, y2); glVertex2i(0, 0);
3829 glTexCoord2f(x2, y2); glVertex2i(w, 0);
3830 glTexCoord2f(x2, y1); glVertex2i(w, h);
3831 glEnd(); GLCHECK();
3832
3833 glBindTexture(GL_TEXTURE_2D, 0); GLCHECK();
3834
3835 glFinish(); GLCHECK();
3836
3837 glXMakeCurrent(pState->display, None, NULL);
3838
3839 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_UPDATE_END,
3840 pScreen->idScreen, p->pixmap, &destRect, sizeof(destRect));
3841 }
3842
3843 XSetErrorHandler(oldHandler);
3844
3845 return VINF_SUCCESS;
3846}
3847
3848#else /* !RT_OS_LINUX */
3849
3850int vmsvga3dBackDefineScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3851{
3852 RT_NOREF(pThisCC, pScreen);
3853 return VERR_NOT_IMPLEMENTED;
3854}
3855
3856int vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3857{
3858 RT_NOREF(pThisCC, pScreen);
3859 return VERR_NOT_IMPLEMENTED;
3860}
3861
3862int vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3863 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3864 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3865{
3866 RT_NOREF(pThisCC, pScreen, destRect, srcImage, srcRect, cRects, paRects);
3867 return VERR_NOT_IMPLEMENTED;
3868}
3869#endif
3870
3871/**
3872 * Create a new 3d context
3873 *
3874 * @returns VBox status code.
3875 * @param pThisCC The VGA/VMSVGA state for ring-3.
3876 * @param cid Context id
3877 */
3878int vmsvga3dContextDefine(PVGASTATECC pThisCC, uint32_t cid)
3879{
3880 return vmsvga3dContextDefineOgl(pThisCC, cid, 0/*fFlags*/);
3881}
3882
3883/**
3884 * Destroys a 3d context.
3885 *
3886 * @returns VBox status code.
3887 * @param pThisCC The VGA/VMSVGA state for ring-3.
3888 * @param pContext The context to destroy.
3889 * @param cid Context id
3890 */
3891static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid)
3892{
3893 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3894 AssertReturn(pState, VERR_NO_MEMORY);
3895 AssertReturn(pContext, VERR_INVALID_PARAMETER);
3896 AssertReturn(pContext->id == cid, VERR_INVALID_PARAMETER);
3897 Log(("vmsvga3dContextDestroyOgl id %x\n", cid));
3898
3899 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3900
3901 if (pContext->id == VMSVGA3D_SHARED_CTX_ID)
3902 {
3903 /* Delete resources which use the shared context. */
3904 vmsvga3dOnSharedContextDestroy(pState);
3905 }
3906
3907 /* Destroy all leftover pixel shaders. */
3908 for (uint32_t i = 0; i < pContext->cPixelShaders; i++)
3909 {
3910 if (pContext->paPixelShader[i].id != SVGA3D_INVALID_ID)
3911 vmsvga3dShaderDestroy(pThisCC, pContext->paPixelShader[i].cid, pContext->paPixelShader[i].id, pContext->paPixelShader[i].type);
3912 }
3913 if (pContext->paPixelShader)
3914 RTMemFree(pContext->paPixelShader);
3915
3916 /* Destroy all leftover vertex shaders. */
3917 for (uint32_t i = 0; i < pContext->cVertexShaders; i++)
3918 {
3919 if (pContext->paVertexShader[i].id != SVGA3D_INVALID_ID)
3920 vmsvga3dShaderDestroy(pThisCC, pContext->paVertexShader[i].cid, pContext->paVertexShader[i].id, pContext->paVertexShader[i].type);
3921 }
3922 if (pContext->paVertexShader)
3923 RTMemFree(pContext->paVertexShader);
3924
3925 if (pContext->state.paVertexShaderConst)
3926 RTMemFree(pContext->state.paVertexShaderConst);
3927 if (pContext->state.paPixelShaderConst)
3928 RTMemFree(pContext->state.paPixelShaderConst);
3929
3930 if (pContext->pShaderContext)
3931 {
3932 int rc = ShaderContextDestroy(pContext->pShaderContext);
3933 AssertRC(rc);
3934 }
3935
3936 if (pContext->idFramebuffer != OPENGL_INVALID_ID)
3937 {
3938 /* Unbind the object from the framebuffer target. */
3939 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0 /* back buffer */);
3940 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3941 pState->ext.glDeleteFramebuffers(1, &pContext->idFramebuffer);
3942 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3943
3944 if (pContext->idReadFramebuffer != OPENGL_INVALID_ID)
3945 {
3946 pState->ext.glDeleteFramebuffers(1, &pContext->idReadFramebuffer);
3947 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3948 }
3949 if (pContext->idDrawFramebuffer != OPENGL_INVALID_ID)
3950 {
3951 pState->ext.glDeleteFramebuffers(1, &pContext->idDrawFramebuffer);
3952 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3953 }
3954 }
3955
3956 vmsvga3dOcclusionQueryDelete(pState, pContext);
3957
3958#ifdef RT_OS_WINDOWS
3959 wglMakeCurrent(pContext->hdc, NULL);
3960 wglDeleteContext(pContext->hglrc);
3961 ReleaseDC(pContext->hwnd, pContext->hdc);
3962
3963 /* Destroy the window we've created. */
3964 int rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_DESTROYWINDOW, (WPARAM)pContext->hwnd, 0);
3965 AssertRC(rc);
3966#elif defined(RT_OS_DARWIN)
3967 vmsvga3dCocoaDestroyViewAndContext(pContext->cocoaView, pContext->cocoaContext);
3968#elif defined(RT_OS_LINUX)
3969 glXMakeCurrent(pState->display, None, NULL);
3970 glXDestroyContext(pState->display, pContext->glxContext);
3971 XDestroyWindow(pState->display, pContext->window);
3972#endif
3973
3974 memset(pContext, 0, sizeof(*pContext));
3975 pContext->id = SVGA3D_INVALID_ID;
3976
3977 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3978 return VINF_SUCCESS;
3979}
3980
3981/**
3982 * Destroy an existing 3d context
3983 *
3984 * @returns VBox status code.
3985 * @param pThisCC The VGA/VMSVGA state for ring-3.
3986 * @param cid Context id
3987 */
3988int vmsvga3dContextDestroy(PVGASTATECC pThisCC, uint32_t cid)
3989{
3990 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3991 AssertReturn(pState, VERR_WRONG_ORDER);
3992
3993 /*
3994 * Resolve the context and hand it to the common worker function.
3995 */
3996 if ( cid < pState->cContexts
3997 && pState->papContexts[cid]->id == cid)
3998 return vmsvga3dContextDestroyOgl(pThisCC, pState->papContexts[cid], cid);
3999
4000 AssertReturn(cid < SVGA3D_MAX_CONTEXT_IDS, VERR_INVALID_PARAMETER);
4001 return VINF_SUCCESS;
4002}
4003
4004/**
4005 * Worker for vmsvga3dChangeMode that resizes a context.
4006 *
4007 * @param pState The VMSVGA3d state.
4008 * @param pContext The context.
4009 */
4010static void vmsvga3dChangeModeOneContext(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
4011{
4012 RT_NOREF(pState, pContext);
4013 /* Do nothing. The window is not used for presenting. */
4014}
4015
4016/* Handle resize */
4017int vmsvga3dChangeMode(PVGASTATECC pThisCC)
4018{
4019 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4020 AssertReturn(pState, VERR_NO_MEMORY);
4021
4022 /* Resize the shared context too. */
4023 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
4024 vmsvga3dChangeModeOneContext(pState, &pState->SharedCtx);
4025
4026 /* Resize all active contexts. */
4027 for (uint32_t i = 0; i < pState->cContexts; i++)
4028 {
4029 PVMSVGA3DCONTEXT pContext = pState->papContexts[i];
4030 if (pContext->id != SVGA3D_INVALID_ID)
4031 vmsvga3dChangeModeOneContext(pState, pContext);
4032 }
4033
4034 return VINF_SUCCESS;
4035}
4036
4037
4038int vmsvga3dSetTransform(PVGASTATECC pThisCC, uint32_t cid, SVGA3dTransformType type, float matrix[16])
4039{
4040 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4041 AssertReturn(pState, VERR_NO_MEMORY);
4042 bool fModelViewChanged = false;
4043
4044 Log(("vmsvga3dSetTransform cid=%u %s\n", cid, vmsvgaTransformToString(type)));
4045
4046 ASSERT_GUEST_RETURN((unsigned)type < SVGA3D_TRANSFORM_MAX, VERR_INVALID_PARAMETER);
4047
4048 PVMSVGA3DCONTEXT pContext;
4049 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4050 AssertRCReturn(rc, rc);
4051
4052 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4053
4054 /* Save this matrix for vm state save/restore. */
4055 pContext->state.aTransformState[type].fValid = true;
4056 memcpy(pContext->state.aTransformState[type].matrix, matrix, sizeof(pContext->state.aTransformState[type].matrix));
4057 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_TRANSFORM;
4058
4059 Log(("Matrix [%d %d %d %d]\n", (int)(matrix[0] * 10.0), (int)(matrix[1] * 10.0), (int)(matrix[2] * 10.0), (int)(matrix[3] * 10.0)));
4060 Log((" [%d %d %d %d]\n", (int)(matrix[4] * 10.0), (int)(matrix[5] * 10.0), (int)(matrix[6] * 10.0), (int)(matrix[7] * 10.0)));
4061 Log((" [%d %d %d %d]\n", (int)(matrix[8] * 10.0), (int)(matrix[9] * 10.0), (int)(matrix[10] * 10.0), (int)(matrix[11] * 10.0)));
4062 Log((" [%d %d %d %d]\n", (int)(matrix[12] * 10.0), (int)(matrix[13] * 10.0), (int)(matrix[14] * 10.0), (int)(matrix[15] * 10.0)));
4063
4064 switch (type)
4065 {
4066 case SVGA3D_TRANSFORM_VIEW:
4067 /* View * World = Model View */
4068 glMatrixMode(GL_MODELVIEW);
4069 glLoadMatrixf(matrix);
4070 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].fValid)
4071 glMultMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].matrix);
4072 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4073 fModelViewChanged = true;
4074 break;
4075
4076 case SVGA3D_TRANSFORM_PROJECTION:
4077 {
4078 rc = ShaderTransformProjection(pContext->state.RectViewPort.w, pContext->state.RectViewPort.h, matrix, false /* fPretransformed */);
4079 AssertRCReturn(rc, rc);
4080 break;
4081 }
4082
4083 case SVGA3D_TRANSFORM_TEXTURE0:
4084 glMatrixMode(GL_TEXTURE);
4085 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4086 glLoadMatrixf(matrix);
4087 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4088 break;
4089
4090 case SVGA3D_TRANSFORM_TEXTURE1:
4091 case SVGA3D_TRANSFORM_TEXTURE2:
4092 case SVGA3D_TRANSFORM_TEXTURE3:
4093 case SVGA3D_TRANSFORM_TEXTURE4:
4094 case SVGA3D_TRANSFORM_TEXTURE5:
4095 case SVGA3D_TRANSFORM_TEXTURE6:
4096 case SVGA3D_TRANSFORM_TEXTURE7:
4097 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_TEXTUREx transform!!\n"));
4098 return VERR_INVALID_PARAMETER;
4099
4100 case SVGA3D_TRANSFORM_WORLD:
4101 /* View * World = Model View */
4102 glMatrixMode(GL_MODELVIEW);
4103 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid)
4104 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
4105 else
4106 glLoadIdentity();
4107 glMultMatrixf(matrix);
4108 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4109 fModelViewChanged = true;
4110 break;
4111
4112 case SVGA3D_TRANSFORM_WORLD1:
4113 case SVGA3D_TRANSFORM_WORLD2:
4114 case SVGA3D_TRANSFORM_WORLD3:
4115 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_WORLDx transform!!\n"));
4116 return VERR_INVALID_PARAMETER;
4117
4118 default:
4119 Log(("vmsvga3dSetTransform: unknown type!!\n"));
4120 return VERR_INVALID_PARAMETER;
4121 }
4122
4123 /* Apparently we need to reset the light and clip data after modifying the modelview matrix. */
4124 if (fModelViewChanged)
4125 {
4126 /* Reprogram the clip planes. */
4127 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aClipPlane); j++)
4128 {
4129 if (pContext->state.aClipPlane[j].fValid == true)
4130 vmsvga3dSetClipPlane(pThisCC, cid, j, pContext->state.aClipPlane[j].plane);
4131 }
4132
4133 /* Reprogram the light data. */
4134 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aLightData); j++)
4135 {
4136 if (pContext->state.aLightData[j].fValidData == true)
4137 vmsvga3dSetLightData(pThisCC, cid, j, &pContext->state.aLightData[j].data);
4138 }
4139 }
4140
4141 return VINF_SUCCESS;
4142}
4143
4144int vmsvga3dSetZRange(PVGASTATECC pThisCC, uint32_t cid, SVGA3dZRange zRange)
4145{
4146 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4147 AssertReturn(pState, VERR_NO_MEMORY);
4148
4149 Log(("vmsvga3dSetZRange cid=%u min=%d max=%d\n", cid, (uint32_t)(zRange.min * 100.0), (uint32_t)(zRange.max * 100.0)));
4150
4151 PVMSVGA3DCONTEXT pContext;
4152 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4153 AssertRCReturn(rc, rc);
4154
4155 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4156
4157 pContext->state.zRange = zRange;
4158 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_ZRANGE;
4159
4160 if (zRange.min < -1.0)
4161 zRange.min = -1.0;
4162 if (zRange.max > 1.0)
4163 zRange.max = 1.0;
4164
4165 glDepthRange((GLdouble)zRange.min, (GLdouble)zRange.max);
4166 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4167 return VINF_SUCCESS;
4168}
4169
4170/**
4171 * Convert SVGA blend op value to its OpenGL equivalent
4172 */
4173static GLenum vmsvga3dBlendOp2GL(uint32_t blendOp)
4174{
4175 switch (blendOp)
4176 {
4177 case SVGA3D_BLENDOP_ZERO:
4178 return GL_ZERO;
4179 case SVGA3D_BLENDOP_ONE:
4180 return GL_ONE;
4181 case SVGA3D_BLENDOP_SRCCOLOR:
4182 return GL_SRC_COLOR;
4183 case SVGA3D_BLENDOP_INVSRCCOLOR:
4184 return GL_ONE_MINUS_SRC_COLOR;
4185 case SVGA3D_BLENDOP_SRCALPHA:
4186 return GL_SRC_ALPHA;
4187 case SVGA3D_BLENDOP_INVSRCALPHA:
4188 return GL_ONE_MINUS_SRC_ALPHA;
4189 case SVGA3D_BLENDOP_DESTALPHA:
4190 return GL_DST_ALPHA;
4191 case SVGA3D_BLENDOP_INVDESTALPHA:
4192 return GL_ONE_MINUS_DST_ALPHA;
4193 case SVGA3D_BLENDOP_DESTCOLOR:
4194 return GL_DST_COLOR;
4195 case SVGA3D_BLENDOP_INVDESTCOLOR:
4196 return GL_ONE_MINUS_DST_COLOR;
4197 case SVGA3D_BLENDOP_SRCALPHASAT:
4198 return GL_SRC_ALPHA_SATURATE;
4199 case SVGA3D_BLENDOP_BLENDFACTOR:
4200 return GL_CONSTANT_COLOR;
4201 case SVGA3D_BLENDOP_INVBLENDFACTOR:
4202 return GL_ONE_MINUS_CONSTANT_COLOR;
4203 default:
4204 AssertFailed();
4205 return GL_ONE;
4206 }
4207}
4208
4209static GLenum vmsvga3dBlendEquation2GL(uint32_t blendEq)
4210{
4211 switch (blendEq)
4212 {
4213 case SVGA3D_BLENDEQ_ADD:
4214 return GL_FUNC_ADD;
4215 case SVGA3D_BLENDEQ_SUBTRACT:
4216 return GL_FUNC_SUBTRACT;
4217 case SVGA3D_BLENDEQ_REVSUBTRACT:
4218 return GL_FUNC_REVERSE_SUBTRACT;
4219 case SVGA3D_BLENDEQ_MINIMUM:
4220 return GL_MIN;
4221 case SVGA3D_BLENDEQ_MAXIMUM:
4222 return GL_MAX;
4223 default:
4224 /* SVGA3D_BLENDEQ_INVALID means that the render state has not been set, therefore use default. */
4225 AssertMsg(blendEq == SVGA3D_BLENDEQ_INVALID, ("blendEq=%d (%#x)\n", blendEq, blendEq));
4226 return GL_FUNC_ADD;
4227 }
4228}
4229
4230static GLenum vmsvgaCmpFunc2GL(uint32_t cmpFunc)
4231{
4232 switch (cmpFunc)
4233 {
4234 case SVGA3D_CMP_NEVER:
4235 return GL_NEVER;
4236 case SVGA3D_CMP_LESS:
4237 return GL_LESS;
4238 case SVGA3D_CMP_EQUAL:
4239 return GL_EQUAL;
4240 case SVGA3D_CMP_LESSEQUAL:
4241 return GL_LEQUAL;
4242 case SVGA3D_CMP_GREATER:
4243 return GL_GREATER;
4244 case SVGA3D_CMP_NOTEQUAL:
4245 return GL_NOTEQUAL;
4246 case SVGA3D_CMP_GREATEREQUAL:
4247 return GL_GEQUAL;
4248 case SVGA3D_CMP_ALWAYS:
4249 return GL_ALWAYS;
4250 default:
4251 Assert(cmpFunc == SVGA3D_CMP_INVALID);
4252 return GL_LESS;
4253 }
4254}
4255
4256static GLenum vmsvgaStencipOp2GL(uint32_t stencilOp)
4257{
4258 switch (stencilOp)
4259 {
4260 case SVGA3D_STENCILOP_KEEP:
4261 return GL_KEEP;
4262 case SVGA3D_STENCILOP_ZERO:
4263 return GL_ZERO;
4264 case SVGA3D_STENCILOP_REPLACE:
4265 return GL_REPLACE;
4266 case SVGA3D_STENCILOP_INCRSAT:
4267 return GL_INCR_WRAP;
4268 case SVGA3D_STENCILOP_DECRSAT:
4269 return GL_DECR_WRAP;
4270 case SVGA3D_STENCILOP_INVERT:
4271 return GL_INVERT;
4272 case SVGA3D_STENCILOP_INCR:
4273 return GL_INCR;
4274 case SVGA3D_STENCILOP_DECR:
4275 return GL_DECR;
4276 default:
4277 Assert(stencilOp == SVGA3D_STENCILOP_INVALID);
4278 return GL_KEEP;
4279 }
4280}
4281
4282int vmsvga3dSetRenderState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cRenderStates, SVGA3dRenderState *pRenderState)
4283{
4284 uint32_t val = UINT32_MAX; /* Shut up MSC. */
4285 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4286 AssertReturn(pState, VERR_NO_MEMORY);
4287
4288 Log(("vmsvga3dSetRenderState cid=%u cRenderStates=%d\n", cid, cRenderStates));
4289
4290 PVMSVGA3DCONTEXT pContext;
4291 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4292 AssertRCReturn(rc, rc);
4293
4294 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4295
4296 for (unsigned i = 0; i < cRenderStates; i++)
4297 {
4298 GLenum enableCap = ~(GLenum)0;
4299 Log(("vmsvga3dSetRenderState: cid=%u state=%s (%d) val=%x\n", cid, vmsvga3dGetRenderStateName(pRenderState[i].state), pRenderState[i].state, pRenderState[i].uintValue));
4300 /* Save the render state for vm state saving. */
4301 ASSERT_GUEST_RETURN((unsigned)pRenderState[i].state < SVGA3D_RS_MAX, VERR_INVALID_PARAMETER);
4302 pContext->state.aRenderState[pRenderState[i].state] = pRenderState[i];
4303
4304 switch (pRenderState[i].state)
4305 {
4306 case SVGA3D_RS_ZENABLE: /* SVGA3dBool */
4307 enableCap = GL_DEPTH_TEST;
4308 val = pRenderState[i].uintValue;
4309 break;
4310
4311 case SVGA3D_RS_ZWRITEENABLE: /* SVGA3dBool */
4312 glDepthMask(!!pRenderState[i].uintValue);
4313 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4314 break;
4315
4316 case SVGA3D_RS_ALPHATESTENABLE: /* SVGA3dBool */
4317 enableCap = GL_ALPHA_TEST;
4318 val = pRenderState[i].uintValue;
4319 break;
4320
4321 case SVGA3D_RS_DITHERENABLE: /* SVGA3dBool */
4322 enableCap = GL_DITHER;
4323 val = pRenderState[i].uintValue;
4324 break;
4325
4326 case SVGA3D_RS_FOGENABLE: /* SVGA3dBool */
4327 enableCap = GL_FOG;
4328 val = pRenderState[i].uintValue;
4329 break;
4330
4331 case SVGA3D_RS_SPECULARENABLE: /* SVGA3dBool */
4332 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4333 break;
4334
4335 case SVGA3D_RS_LIGHTINGENABLE: /* SVGA3dBool */
4336 enableCap = GL_LIGHTING;
4337 val = pRenderState[i].uintValue;
4338 break;
4339
4340 case SVGA3D_RS_NORMALIZENORMALS: /* SVGA3dBool */
4341 /* not applicable */
4342 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4343 break;
4344
4345 case SVGA3D_RS_POINTSPRITEENABLE: /* SVGA3dBool */
4346 enableCap = GL_POINT_SPRITE_ARB;
4347 val = pRenderState[i].uintValue;
4348 break;
4349
4350 case SVGA3D_RS_POINTSIZE: /* float */
4351 /** @todo we need to apply scaling for point sizes below the min or above the max; see Wine) */
4352 if (pRenderState[i].floatValue < pState->caps.flPointSize[0])
4353 pRenderState[i].floatValue = pState->caps.flPointSize[0];
4354 if (pRenderState[i].floatValue > pState->caps.flPointSize[1])
4355 pRenderState[i].floatValue = pState->caps.flPointSize[1];
4356
4357 glPointSize(pRenderState[i].floatValue);
4358 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4359 Log(("SVGA3D_RS_POINTSIZE: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4360 break;
4361
4362 case SVGA3D_RS_POINTSIZEMIN: /* float */
4363 pState->ext.glPointParameterf(GL_POINT_SIZE_MIN, pRenderState[i].floatValue);
4364 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4365 Log(("SVGA3D_RS_POINTSIZEMIN: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4366 break;
4367
4368 case SVGA3D_RS_POINTSIZEMAX: /* float */
4369 pState->ext.glPointParameterf(GL_POINT_SIZE_MAX, pRenderState[i].floatValue);
4370 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4371 Log(("SVGA3D_RS_POINTSIZEMAX: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4372 break;
4373
4374 case SVGA3D_RS_POINTSCALEENABLE: /* SVGA3dBool */
4375 case SVGA3D_RS_POINTSCALE_A: /* float */
4376 case SVGA3D_RS_POINTSCALE_B: /* float */
4377 case SVGA3D_RS_POINTSCALE_C: /* float */
4378 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4379 break;
4380
4381 case SVGA3D_RS_AMBIENT: /* SVGA3dColor */
4382 {
4383 GLfloat color[4]; /* red, green, blue, alpha */
4384
4385 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4386
4387 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, color);
4388 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4389 break;
4390 }
4391
4392 case SVGA3D_RS_CLIPPLANEENABLE: /* SVGA3dClipPlanes */
4393 {
4394 AssertCompile(SVGA3D_CLIPPLANE_MAX == (1 << 5));
4395 for (uint32_t j = 0; j <= 5; j++)
4396 {
4397 if (pRenderState[i].uintValue & RT_BIT(j))
4398 glEnable(GL_CLIP_PLANE0 + j);
4399 else
4400 glDisable(GL_CLIP_PLANE0 + j);
4401 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4402 }
4403 break;
4404 }
4405
4406 case SVGA3D_RS_FOGCOLOR: /* SVGA3dColor */
4407 {
4408 GLfloat color[4]; /* red, green, blue, alpha */
4409
4410 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4411
4412 glFogfv(GL_FOG_COLOR, color);
4413 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4414 break;
4415 }
4416
4417 case SVGA3D_RS_FOGSTART: /* float */
4418 glFogf(GL_FOG_START, pRenderState[i].floatValue);
4419 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4420 break;
4421
4422 case SVGA3D_RS_FOGEND: /* float */
4423 glFogf(GL_FOG_END, pRenderState[i].floatValue);
4424 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4425 break;
4426
4427 case SVGA3D_RS_FOGDENSITY: /* float */
4428 glFogf(GL_FOG_DENSITY, pRenderState[i].floatValue);
4429 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4430 break;
4431
4432 case SVGA3D_RS_RANGEFOGENABLE: /* SVGA3dBool */
4433 glFogi(GL_FOG_COORD_SRC, (pRenderState[i].uintValue) ? GL_FOG_COORD : GL_FRAGMENT_DEPTH);
4434 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4435 break;
4436
4437 case SVGA3D_RS_FOGMODE: /* SVGA3dFogMode */
4438 {
4439 SVGA3dFogMode mode;
4440 mode.uintValue = pRenderState[i].uintValue;
4441
4442 enableCap = GL_FOG_MODE;
4443 switch (mode.s.function)
4444 {
4445 case SVGA3D_FOGFUNC_EXP:
4446 val = GL_EXP;
4447 break;
4448 case SVGA3D_FOGFUNC_EXP2:
4449 val = GL_EXP2;
4450 break;
4451 case SVGA3D_FOGFUNC_LINEAR:
4452 val = GL_LINEAR;
4453 break;
4454 default:
4455 AssertMsgFailedReturn(("Unexpected fog function %d\n", mode.s.function), VERR_INTERNAL_ERROR);
4456 break;
4457 }
4458
4459 /** @todo how to switch between vertex and pixel fog modes??? */
4460 Assert(mode.s.type == SVGA3D_FOGTYPE_PIXEL);
4461#if 0
4462 /* The fog type determines the render state. */
4463 switch (mode.s.type)
4464 {
4465 case SVGA3D_FOGTYPE_VERTEX:
4466 renderState = D3DRS_FOGVERTEXMODE;
4467 break;
4468 case SVGA3D_FOGTYPE_PIXEL:
4469 renderState = D3DRS_FOGTABLEMODE;
4470 break;
4471 default:
4472 AssertMsgFailedReturn(("Unexpected fog type %d\n", mode.s.type), VERR_INTERNAL_ERROR);
4473 break;
4474 }
4475#endif
4476
4477 /* Set the fog base to depth or range. */
4478 switch (mode.s.base)
4479 {
4480 case SVGA3D_FOGBASE_DEPTHBASED:
4481 glFogi(GL_FOG_COORD_SRC, GL_FRAGMENT_DEPTH);
4482 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4483 break;
4484 case SVGA3D_FOGBASE_RANGEBASED:
4485 glFogi(GL_FOG_COORD_SRC, GL_FOG_COORD);
4486 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4487 break;
4488 default:
4489 /* ignore */
4490 AssertMsgFailed(("Unexpected fog base %d\n", mode.s.base));
4491 break;
4492 }
4493 break;
4494 }
4495
4496 case SVGA3D_RS_FILLMODE: /* SVGA3dFillMode */
4497 {
4498 SVGA3dFillMode mode;
4499
4500 mode.uintValue = pRenderState[i].uintValue;
4501
4502 switch (mode.s.mode)
4503 {
4504 case SVGA3D_FILLMODE_POINT:
4505 val = GL_POINT;
4506 break;
4507 case SVGA3D_FILLMODE_LINE:
4508 val = GL_LINE;
4509 break;
4510 case SVGA3D_FILLMODE_FILL:
4511 val = GL_FILL;
4512 break;
4513 default:
4514 AssertMsgFailedReturn(("Unexpected fill mode %d\n", mode.s.mode), VERR_INTERNAL_ERROR);
4515 break;
4516 }
4517 /* @note only front and back faces */
4518 Assert(mode.s.face == SVGA3D_FACE_FRONT_BACK);
4519 glPolygonMode(GL_FRONT_AND_BACK, val);
4520 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4521 break;
4522 }
4523
4524 case SVGA3D_RS_SHADEMODE: /* SVGA3dShadeMode */
4525 switch (pRenderState[i].uintValue)
4526 {
4527 case SVGA3D_SHADEMODE_FLAT:
4528 val = GL_FLAT;
4529 break;
4530
4531 case SVGA3D_SHADEMODE_SMOOTH:
4532 val = GL_SMOOTH;
4533 break;
4534
4535 default:
4536 AssertMsgFailedReturn(("Unexpected shade mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4537 break;
4538 }
4539
4540 glShadeModel(val);
4541 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4542 break;
4543
4544 case SVGA3D_RS_LINEPATTERN: /* SVGA3dLinePattern */
4545 /* No longer supported by d3d; mesagl comments suggest not all backends support it */
4546 /** @todo */
4547 Log(("WARNING: SVGA3D_RS_LINEPATTERN %x not supported!!\n", pRenderState[i].uintValue));
4548 /*
4549 renderState = D3DRS_LINEPATTERN;
4550 val = pRenderState[i].uintValue;
4551 */
4552 break;
4553
4554 case SVGA3D_RS_LINEAA: /* SVGA3dBool */
4555 enableCap = GL_LINE_SMOOTH;
4556 val = pRenderState[i].uintValue;
4557 break;
4558
4559 case SVGA3D_RS_LINEWIDTH: /* float */
4560 glLineWidth(pRenderState[i].floatValue);
4561 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4562 break;
4563
4564 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
4565 {
4566 /* Refresh the blending state based on the new enable setting.
4567 * This will take existing states and set them using either glBlend* or glBlend*Separate.
4568 */
4569 static SVGA3dRenderStateName const saRefreshState[] =
4570 {
4571 SVGA3D_RS_SRCBLEND,
4572 SVGA3D_RS_BLENDEQUATION
4573 };
4574 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4575 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4576 {
4577 renderstate[j].state = saRefreshState[j];
4578 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4579 }
4580
4581 rc = vmsvga3dSetRenderState(pThisCC, cid, 2, renderstate);
4582 AssertRCReturn(rc, rc);
4583
4584 if (pContext->state.aRenderState[SVGA3D_RS_BLENDENABLE].uintValue != 0)
4585 continue; /* Ignore if blend is enabled */
4586 /* Apply SVGA3D_RS_SEPARATEALPHABLENDENABLE as SVGA3D_RS_BLENDENABLE */
4587 } RT_FALL_THRU();
4588
4589 case SVGA3D_RS_BLENDENABLE: /* SVGA3dBool */
4590 enableCap = GL_BLEND;
4591 val = pRenderState[i].uintValue;
4592 break;
4593
4594 case SVGA3D_RS_SRCBLENDALPHA: /* SVGA3dBlendOp */
4595 case SVGA3D_RS_DSTBLENDALPHA: /* SVGA3dBlendOp */
4596 case SVGA3D_RS_SRCBLEND: /* SVGA3dBlendOp */
4597 case SVGA3D_RS_DSTBLEND: /* SVGA3dBlendOp */
4598 {
4599 GLint srcRGB, srcAlpha, dstRGB, dstAlpha;
4600 GLint blendop = vmsvga3dBlendOp2GL(pRenderState[i].uintValue);
4601
4602 glGetIntegerv(GL_BLEND_SRC_RGB, &srcRGB);
4603 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4604 glGetIntegerv(GL_BLEND_DST_RGB, &dstRGB);
4605 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4606 glGetIntegerv(GL_BLEND_DST_ALPHA, &dstAlpha);
4607 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4608 glGetIntegerv(GL_BLEND_SRC_ALPHA, &srcAlpha);
4609 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4610
4611 switch (pRenderState[i].state)
4612 {
4613 case SVGA3D_RS_SRCBLEND:
4614 srcRGB = blendop;
4615 break;
4616 case SVGA3D_RS_DSTBLEND:
4617 dstRGB = blendop;
4618 break;
4619 case SVGA3D_RS_SRCBLENDALPHA:
4620 srcAlpha = blendop;
4621 break;
4622 case SVGA3D_RS_DSTBLENDALPHA:
4623 dstAlpha = blendop;
4624 break;
4625 default:
4626 /* not possible; shut up gcc */
4627 AssertFailed();
4628 break;
4629 }
4630
4631 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4632 pState->ext.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
4633 else
4634 glBlendFunc(srcRGB, dstRGB);
4635 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4636 break;
4637 }
4638
4639 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
4640 case SVGA3D_RS_BLENDEQUATION: /* SVGA3dBlendEquation */
4641 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4642 {
4643 GLenum const modeRGB = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATION].uintValue);
4644 GLenum const modeAlpha = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATIONALPHA].uintValue);
4645 pState->ext.glBlendEquationSeparate(modeRGB, modeAlpha);
4646 }
4647 else
4648 {
4649#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4650 glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4651#else
4652 pState->ext.glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4653#endif
4654 }
4655 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4656 break;
4657
4658 case SVGA3D_RS_BLENDCOLOR: /* SVGA3dColor */
4659 {
4660 GLfloat red, green, blue, alpha;
4661
4662 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &red, &green, &blue, &alpha);
4663
4664#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4665 glBlendColor(red, green, blue, alpha);
4666#else
4667 pState->ext.glBlendColor(red, green, blue, alpha);
4668#endif
4669 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4670 break;
4671 }
4672
4673 case SVGA3D_RS_CULLMODE: /* SVGA3dFace */
4674 {
4675 GLenum mode = GL_BACK; /* default for OpenGL */
4676
4677 switch (pRenderState[i].uintValue)
4678 {
4679 case SVGA3D_FACE_NONE:
4680 break;
4681 case SVGA3D_FACE_FRONT:
4682 mode = GL_FRONT;
4683 break;
4684 case SVGA3D_FACE_BACK:
4685 mode = GL_BACK;
4686 break;
4687 case SVGA3D_FACE_FRONT_BACK:
4688 mode = GL_FRONT_AND_BACK;
4689 break;
4690 default:
4691 AssertMsgFailedReturn(("Unexpected cull mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4692 break;
4693 }
4694 enableCap = GL_CULL_FACE;
4695 if (pRenderState[i].uintValue != SVGA3D_FACE_NONE)
4696 {
4697 glCullFace(mode);
4698 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4699 val = 1;
4700 }
4701 else
4702 val = 0;
4703 break;
4704 }
4705
4706 case SVGA3D_RS_ZFUNC: /* SVGA3dCmpFunc */
4707 glDepthFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue));
4708 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4709 break;
4710
4711 case SVGA3D_RS_ALPHAFUNC: /* SVGA3dCmpFunc */
4712 {
4713 GLclampf ref;
4714
4715 glGetFloatv(GL_ALPHA_TEST_REF, &ref);
4716 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4717 glAlphaFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue), ref);
4718 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4719 break;
4720 }
4721
4722 case SVGA3D_RS_ALPHAREF: /* float (0.0 .. 1.0) */
4723 {
4724 GLint func;
4725
4726 glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
4727 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4728 glAlphaFunc(func, pRenderState[i].floatValue);
4729 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4730 break;
4731 }
4732
4733 case SVGA3D_RS_STENCILENABLE2SIDED: /* SVGA3dBool */
4734 {
4735 /* Refresh the stencil state based on the new enable setting.
4736 * This will take existing states and set them using either glStencil or glStencil*Separate.
4737 */
4738 static SVGA3dRenderStateName const saRefreshState[] =
4739 {
4740 SVGA3D_RS_STENCILFUNC,
4741 SVGA3D_RS_STENCILFAIL,
4742 SVGA3D_RS_CCWSTENCILFUNC,
4743 SVGA3D_RS_CCWSTENCILFAIL
4744 };
4745 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4746 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4747 {
4748 renderstate[j].state = saRefreshState[j];
4749 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4750 }
4751
4752 rc = vmsvga3dSetRenderState(pThisCC, cid, RT_ELEMENTS(renderstate), renderstate);
4753 AssertRCReturn(rc, rc);
4754
4755 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE].uintValue != 0)
4756 continue; /* Ignore if stencil is enabled */
4757 /* Apply SVGA3D_RS_STENCILENABLE2SIDED as SVGA3D_RS_STENCILENABLE. */
4758 } RT_FALL_THRU();
4759
4760 case SVGA3D_RS_STENCILENABLE: /* SVGA3dBool */
4761 enableCap = GL_STENCIL_TEST;
4762 val = pRenderState[i].uintValue;
4763 break;
4764
4765 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4766 case SVGA3D_RS_STENCILREF: /* uint32_t */
4767 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4768 {
4769 GLint func, ref;
4770 GLuint mask;
4771
4772 /* Query current values to have all parameters for glStencilFunc[Separate]. */
4773 glGetIntegerv(GL_STENCIL_FUNC, &func);
4774 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4775 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4776 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4777 glGetIntegerv(GL_STENCIL_REF, &ref);
4778 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4779
4780 /* Update the changed value. */
4781 switch (pRenderState[i].state)
4782 {
4783 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4784 func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4785 break;
4786
4787 case SVGA3D_RS_STENCILREF: /* uint32_t */
4788 ref = pRenderState[i].uintValue;
4789 break;
4790
4791 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4792 mask = pRenderState[i].uintValue;
4793 break;
4794
4795 default:
4796 /* not possible; shut up gcc */
4797 AssertFailed();
4798 break;
4799 }
4800
4801 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4802 {
4803 pState->ext.glStencilFuncSeparate(GL_FRONT, func, ref, mask);
4804 }
4805 else
4806 {
4807 glStencilFunc(func, ref, mask);
4808 }
4809 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4810 break;
4811 }
4812
4813 case SVGA3D_RS_STENCILWRITEMASK: /* uint32_t */
4814 glStencilMask(pRenderState[i].uintValue);
4815 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4816 break;
4817
4818 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4819 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4820 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4821 {
4822 GLint sfail, dpfail, dppass;
4823 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4824
4825 glGetIntegerv(GL_STENCIL_FAIL, &sfail);
4826 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4827 glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail);
4828 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4829 glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass);
4830 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4831
4832 switch (pRenderState[i].state)
4833 {
4834 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4835 sfail = stencilop;
4836 break;
4837 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4838 dpfail = stencilop;
4839 break;
4840 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4841 dppass = stencilop;
4842 break;
4843 default:
4844 /* not possible; shut up gcc */
4845 AssertFailed();
4846 break;
4847 }
4848 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4849 {
4850 pState->ext.glStencilOpSeparate(GL_FRONT, sfail, dpfail, dppass);
4851 }
4852 else
4853 {
4854 glStencilOp(sfail, dpfail, dppass);
4855 }
4856 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4857 break;
4858 }
4859
4860 case SVGA3D_RS_CCWSTENCILFUNC: /* SVGA3dCmpFunc */
4861 {
4862 GLint ref;
4863 GLuint mask;
4864 GLint const func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4865
4866 /* GL_STENCIL_VALUE_MASK and GL_STENCIL_REF are the same for both GL_FRONT and GL_BACK. */
4867 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4868 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4869 glGetIntegerv(GL_STENCIL_REF, &ref);
4870 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4871
4872 pState->ext.glStencilFuncSeparate(GL_BACK, func, ref, mask);
4873 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4874 break;
4875 }
4876
4877 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
4878 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
4879 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
4880 {
4881 GLint sfail, dpfail, dppass;
4882 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4883
4884 glGetIntegerv(GL_STENCIL_BACK_FAIL, &sfail);
4885 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4886 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail);
4887 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4888 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass);
4889 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4890
4891 switch (pRenderState[i].state)
4892 {
4893 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
4894 sfail = stencilop;
4895 break;
4896 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
4897 dpfail = stencilop;
4898 break;
4899 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
4900 dppass = stencilop;
4901 break;
4902 default:
4903 /* not possible; shut up gcc */
4904 AssertFailed();
4905 break;
4906 }
4907 pState->ext.glStencilOpSeparate(GL_BACK, sfail, dpfail, dppass);
4908 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4909 break;
4910 }
4911
4912 case SVGA3D_RS_ZBIAS: /* float */
4913 /** @todo unknown meaning; depth bias is not identical
4914 renderState = D3DRS_DEPTHBIAS;
4915 val = pRenderState[i].uintValue;
4916 */
4917 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_RS_ZBIAS\n"));
4918 break;
4919
4920 case SVGA3D_RS_DEPTHBIAS: /* float */
4921 {
4922 GLfloat factor;
4923
4924 /** @todo not sure if the d3d & ogl definitions are identical. */
4925
4926 /* Do not change the factor part. */
4927 glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor);
4928 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4929
4930 glPolygonOffset(factor, pRenderState[i].floatValue);
4931 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4932 break;
4933 }
4934
4935 case SVGA3D_RS_SLOPESCALEDEPTHBIAS: /* float */
4936 {
4937 GLfloat units;
4938
4939 /** @todo not sure if the d3d & ogl definitions are identical. */
4940
4941 /* Do not change the factor part. */
4942 glGetFloatv(GL_POLYGON_OFFSET_UNITS, &units);
4943 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4944
4945 glPolygonOffset(pRenderState[i].floatValue, units);
4946 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4947 break;
4948 }
4949
4950 case SVGA3D_RS_COLORWRITEENABLE: /* SVGA3dColorMask */
4951 {
4952 GLboolean red, green, blue, alpha;
4953 SVGA3dColorMask mask;
4954
4955 mask.uintValue = pRenderState[i].uintValue;
4956
4957 red = mask.s.red;
4958 green = mask.s.green;
4959 blue = mask.s.blue;
4960 alpha = mask.s.alpha;
4961
4962 glColorMask(red, green, blue, alpha);
4963 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4964 break;
4965 }
4966
4967 case SVGA3D_RS_COLORWRITEENABLE1: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4968 case SVGA3D_RS_COLORWRITEENABLE2: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4969 case SVGA3D_RS_COLORWRITEENABLE3: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4970 Log(("vmsvga3dSetRenderState: WARNING SVGA3D_RS_COLORWRITEENABLEx not supported!!\n"));
4971 break;
4972
4973 case SVGA3D_RS_SCISSORTESTENABLE: /* SVGA3dBool */
4974 enableCap = GL_SCISSOR_TEST;
4975 val = pRenderState[i].uintValue;
4976 break;
4977
4978#if 0
4979 case SVGA3D_RS_DIFFUSEMATERIALSOURCE: /* SVGA3dVertexMaterial */
4980 AssertCompile(D3DMCS_COLOR2 == SVGA3D_VERTEXMATERIAL_SPECULAR);
4981 renderState = D3DRS_DIFFUSEMATERIALSOURCE;
4982 val = pRenderState[i].uintValue;
4983 break;
4984
4985 case SVGA3D_RS_SPECULARMATERIALSOURCE: /* SVGA3dVertexMaterial */
4986 renderState = D3DRS_SPECULARMATERIALSOURCE;
4987 val = pRenderState[i].uintValue;
4988 break;
4989
4990 case SVGA3D_RS_AMBIENTMATERIALSOURCE: /* SVGA3dVertexMaterial */
4991 renderState = D3DRS_AMBIENTMATERIALSOURCE;
4992 val = pRenderState[i].uintValue;
4993 break;
4994
4995 case SVGA3D_RS_EMISSIVEMATERIALSOURCE: /* SVGA3dVertexMaterial */
4996 renderState = D3DRS_EMISSIVEMATERIALSOURCE;
4997 val = pRenderState[i].uintValue;
4998 break;
4999#endif
5000
5001 case SVGA3D_RS_WRAP3: /* SVGA3dWrapFlags */
5002 case SVGA3D_RS_WRAP4: /* SVGA3dWrapFlags */
5003 case SVGA3D_RS_WRAP5: /* SVGA3dWrapFlags */
5004 case SVGA3D_RS_WRAP6: /* SVGA3dWrapFlags */
5005 case SVGA3D_RS_WRAP7: /* SVGA3dWrapFlags */
5006 case SVGA3D_RS_WRAP8: /* SVGA3dWrapFlags */
5007 case SVGA3D_RS_WRAP9: /* SVGA3dWrapFlags */
5008 case SVGA3D_RS_WRAP10: /* SVGA3dWrapFlags */
5009 case SVGA3D_RS_WRAP11: /* SVGA3dWrapFlags */
5010 case SVGA3D_RS_WRAP12: /* SVGA3dWrapFlags */
5011 case SVGA3D_RS_WRAP13: /* SVGA3dWrapFlags */
5012 case SVGA3D_RS_WRAP14: /* SVGA3dWrapFlags */
5013 case SVGA3D_RS_WRAP15: /* SVGA3dWrapFlags */
5014 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_WRAPx (x >= 3)\n"));
5015 break;
5016
5017 case SVGA3D_RS_LASTPIXEL: /* SVGA3dBool */
5018 case SVGA3D_RS_TWEENFACTOR: /* float */
5019 case SVGA3D_RS_INDEXEDVERTEXBLENDENABLE: /* SVGA3dBool */
5020 case SVGA3D_RS_VERTEXBLEND: /* SVGA3dVertexBlendFlags */
5021 Log(("vmsvga3dSetRenderState: WARNING not applicable!!\n"));
5022 break;
5023
5024 case SVGA3D_RS_MULTISAMPLEANTIALIAS: /* SVGA3dBool */
5025 enableCap = GL_MULTISAMPLE;
5026 val = pRenderState[i].uintValue;
5027 break;
5028
5029 case SVGA3D_RS_MULTISAMPLEMASK: /* uint32_t */
5030 case SVGA3D_RS_ANTIALIASEDLINEENABLE: /* SVGA3dBool */
5031 Log(("vmsvga3dSetRenderState: WARNING not applicable??!!\n"));
5032 break;
5033
5034 case SVGA3D_RS_COORDINATETYPE: /* SVGA3dCoordinateType */
5035 Assert(pRenderState[i].uintValue == SVGA3D_COORDINATE_LEFTHANDED);
5036 /** @todo setup a view matrix to scale the world space by -1 in the z-direction for right handed coordinates. */
5037 /*
5038 renderState = D3DRS_COORDINATETYPE;
5039 val = pRenderState[i].uintValue;
5040 */
5041 break;
5042
5043 case SVGA3D_RS_FRONTWINDING: /* SVGA3dFrontWinding */
5044 Assert(pRenderState[i].uintValue == SVGA3D_FRONTWINDING_CW);
5045 /* Invert the selected mode because of y-inversion (?) */
5046 glFrontFace((pRenderState[i].uintValue != SVGA3D_FRONTWINDING_CW) ? GL_CW : GL_CCW);
5047 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5048 break;
5049
5050 case SVGA3D_RS_OUTPUTGAMMA: /* float */
5051 //AssertFailed();
5052 /*
5053 D3DRS_SRGBWRITEENABLE ??
5054 renderState = D3DRS_OUTPUTGAMMA;
5055 val = pRenderState[i].uintValue;
5056 */
5057 break;
5058
5059#if 0
5060
5061 case SVGA3D_RS_VERTEXMATERIALENABLE: /* SVGA3dBool */
5062 //AssertFailed();
5063 renderState = D3DRS_INDEXEDVERTEXBLENDENABLE; /* correct?? */
5064 val = pRenderState[i].uintValue;
5065 break;
5066
5067 case SVGA3D_RS_TEXTUREFACTOR: /* SVGA3dColor */
5068 renderState = D3DRS_TEXTUREFACTOR;
5069 val = pRenderState[i].uintValue;
5070 break;
5071
5072 case SVGA3D_RS_LOCALVIEWER: /* SVGA3dBool */
5073 renderState = D3DRS_LOCALVIEWER;
5074 val = pRenderState[i].uintValue;
5075 break;
5076
5077 case SVGA3D_RS_ZVISIBLE: /* SVGA3dBool */
5078 AssertFailed();
5079 /*
5080 renderState = D3DRS_ZVISIBLE;
5081 val = pRenderState[i].uintValue;
5082 */
5083 break;
5084
5085 case SVGA3D_RS_CLIPPING: /* SVGA3dBool */
5086 renderState = D3DRS_CLIPPING;
5087 val = pRenderState[i].uintValue;
5088 break;
5089
5090 case SVGA3D_RS_WRAP0: /* SVGA3dWrapFlags */
5091 glTexParameter GL_TEXTURE_WRAP_S
5092 Assert(SVGA3D_WRAPCOORD_3 == D3DWRAPCOORD_3);
5093 renderState = D3DRS_WRAP0;
5094 val = pRenderState[i].uintValue;
5095 break;
5096
5097 case SVGA3D_RS_WRAP1: /* SVGA3dWrapFlags */
5098 glTexParameter GL_TEXTURE_WRAP_T
5099 renderState = D3DRS_WRAP1;
5100 val = pRenderState[i].uintValue;
5101 break;
5102
5103 case SVGA3D_RS_WRAP2: /* SVGA3dWrapFlags */
5104 glTexParameter GL_TEXTURE_WRAP_R
5105 renderState = D3DRS_WRAP2;
5106 val = pRenderState[i].uintValue;
5107 break;
5108
5109
5110 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
5111 renderState = D3DRS_SEPARATEALPHABLENDENABLE;
5112 val = pRenderState[i].uintValue;
5113 break;
5114
5115
5116 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
5117 renderState = D3DRS_BLENDOPALPHA;
5118 val = pRenderState[i].uintValue;
5119 break;
5120
5121 case SVGA3D_RS_TRANSPARENCYANTIALIAS: /* SVGA3dTransparencyAntialiasType */
5122 AssertFailed();
5123 /*
5124 renderState = D3DRS_TRANSPARENCYANTIALIAS;
5125 val = pRenderState[i].uintValue;
5126 */
5127 break;
5128
5129#endif
5130 default:
5131 AssertFailed();
5132 break;
5133 }
5134
5135 if (enableCap != ~(GLenum)0)
5136 {
5137 if (val)
5138 glEnable(enableCap);
5139 else
5140 glDisable(enableCap);
5141 }
5142 }
5143
5144 return VINF_SUCCESS;
5145}
5146
5147int vmsvga3dSetRenderTarget(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRenderTargetType type, SVGA3dSurfaceImageId target)
5148{
5149 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5150
5151 AssertReturn(pState, VERR_NO_MEMORY);
5152 AssertReturn((unsigned)type < SVGA3D_RT_MAX, VERR_INVALID_PARAMETER);
5153
5154 LogFunc(("cid=%u type=%x sid=%u\n", cid, type, target.sid));
5155
5156 PVMSVGA3DCONTEXT pContext;
5157 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5158 AssertRCReturn(rc, rc);
5159
5160 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5161
5162 /* Save for vm state save/restore. */
5163 pContext->state.aRenderTargets[type] = target.sid;
5164
5165 if (target.sid == SVGA3D_INVALID_ID)
5166 {
5167 /* Disable render target. */
5168 switch (type)
5169 {
5170 case SVGA3D_RT_DEPTH:
5171 case SVGA3D_RT_STENCIL:
5172 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER, (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
5173 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5174 break;
5175
5176 case SVGA3D_RT_COLOR0:
5177 case SVGA3D_RT_COLOR1:
5178 case SVGA3D_RT_COLOR2:
5179 case SVGA3D_RT_COLOR3:
5180 case SVGA3D_RT_COLOR4:
5181 case SVGA3D_RT_COLOR5:
5182 case SVGA3D_RT_COLOR6:
5183 case SVGA3D_RT_COLOR7:
5184 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0, 0, 0, 0);
5185 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5186 break;
5187
5188 default:
5189 AssertFailedReturn(VERR_INVALID_PARAMETER);
5190 }
5191 return VINF_SUCCESS;
5192 }
5193
5194 PVMSVGA3DSURFACE pRenderTarget;
5195 rc = vmsvga3dSurfaceFromSid(pState, target.sid, &pRenderTarget);
5196 AssertRCReturn(rc, rc);
5197
5198 switch (type)
5199 {
5200 case SVGA3D_RT_DEPTH:
5201 case SVGA3D_RT_STENCIL:
5202#if 1
5203 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5204 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5205 {
5206 LogFunc(("create depth texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n",
5207 target.sid, pRenderTarget->surfaceFlags, pRenderTarget->format));
5208 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pRenderTarget);
5209 AssertRCReturn(rc, rc);
5210 }
5211
5212 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5213 Assert(!pRenderTarget->fDirty);
5214
5215 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5216
5217 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER,
5218 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5219 GL_TEXTURE_2D, pRenderTarget->oglId.texture, target.mipmap);
5220 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5221#else
5222 AssertReturn(target.mipmap == 0, VERR_INVALID_PARAMETER);
5223 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5224 {
5225 Log(("vmsvga3dSetRenderTarget: create renderbuffer to be used as render target; surface id=%x type=%d format=%d\n", target.sid, pRenderTarget->surfaceFlags, pRenderTarget->internalFormatGL));
5226 pContext = &pState->SharedCtx;
5227 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5228
5229 pState->ext.glGenRenderbuffers(1, &pRenderTarget->oglId.renderbuffer);
5230 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5231 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_RENDERBUFFER;
5232
5233 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5234 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5235
5236 pState->ext.glRenderbufferStorage(GL_RENDERBUFFER,
5237 pRenderTarget->internalFormatGL,
5238 pRenderTarget->paMipmapLevels[0].mipmapSize.width,
5239 pRenderTarget->paMipmapLevels[0].mipmapSize.height);
5240 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5241
5242 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, OPENGL_INVALID_ID);
5243 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5244
5245 pContext = pState->papContexts[cid];
5246 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5247 pRenderTarget->idWeakContextAssociation = cid;
5248 }
5249
5250 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5251 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5252 Assert(!pRenderTarget->fDirty);
5253 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5254
5255 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5256
5257 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
5258 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5259 GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5260 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5261#endif
5262 break;
5263
5264 case SVGA3D_RT_COLOR0:
5265 case SVGA3D_RT_COLOR1:
5266 case SVGA3D_RT_COLOR2:
5267 case SVGA3D_RT_COLOR3:
5268 case SVGA3D_RT_COLOR4:
5269 case SVGA3D_RT_COLOR5:
5270 case SVGA3D_RT_COLOR6:
5271 case SVGA3D_RT_COLOR7:
5272 {
5273 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5274 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5275 {
5276 Log(("vmsvga3dSetRenderTarget: create texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n", target.sid, pRenderTarget->surfaceFlags, pRenderTarget->format));
5277 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pRenderTarget);
5278 AssertRCReturn(rc, rc);
5279 }
5280
5281 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5282 Assert(!pRenderTarget->fDirty);
5283
5284 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_RENDERTARGET;
5285
5286 GLenum textarget;
5287 if (pRenderTarget->surfaceFlags & SVGA3D_SURFACE_CUBEMAP)
5288 textarget = vmsvga3dCubemapFaceFromIndex(target.face);
5289 else
5290 textarget = GL_TEXTURE_2D;
5291 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0,
5292 textarget, pRenderTarget->oglId.texture, target.mipmap);
5293 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5294
5295#ifdef DEBUG
5296 GLenum status = pState->ext.glCheckFramebufferStatus(GL_FRAMEBUFFER);
5297 if (status != GL_FRAMEBUFFER_COMPLETE)
5298 Log(("vmsvga3dSetRenderTarget: WARNING: glCheckFramebufferStatus returned %x\n", status));
5299#endif
5300 /** @todo use glDrawBuffers too? */
5301 break;
5302 }
5303
5304 default:
5305 AssertFailedReturn(VERR_INVALID_PARAMETER);
5306 }
5307
5308 return VINF_SUCCESS;
5309}
5310
5311#if 0
5312/**
5313 * Convert SVGA texture combiner value to its D3D equivalent
5314 */
5315static DWORD vmsvga3dTextureCombiner2D3D(uint32_t value)
5316{
5317 switch (value)
5318 {
5319 case SVGA3D_TC_DISABLE:
5320 return D3DTOP_DISABLE;
5321 case SVGA3D_TC_SELECTARG1:
5322 return D3DTOP_SELECTARG1;
5323 case SVGA3D_TC_SELECTARG2:
5324 return D3DTOP_SELECTARG2;
5325 case SVGA3D_TC_MODULATE:
5326 return D3DTOP_MODULATE;
5327 case SVGA3D_TC_ADD:
5328 return D3DTOP_ADD;
5329 case SVGA3D_TC_ADDSIGNED:
5330 return D3DTOP_ADDSIGNED;
5331 case SVGA3D_TC_SUBTRACT:
5332 return D3DTOP_SUBTRACT;
5333 case SVGA3D_TC_BLENDTEXTUREALPHA:
5334 return D3DTOP_BLENDTEXTUREALPHA;
5335 case SVGA3D_TC_BLENDDIFFUSEALPHA:
5336 return D3DTOP_BLENDDIFFUSEALPHA;
5337 case SVGA3D_TC_BLENDCURRENTALPHA:
5338 return D3DTOP_BLENDCURRENTALPHA;
5339 case SVGA3D_TC_BLENDFACTORALPHA:
5340 return D3DTOP_BLENDFACTORALPHA;
5341 case SVGA3D_TC_MODULATE2X:
5342 return D3DTOP_MODULATE2X;
5343 case SVGA3D_TC_MODULATE4X:
5344 return D3DTOP_MODULATE4X;
5345 case SVGA3D_TC_DSDT:
5346 AssertFailed(); /** @todo ??? */
5347 return D3DTOP_DISABLE;
5348 case SVGA3D_TC_DOTPRODUCT3:
5349 return D3DTOP_DOTPRODUCT3;
5350 case SVGA3D_TC_BLENDTEXTUREALPHAPM:
5351 return D3DTOP_BLENDTEXTUREALPHAPM;
5352 case SVGA3D_TC_ADDSIGNED2X:
5353 return D3DTOP_ADDSIGNED2X;
5354 case SVGA3D_TC_ADDSMOOTH:
5355 return D3DTOP_ADDSMOOTH;
5356 case SVGA3D_TC_PREMODULATE:
5357 return D3DTOP_PREMODULATE;
5358 case SVGA3D_TC_MODULATEALPHA_ADDCOLOR:
5359 return D3DTOP_MODULATEALPHA_ADDCOLOR;
5360 case SVGA3D_TC_MODULATECOLOR_ADDALPHA:
5361 return D3DTOP_MODULATECOLOR_ADDALPHA;
5362 case SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR:
5363 return D3DTOP_MODULATEINVALPHA_ADDCOLOR;
5364 case SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA:
5365 return D3DTOP_MODULATEINVCOLOR_ADDALPHA;
5366 case SVGA3D_TC_BUMPENVMAPLUMINANCE:
5367 return D3DTOP_BUMPENVMAPLUMINANCE;
5368 case SVGA3D_TC_MULTIPLYADD:
5369 return D3DTOP_MULTIPLYADD;
5370 case SVGA3D_TC_LERP:
5371 return D3DTOP_LERP;
5372 default:
5373 AssertFailed();
5374 return D3DTOP_DISABLE;
5375 }
5376}
5377
5378/**
5379 * Convert SVGA texture arg data value to its D3D equivalent
5380 */
5381static DWORD vmsvga3dTextureArgData2D3D(uint32_t value)
5382{
5383 switch (value)
5384 {
5385 case SVGA3D_TA_CONSTANT:
5386 return D3DTA_CONSTANT;
5387 case SVGA3D_TA_PREVIOUS:
5388 return D3DTA_CURRENT; /* current = previous */
5389 case SVGA3D_TA_DIFFUSE:
5390 return D3DTA_DIFFUSE;
5391 case SVGA3D_TA_TEXTURE:
5392 return D3DTA_TEXTURE;
5393 case SVGA3D_TA_SPECULAR:
5394 return D3DTA_SPECULAR;
5395 default:
5396 AssertFailed();
5397 return 0;
5398 }
5399}
5400
5401/**
5402 * Convert SVGA texture transform flag value to its D3D equivalent
5403 */
5404static DWORD vmsvga3dTextTransformFlags2D3D(uint32_t value)
5405{
5406 switch (value)
5407 {
5408 case SVGA3D_TEX_TRANSFORM_OFF:
5409 return D3DTTFF_DISABLE;
5410 case SVGA3D_TEX_TRANSFORM_S:
5411 return D3DTTFF_COUNT1; /** @todo correct? */
5412 case SVGA3D_TEX_TRANSFORM_T:
5413 return D3DTTFF_COUNT2; /** @todo correct? */
5414 case SVGA3D_TEX_TRANSFORM_R:
5415 return D3DTTFF_COUNT3; /** @todo correct? */
5416 case SVGA3D_TEX_TRANSFORM_Q:
5417 return D3DTTFF_COUNT4; /** @todo correct? */
5418 case SVGA3D_TEX_PROJECTED:
5419 return D3DTTFF_PROJECTED;
5420 default:
5421 AssertFailed();
5422 return 0;
5423 }
5424}
5425#endif
5426
5427static GLenum vmsvga3dTextureAddress2OGL(SVGA3dTextureAddress value)
5428{
5429 switch (value)
5430 {
5431 case SVGA3D_TEX_ADDRESS_WRAP:
5432 return GL_REPEAT;
5433 case SVGA3D_TEX_ADDRESS_MIRROR:
5434 return GL_MIRRORED_REPEAT;
5435 case SVGA3D_TEX_ADDRESS_CLAMP:
5436 return GL_CLAMP_TO_EDGE;
5437 case SVGA3D_TEX_ADDRESS_BORDER:
5438 return GL_CLAMP_TO_BORDER;
5439 case SVGA3D_TEX_ADDRESS_MIRRORONCE:
5440 AssertFailed();
5441 return GL_CLAMP_TO_EDGE_SGIS; /** @todo correct? */
5442
5443 case SVGA3D_TEX_ADDRESS_EDGE:
5444 case SVGA3D_TEX_ADDRESS_INVALID:
5445 default:
5446 AssertFailed();
5447 return GL_REPEAT; /* default */
5448 }
5449}
5450
5451static GLenum vmsvga3dTextureFilter2OGL(SVGA3dTextureFilter value)
5452{
5453 switch (value)
5454 {
5455 case SVGA3D_TEX_FILTER_NONE:
5456 case SVGA3D_TEX_FILTER_LINEAR:
5457 case SVGA3D_TEX_FILTER_ANISOTROPIC: /* Anisotropic filtering is controlled by SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL */
5458 return GL_LINEAR;
5459 case SVGA3D_TEX_FILTER_NEAREST:
5460 return GL_NEAREST;
5461 case SVGA3D_TEX_FILTER_FLATCUBIC: // Deprecated, not implemented
5462 case SVGA3D_TEX_FILTER_GAUSSIANCUBIC: // Deprecated, not implemented
5463 case SVGA3D_TEX_FILTER_PYRAMIDALQUAD: // Not currently implemented
5464 case SVGA3D_TEX_FILTER_GAUSSIANQUAD: // Not currently implemented
5465 default:
5466 AssertFailed();
5467 return GL_LINEAR; /* default */
5468 }
5469}
5470
5471uint32_t vmsvga3dSVGA3dColor2RGBA(SVGA3dColor value)
5472{
5473 /* flip the red and blue bytes */
5474 uint8_t blue = value & 0xff;
5475 uint8_t red = (value >> 16) & 0xff;
5476 return (value & 0xff00ff00) | red | (blue << 16);
5477}
5478
5479int vmsvga3dSetTextureState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cTextureStates, SVGA3dTextureState *pTextureState)
5480{
5481 GLenum val = ~(GLenum)0; /* Shut up MSC. */
5482 GLenum currentStage = ~(GLenum)0;
5483 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5484 AssertReturn(pState, VERR_NO_MEMORY);
5485
5486 Log(("vmsvga3dSetTextureState %x cTextureState=%d\n", cid, cTextureStates));
5487
5488 PVMSVGA3DCONTEXT pContext;
5489 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5490 AssertRCReturn(rc, rc);
5491
5492 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5493
5494 /* Which texture is active for the current stage. Needed to use right OpenGL target when setting parameters. */
5495 PVMSVGA3DSURFACE pCurrentTextureSurface = NULL;
5496
5497 for (uint32_t i = 0; i < cTextureStates; ++i)
5498 {
5499 GLenum textureType = ~(GLenum)0;
5500#if 0
5501 GLenum samplerType = ~(GLenum)0;
5502#endif
5503
5504 LogFunc(("cid=%u stage=%d type=%s (%x) val=%x\n",
5505 cid, pTextureState[i].stage, vmsvga3dTextureStateToString(pTextureState[i].name), pTextureState[i].name, pTextureState[i].value));
5506
5507 /* Record the texture state for vm state saving. */
5508 if ( pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates)
5509 && (unsigned)pTextureState[i].name < RT_ELEMENTS(pContext->state.aTextureStates[0]))
5510 {
5511 pContext->state.aTextureStates[pTextureState[i].stage][pTextureState[i].name] = pTextureState[i];
5512 }
5513
5514 /* Activate the right texture unit for subsequent texture state changes. */
5515 if (pTextureState[i].stage != currentStage || i == 0)
5516 {
5517 /** @todo Is this the appropriate limit for all kinds of textures? It is the
5518 * size of aSidActiveTextures and for binding/unbinding we cannot exceed it. */
5519 if (pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates))
5520 {
5521 pState->ext.glActiveTexture(GL_TEXTURE0 + pTextureState[i].stage);
5522 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5523 currentStage = pTextureState[i].stage;
5524 }
5525 else
5526 {
5527 AssertMsgFailed(("pTextureState[%d].stage=%#x name=%#x\n", i, pTextureState[i].stage, pTextureState[i].name));
5528 continue;
5529 }
5530
5531 if (pContext->aSidActiveTextures[currentStage] != SVGA3D_INVALID_ID)
5532 {
5533 rc = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[currentStage], &pCurrentTextureSurface);
5534 AssertRCReturn(rc, rc);
5535 }
5536 else
5537 pCurrentTextureSurface = NULL; /* Make sure that no stale pointer is used. */
5538 }
5539
5540 switch (pTextureState[i].name)
5541 {
5542 case SVGA3D_TS_BUMPENVMAT00: /* float */
5543 case SVGA3D_TS_BUMPENVMAT01: /* float */
5544 case SVGA3D_TS_BUMPENVMAT10: /* float */
5545 case SVGA3D_TS_BUMPENVMAT11: /* float */
5546 case SVGA3D_TS_BUMPENVLSCALE: /* float */
5547 case SVGA3D_TS_BUMPENVLOFFSET: /* float */
5548 Log(("vmsvga3dSetTextureState: bump mapping texture options not supported!!\n"));
5549 break;
5550
5551 case SVGA3D_TS_COLOROP: /* SVGA3dTextureCombiner */
5552 case SVGA3D_TS_COLORARG0: /* SVGA3dTextureArgData */
5553 case SVGA3D_TS_COLORARG1: /* SVGA3dTextureArgData */
5554 case SVGA3D_TS_COLORARG2: /* SVGA3dTextureArgData */
5555 case SVGA3D_TS_ALPHAOP: /* SVGA3dTextureCombiner */
5556 case SVGA3D_TS_ALPHAARG0: /* SVGA3dTextureArgData */
5557 case SVGA3D_TS_ALPHAARG1: /* SVGA3dTextureArgData */
5558 case SVGA3D_TS_ALPHAARG2: /* SVGA3dTextureArgData */
5559 /** @todo not used by MesaGL */
5560 Log(("vmsvga3dSetTextureState: colorop/alphaop not yet supported!!\n"));
5561 break;
5562#if 0
5563
5564 case SVGA3D_TS_TEXCOORDINDEX: /* uint32_t */
5565 textureType = D3DTSS_TEXCOORDINDEX;
5566 val = pTextureState[i].value;
5567 break;
5568
5569 case SVGA3D_TS_TEXTURETRANSFORMFLAGS: /* SVGA3dTexTransformFlags */
5570 textureType = D3DTSS_TEXTURETRANSFORMFLAGS;
5571 val = vmsvga3dTextTransformFlags2D3D(pTextureState[i].value);
5572 break;
5573#endif
5574
5575 case SVGA3D_TS_BIND_TEXTURE: /* SVGA3dSurfaceId */
5576 {
5577 uint32_t const sid = pTextureState[i].value;
5578
5579 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u replacing sid=%u\n",
5580 currentStage, sid, pContext->aSidActiveTextures[currentStage]));
5581
5582 /* Only if texture actually changed. */ /// @todo needs testing.
5583 if (pContext->aSidActiveTextures[currentStage] != sid)
5584 {
5585 if (pCurrentTextureSurface)
5586 {
5587 /* Unselect the currently associated texture. */
5588 glBindTexture(pCurrentTextureSurface->targetGL, 0);
5589 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5590
5591 if (currentStage < 8)
5592 {
5593 /* Necessary for the fixed pipeline. */
5594 glDisable(pCurrentTextureSurface->targetGL);
5595 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5596 }
5597
5598 pCurrentTextureSurface = NULL;
5599 }
5600
5601 if (sid == SVGA3D_INVALID_ID)
5602 {
5603 Assert(pCurrentTextureSurface == NULL);
5604 }
5605 else
5606 {
5607 PVMSVGA3DSURFACE pSurface;
5608 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
5609 AssertRCReturn(rc, rc);
5610
5611 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u (%d,%d) replacing sid=%u\n",
5612 currentStage, sid, pSurface->paMipmapLevels[0].mipmapSize.width,
5613 pSurface->paMipmapLevels[0].mipmapSize.height, pContext->aSidActiveTextures[currentStage]));
5614
5615 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
5616 {
5617 Log(("CreateTexture (%d,%d) levels=%d\n",
5618 pSurface->paMipmapLevels[0].mipmapSize.width, pSurface->paMipmapLevels[0].mipmapSize.height, pSurface->faces[0].numMipLevels));
5619 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pSurface);
5620 AssertRCReturn(rc, rc);
5621 }
5622
5623 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
5624 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5625
5626 if (currentStage < 8)
5627 {
5628 /* Necessary for the fixed pipeline. */
5629 glEnable(pSurface->targetGL);
5630 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5631 }
5632
5633 /* Remember the currently active texture. */
5634 pCurrentTextureSurface = pSurface;
5635
5636 /* Recreate the texture state as glBindTexture resets them all (sigh). */
5637 for (uint32_t iStage = 0; iStage < RT_ELEMENTS(pContext->state.aTextureStates); iStage++)
5638 {
5639 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aTextureStates[0]); j++)
5640 {
5641 SVGA3dTextureState *pTextureStateIter = &pContext->state.aTextureStates[iStage][j];
5642
5643 if ( pTextureStateIter->name != SVGA3D_TS_INVALID
5644 && pTextureStateIter->name != SVGA3D_TS_BIND_TEXTURE)
5645 vmsvga3dSetTextureState(pThisCC, pContext->id, 1, pTextureStateIter);
5646 }
5647 }
5648 }
5649
5650 pContext->aSidActiveTextures[currentStage] = sid;
5651 }
5652
5653 /* Finished; continue with the next one. */
5654 continue;
5655 }
5656
5657 case SVGA3D_TS_ADDRESSW: /* SVGA3dTextureAddress */
5658 textureType = GL_TEXTURE_WRAP_R; /* R = W */
5659 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5660 break;
5661
5662 case SVGA3D_TS_ADDRESSU: /* SVGA3dTextureAddress */
5663 textureType = GL_TEXTURE_WRAP_S; /* S = U */
5664 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5665 break;
5666
5667 case SVGA3D_TS_ADDRESSV: /* SVGA3dTextureAddress */
5668 textureType = GL_TEXTURE_WRAP_T; /* T = V */
5669 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5670 break;
5671
5672 case SVGA3D_TS_MIPFILTER: /* SVGA3dTextureFilter */
5673 case SVGA3D_TS_MINFILTER: /* SVGA3dTextureFilter */
5674 {
5675 uint32_t mipFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MIPFILTER].value;
5676 uint32_t minFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MINFILTER].value;
5677
5678 /* If SVGA3D_TS_MIPFILTER is set to NONE, then use SVGA3D_TS_MIPFILTER, otherwise SVGA3D_TS_MIPFILTER enables mipmap minification. */
5679 textureType = GL_TEXTURE_MIN_FILTER;
5680 if (mipFilter != SVGA3D_TEX_FILTER_NONE)
5681 {
5682 if (minFilter == SVGA3D_TEX_FILTER_NEAREST)
5683 {
5684 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5685 val = GL_NEAREST_MIPMAP_LINEAR;
5686 else
5687 val = GL_NEAREST_MIPMAP_NEAREST;
5688 }
5689 else
5690 {
5691 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5692 val = GL_LINEAR_MIPMAP_LINEAR;
5693 else
5694 val = GL_LINEAR_MIPMAP_NEAREST;
5695 }
5696 }
5697 else
5698 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)minFilter);
5699 break;
5700 }
5701
5702 case SVGA3D_TS_MAGFILTER: /* SVGA3dTextureFilter */
5703 textureType = GL_TEXTURE_MAG_FILTER;
5704 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)pTextureState[i].value);
5705 Assert(val == GL_NEAREST || val == GL_LINEAR);
5706 break;
5707
5708 case SVGA3D_TS_BORDERCOLOR: /* SVGA3dColor */
5709 {
5710 GLfloat color[4]; /* red, green, blue, alpha */
5711 vmsvgaColor2GLFloatArray(pTextureState[i].value, &color[0], &color[1], &color[2], &color[3]);
5712
5713 GLenum targetGL;
5714 if (pCurrentTextureSurface)
5715 targetGL = pCurrentTextureSurface->targetGL;
5716 else
5717 {
5718 /* No texture bound, assume 2D. */
5719 targetGL = GL_TEXTURE_2D;
5720 }
5721
5722 glTexParameterfv(targetGL, GL_TEXTURE_BORDER_COLOR, color); /* Identical; default 0.0 identical too */
5723 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5724 break;
5725 }
5726
5727 case SVGA3D_TS_TEXTURE_LOD_BIAS: /* float */
5728 {
5729 GLenum targetGL;
5730 if (pCurrentTextureSurface)
5731 targetGL = pCurrentTextureSurface->targetGL;
5732 else
5733 {
5734 /* No texture bound, assume 2D. */
5735 targetGL = GL_TEXTURE_2D;
5736 }
5737
5738 glTexParameterf(targetGL, GL_TEXTURE_LOD_BIAS, pTextureState[i].floatValue); /* Identical; default 0.0 identical too */
5739 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5740 break;
5741 }
5742
5743 case SVGA3D_TS_TEXTURE_MIPMAP_LEVEL: /* uint32_t */
5744 textureType = GL_TEXTURE_BASE_LEVEL;
5745 val = pTextureState[i].value;
5746 break;
5747
5748 case SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL: /* uint32_t */
5749 if (pState->caps.fTextureFilterAnisotropicSupported)
5750 {
5751 textureType = GL_TEXTURE_MAX_ANISOTROPY_EXT;
5752 val = RT_MIN((GLint)pTextureState[i].value, pState->caps.maxTextureAnisotropy);
5753 } /* otherwise ignore. */
5754 break;
5755
5756#if 0
5757 case SVGA3D_TS_GAMMA: /* float */
5758 samplerType = D3DSAMP_SRGBTEXTURE;
5759 /* Boolean in D3D */
5760 if (pTextureState[i].floatValue == 1.0f)
5761 val = FALSE;
5762 else
5763 val = TRUE;
5764 break;
5765#endif
5766 /* Internal commands, that don't map directly to the SetTextureStageState API. */
5767 case SVGA3D_TS_TEXCOORDGEN: /* SVGA3dTextureCoordGen */
5768 AssertFailed();
5769 break;
5770
5771 default:
5772 //AssertFailed();
5773 break;
5774 }
5775
5776 if (textureType != ~(GLenum)0)
5777 {
5778 GLenum targetGL;
5779 if (pCurrentTextureSurface)
5780 targetGL = pCurrentTextureSurface->targetGL;
5781 else
5782 {
5783 /* No texture bound, assume 2D. */
5784 targetGL = GL_TEXTURE_2D;
5785 }
5786
5787 switch (pTextureState[i].name)
5788 {
5789 case SVGA3D_TS_MINFILTER:
5790 case SVGA3D_TS_MAGFILTER:
5791 {
5792 if (pState->caps.fTextureFilterAnisotropicSupported)
5793 {
5794 uint32_t const anisotropyLevel = (SVGA3dTextureFilter)pTextureState[i].value == SVGA3D_TEX_FILTER_ANISOTROPIC
5795 ? RT_MAX(1, pContext->state.aTextureStates[currentStage][SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL].value)
5796 : 1;
5797 glTexParameteri(targetGL, GL_TEXTURE_MAX_ANISOTROPY_EXT, RT_MIN((GLint)anisotropyLevel, pState->caps.maxTextureAnisotropy));
5798 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5799 }
5800 } break;
5801
5802 default: break;
5803 }
5804
5805 glTexParameteri(targetGL, textureType, val);
5806 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5807 }
5808 }
5809
5810 return VINF_SUCCESS;
5811}
5812
5813int vmsvga3dSetMaterial(PVGASTATECC pThisCC, uint32_t cid, SVGA3dFace face, SVGA3dMaterial *pMaterial)
5814{
5815 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5816 AssertReturn(pState, VERR_NO_MEMORY);
5817
5818 LogFunc(("cid=%u face %d\n", cid, face));
5819
5820 PVMSVGA3DCONTEXT pContext;
5821 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5822 AssertRCReturn(rc, rc);
5823
5824 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5825
5826 GLenum oglFace;
5827 switch (face)
5828 {
5829 case SVGA3D_FACE_NONE:
5830 case SVGA3D_FACE_FRONT:
5831 oglFace = GL_FRONT;
5832 break;
5833
5834 case SVGA3D_FACE_BACK:
5835 oglFace = GL_BACK;
5836 break;
5837
5838 case SVGA3D_FACE_FRONT_BACK:
5839 oglFace = GL_FRONT_AND_BACK;
5840 break;
5841
5842 default:
5843 AssertFailedReturn(VERR_INVALID_PARAMETER);
5844 }
5845
5846 /* Save for vm state save/restore. */
5847 pContext->state.aMaterial[face].fValid = true;
5848 pContext->state.aMaterial[face].material = *pMaterial;
5849 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_MATERIAL;
5850
5851 glMaterialfv(oglFace, GL_DIFFUSE, pMaterial->diffuse);
5852 glMaterialfv(oglFace, GL_AMBIENT, pMaterial->ambient);
5853 glMaterialfv(oglFace, GL_SPECULAR, pMaterial->specular);
5854 glMaterialfv(oglFace, GL_EMISSION, pMaterial->emissive);
5855 glMaterialfv(oglFace, GL_SHININESS, &pMaterial->shininess);
5856 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5857
5858 return VINF_SUCCESS;
5859}
5860
5861/** @todo Move into separate library as we are using logic from Wine here. */
5862int vmsvga3dSetLightData(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, SVGA3dLightData *pData)
5863{
5864 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5865 AssertReturn(pState, VERR_NO_MEMORY);
5866
5867 LogFunc(("vmsvga3dSetLightData cid=%u index=%d type=%d\n", cid, index, pData->type));
5868 ASSERT_GUEST_RETURN(index < SVGA3D_MAX_LIGHTS, VERR_INVALID_PARAMETER);
5869
5870 PVMSVGA3DCONTEXT pContext;
5871 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5872 AssertRCReturn(rc, rc);
5873
5874 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5875
5876 /* Store for vm state save/restore */
5877 pContext->state.aLightData[index].fValidData = true;
5878 pContext->state.aLightData[index].data = *pData;
5879
5880 if ( pData->attenuation0 < 0.0f
5881 || pData->attenuation1 < 0.0f
5882 || pData->attenuation2 < 0.0f)
5883 {
5884 Log(("vmsvga3dSetLightData: invalid negative attenuation values!!\n"));
5885 return VINF_SUCCESS; /* ignore; could crash the GL driver */
5886 }
5887
5888 /* Light settings are affected by the model view in OpenGL, the View transform in direct3d */
5889 glMatrixMode(GL_MODELVIEW);
5890 glPushMatrix();
5891 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
5892
5893 glLightfv(GL_LIGHT0 + index, GL_DIFFUSE, pData->diffuse);
5894 glLightfv(GL_LIGHT0 + index, GL_SPECULAR, pData->specular);
5895 glLightfv(GL_LIGHT0 + index, GL_AMBIENT, pData->ambient);
5896
5897 float QuadAttenuation;
5898 if (pData->range * pData->range >= FLT_MIN)
5899 QuadAttenuation = 1.4f / (pData->range * pData->range);
5900 else
5901 QuadAttenuation = 0.0f;
5902
5903 switch (pData->type)
5904 {
5905 case SVGA3D_LIGHTTYPE_POINT:
5906 {
5907 GLfloat position[4];
5908
5909 position[0] = pData->position[0];
5910 position[1] = pData->position[1];
5911 position[2] = pData->position[2];
5912 position[3] = 1.0f;
5913
5914 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
5915 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5916
5917 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
5918 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5919
5920 /* Attenuation - Are these right? guessing... */
5921 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
5922 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5923
5924 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
5925 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5926
5927 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
5928 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5929
5930 /** @todo range */
5931 break;
5932 }
5933
5934 case SVGA3D_LIGHTTYPE_SPOT1:
5935 {
5936 GLfloat exponent;
5937 GLfloat position[4];
5938 const GLfloat pi = 4.0f * atanf(1.0f);
5939
5940 position[0] = pData->position[0];
5941 position[1] = pData->position[1];
5942 position[2] = pData->position[2];
5943 position[3] = 1.0f;
5944
5945 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
5946 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5947
5948 position[0] = pData->direction[0];
5949 position[1] = pData->direction[1];
5950 position[2] = pData->direction[2];
5951 position[3] = 1.0f;
5952
5953 glLightfv(GL_LIGHT0 + index, GL_SPOT_DIRECTION, position);
5954 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5955
5956 /*
5957 * opengl-ish and d3d-ish spot lights use too different models for the
5958 * light "intensity" as a function of the angle towards the main light direction,
5959 * so we only can approximate very roughly.
5960 * however spot lights are rather rarely used in games (if ever used at all).
5961 * furthermore if still used, probably nobody pays attention to such details.
5962 */
5963 if (pData->falloff == 0)
5964 {
5965 /* Falloff = 0 is easy, because d3d's and opengl's spot light equations have the
5966 * falloff resp. exponent parameter as an exponent, so the spot light lighting
5967 * will always be 1.0 for both of them, and we don't have to care for the
5968 * rest of the rather complex calculation
5969 */
5970 exponent = 0.0f;
5971 }
5972 else
5973 {
5974 float rho = pData->theta + (pData->phi - pData->theta) / (2 * pData->falloff);
5975 if (rho < 0.0001f)
5976 rho = 0.0001f;
5977 exponent = -0.3f/log(cos(rho/2));
5978 }
5979 if (exponent > 128.0f)
5980 exponent = 128.0f;
5981
5982 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, exponent);
5983 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5984
5985 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, pData->phi * 90.0 / pi);
5986 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5987
5988 /* Attenuation - Are these right? guessing... */
5989 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
5990 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5991
5992 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
5993 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5994
5995 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
5996 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5997
5998 /** @todo range */
5999 break;
6000 }
6001
6002 case SVGA3D_LIGHTTYPE_DIRECTIONAL:
6003 {
6004 GLfloat position[4];
6005
6006 position[0] = -pData->direction[0];
6007 position[1] = -pData->direction[1];
6008 position[2] = -pData->direction[2];
6009 position[3] = 0.0f;
6010
6011 glLightfv(GL_LIGHT0 + index, GL_POSITION, position); /* Note gl uses w position of 0 for direction! */
6012 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6013
6014 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6015 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6016
6017 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, 0.0f);
6018 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6019 break;
6020 }
6021
6022 case SVGA3D_LIGHTTYPE_SPOT2:
6023 default:
6024 Log(("Unsupported light type!!\n"));
6025 rc = VERR_INVALID_PARAMETER;
6026 break;
6027 }
6028
6029 /* Restore the modelview matrix */
6030 glPopMatrix();
6031
6032 return rc;
6033}
6034
6035int vmsvga3dSetLightEnabled(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, uint32_t enabled)
6036{
6037 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6038 AssertReturn(pState, VERR_NO_MEMORY);
6039
6040 LogFunc(("cid=%u %d -> %d\n", cid, index, enabled));
6041
6042 PVMSVGA3DCONTEXT pContext;
6043 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6044 AssertRCReturn(rc, rc);
6045
6046 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6047
6048 /* Store for vm state save/restore */
6049 if (index < SVGA3D_MAX_LIGHTS)
6050 pContext->state.aLightData[index].fEnabled = !!enabled;
6051 else
6052 AssertFailed();
6053
6054 if (enabled)
6055 {
6056 if (index < SVGA3D_MAX_LIGHTS)
6057 {
6058 /* Load the default settings if none have been set yet. */
6059 if (!pContext->state.aLightData[index].fValidData)
6060 vmsvga3dSetLightData(pThisCC, cid, index, (SVGA3dLightData *)&vmsvga3d_default_light);
6061 }
6062 glEnable(GL_LIGHT0 + index);
6063 }
6064 else
6065 glDisable(GL_LIGHT0 + index);
6066
6067 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6068 return VINF_SUCCESS;
6069}
6070
6071int vmsvga3dSetViewPort(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6072{
6073 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6074 AssertReturn(pState, VERR_NO_MEMORY);
6075
6076 Log(("vmsvga3dSetViewPort cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6077
6078 PVMSVGA3DCONTEXT pContext;
6079 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6080 AssertRCReturn(rc, rc);
6081
6082 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6083
6084 /* Save for vm state save/restore. */
6085 pContext->state.RectViewPort = *pRect;
6086 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VIEWPORT;
6087
6088 /** @todo y-inversion for partial viewport coordinates? */
6089 glViewport(pRect->x, pRect->y, pRect->w, pRect->h);
6090 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6091
6092 /* Reset the projection matrix as that relies on the viewport setting. */
6093 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6094 vmsvga3dSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION,
6095 pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6096 else
6097 {
6098 float matrix[16];
6099
6100 /* identity matrix if no matrix set. */
6101 memset(matrix, 0, sizeof(matrix));
6102 matrix[0] = 1.0;
6103 matrix[5] = 1.0;
6104 matrix[10] = 1.0;
6105 matrix[15] = 1.0;
6106 vmsvga3dSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION, matrix);
6107 }
6108
6109 return VINF_SUCCESS;
6110}
6111
6112int vmsvga3dSetClipPlane(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, float plane[4])
6113{
6114 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6115 AssertReturn(pState, VERR_NO_MEMORY);
6116 double oglPlane[4];
6117
6118 Log(("vmsvga3dSetClipPlane cid=%u %d (%d,%d)(%d,%d)\n", cid, index, (unsigned)(plane[0] * 100.0), (unsigned)(plane[1] * 100.0), (unsigned)(plane[2] * 100.0), (unsigned)(plane[3] * 100.0)));
6119 AssertReturn(index < SVGA3D_CLIPPLANE_MAX, VERR_INVALID_PARAMETER);
6120
6121 PVMSVGA3DCONTEXT pContext;
6122 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6123 AssertRCReturn(rc, rc);
6124
6125 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6126
6127 /* Store for vm state save/restore. */
6128 pContext->state.aClipPlane[index].fValid = true;
6129 memcpy(pContext->state.aClipPlane[index].plane, plane, sizeof(pContext->state.aClipPlane[index].plane));
6130
6131 /** @todo clip plane affected by model view in OpenGL & view in D3D + vertex shader -> not transformed (see Wine; state.c clipplane) */
6132 oglPlane[0] = (double)plane[0];
6133 oglPlane[1] = (double)plane[1];
6134 oglPlane[2] = (double)plane[2];
6135 oglPlane[3] = (double)plane[3];
6136
6137 glClipPlane(GL_CLIP_PLANE0 + index, oglPlane);
6138 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6139
6140 return VINF_SUCCESS;
6141}
6142
6143int vmsvga3dSetScissorRect(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6144{
6145 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6146 AssertReturn(pState, VERR_NO_MEMORY);
6147
6148 Log(("vmsvga3dSetScissorRect cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6149
6150 PVMSVGA3DCONTEXT pContext;
6151 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6152 AssertRCReturn(rc, rc);
6153
6154 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6155
6156 /* Store for vm state save/restore. */
6157 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_SCISSORRECT;
6158 pContext->state.RectScissor = *pRect;
6159
6160 glScissor(pRect->x, pRect->y, pRect->w, pRect->h);
6161 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6162
6163 return VINF_SUCCESS;
6164}
6165
6166static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha)
6167{
6168 /* Convert byte color components to float (0-1.0) */
6169 *pAlpha = (GLfloat)(color >> 24) / 255.0;
6170 *pRed = (GLfloat)((color >> 16) & 0xff) / 255.0;
6171 *pGreen = (GLfloat)((color >> 8) & 0xff) / 255.0;
6172 *pBlue = (GLfloat)(color & 0xff) / 255.0;
6173}
6174
6175int vmsvga3dCommandClear(PVGASTATECC pThisCC, uint32_t cid, SVGA3dClearFlag clearFlag, uint32_t color, float depth, uint32_t stencil,
6176 uint32_t cRects, SVGA3dRect *pRect)
6177{
6178 GLbitfield mask = 0;
6179 GLbitfield restoreMask = 0;
6180 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6181 AssertReturn(pState, VERR_NO_MEMORY);
6182 GLboolean fDepthWriteEnabled = GL_FALSE;
6183 GLboolean afColorWriteEnabled[4] = { GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE };
6184
6185 Log(("vmsvga3dCommandClear cid=%u clearFlag=%x color=%x depth=%d stencil=%x cRects=%d\n", cid, clearFlag, color, (uint32_t)(depth * 100.0), stencil, cRects));
6186
6187 PVMSVGA3DCONTEXT pContext;
6188 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6189 AssertRCReturn(rc, rc);
6190
6191 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6192
6193 if (clearFlag & SVGA3D_CLEAR_COLOR)
6194 {
6195 GLfloat red, green, blue, alpha;
6196 vmsvgaColor2GLFloatArray(color, &red, &green, &blue, &alpha);
6197
6198 /* Set the color clear value. */
6199 glClearColor(red, green, blue, alpha);
6200 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6201
6202 mask |= GL_COLOR_BUFFER_BIT;
6203
6204 /* glClear will not clear the color buffer if writing is disabled. */
6205 glGetBooleanv(GL_COLOR_WRITEMASK, afColorWriteEnabled);
6206 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6207 if ( afColorWriteEnabled[0] == GL_FALSE
6208 || afColorWriteEnabled[1] == GL_FALSE
6209 || afColorWriteEnabled[2] == GL_FALSE
6210 || afColorWriteEnabled[3] == GL_FALSE)
6211 {
6212 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
6213 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6214
6215 restoreMask |= GL_COLOR_BUFFER_BIT;
6216 }
6217
6218 }
6219
6220 if (clearFlag & SVGA3D_CLEAR_STENCIL)
6221 {
6222 /** @todo possibly the same problem as with glDepthMask */
6223 glClearStencil(stencil);
6224 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6225
6226 mask |= GL_STENCIL_BUFFER_BIT;
6227 }
6228
6229 if (clearFlag & SVGA3D_CLEAR_DEPTH)
6230 {
6231 glClearDepth((GLdouble)depth);
6232 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6233
6234 mask |= GL_DEPTH_BUFFER_BIT;
6235
6236 /* glClear will not clear the depth buffer if writing is disabled. */
6237 glGetBooleanv(GL_DEPTH_WRITEMASK, &fDepthWriteEnabled);
6238 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6239 if (fDepthWriteEnabled == GL_FALSE)
6240 {
6241 glDepthMask(GL_TRUE);
6242 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6243
6244 restoreMask |= GL_DEPTH_BUFFER_BIT;
6245 }
6246 }
6247
6248 /* Save the current scissor test bit and scissor box. */
6249 glPushAttrib(GL_SCISSOR_BIT);
6250 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6251
6252 if (cRects)
6253 {
6254 glEnable(GL_SCISSOR_TEST);
6255 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6256
6257 for (uint32_t i = 0; i < cRects; ++i)
6258 {
6259 LogFunc(("rect [%d] %d,%d %dx%d)\n", i, pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h));
6260 glScissor(pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h);
6261 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6262
6263 glClear(mask);
6264 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6265 }
6266 }
6267 else
6268 {
6269 glDisable(GL_SCISSOR_TEST);
6270 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6271
6272 glClear(mask);
6273 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6274 }
6275
6276 /* Restore the old scissor test bit and box */
6277 glPopAttrib();
6278 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6279
6280 /* Restore the write states. */
6281 if (restoreMask & GL_COLOR_BUFFER_BIT)
6282 {
6283 glColorMask(afColorWriteEnabled[0],
6284 afColorWriteEnabled[1],
6285 afColorWriteEnabled[2],
6286 afColorWriteEnabled[3]);
6287 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6288 }
6289
6290 if (restoreMask & GL_DEPTH_BUFFER_BIT)
6291 {
6292 glDepthMask(fDepthWriteEnabled);
6293 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6294 }
6295
6296 return VINF_SUCCESS;
6297}
6298
6299/* Convert VMWare vertex declaration to its OpenGL equivalent. */
6300int vmsvga3dVertexDecl2OGL(SVGA3dVertexArrayIdentity &identity, GLint &size, GLenum &type, GLboolean &normalized, uint32_t &cbAttrib)
6301{
6302 normalized = GL_FALSE;
6303 switch (identity.type)
6304 {
6305 case SVGA3D_DECLTYPE_FLOAT1:
6306 size = 1;
6307 type = GL_FLOAT;
6308 cbAttrib = sizeof(float);
6309 break;
6310 case SVGA3D_DECLTYPE_FLOAT2:
6311 size = 2;
6312 type = GL_FLOAT;
6313 cbAttrib = 2 * sizeof(float);
6314 break;
6315 case SVGA3D_DECLTYPE_FLOAT3:
6316 size = 3;
6317 type = GL_FLOAT;
6318 cbAttrib = 3 * sizeof(float);
6319 break;
6320 case SVGA3D_DECLTYPE_FLOAT4:
6321 size = 4;
6322 type = GL_FLOAT;
6323 cbAttrib = 4 * sizeof(float);
6324 break;
6325
6326 case SVGA3D_DECLTYPE_D3DCOLOR:
6327 size = GL_BGRA; /* @note requires GL_ARB_vertex_array_bgra */
6328 type = GL_UNSIGNED_BYTE;
6329 normalized = GL_TRUE; /* glVertexAttribPointer fails otherwise */
6330 cbAttrib = sizeof(uint32_t);
6331 break;
6332
6333 case SVGA3D_DECLTYPE_UBYTE4N:
6334 normalized = GL_TRUE;
6335 RT_FALL_THRU();
6336 case SVGA3D_DECLTYPE_UBYTE4:
6337 size = 4;
6338 type = GL_UNSIGNED_BYTE;
6339 cbAttrib = sizeof(uint32_t);
6340 break;
6341
6342 case SVGA3D_DECLTYPE_SHORT2N:
6343 normalized = GL_TRUE;
6344 RT_FALL_THRU();
6345 case SVGA3D_DECLTYPE_SHORT2:
6346 size = 2;
6347 type = GL_SHORT;
6348 cbAttrib = 2 * sizeof(uint16_t);
6349 break;
6350
6351 case SVGA3D_DECLTYPE_SHORT4N:
6352 normalized = GL_TRUE;
6353 RT_FALL_THRU();
6354 case SVGA3D_DECLTYPE_SHORT4:
6355 size = 4;
6356 type = GL_SHORT;
6357 cbAttrib = 4 * sizeof(uint16_t);
6358 break;
6359
6360 case SVGA3D_DECLTYPE_USHORT4N:
6361 normalized = GL_TRUE;
6362 size = 4;
6363 type = GL_UNSIGNED_SHORT;
6364 cbAttrib = 4 * sizeof(uint16_t);
6365 break;
6366
6367 case SVGA3D_DECLTYPE_USHORT2N:
6368 normalized = GL_TRUE;
6369 size = 2;
6370 type = GL_UNSIGNED_SHORT;
6371 cbAttrib = 2 * sizeof(uint16_t);
6372 break;
6373
6374 case SVGA3D_DECLTYPE_UDEC3:
6375 size = 3;
6376 type = GL_UNSIGNED_INT_2_10_10_10_REV; /** @todo correct? */
6377 cbAttrib = sizeof(uint32_t);
6378 break;
6379
6380 case SVGA3D_DECLTYPE_DEC3N:
6381 normalized = true;
6382 size = 3;
6383 type = GL_INT_2_10_10_10_REV; /** @todo correct? */
6384 cbAttrib = sizeof(uint32_t);
6385 break;
6386
6387 case SVGA3D_DECLTYPE_FLOAT16_2:
6388 size = 2;
6389 type = GL_HALF_FLOAT;
6390 cbAttrib = 2 * sizeof(uint16_t);
6391 break;
6392 case SVGA3D_DECLTYPE_FLOAT16_4:
6393 size = 4;
6394 type = GL_HALF_FLOAT;
6395 cbAttrib = 4 * sizeof(uint16_t);
6396 break;
6397 default:
6398 AssertFailedReturn(VERR_INVALID_PARAMETER);
6399 }
6400
6401 //pVertexElement->Method = identity.method;
6402 //pVertexElement->Usage = identity.usage;
6403
6404 return VINF_SUCCESS;
6405}
6406
6407static float vmsvga3dFloat16To32(uint16_t f16)
6408{
6409 /* From Wiki */
6410#ifndef INFINITY
6411 static uint32_t const sBitsINFINITY = UINT32_C(0x7f800000);
6412 #define INFINITY (*(float const *)&sBitsINFINITY)
6413#endif
6414#ifndef NAN
6415 static uint32_t const sBitsNAN = UINT32_C(0x7fc00000);
6416 #define NAN (*(float const *)&sBitsNAN)
6417#endif
6418
6419 uint16_t const s = (f16 >> UINT16_C(15)) & UINT16_C(0x1);
6420 uint16_t const e = (f16 >> UINT16_C(10)) & UINT16_C(0x1f);
6421 uint16_t const m = (f16 ) & UINT16_C(0x3ff);
6422
6423 float result = s ? 1.0f : -1.0f;
6424 if (e == 0)
6425 {
6426 if (m == 0)
6427 result *= 0.0f; /* zero, -0 */
6428 else
6429 result *= (float)m / 1024.0f / 16384.0f; /* subnormal numbers: sign * 2^-14 * 0.m */
6430 }
6431 else if (e == 0x1f)
6432 {
6433 if (m == 0)
6434 result *= INFINITY; /* +-infinity */
6435 else
6436 result = NAN; /* NAN */
6437 }
6438 else
6439 {
6440 result *= powf(2.0f, (float)e - 15.0f) * (1.0f + (float)m / 1024.0f); /* sign * 2^(e-15) * 1.m */
6441 }
6442
6443 return result;
6444}
6445
6446/* Set a vertex attribute according to VMSVGA vertex declaration. */
6447static int vmsvga3dSetVertexAttrib(PVMSVGA3DSTATE pState, GLuint index, SVGA3dVertexArrayIdentity const *pIdentity, GLvoid const *pv)
6448{
6449 switch (pIdentity->type)
6450 {
6451 case SVGA3D_DECLTYPE_FLOAT1:
6452 {
6453 /* "One-component float expanded to (float, 0, 0, 1)." */
6454 GLfloat const *p = (GLfloat *)pv;
6455 GLfloat const v[4] = { p[0], 0.0f, 0.0f, 1.0f };
6456 pState->ext.glVertexAttrib4fv(index, v);
6457 break;
6458 }
6459 case SVGA3D_DECLTYPE_FLOAT2:
6460 {
6461 /* "Two-component float expanded to (float, float, 0, 1)." */
6462 GLfloat const *p = (GLfloat *)pv;
6463 GLfloat const v[4] = { p[0], p[1], 0.0f, 1.0f };
6464 pState->ext.glVertexAttrib4fv(index, v);
6465 break;
6466 }
6467 case SVGA3D_DECLTYPE_FLOAT3:
6468 {
6469 /* "Three-component float expanded to (float, float, float, 1)." */
6470 GLfloat const *p = (GLfloat *)pv;
6471 GLfloat const v[4] = { p[0], p[1], p[2], 1.0f };
6472 pState->ext.glVertexAttrib4fv(index, v);
6473 break;
6474 }
6475 case SVGA3D_DECLTYPE_FLOAT4:
6476 pState->ext.glVertexAttrib4fv(index, (GLfloat const *)pv);
6477 break;
6478 case SVGA3D_DECLTYPE_D3DCOLOR:
6479 /** @todo Need to swap bytes? */
6480 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6481 break;
6482 case SVGA3D_DECLTYPE_UBYTE4:
6483 pState->ext.glVertexAttrib4ubv(index, (GLubyte const *)pv);
6484 break;
6485 case SVGA3D_DECLTYPE_SHORT2:
6486 {
6487 /* "Two-component, signed short expanded to (value, value, 0, 1)." */
6488 GLshort const *p = (GLshort const *)pv;
6489 GLshort const v[4] = { p[0], p[1], 0, 1 };
6490 pState->ext.glVertexAttrib4sv(index, v);
6491 break;
6492 }
6493 case SVGA3D_DECLTYPE_SHORT4:
6494 pState->ext.glVertexAttrib4sv(index, (GLshort const *)pv);
6495 break;
6496 case SVGA3D_DECLTYPE_UBYTE4N:
6497 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6498 break;
6499 case SVGA3D_DECLTYPE_SHORT2N:
6500 {
6501 /* "Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1)." */
6502 GLshort const *p = (GLshort const *)pv;
6503 GLshort const v[4] = { p[0], p[1], 0, 1 };
6504 pState->ext.glVertexAttrib4Nsv(index, v);
6505 break;
6506 }
6507 case SVGA3D_DECLTYPE_SHORT4N:
6508 pState->ext.glVertexAttrib4Nsv(index, (GLshort const *)pv);
6509 break;
6510 case SVGA3D_DECLTYPE_USHORT2N:
6511 {
6512 GLushort const *p = (GLushort const *)pv;
6513 GLushort const v[4] = { p[0], p[1], 0, 1 };
6514 pState->ext.glVertexAttrib4Nusv(index, v);
6515 break;
6516 }
6517 case SVGA3D_DECLTYPE_USHORT4N:
6518 pState->ext.glVertexAttrib4Nusv(index, (GLushort const *)pv);
6519 break;
6520 case SVGA3D_DECLTYPE_UDEC3:
6521 {
6522 /** @todo Test */
6523 /* "Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1)." */
6524 uint32_t const u32 = *(uint32_t *)pv;
6525 GLfloat const v[4] = { (float)(u32 & 0x3ff), (float)((u32 >> 10) & 0x3ff), (float)((u32 >> 20) & 0x3ff), 1.0f };
6526 pState->ext.glVertexAttrib4fv(index, v);
6527 break;
6528 }
6529 case SVGA3D_DECLTYPE_DEC3N:
6530 {
6531 /** @todo Test */
6532 /* "Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)." */
6533 uint32_t const u32 = *(uint32_t *)pv;
6534 GLfloat const v[4] = { (u32 & 0x3ff) / 511.0f, ((u32 >> 10) & 0x3ff) / 511.0f, ((u32 >> 20) & 0x3ff) / 511.0f, 1.0f };
6535 pState->ext.glVertexAttrib4fv(index, v);
6536 break;
6537 }
6538 case SVGA3D_DECLTYPE_FLOAT16_2:
6539 {
6540 /** @todo Test */
6541 /* "Two-component, 16-bit, floating point expanded to (value, value, 0, 1)." */
6542 uint16_t const *p = (uint16_t *)pv;
6543 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]), 0.0f, 1.0f };
6544 pState->ext.glVertexAttrib4fv(index, v);
6545 break;
6546 }
6547 case SVGA3D_DECLTYPE_FLOAT16_4:
6548 {
6549 /** @todo Test */
6550 uint16_t const *p = (uint16_t *)pv;
6551 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]),
6552 vmsvga3dFloat16To32(p[2]), vmsvga3dFloat16To32(p[3]) };
6553 pState->ext.glVertexAttrib4fv(index, v);
6554 break;
6555 }
6556 default:
6557 AssertFailedReturn(VERR_INVALID_PARAMETER);
6558 }
6559
6560 return VINF_SUCCESS;
6561}
6562
6563/* Convert VMWare primitive type to its OpenGL equivalent. */
6564/* Calculate the vertex count based on the primitive type and nr of primitives. */
6565int vmsvga3dPrimitiveType2OGL(SVGA3dPrimitiveType PrimitiveType, GLenum *pMode, uint32_t cPrimitiveCount, uint32_t *pcVertices)
6566{
6567 switch (PrimitiveType)
6568 {
6569 case SVGA3D_PRIMITIVE_TRIANGLELIST:
6570 *pMode = GL_TRIANGLES;
6571 *pcVertices = cPrimitiveCount * 3;
6572 break;
6573 case SVGA3D_PRIMITIVE_POINTLIST:
6574 *pMode = GL_POINTS;
6575 *pcVertices = cPrimitiveCount;
6576 break;
6577 case SVGA3D_PRIMITIVE_LINELIST:
6578 *pMode = GL_LINES;
6579 *pcVertices = cPrimitiveCount * 2;
6580 break;
6581 case SVGA3D_PRIMITIVE_LINESTRIP:
6582 *pMode = GL_LINE_STRIP;
6583 *pcVertices = cPrimitiveCount + 1;
6584 break;
6585 case SVGA3D_PRIMITIVE_TRIANGLESTRIP:
6586 *pMode = GL_TRIANGLE_STRIP;
6587 *pcVertices = cPrimitiveCount + 2;
6588 break;
6589 case SVGA3D_PRIMITIVE_TRIANGLEFAN:
6590 *pMode = GL_TRIANGLE_FAN;
6591 *pcVertices = cPrimitiveCount + 2;
6592 break;
6593 default:
6594 return VERR_INVALID_PARAMETER;
6595 }
6596 return VINF_SUCCESS;
6597}
6598
6599static int vmsvga3dResetTransformMatrices(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
6600{
6601 int rc;
6602
6603 /* Reset the view matrix (also takes the world matrix into account). */
6604 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid == true)
6605 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW,
6606 pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6607 else
6608 {
6609 float matrix[16];
6610
6611 /* identity matrix if no matrix set. */
6612 memset(matrix, 0, sizeof(matrix));
6613 matrix[0] = 1.0;
6614 matrix[5] = 1.0;
6615 matrix[10] = 1.0;
6616 matrix[15] = 1.0;
6617 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW, matrix);
6618 }
6619
6620 /* Reset the projection matrix. */
6621 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6622 {
6623 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6624 }
6625 else
6626 {
6627 float matrix[16];
6628
6629 /* identity matrix if no matrix set. */
6630 memset(matrix, 0, sizeof(matrix));
6631 matrix[0] = 1.0;
6632 matrix[5] = 1.0;
6633 matrix[10] = 1.0;
6634 matrix[15] = 1.0;
6635 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, matrix);
6636 }
6637 AssertRC(rc);
6638 return rc;
6639}
6640
6641static int vmsvga3dDrawPrimitivesProcessVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext,
6642 uint32_t iVertexDeclBase, uint32_t numVertexDecls,
6643 SVGA3dVertexDecl *pVertexDecl,
6644 SVGA3dVertexDivisor const *paVertexDivisors)
6645{
6646 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6647 unsigned const sidVertex = pVertexDecl[0].array.surfaceId;
6648
6649 PVMSVGA3DSURFACE pVertexSurface;
6650 int rc = vmsvga3dSurfaceFromSid(pState, sidVertex, &pVertexSurface);
6651 AssertRCReturn(rc, rc);
6652
6653 Log(("vmsvga3dDrawPrimitives: vertex surface sid=%u\n", sidVertex));
6654
6655 /* Create and/or bind the vertex buffer. */
6656 if (pVertexSurface->oglId.buffer == OPENGL_INVALID_ID)
6657 {
6658 Log(("vmsvga3dDrawPrimitives: create vertex buffer fDirty=%d size=%x bytes\n", pVertexSurface->fDirty, pVertexSurface->paMipmapLevels[0].cbSurface));
6659 PVMSVGA3DCONTEXT pSavedCtx = pContext;
6660 pContext = &pState->SharedCtx;
6661 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6662
6663 pState->ext.glGenBuffers(1, &pVertexSurface->oglId.buffer);
6664 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6665 pVertexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
6666
6667 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6668 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6669
6670 Assert(pVertexSurface->fDirty);
6671 /** @todo rethink usage dynamic/static */
6672 pState->ext.glBufferData(GL_ARRAY_BUFFER, pVertexSurface->paMipmapLevels[0].cbSurface, pVertexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
6673 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6674
6675 pVertexSurface->paMipmapLevels[0].fDirty = false;
6676 pVertexSurface->fDirty = false;
6677
6678 pVertexSurface->surfaceFlags |= SVGA3D_SURFACE_HINT_VERTEXBUFFER;
6679
6680 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, OPENGL_INVALID_ID);
6681 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6682
6683 pContext = pSavedCtx;
6684 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6685 }
6686
6687 Assert(pVertexSurface->fDirty == false);
6688 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6689 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6690
6691 /* Setup the vertex declarations. */
6692 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6693 {
6694 GLint size;
6695 GLenum type;
6696 GLboolean normalized;
6697 uint32_t cbAttrib;
6698 GLuint index = iVertexDeclBase + iVertex;
6699
6700 Log(("vmsvga3dDrawPrimitives: array index %d type=%s (%d) method=%s (%d) usage=%s (%d) usageIndex=%d stride=%d offset=%d\n", index, vmsvgaDeclType2String(pVertexDecl[iVertex].identity.type), pVertexDecl[iVertex].identity.type, vmsvgaDeclMethod2String(pVertexDecl[iVertex].identity.method), pVertexDecl[iVertex].identity.method, vmsvgaDeclUsage2String(pVertexDecl[iVertex].identity.usage), pVertexDecl[iVertex].identity.usage, pVertexDecl[iVertex].identity.usageIndex, pVertexDecl[iVertex].array.stride, pVertexDecl[iVertex].array.offset));
6701
6702 rc = vmsvga3dVertexDecl2OGL(pVertexDecl[iVertex].identity, size, type, normalized, cbAttrib);
6703 AssertRCReturn(rc, rc);
6704
6705 ASSERT_GUEST_RETURN( pVertexSurface->paMipmapLevels[0].cbSurface >= pVertexDecl[iVertex].array.offset
6706 && pVertexSurface->paMipmapLevels[0].cbSurface - pVertexDecl[iVertex].array.offset >= cbAttrib,
6707 VERR_INVALID_PARAMETER);
6708 RT_UNTRUSTED_VALIDATED_FENCE();
6709
6710 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6711 {
6712 /* Use numbered vertex arrays (or attributes) when shaders are active. */
6713 if (pVertexDecl[iVertex].array.stride)
6714 {
6715 pState->ext.glEnableVertexAttribArray(index);
6716 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6717 pState->ext.glVertexAttribPointer(index, size, type, normalized, pVertexDecl[iVertex].array.stride,
6718 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6719 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6720
6721 GLuint divisor = paVertexDivisors && paVertexDivisors[index].s.instanceData ? 1 : 0;
6722 pState->ext.glVertexAttribDivisor(index, divisor);
6723 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6724
6725 /** @todo case SVGA3D_DECLUSAGE_COLOR: color component order not identical!! test GL_BGRA!! */
6726 }
6727 else
6728 {
6729 /*
6730 * D3D and OpenGL have a different meaning of value zero for the vertex array stride:
6731 * - D3D (VMSVGA): "use a zero stride to tell the runtime not to increment the vertex buffer offset."
6732 * - OpenGL: "If stride is 0, the generic vertex attributes are understood to be tightly packed in the array."
6733 * VMSVGA uses the D3D semantics.
6734 *
6735 * Use glVertexAttrib in order to tell OpenGL to reuse the zero stride attributes for each vertex.
6736 */
6737 pState->ext.glDisableVertexAttribArray(index);
6738 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6739
6740 const GLvoid *v = (uint8_t *)pVertexSurface->paMipmapLevels[0].pSurfaceData + pVertexDecl[iVertex].array.offset;
6741 vmsvga3dSetVertexAttrib(pState, index, &pVertexDecl[iVertex].identity, v);
6742 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6743 }
6744 }
6745 else
6746 {
6747 if (pVertexDecl[iVertex].array.stride == 0)
6748 {
6749 /* Zero stride means that the attribute pointer must not be increased.
6750 * See comment about stride in vmsvga3dDrawPrimitives.
6751 */
6752 LogRelMax(8, ("VMSVGA: Warning: zero stride array in fixed function pipeline\n"));
6753 AssertFailed();
6754 }
6755
6756 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6757 switch (pVertexDecl[iVertex].identity.usage)
6758 {
6759 case SVGA3D_DECLUSAGE_POSITIONT:
6760 case SVGA3D_DECLUSAGE_POSITION:
6761 {
6762 glEnableClientState(GL_VERTEX_ARRAY);
6763 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6764 glVertexPointer(size, type, pVertexDecl[iVertex].array.stride,
6765 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6766 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6767 break;
6768 }
6769 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6770 AssertFailed();
6771 break;
6772 case SVGA3D_DECLUSAGE_BLENDINDICES:
6773 AssertFailed();
6774 break;
6775 case SVGA3D_DECLUSAGE_NORMAL:
6776 glEnableClientState(GL_NORMAL_ARRAY);
6777 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6778 glNormalPointer(type, pVertexDecl[iVertex].array.stride,
6779 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6780 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6781 break;
6782 case SVGA3D_DECLUSAGE_PSIZE:
6783 AssertFailed();
6784 break;
6785 case SVGA3D_DECLUSAGE_TEXCOORD:
6786 /* Specify the affected texture unit. */
6787#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6788 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6789#else
6790 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6791#endif
6792 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
6793 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6794 glTexCoordPointer(size, type, pVertexDecl[iVertex].array.stride,
6795 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6796 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6797 break;
6798 case SVGA3D_DECLUSAGE_TANGENT:
6799 AssertFailed();
6800 break;
6801 case SVGA3D_DECLUSAGE_BINORMAL:
6802 AssertFailed();
6803 break;
6804 case SVGA3D_DECLUSAGE_TESSFACTOR:
6805 AssertFailed();
6806 break;
6807 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! test GL_BGRA!! */
6808 glEnableClientState(GL_COLOR_ARRAY);
6809 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6810 glColorPointer(size, type, pVertexDecl[iVertex].array.stride,
6811 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6812 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6813 break;
6814 case SVGA3D_DECLUSAGE_FOG:
6815 glEnableClientState(GL_FOG_COORD_ARRAY);
6816 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6817 pState->ext.glFogCoordPointer(type, pVertexDecl[iVertex].array.stride,
6818 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6819 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6820 break;
6821 case SVGA3D_DECLUSAGE_DEPTH:
6822 AssertFailed();
6823 break;
6824 case SVGA3D_DECLUSAGE_SAMPLE:
6825 AssertFailed();
6826 break;
6827 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
6828 }
6829 }
6830
6831#ifdef LOG_ENABLED
6832 if (pVertexDecl[iVertex].array.stride == 0)
6833 Log(("vmsvga3dDrawPrimitives: stride == 0! Can be valid\n"));
6834#endif
6835 }
6836
6837 return VINF_SUCCESS;
6838}
6839
6840static int vmsvga3dDrawPrimitivesCleanupVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t iVertexDeclBase,
6841 uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl)
6842{
6843 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6844
6845 /* Clean up the vertex declarations. */
6846 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6847 {
6848 if (pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT)
6849 {
6850 /* Reset the transformation matrices in case of a switch back from pretransformed mode. */
6851 Log(("vmsvga3dDrawPrimitivesCleanupVertexDecls: reset world and projection matrices after transformation reset (pre-transformed -> transformed)\n"));
6852 vmsvga3dResetTransformMatrices(pThisCC, pContext);
6853 }
6854
6855 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6856 {
6857 /* Use numbered vertex arrays when shaders are active. */
6858 pState->ext.glVertexAttribDivisor(iVertexDeclBase + iVertex, 0);
6859 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6860 pState->ext.glDisableVertexAttribArray(iVertexDeclBase + iVertex);
6861 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6862 }
6863 else
6864 {
6865 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6866 switch (pVertexDecl[iVertex].identity.usage)
6867 {
6868 case SVGA3D_DECLUSAGE_POSITION:
6869 case SVGA3D_DECLUSAGE_POSITIONT:
6870 glDisableClientState(GL_VERTEX_ARRAY);
6871 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6872 break;
6873 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6874 break;
6875 case SVGA3D_DECLUSAGE_BLENDINDICES:
6876 break;
6877 case SVGA3D_DECLUSAGE_NORMAL:
6878 glDisableClientState(GL_NORMAL_ARRAY);
6879 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6880 break;
6881 case SVGA3D_DECLUSAGE_PSIZE:
6882 break;
6883 case SVGA3D_DECLUSAGE_TEXCOORD:
6884 /* Specify the affected texture unit. */
6885#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6886 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6887#else
6888 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6889#endif
6890 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
6891 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6892 break;
6893 case SVGA3D_DECLUSAGE_TANGENT:
6894 break;
6895 case SVGA3D_DECLUSAGE_BINORMAL:
6896 break;
6897 case SVGA3D_DECLUSAGE_TESSFACTOR:
6898 break;
6899 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! */
6900 glDisableClientState(GL_COLOR_ARRAY);
6901 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6902 break;
6903 case SVGA3D_DECLUSAGE_FOG:
6904 glDisableClientState(GL_FOG_COORD_ARRAY);
6905 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6906 break;
6907 case SVGA3D_DECLUSAGE_DEPTH:
6908 break;
6909 case SVGA3D_DECLUSAGE_SAMPLE:
6910 break;
6911 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
6912 }
6913 }
6914 }
6915 /* Unbind the vertex buffer after usage. */
6916 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
6917 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6918 return VINF_SUCCESS;
6919}
6920
6921int vmsvga3dDrawPrimitives(PVGASTATECC pThisCC, uint32_t cid, uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl,
6922 uint32_t numRanges, SVGA3dPrimitiveRange *pRange, uint32_t cVertexDivisor,
6923 SVGA3dVertexDivisor *pVertexDivisor)
6924{
6925 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6926 AssertReturn(pState, VERR_INTERNAL_ERROR);
6927 uint32_t iCurrentVertex;
6928
6929 Log(("vmsvga3dDrawPrimitives cid=%u numVertexDecls=%d numRanges=%d, cVertexDivisor=%d\n", cid, numVertexDecls, numRanges, cVertexDivisor));
6930
6931 /* Caller already check these, but it cannot hurt to check again... */
6932 AssertReturn(numVertexDecls && numVertexDecls <= SVGA3D_MAX_VERTEX_ARRAYS, VERR_INVALID_PARAMETER);
6933 AssertReturn(numRanges && numRanges <= SVGA3D_MAX_DRAW_PRIMITIVE_RANGES, VERR_INVALID_PARAMETER);
6934 AssertReturn(!cVertexDivisor || cVertexDivisor == numVertexDecls, VERR_INVALID_PARAMETER);
6935
6936 if (!cVertexDivisor)
6937 pVertexDivisor = NULL; /* Be sure. */
6938
6939 PVMSVGA3DCONTEXT pContext;
6940 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6941 AssertRCReturn(rc, rc);
6942
6943 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6944
6945 /* Check for pretransformed vertex declarations. */
6946 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6947 {
6948 switch (pVertexDecl[iVertex].identity.usage)
6949 {
6950 case SVGA3D_DECLUSAGE_POSITIONT:
6951 Log(("ShaderSetPositionTransformed: (%d,%d)\n", pContext->state.RectViewPort.w, pContext->state.RectViewPort.h));
6952 RT_FALL_THRU();
6953 case SVGA3D_DECLUSAGE_POSITION:
6954 ShaderSetPositionTransformed(pContext->pShaderContext, pContext->state.RectViewPort.w,
6955 pContext->state.RectViewPort.h,
6956 pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT);
6957 break;
6958 default: /* Shut up MSC. */ break;
6959 }
6960 }
6961
6962 /* Flush any shader changes; after (!) checking the vertex declarations to deal with pre-transformed vertices. */
6963 if (pContext->pShaderContext)
6964 {
6965 uint32_t rtHeight = 0;
6966
6967 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA_ID_INVALID)
6968 {
6969 PVMSVGA3DSURFACE pRenderTarget;
6970 rc = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pRenderTarget);
6971 AssertRCReturn(rc, rc);
6972
6973 rtHeight = pRenderTarget->paMipmapLevels[0].mipmapSize.height;
6974 }
6975
6976 ShaderUpdateState(pContext->pShaderContext, rtHeight);
6977 }
6978
6979 /* Try to figure out if instancing is used.
6980 * Support simple instancing case with one set of indexed data and one set per-instance data.
6981 */
6982 uint32_t cInstances = 0;
6983 for (uint32_t iVertexDivisor = 0; iVertexDivisor < cVertexDivisor; ++iVertexDivisor)
6984 {
6985 if (pVertexDivisor[iVertexDivisor].s.indexedData)
6986 {
6987 if (cInstances == 0)
6988 cInstances = pVertexDivisor[iVertexDivisor].s.count;
6989 else
6990 Assert(cInstances == pVertexDivisor[iVertexDivisor].s.count);
6991 }
6992 else if (pVertexDivisor[iVertexDivisor].s.instanceData)
6993 {
6994 Assert(pVertexDivisor[iVertexDivisor].s.count == 1);
6995 }
6996 }
6997
6998 /* Process all vertex declarations. Each vertex buffer is represented by one stream. */
6999 iCurrentVertex = 0;
7000 while (iCurrentVertex < numVertexDecls)
7001 {
7002 uint32_t sidVertex = SVGA_ID_INVALID;
7003 uint32_t iVertex;
7004
7005 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7006 {
7007 if ( sidVertex != SVGA_ID_INVALID
7008 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7009 )
7010 break;
7011 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7012 }
7013
7014 rc = vmsvga3dDrawPrimitivesProcessVertexDecls(pThisCC, pContext, iCurrentVertex, iVertex - iCurrentVertex,
7015 &pVertexDecl[iCurrentVertex], pVertexDivisor);
7016 AssertRCReturn(rc, rc);
7017
7018 iCurrentVertex = iVertex;
7019 }
7020
7021 /* Now draw the primitives. */
7022 for (unsigned iPrimitive = 0; iPrimitive < numRanges; iPrimitive++)
7023 {
7024 GLenum modeDraw;
7025 unsigned const sidIndex = pRange[iPrimitive].indexArray.surfaceId;
7026 PVMSVGA3DSURFACE pIndexSurface = NULL;
7027 unsigned cVertices;
7028
7029 Log(("Primitive %d: type %s\n", iPrimitive, vmsvga3dPrimitiveType2String(pRange[iPrimitive].primType)));
7030 rc = vmsvga3dPrimitiveType2OGL(pRange[iPrimitive].primType, &modeDraw, pRange[iPrimitive].primitiveCount, &cVertices);
7031 if (RT_FAILURE(rc))
7032 {
7033 AssertRC(rc);
7034 goto internal_error;
7035 }
7036
7037 if (sidIndex != SVGA3D_INVALID_ID)
7038 {
7039 AssertMsg(pRange[iPrimitive].indexWidth == sizeof(uint32_t) || pRange[iPrimitive].indexWidth == sizeof(uint16_t), ("Unsupported primitive width %d\n", pRange[iPrimitive].indexWidth));
7040
7041 rc = vmsvga3dSurfaceFromSid(pState, sidIndex, &pIndexSurface);
7042 if (RT_FAILURE(rc))
7043 {
7044 AssertRC(rc);
7045 goto internal_error;
7046 }
7047
7048 Log(("vmsvga3dDrawPrimitives: index surface sid=%u\n", sidIndex));
7049
7050 if (pIndexSurface->oglId.buffer == OPENGL_INVALID_ID)
7051 {
7052 Log(("vmsvga3dDrawPrimitives: create index buffer fDirty=%d size=%x bytes\n", pIndexSurface->fDirty, pIndexSurface->paMipmapLevels[0].cbSurface));
7053 pContext = &pState->SharedCtx;
7054 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7055
7056 pState->ext.glGenBuffers(1, &pIndexSurface->oglId.buffer);
7057 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7058 pIndexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
7059
7060 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7061 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7062
7063 Assert(pIndexSurface->fDirty);
7064
7065 /** @todo rethink usage dynamic/static */
7066 pState->ext.glBufferData(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->paMipmapLevels[0].cbSurface, pIndexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
7067 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7068
7069 pIndexSurface->paMipmapLevels[0].fDirty = false;
7070 pIndexSurface->fDirty = false;
7071
7072 pIndexSurface->surfaceFlags |= SVGA3D_SURFACE_HINT_INDEXBUFFER;
7073
7074 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, OPENGL_INVALID_ID);
7075 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7076
7077 pContext = pState->papContexts[cid];
7078 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7079 }
7080 Assert(pIndexSurface->fDirty == false);
7081
7082 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7083 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7084 }
7085
7086 if (!pIndexSurface)
7087 {
7088 /* Render without an index buffer */
7089 Log(("DrawPrimitive %d cPrimitives=%d cVertices=%d index index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pRange[iPrimitive].indexBias, cInstances));
7090 if (cInstances == 0)
7091 {
7092 glDrawArrays(modeDraw, pRange[iPrimitive].indexBias, cVertices);
7093 }
7094 else
7095 {
7096 pState->ext.glDrawArraysInstanced(modeDraw, pRange[iPrimitive].indexBias, cVertices, cInstances);
7097 }
7098 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7099 }
7100 else
7101 {
7102 Assert(pRange[iPrimitive].indexWidth == pRange[iPrimitive].indexArray.stride);
7103
7104 GLenum indexType;
7105 switch (pRange[iPrimitive].indexWidth)
7106 {
7107 case 1: indexType = GL_UNSIGNED_BYTE; break;
7108 case 2: indexType = GL_UNSIGNED_SHORT; break;
7109 default: AssertMsgFailed(("indexWidth %d\n", pRange[iPrimitive].indexWidth));
7110 RT_FALL_THROUGH();
7111 case 4: indexType = GL_UNSIGNED_INT; break;
7112 }
7113
7114 Log(("DrawIndexedPrimitive %d cPrimitives=%d cVertices=%d hint.first=%d hint.last=%d index offset=%d primitivecount=%d index width=%d index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pVertexDecl[0].rangeHint.first, pVertexDecl[0].rangeHint.last, pRange[iPrimitive].indexArray.offset, pRange[iPrimitive].primitiveCount, pRange[iPrimitive].indexWidth, pRange[iPrimitive].indexBias, cInstances));
7115 if (cInstances == 0)
7116 {
7117 /* Render with an index buffer */
7118 if (pRange[iPrimitive].indexBias == 0)
7119 glDrawElements(modeDraw,
7120 cVertices,
7121 indexType,
7122 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset); /* byte offset in indices buffer */
7123 else
7124 pState->ext.glDrawElementsBaseVertex(modeDraw,
7125 cVertices,
7126 indexType,
7127 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7128 pRange[iPrimitive].indexBias); /* basevertex */
7129 }
7130 else
7131 {
7132 /* Render with an index buffer */
7133 if (pRange[iPrimitive].indexBias == 0)
7134 pState->ext.glDrawElementsInstanced(modeDraw,
7135 cVertices,
7136 indexType,
7137 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7138 cInstances);
7139 else
7140 pState->ext.glDrawElementsInstancedBaseVertex(modeDraw,
7141 cVertices,
7142 indexType,
7143 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7144 cInstances,
7145 pRange[iPrimitive].indexBias); /* basevertex */
7146 }
7147 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7148
7149 /* Unbind the index buffer after usage. */
7150 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
7151 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7152 }
7153 }
7154
7155internal_error:
7156
7157 /* Deactivate the vertex declarations. */
7158 iCurrentVertex = 0;
7159 while (iCurrentVertex < numVertexDecls)
7160 {
7161 uint32_t sidVertex = SVGA_ID_INVALID;
7162 uint32_t iVertex;
7163
7164 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7165 {
7166 if ( sidVertex != SVGA_ID_INVALID
7167 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7168 )
7169 break;
7170 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7171 }
7172
7173 rc = vmsvga3dDrawPrimitivesCleanupVertexDecls(pThisCC, pContext, iCurrentVertex,
7174 iVertex - iCurrentVertex, &pVertexDecl[iCurrentVertex]);
7175 AssertRCReturn(rc, rc);
7176
7177 iCurrentVertex = iVertex;
7178 }
7179
7180#ifdef DEBUG
7181 /* Check whether 'activeTexture' on texture unit 'i' matches what we expect. */
7182 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); ++i)
7183 {
7184 if (pContext->aSidActiveTextures[i] != SVGA3D_INVALID_ID)
7185 {
7186 PVMSVGA3DSURFACE pTexture;
7187 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[i], &pTexture);
7188 AssertContinue(RT_SUCCESS(rc2));
7189
7190 GLint activeTextureUnit = 0;
7191 glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTextureUnit);
7192 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7193
7194 pState->ext.glActiveTexture(GL_TEXTURE0 + i);
7195 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7196
7197 GLint activeTexture = 0;
7198 glGetIntegerv(pTexture->bindingGL, &activeTexture);
7199 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7200
7201 pState->ext.glActiveTexture(activeTextureUnit);
7202 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7203
7204 AssertMsg(pTexture->oglId.texture == (GLuint)activeTexture,
7205 ("%d vs %d unit %d (active unit %d) sid=%u\n", pTexture->oglId.texture, activeTexture, i,
7206 activeTextureUnit - GL_TEXTURE0, pContext->aSidActiveTextures[i]));
7207 }
7208 }
7209#endif
7210
7211#if 0
7212 /* Dump render target to a bitmap. */
7213 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA3D_INVALID_ID)
7214 {
7215 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0]);
7216 PVMSVGA3DSURFACE pSurface;
7217 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pSurface);
7218 if (RT_SUCCESS(rc2))
7219 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post");
7220# if 0
7221 /* Stage 0 texture. */
7222 if (pContext->aSidActiveTextures[0] != SVGA3D_INVALID_ID)
7223 {
7224 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->aSidActiveTextures[0]);
7225 rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[0], &pSurface);
7226 if (RT_SUCCESS(rc2))
7227 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post-tx");
7228 }
7229# endif
7230 }
7231#endif
7232
7233 return rc;
7234}
7235
7236
7237int vmsvga3dShaderDefine(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type, uint32_t cbData, uint32_t *pShaderData)
7238{
7239 PVMSVGA3DSHADER pShader;
7240 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7241 AssertReturn(pState, VERR_NO_MEMORY);
7242
7243 Log(("vmsvga3dShaderDefine cid=%u shid=%d type=%s cbData=0x%x\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cbData));
7244
7245 PVMSVGA3DCONTEXT pContext;
7246 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7247 AssertRCReturn(rc, rc);
7248
7249 AssertReturn(shid < SVGA3D_MAX_SHADER_IDS, VERR_INVALID_PARAMETER);
7250
7251 rc = vmsvga3dShaderParse(cbData, pShaderData);
7252 if (RT_FAILURE(rc))
7253 {
7254 AssertRC(rc);
7255 vmsvga3dShaderLogRel("Failed to parse", type, cbData, pShaderData);
7256 return rc;
7257 }
7258
7259 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7260
7261 if (type == SVGA3D_SHADERTYPE_VS)
7262 {
7263 if (shid >= pContext->cVertexShaders)
7264 {
7265 void *pvNew = RTMemRealloc(pContext->paVertexShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7266 AssertReturn(pvNew, VERR_NO_MEMORY);
7267 pContext->paVertexShader = (PVMSVGA3DSHADER)pvNew;
7268 memset(&pContext->paVertexShader[pContext->cVertexShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cVertexShaders));
7269 for (uint32_t i = pContext->cVertexShaders; i < shid + 1; i++)
7270 pContext->paVertexShader[i].id = SVGA3D_INVALID_ID;
7271 pContext->cVertexShaders = shid + 1;
7272 }
7273 /* If one already exists with this id, then destroy it now. */
7274 if (pContext->paVertexShader[shid].id != SVGA3D_INVALID_ID)
7275 vmsvga3dShaderDestroy(pThisCC, cid, shid, pContext->paVertexShader[shid].type);
7276
7277 pShader = &pContext->paVertexShader[shid];
7278 }
7279 else
7280 {
7281 Assert(type == SVGA3D_SHADERTYPE_PS);
7282 if (shid >= pContext->cPixelShaders)
7283 {
7284 void *pvNew = RTMemRealloc(pContext->paPixelShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7285 AssertReturn(pvNew, VERR_NO_MEMORY);
7286 pContext->paPixelShader = (PVMSVGA3DSHADER)pvNew;
7287 memset(&pContext->paPixelShader[pContext->cPixelShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cPixelShaders));
7288 for (uint32_t i = pContext->cPixelShaders; i < shid + 1; i++)
7289 pContext->paPixelShader[i].id = SVGA3D_INVALID_ID;
7290 pContext->cPixelShaders = shid + 1;
7291 }
7292 /* If one already exists with this id, then destroy it now. */
7293 if (pContext->paPixelShader[shid].id != SVGA3D_INVALID_ID)
7294 vmsvga3dShaderDestroy(pThisCC, cid, shid, pContext->paPixelShader[shid].type);
7295
7296 pShader = &pContext->paPixelShader[shid];
7297 }
7298
7299 memset(pShader, 0, sizeof(*pShader));
7300 pShader->id = shid;
7301 pShader->cid = cid;
7302 pShader->type = type;
7303 pShader->cbData = cbData;
7304 pShader->pShaderProgram = RTMemAllocZ(cbData);
7305 AssertReturn(pShader->pShaderProgram, VERR_NO_MEMORY);
7306 memcpy(pShader->pShaderProgram, pShaderData, cbData);
7307
7308#ifdef DUMP_SHADER_DISASSEMBLY
7309 LPD3DXBUFFER pDisassembly;
7310 HRESULT hr = D3DXDisassembleShader((const DWORD *)pShaderData, FALSE, NULL, &pDisassembly);
7311 if (hr == D3D_OK)
7312 {
7313 Log(("Shader disassembly:\n%s\n", pDisassembly->GetBufferPointer()));
7314 pDisassembly->Release();
7315 }
7316#endif
7317
7318 switch (type)
7319 {
7320 case SVGA3D_SHADERTYPE_VS:
7321 rc = ShaderCreateVertexShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pVertexShader);
7322 AssertRC(rc);
7323 break;
7324
7325 case SVGA3D_SHADERTYPE_PS:
7326 rc = ShaderCreatePixelShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pPixelShader);
7327 AssertRC(rc);
7328 break;
7329
7330 default:
7331 AssertFailedReturn(VERR_INVALID_PARAMETER);
7332 }
7333 if (rc != VINF_SUCCESS)
7334 {
7335 vmsvga3dShaderLogRel("Failed to create", type, cbData, pShaderData);
7336
7337 RTMemFree(pShader->pShaderProgram);
7338 memset(pShader, 0, sizeof(*pShader));
7339 pShader->id = SVGA3D_INVALID_ID;
7340 }
7341
7342 return rc;
7343}
7344
7345int vmsvga3dShaderDestroy(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type)
7346{
7347 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7348 AssertReturn(pState, VERR_NO_MEMORY);
7349 PVMSVGA3DSHADER pShader = NULL;
7350
7351 Log(("vmsvga3dShaderDestroy cid=%u shid=%d type=%s\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL"));
7352
7353 PVMSVGA3DCONTEXT pContext;
7354 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7355 AssertRCReturn(rc, rc);
7356
7357 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7358
7359 if (type == SVGA3D_SHADERTYPE_VS)
7360 {
7361 if ( shid < pContext->cVertexShaders
7362 && pContext->paVertexShader[shid].id == shid)
7363 {
7364 pShader = &pContext->paVertexShader[shid];
7365 rc = ShaderDestroyVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7366 AssertRC(rc);
7367 }
7368 }
7369 else
7370 {
7371 Assert(type == SVGA3D_SHADERTYPE_PS);
7372 if ( shid < pContext->cPixelShaders
7373 && pContext->paPixelShader[shid].id == shid)
7374 {
7375 pShader = &pContext->paPixelShader[shid];
7376 rc = ShaderDestroyPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7377 AssertRC(rc);
7378 }
7379 }
7380
7381 if (pShader)
7382 {
7383 if (pShader->pShaderProgram)
7384 RTMemFree(pShader->pShaderProgram);
7385 memset(pShader, 0, sizeof(*pShader));
7386 pShader->id = SVGA3D_INVALID_ID;
7387 }
7388 else
7389 AssertFailedReturn(VERR_INVALID_PARAMETER);
7390
7391 return VINF_SUCCESS;
7392}
7393
7394int vmsvga3dShaderSet(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid, SVGA3dShaderType type, uint32_t shid)
7395{
7396 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7397 AssertReturn(pState, VERR_NO_MEMORY);
7398 int rc;
7399
7400 Log(("vmsvga3dShaderSet cid=%u type=%s shid=%d\n", cid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", shid));
7401
7402 if (!pContext)
7403 {
7404 rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7405 AssertRCReturn(rc, rc);
7406 }
7407
7408 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7409
7410 if (type == SVGA3D_SHADERTYPE_VS)
7411 {
7412 /* Save for vm state save/restore. */
7413 pContext->state.shidVertex = shid;
7414 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VERTEXSHADER;
7415
7416 if ( shid < pContext->cVertexShaders
7417 && pContext->paVertexShader[shid].id == shid)
7418 {
7419 PVMSVGA3DSHADER pShader = &pContext->paVertexShader[shid];
7420 Assert(type == pShader->type);
7421
7422 rc = ShaderSetVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7423 AssertRCReturn(rc, rc);
7424 }
7425 else
7426 if (shid == SVGA_ID_INVALID)
7427 {
7428 /* Unselect shader. */
7429 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7430 AssertRCReturn(rc, rc);
7431 }
7432 else
7433 AssertFailedReturn(VERR_INVALID_PARAMETER);
7434 }
7435 else
7436 {
7437 /* Save for vm state save/restore. */
7438 pContext->state.shidPixel = shid;
7439 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_PIXELSHADER;
7440
7441 Assert(type == SVGA3D_SHADERTYPE_PS);
7442 if ( shid < pContext->cPixelShaders
7443 && pContext->paPixelShader[shid].id == shid)
7444 {
7445 PVMSVGA3DSHADER pShader = &pContext->paPixelShader[shid];
7446 Assert(type == pShader->type);
7447
7448 rc = ShaderSetPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7449 AssertRCReturn(rc, rc);
7450 }
7451 else
7452 if (shid == SVGA_ID_INVALID)
7453 {
7454 /* Unselect shader. */
7455 rc = ShaderSetPixelShader(pContext->pShaderContext, NULL);
7456 AssertRCReturn(rc, rc);
7457 }
7458 else
7459 AssertFailedReturn(VERR_INVALID_PARAMETER);
7460 }
7461
7462 return VINF_SUCCESS;
7463}
7464
7465int vmsvga3dShaderSetConst(PVGASTATECC pThisCC, uint32_t cid, uint32_t reg, SVGA3dShaderType type, SVGA3dShaderConstType ctype, uint32_t cRegisters, uint32_t *pValues)
7466{
7467 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7468 AssertReturn(pState, VERR_NO_MEMORY);
7469
7470 Log(("vmsvga3dShaderSetConst cid=%u reg=%x type=%s cregs=%d ctype=%x\n", cid, reg, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cRegisters, ctype));
7471
7472 PVMSVGA3DCONTEXT pContext;
7473 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7474 AssertRCReturn(rc, rc);
7475
7476 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7477
7478 for (uint32_t i = 0; i < cRegisters; i++)
7479 {
7480#ifdef LOG_ENABLED
7481 switch (ctype)
7482 {
7483 case SVGA3D_CONST_TYPE_FLOAT:
7484 {
7485 float *pValuesF = (float *)pValues;
7486 Log(("ConstantF %d: value=" FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR "\n",
7487 reg + i, FLOAT_FMT_ARGS(pValuesF[i*4 + 0]), FLOAT_FMT_ARGS(pValuesF[i*4 + 1]), FLOAT_FMT_ARGS(pValuesF[i*4 + 2]), FLOAT_FMT_ARGS(pValuesF[i*4 + 3])));
7488 break;
7489 }
7490
7491 case SVGA3D_CONST_TYPE_INT:
7492 Log(("ConstantI %d: value=%d, %d, %d, %d\n", reg + i, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]));
7493 break;
7494
7495 case SVGA3D_CONST_TYPE_BOOL:
7496 Log(("ConstantB %d: value=%d, %d, %d, %d\n", reg + i, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]));
7497 break;
7498 }
7499#endif
7500 vmsvga3dSaveShaderConst(pContext, reg + i, type, ctype, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]);
7501 }
7502
7503 switch (type)
7504 {
7505 case SVGA3D_SHADERTYPE_VS:
7506 switch (ctype)
7507 {
7508 case SVGA3D_CONST_TYPE_FLOAT:
7509 rc = ShaderSetVertexShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7510 break;
7511
7512 case SVGA3D_CONST_TYPE_INT:
7513 rc = ShaderSetVertexShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7514 break;
7515
7516 case SVGA3D_CONST_TYPE_BOOL:
7517 rc = ShaderSetVertexShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7518 break;
7519
7520 default:
7521 AssertFailedReturn(VERR_INVALID_PARAMETER);
7522 }
7523 AssertRCReturn(rc, rc);
7524 break;
7525
7526 case SVGA3D_SHADERTYPE_PS:
7527 switch (ctype)
7528 {
7529 case SVGA3D_CONST_TYPE_FLOAT:
7530 rc = ShaderSetPixelShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7531 break;
7532
7533 case SVGA3D_CONST_TYPE_INT:
7534 rc = ShaderSetPixelShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7535 break;
7536
7537 case SVGA3D_CONST_TYPE_BOOL:
7538 rc = ShaderSetPixelShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7539 break;
7540
7541 default:
7542 AssertFailedReturn(VERR_INVALID_PARAMETER);
7543 }
7544 AssertRCReturn(rc, rc);
7545 break;
7546
7547 default:
7548 AssertFailedReturn(VERR_INVALID_PARAMETER);
7549 }
7550
7551 return VINF_SUCCESS;
7552}
7553
7554int vmsvga3dOcclusionQueryCreate(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7555{
7556 AssertReturn(pState->ext.glGenQueries, VERR_NOT_SUPPORTED);
7557 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7558
7559 GLuint idQuery = 0;
7560 pState->ext.glGenQueries(1, &idQuery);
7561 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7562 AssertReturn(idQuery, VERR_INTERNAL_ERROR);
7563 pContext->occlusion.idQuery = idQuery;
7564 return VINF_SUCCESS;
7565}
7566
7567int vmsvga3dOcclusionQueryDelete(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7568{
7569 AssertReturn(pState->ext.glDeleteQueries, VERR_NOT_SUPPORTED);
7570 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7571
7572 if (pContext->occlusion.idQuery)
7573 {
7574 pState->ext.glDeleteQueries(1, &pContext->occlusion.idQuery);
7575 }
7576 return VINF_SUCCESS;
7577}
7578
7579int vmsvga3dOcclusionQueryBegin(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7580{
7581 AssertReturn(pState->ext.glBeginQuery, VERR_NOT_SUPPORTED);
7582 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7583
7584 pState->ext.glBeginQuery(GL_ANY_SAMPLES_PASSED, pContext->occlusion.idQuery);
7585 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7586 return VINF_SUCCESS;
7587}
7588
7589int vmsvga3dOcclusionQueryEnd(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7590{
7591 AssertReturn(pState->ext.glEndQuery, VERR_NOT_SUPPORTED);
7592 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7593
7594 pState->ext.glEndQuery(GL_ANY_SAMPLES_PASSED);
7595 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7596 return VINF_SUCCESS;
7597}
7598
7599int vmsvga3dOcclusionQueryGetData(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, uint32_t *pu32Pixels)
7600{
7601 AssertReturn(pState->ext.glGetQueryObjectuiv, VERR_NOT_SUPPORTED);
7602 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7603
7604 GLuint pixels = 0;
7605 pState->ext.glGetQueryObjectuiv(pContext->occlusion.idQuery, GL_QUERY_RESULT, &pixels);
7606 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7607
7608 *pu32Pixels = (uint32_t)pixels;
7609 return VINF_SUCCESS;
7610}
Note: See TracBrowser for help on using the repository browser.

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