VirtualBox

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

Last change on this file since 84909 was 84888, checked in by vboxsync, 5 years ago

FE/Qt,Devices/Graphics: experimental GLX graphics output: use TEXTURE_2D

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 293.2 KB
Line 
1/* $Id: DevVGA-SVGA3d-ogl.cpp 84888 2020-06-21 18:41:16Z 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 * Using TEXTURE_2D because Intel Mesa driver does not seem to support TEXTURE_RECTANGLE for GLX pixmaps.
3518 */
3519 static int const aConfigAttribList[] =
3520 {
3521 // GLX_RENDER_TYPE, GLX_RGBA_BIT,
3522 // GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
3523 // GLX_X_RENDERABLE, True, // Render to GLX pixmaps
3524 GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT, // Must support GLX pixmaps
3525 GLX_BIND_TO_TEXTURE_RGBA_EXT, True, // Must support GLX_EXT_texture_from_pixmap
3526 GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT, // Must support GL_TEXTURE_2D for the frontend code
3527 GLX_DOUBLEBUFFER, False, // No need for double buffering for a pixmap.
3528 GLX_RED_SIZE, 8, // True color RGB with 8 bits per channel.
3529 GLX_GREEN_SIZE, 8,
3530 GLX_BLUE_SIZE, 8,
3531 GLX_ALPHA_SIZE, 8,
3532 GLX_STENCIL_SIZE, 0, // No stencil buffer
3533 GLX_DEPTH_SIZE, 0, // No depth buffer
3534 GLX_CONFIG_CAVEAT, GLX_NONE,
3535 None
3536 };
3537
3538 /* Find a suitable FB config. */
3539 int cConfigs = 0;
3540 GLXFBConfig *paConfigs = glXChooseFBConfig(pState->display, 0, aConfigAttribList, &cConfigs);
3541 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: paConfigs %p cConfigs %d\n", (void *)paConfigs, cConfigs));
3542 if (paConfigs)
3543 {
3544 XVisualInfo *vi = NULL;
3545 int i = 0;
3546 for (; i < cConfigs; ++i)
3547 {
3548 /* Use XFree to free the data returned in the previous iteration of this loop. */
3549 if (vi)
3550 XFree(vi);
3551
3552 vi = glXGetVisualFromFBConfig(pState->display, paConfigs[i]);
3553 if (!vi)
3554 continue;
3555
3556 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: %p vid %lu screen %d depth %d r %lu g %lu b %lu clrmap %d bitsperrgb %d\n",
3557 (void *)vi->visual, vi->visualid, vi->screen, vi->depth,
3558 vi->red_mask, vi->green_mask, vi->blue_mask, vi->colormap_size, vi->bits_per_rgb));
3559
3560 /* Search for 32 bits per pixel. */
3561 if (vi->depth != 32)
3562 continue;
3563
3564 /* 8 bits per color component is enough. */
3565 if (vi->bits_per_rgb != 8)
3566 continue;
3567
3568 /* Render to pixmap. */
3569 int value = 0;
3570 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_DRAWABLE_TYPE, &value);
3571 if (!(value & GLX_PIXMAP_BIT))
3572 continue;
3573
3574 /* Pixmap will be used as TEXTURE_2D. */
3575 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_TARGETS_EXT, &value);
3576 if (!(value & GLX_TEXTURE_2D_BIT_EXT))
3577 continue;
3578
3579 /* Need to bind to a texture using GLX_EXT_texture_from_pixmap. */
3580 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &value);
3581 if (value == 0)
3582 {
3583 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &value);
3584 if (value == 0)
3585 continue;
3586 }
3587
3588 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_Y_INVERTED_EXT, &value);
3589 p->fYInverted = (value == 1);
3590
3591 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_BIND_TO_MIPMAP_TEXTURE_EXT, &value);
3592 p->fMipmap = (value > 0);
3593
3594 /* This FB config can be used. */
3595 break;
3596 }
3597
3598 if (i < cConfigs)
3599 {
3600 /* Found a suitable config with index i. */
3601 p->visualid = vi->visualid;
3602
3603 Window const rootWindow = RootWindow(pState->display, vi->screen);
3604 p->pixmap = XCreatePixmap(pState->display, rootWindow, cWidth, cHeight, vi->depth);
3605 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->pixmap %ld\n", p->pixmap));
3606
3607 static int const aPixmapAttribList[] =
3608 {
3609 GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
3610 GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT,
3611 GLX_MIPMAP_TEXTURE_EXT, p->fMipmap,
3612 None
3613 };
3614 p->glxpixmap = glXCreatePixmap(pState->display, paConfigs[i], p->pixmap, aPixmapAttribList);
3615 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxpixmap %ld\n", p->glxpixmap));
3616
3617 p->glxctx = glXCreateContext(pState->display, vi, pState->SharedCtx.glxContext, GL_TRUE);
3618 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxctx %p\n", (void *)p->glxctx));
3619
3620 XSync(pState->display, False);
3621 }
3622 else
3623 {
3624 /* A suitable config is not found. */
3625 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: no FBConfig\n"));
3626 rc = VERR_NOT_SUPPORTED;
3627 }
3628
3629 if (vi)
3630 XFree(vi);
3631
3632 /* "Use XFree to free the memory returned by glXChooseFBConfig." */
3633 XFree(paConfigs);
3634 }
3635 else
3636 {
3637 /* glXChooseFBConfig failed. */
3638 rc = VERR_NOT_SUPPORTED;
3639 }
3640
3641 XSetErrorHandler(oldHandler);
3642 return rc;
3643}
3644
3645/* Destroy a HW accelerated screen. */
3646static void vmsvga3dHwScreenDestroy(PVMSVGA3DSTATE pState, VMSVGAHWSCREEN *p)
3647{
3648 if (p)
3649 {
3650 LogRel4(("VMSVGA: vmsvga3dHwScreenDestroy: p->glxpixmap %ld, ctx %p\n", p->glxpixmap, (void *)p->glxctx));
3651 if (p->glxctx)
3652 {
3653 /* GLX context is changed here, so other code has to set the appropriate context again. */
3654 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3655 glXMakeCurrent(pState->display, None, NULL);
3656 glXDestroyContext(pState->display, p->glxctx);
3657 }
3658
3659 if (p->glxpixmap)
3660 glXDestroyPixmap(pState->display, p->glxpixmap);
3661
3662 if (p->pixmap)
3663 XFreePixmap(pState->display, p->pixmap);
3664
3665 RT_ZERO(*p);
3666 }
3667}
3668
3669#define GLCHECK() \
3670 do { \
3671 int glErr = glGetError(); \
3672 if (glErr != GL_NO_ERROR) LogRel4(("VMSVGA: GL error 0x%x @%d\n", glErr, __LINE__)); \
3673 } while(0)
3674
3675int vmsvga3dBackDefineScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3676{
3677 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: screen %u\n", pScreen->idScreen));
3678
3679 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3680 AssertReturn(pState, VERR_NOT_SUPPORTED);
3681
3682 Assert(pScreen->pHwScreen == NULL);
3683
3684 VMSVGAHWSCREEN *p = (VMSVGAHWSCREEN *)RTMemAllocZ(sizeof(VMSVGAHWSCREEN));
3685 AssertPtrReturn(p, VERR_NO_MEMORY);
3686
3687 int rc = vmsvga3dHwScreenCreate(pState, pScreen->cWidth, pScreen->cHeight, p);
3688 if (RT_SUCCESS(rc))
3689 {
3690 /*
3691 * Setup the OpenGL context of the screen.
3692 */
3693
3694 /* GLX context is changed here, so other code has to set the appropriate context again. */
3695 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3696
3697 Bool const fSuccess = glXMakeCurrent(pState->display, p->glxpixmap, p->glxctx);
3698 if (fSuccess)
3699 {
3700 /* Work in screen coordinates. */
3701 glMatrixMode(GL_MODELVIEW);
3702 glLoadIdentity();
3703 glOrtho(0, pScreen->cWidth, 0, pScreen->cHeight, -1, 1);
3704 glMatrixMode(GL_PROJECTION);
3705 glLoadIdentity();
3706
3707 /* Set GL state. */
3708 glClearColor(0, 0, 0, 1);
3709 glEnable(GL_TEXTURE_2D);
3710 glDisable(GL_DEPTH_TEST);
3711 glDisable(GL_CULL_FACE);
3712
3713 /* Clear the pixmap. */
3714 glClear(GL_COLOR_BUFFER_BIT);
3715 glFinish();
3716
3717 glXMakeCurrent(pState->display, None, NULL);
3718
3719 rc = vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_CREATED,
3720 pScreen->idScreen, p->pixmap, &p->visualid, sizeof(p->visualid));
3721 }
3722 else
3723 {
3724 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: failed to set current context\n"));
3725 rc = VERR_NOT_SUPPORTED;
3726 }
3727 }
3728
3729 if (RT_SUCCESS(rc))
3730 {
3731 pScreen->pHwScreen = p;
3732 }
3733 else
3734 {
3735 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: %Rrc\n", rc));
3736 vmsvga3dHwScreenDestroy(pState, p);
3737 RTMemFree(p);
3738 }
3739
3740 return rc;
3741}
3742
3743int vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3744{
3745 LogRel4(("VMSVGA: vmsvga3dBackDestroyScreen: screen %u\n", pScreen->idScreen));
3746
3747 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3748 AssertReturn(pState, VERR_NOT_SUPPORTED);
3749
3750 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3751
3752 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3753 if (p)
3754 {
3755 pScreen->pHwScreen = NULL;
3756
3757 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_DESTROYED,
3758 pScreen->idScreen, p->pixmap, NULL, 0);
3759
3760 vmsvga3dHwScreenDestroy(pState, p);
3761 RTMemFree(p);
3762 }
3763
3764 XSetErrorHandler(oldHandler);
3765
3766 return VINF_SUCCESS;
3767}
3768
3769/* Blit a surface to the GLX pixmap. */
3770int vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3771 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3772 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3773{
3774 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3775 AssertReturn(pState, VERR_NOT_SUPPORTED);
3776
3777 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3778 AssertReturn(p, VERR_NOT_SUPPORTED);
3779
3780 PVMSVGA3DSURFACE pSurface;
3781 int rc = vmsvga3dSurfaceFromSid(pState, srcImage.sid, &pSurface);
3782 AssertRCReturn(rc, rc);
3783
3784 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
3785 {
3786 LogFunc(("src sid=%u flags=0x%x format=%d -> create texture\n", srcImage.sid, pSurface->surfaceFlags, pSurface->format));
3787 rc = vmsvga3dBackCreateTexture(pState, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID, pSurface);
3788 AssertRCReturn(rc, rc);
3789 }
3790
3791 AssertReturn(pSurface->enmOGLResType == VMSVGA3D_OGLRESTYPE_TEXTURE, VERR_NOT_SUPPORTED);
3792
3793 PVMSVGA3DMIPMAPLEVEL pMipLevel;
3794 rc = vmsvga3dMipmapLevel(pSurface, srcImage.face, srcImage.mipmap, &pMipLevel);
3795 AssertRCReturn(rc, rc);
3796
3797 /** @todo Implement. */
3798 RT_NOREF(destRect, cRects, paRects);
3799
3800 /* GLX context is changed here, so other code has to set appropriate context again. */
3801 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3802
3803 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3804
3805 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_UPDATE_BEGIN, pScreen->idScreen, p->pixmap, NULL, 0);
3806
3807 GLint const w = pScreen->cWidth;
3808 GLint const h = pScreen->cHeight;
3809
3810 GLfloat const wSurf = (GLfloat)pMipLevel->mipmapSize.width;
3811 GLfloat const hSurf = (GLfloat)pMipLevel->mipmapSize.height;
3812 GLfloat const x1 = (GLfloat)srcRect.left / wSurf;
3813 GLfloat const y1 = (GLfloat)srcRect.top / hSurf;
3814 GLfloat const x2 = (GLfloat)srcRect.right / wSurf;
3815 GLfloat const y2 = (GLfloat)srcRect.bottom / hSurf;
3816
3817 //printf("blit to screen src %fx%f %u,%u %u,%u (%f,%f %f,%f) dest %dx%d %u,%u %u,%u\n",
3818 // wSurf, hSurf, srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, x1, y1, x2, y2,
3819 // w, h, destRect.left, destRect.top, destRect.right, destRect.bottom);
3820
3821 Bool fSuccess = glXMakeCurrent(pState->display, p->glxpixmap, p->glxctx);
3822 if (fSuccess)
3823 {
3824 glClear(GL_COLOR_BUFFER_BIT);
3825
3826 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture); GLCHECK();
3827
3828 glBegin(GL_QUADS);
3829 /** @todo Y inversion. */
3830 glTexCoord2f(x1, y1); glVertex2i(0, h);
3831 glTexCoord2f(x1, y2); glVertex2i(0, 0);
3832 glTexCoord2f(x2, y2); glVertex2i(w, 0);
3833 glTexCoord2f(x2, y1); glVertex2i(w, h);
3834 glEnd(); GLCHECK();
3835
3836 glBindTexture(GL_TEXTURE_2D, 0); GLCHECK();
3837
3838 glFinish(); GLCHECK();
3839
3840 glXMakeCurrent(pState->display, None, NULL);
3841
3842 vmsvga3dDrvNotifyHwScreen(pThisCC, VBOX3D_NOTIFY_TYPE_HW_SCREEN_UPDATE_END,
3843 pScreen->idScreen, p->pixmap, &destRect, sizeof(destRect));
3844 }
3845
3846 XSetErrorHandler(oldHandler);
3847
3848 return VINF_SUCCESS;
3849}
3850
3851#else /* !RT_OS_LINUX */
3852
3853int vmsvga3dBackDefineScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3854{
3855 RT_NOREF(pThisCC, pScreen);
3856 return VERR_NOT_IMPLEMENTED;
3857}
3858
3859int vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3860{
3861 RT_NOREF(pThisCC, pScreen);
3862 return VERR_NOT_IMPLEMENTED;
3863}
3864
3865int vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3866 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3867 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3868{
3869 RT_NOREF(pThisCC, pScreen, destRect, srcImage, srcRect, cRects, paRects);
3870 return VERR_NOT_IMPLEMENTED;
3871}
3872#endif
3873
3874/**
3875 * Create a new 3d context
3876 *
3877 * @returns VBox status code.
3878 * @param pThisCC The VGA/VMSVGA state for ring-3.
3879 * @param cid Context id
3880 */
3881int vmsvga3dContextDefine(PVGASTATECC pThisCC, uint32_t cid)
3882{
3883 return vmsvga3dContextDefineOgl(pThisCC, cid, 0/*fFlags*/);
3884}
3885
3886/**
3887 * Destroys a 3d context.
3888 *
3889 * @returns VBox status code.
3890 * @param pThisCC The VGA/VMSVGA state for ring-3.
3891 * @param pContext The context to destroy.
3892 * @param cid Context id
3893 */
3894static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid)
3895{
3896 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3897 AssertReturn(pState, VERR_NO_MEMORY);
3898 AssertReturn(pContext, VERR_INVALID_PARAMETER);
3899 AssertReturn(pContext->id == cid, VERR_INVALID_PARAMETER);
3900 Log(("vmsvga3dContextDestroyOgl id %x\n", cid));
3901
3902 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3903
3904 if (pContext->id == VMSVGA3D_SHARED_CTX_ID)
3905 {
3906 /* Delete resources which use the shared context. */
3907 vmsvga3dOnSharedContextDestroy(pState);
3908 }
3909
3910 /* Destroy all leftover pixel shaders. */
3911 for (uint32_t i = 0; i < pContext->cPixelShaders; i++)
3912 {
3913 if (pContext->paPixelShader[i].id != SVGA3D_INVALID_ID)
3914 vmsvga3dShaderDestroy(pThisCC, pContext->paPixelShader[i].cid, pContext->paPixelShader[i].id, pContext->paPixelShader[i].type);
3915 }
3916 if (pContext->paPixelShader)
3917 RTMemFree(pContext->paPixelShader);
3918
3919 /* Destroy all leftover vertex shaders. */
3920 for (uint32_t i = 0; i < pContext->cVertexShaders; i++)
3921 {
3922 if (pContext->paVertexShader[i].id != SVGA3D_INVALID_ID)
3923 vmsvga3dShaderDestroy(pThisCC, pContext->paVertexShader[i].cid, pContext->paVertexShader[i].id, pContext->paVertexShader[i].type);
3924 }
3925 if (pContext->paVertexShader)
3926 RTMemFree(pContext->paVertexShader);
3927
3928 if (pContext->state.paVertexShaderConst)
3929 RTMemFree(pContext->state.paVertexShaderConst);
3930 if (pContext->state.paPixelShaderConst)
3931 RTMemFree(pContext->state.paPixelShaderConst);
3932
3933 if (pContext->pShaderContext)
3934 {
3935 int rc = ShaderContextDestroy(pContext->pShaderContext);
3936 AssertRC(rc);
3937 }
3938
3939 if (pContext->idFramebuffer != OPENGL_INVALID_ID)
3940 {
3941 /* Unbind the object from the framebuffer target. */
3942 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0 /* back buffer */);
3943 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3944 pState->ext.glDeleteFramebuffers(1, &pContext->idFramebuffer);
3945 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3946
3947 if (pContext->idReadFramebuffer != OPENGL_INVALID_ID)
3948 {
3949 pState->ext.glDeleteFramebuffers(1, &pContext->idReadFramebuffer);
3950 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3951 }
3952 if (pContext->idDrawFramebuffer != OPENGL_INVALID_ID)
3953 {
3954 pState->ext.glDeleteFramebuffers(1, &pContext->idDrawFramebuffer);
3955 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3956 }
3957 }
3958
3959 vmsvga3dOcclusionQueryDelete(pState, pContext);
3960
3961#ifdef RT_OS_WINDOWS
3962 wglMakeCurrent(pContext->hdc, NULL);
3963 wglDeleteContext(pContext->hglrc);
3964 ReleaseDC(pContext->hwnd, pContext->hdc);
3965
3966 /* Destroy the window we've created. */
3967 int rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_DESTROYWINDOW, (WPARAM)pContext->hwnd, 0);
3968 AssertRC(rc);
3969#elif defined(RT_OS_DARWIN)
3970 vmsvga3dCocoaDestroyViewAndContext(pContext->cocoaView, pContext->cocoaContext);
3971#elif defined(RT_OS_LINUX)
3972 glXMakeCurrent(pState->display, None, NULL);
3973 glXDestroyContext(pState->display, pContext->glxContext);
3974 XDestroyWindow(pState->display, pContext->window);
3975#endif
3976
3977 memset(pContext, 0, sizeof(*pContext));
3978 pContext->id = SVGA3D_INVALID_ID;
3979
3980 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3981 return VINF_SUCCESS;
3982}
3983
3984/**
3985 * Destroy an existing 3d context
3986 *
3987 * @returns VBox status code.
3988 * @param pThisCC The VGA/VMSVGA state for ring-3.
3989 * @param cid Context id
3990 */
3991int vmsvga3dContextDestroy(PVGASTATECC pThisCC, uint32_t cid)
3992{
3993 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3994 AssertReturn(pState, VERR_WRONG_ORDER);
3995
3996 /*
3997 * Resolve the context and hand it to the common worker function.
3998 */
3999 if ( cid < pState->cContexts
4000 && pState->papContexts[cid]->id == cid)
4001 return vmsvga3dContextDestroyOgl(pThisCC, pState->papContexts[cid], cid);
4002
4003 AssertReturn(cid < SVGA3D_MAX_CONTEXT_IDS, VERR_INVALID_PARAMETER);
4004 return VINF_SUCCESS;
4005}
4006
4007/**
4008 * Worker for vmsvga3dChangeMode that resizes a context.
4009 *
4010 * @param pState The VMSVGA3d state.
4011 * @param pContext The context.
4012 */
4013static void vmsvga3dChangeModeOneContext(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
4014{
4015 RT_NOREF(pState, pContext);
4016 /* Do nothing. The window is not used for presenting. */
4017}
4018
4019/* Handle resize */
4020int vmsvga3dChangeMode(PVGASTATECC pThisCC)
4021{
4022 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4023 AssertReturn(pState, VERR_NO_MEMORY);
4024
4025 /* Resize the shared context too. */
4026 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
4027 vmsvga3dChangeModeOneContext(pState, &pState->SharedCtx);
4028
4029 /* Resize all active contexts. */
4030 for (uint32_t i = 0; i < pState->cContexts; i++)
4031 {
4032 PVMSVGA3DCONTEXT pContext = pState->papContexts[i];
4033 if (pContext->id != SVGA3D_INVALID_ID)
4034 vmsvga3dChangeModeOneContext(pState, pContext);
4035 }
4036
4037 return VINF_SUCCESS;
4038}
4039
4040
4041int vmsvga3dSetTransform(PVGASTATECC pThisCC, uint32_t cid, SVGA3dTransformType type, float matrix[16])
4042{
4043 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4044 AssertReturn(pState, VERR_NO_MEMORY);
4045 bool fModelViewChanged = false;
4046
4047 Log(("vmsvga3dSetTransform cid=%u %s\n", cid, vmsvgaTransformToString(type)));
4048
4049 ASSERT_GUEST_RETURN((unsigned)type < SVGA3D_TRANSFORM_MAX, VERR_INVALID_PARAMETER);
4050
4051 PVMSVGA3DCONTEXT pContext;
4052 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4053 AssertRCReturn(rc, rc);
4054
4055 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4056
4057 /* Save this matrix for vm state save/restore. */
4058 pContext->state.aTransformState[type].fValid = true;
4059 memcpy(pContext->state.aTransformState[type].matrix, matrix, sizeof(pContext->state.aTransformState[type].matrix));
4060 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_TRANSFORM;
4061
4062 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)));
4063 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)));
4064 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)));
4065 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)));
4066
4067 switch (type)
4068 {
4069 case SVGA3D_TRANSFORM_VIEW:
4070 /* View * World = Model View */
4071 glMatrixMode(GL_MODELVIEW);
4072 glLoadMatrixf(matrix);
4073 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].fValid)
4074 glMultMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].matrix);
4075 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4076 fModelViewChanged = true;
4077 break;
4078
4079 case SVGA3D_TRANSFORM_PROJECTION:
4080 {
4081 rc = ShaderTransformProjection(pContext->state.RectViewPort.w, pContext->state.RectViewPort.h, matrix, false /* fPretransformed */);
4082 AssertRCReturn(rc, rc);
4083 break;
4084 }
4085
4086 case SVGA3D_TRANSFORM_TEXTURE0:
4087 glMatrixMode(GL_TEXTURE);
4088 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4089 glLoadMatrixf(matrix);
4090 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4091 break;
4092
4093 case SVGA3D_TRANSFORM_TEXTURE1:
4094 case SVGA3D_TRANSFORM_TEXTURE2:
4095 case SVGA3D_TRANSFORM_TEXTURE3:
4096 case SVGA3D_TRANSFORM_TEXTURE4:
4097 case SVGA3D_TRANSFORM_TEXTURE5:
4098 case SVGA3D_TRANSFORM_TEXTURE6:
4099 case SVGA3D_TRANSFORM_TEXTURE7:
4100 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_TEXTUREx transform!!\n"));
4101 return VERR_INVALID_PARAMETER;
4102
4103 case SVGA3D_TRANSFORM_WORLD:
4104 /* View * World = Model View */
4105 glMatrixMode(GL_MODELVIEW);
4106 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid)
4107 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
4108 else
4109 glLoadIdentity();
4110 glMultMatrixf(matrix);
4111 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4112 fModelViewChanged = true;
4113 break;
4114
4115 case SVGA3D_TRANSFORM_WORLD1:
4116 case SVGA3D_TRANSFORM_WORLD2:
4117 case SVGA3D_TRANSFORM_WORLD3:
4118 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_WORLDx transform!!\n"));
4119 return VERR_INVALID_PARAMETER;
4120
4121 default:
4122 Log(("vmsvga3dSetTransform: unknown type!!\n"));
4123 return VERR_INVALID_PARAMETER;
4124 }
4125
4126 /* Apparently we need to reset the light and clip data after modifying the modelview matrix. */
4127 if (fModelViewChanged)
4128 {
4129 /* Reprogram the clip planes. */
4130 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aClipPlane); j++)
4131 {
4132 if (pContext->state.aClipPlane[j].fValid == true)
4133 vmsvga3dSetClipPlane(pThisCC, cid, j, pContext->state.aClipPlane[j].plane);
4134 }
4135
4136 /* Reprogram the light data. */
4137 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aLightData); j++)
4138 {
4139 if (pContext->state.aLightData[j].fValidData == true)
4140 vmsvga3dSetLightData(pThisCC, cid, j, &pContext->state.aLightData[j].data);
4141 }
4142 }
4143
4144 return VINF_SUCCESS;
4145}
4146
4147int vmsvga3dSetZRange(PVGASTATECC pThisCC, uint32_t cid, SVGA3dZRange zRange)
4148{
4149 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4150 AssertReturn(pState, VERR_NO_MEMORY);
4151
4152 Log(("vmsvga3dSetZRange cid=%u min=%d max=%d\n", cid, (uint32_t)(zRange.min * 100.0), (uint32_t)(zRange.max * 100.0)));
4153
4154 PVMSVGA3DCONTEXT pContext;
4155 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4156 AssertRCReturn(rc, rc);
4157
4158 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4159
4160 pContext->state.zRange = zRange;
4161 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_ZRANGE;
4162
4163 if (zRange.min < -1.0)
4164 zRange.min = -1.0;
4165 if (zRange.max > 1.0)
4166 zRange.max = 1.0;
4167
4168 glDepthRange((GLdouble)zRange.min, (GLdouble)zRange.max);
4169 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4170 return VINF_SUCCESS;
4171}
4172
4173/**
4174 * Convert SVGA blend op value to its OpenGL equivalent
4175 */
4176static GLenum vmsvga3dBlendOp2GL(uint32_t blendOp)
4177{
4178 switch (blendOp)
4179 {
4180 case SVGA3D_BLENDOP_ZERO:
4181 return GL_ZERO;
4182 case SVGA3D_BLENDOP_ONE:
4183 return GL_ONE;
4184 case SVGA3D_BLENDOP_SRCCOLOR:
4185 return GL_SRC_COLOR;
4186 case SVGA3D_BLENDOP_INVSRCCOLOR:
4187 return GL_ONE_MINUS_SRC_COLOR;
4188 case SVGA3D_BLENDOP_SRCALPHA:
4189 return GL_SRC_ALPHA;
4190 case SVGA3D_BLENDOP_INVSRCALPHA:
4191 return GL_ONE_MINUS_SRC_ALPHA;
4192 case SVGA3D_BLENDOP_DESTALPHA:
4193 return GL_DST_ALPHA;
4194 case SVGA3D_BLENDOP_INVDESTALPHA:
4195 return GL_ONE_MINUS_DST_ALPHA;
4196 case SVGA3D_BLENDOP_DESTCOLOR:
4197 return GL_DST_COLOR;
4198 case SVGA3D_BLENDOP_INVDESTCOLOR:
4199 return GL_ONE_MINUS_DST_COLOR;
4200 case SVGA3D_BLENDOP_SRCALPHASAT:
4201 return GL_SRC_ALPHA_SATURATE;
4202 case SVGA3D_BLENDOP_BLENDFACTOR:
4203 return GL_CONSTANT_COLOR;
4204 case SVGA3D_BLENDOP_INVBLENDFACTOR:
4205 return GL_ONE_MINUS_CONSTANT_COLOR;
4206 default:
4207 AssertFailed();
4208 return GL_ONE;
4209 }
4210}
4211
4212static GLenum vmsvga3dBlendEquation2GL(uint32_t blendEq)
4213{
4214 switch (blendEq)
4215 {
4216 case SVGA3D_BLENDEQ_ADD:
4217 return GL_FUNC_ADD;
4218 case SVGA3D_BLENDEQ_SUBTRACT:
4219 return GL_FUNC_SUBTRACT;
4220 case SVGA3D_BLENDEQ_REVSUBTRACT:
4221 return GL_FUNC_REVERSE_SUBTRACT;
4222 case SVGA3D_BLENDEQ_MINIMUM:
4223 return GL_MIN;
4224 case SVGA3D_BLENDEQ_MAXIMUM:
4225 return GL_MAX;
4226 default:
4227 /* SVGA3D_BLENDEQ_INVALID means that the render state has not been set, therefore use default. */
4228 AssertMsg(blendEq == SVGA3D_BLENDEQ_INVALID, ("blendEq=%d (%#x)\n", blendEq, blendEq));
4229 return GL_FUNC_ADD;
4230 }
4231}
4232
4233static GLenum vmsvgaCmpFunc2GL(uint32_t cmpFunc)
4234{
4235 switch (cmpFunc)
4236 {
4237 case SVGA3D_CMP_NEVER:
4238 return GL_NEVER;
4239 case SVGA3D_CMP_LESS:
4240 return GL_LESS;
4241 case SVGA3D_CMP_EQUAL:
4242 return GL_EQUAL;
4243 case SVGA3D_CMP_LESSEQUAL:
4244 return GL_LEQUAL;
4245 case SVGA3D_CMP_GREATER:
4246 return GL_GREATER;
4247 case SVGA3D_CMP_NOTEQUAL:
4248 return GL_NOTEQUAL;
4249 case SVGA3D_CMP_GREATEREQUAL:
4250 return GL_GEQUAL;
4251 case SVGA3D_CMP_ALWAYS:
4252 return GL_ALWAYS;
4253 default:
4254 Assert(cmpFunc == SVGA3D_CMP_INVALID);
4255 return GL_LESS;
4256 }
4257}
4258
4259static GLenum vmsvgaStencipOp2GL(uint32_t stencilOp)
4260{
4261 switch (stencilOp)
4262 {
4263 case SVGA3D_STENCILOP_KEEP:
4264 return GL_KEEP;
4265 case SVGA3D_STENCILOP_ZERO:
4266 return GL_ZERO;
4267 case SVGA3D_STENCILOP_REPLACE:
4268 return GL_REPLACE;
4269 case SVGA3D_STENCILOP_INCRSAT:
4270 return GL_INCR_WRAP;
4271 case SVGA3D_STENCILOP_DECRSAT:
4272 return GL_DECR_WRAP;
4273 case SVGA3D_STENCILOP_INVERT:
4274 return GL_INVERT;
4275 case SVGA3D_STENCILOP_INCR:
4276 return GL_INCR;
4277 case SVGA3D_STENCILOP_DECR:
4278 return GL_DECR;
4279 default:
4280 Assert(stencilOp == SVGA3D_STENCILOP_INVALID);
4281 return GL_KEEP;
4282 }
4283}
4284
4285int vmsvga3dSetRenderState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cRenderStates, SVGA3dRenderState *pRenderState)
4286{
4287 uint32_t val = UINT32_MAX; /* Shut up MSC. */
4288 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4289 AssertReturn(pState, VERR_NO_MEMORY);
4290
4291 Log(("vmsvga3dSetRenderState cid=%u cRenderStates=%d\n", cid, cRenderStates));
4292
4293 PVMSVGA3DCONTEXT pContext;
4294 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4295 AssertRCReturn(rc, rc);
4296
4297 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4298
4299 for (unsigned i = 0; i < cRenderStates; i++)
4300 {
4301 GLenum enableCap = ~(GLenum)0;
4302 Log(("vmsvga3dSetRenderState: cid=%u state=%s (%d) val=%x\n", cid, vmsvga3dGetRenderStateName(pRenderState[i].state), pRenderState[i].state, pRenderState[i].uintValue));
4303 /* Save the render state for vm state saving. */
4304 ASSERT_GUEST_RETURN((unsigned)pRenderState[i].state < SVGA3D_RS_MAX, VERR_INVALID_PARAMETER);
4305 pContext->state.aRenderState[pRenderState[i].state] = pRenderState[i];
4306
4307 switch (pRenderState[i].state)
4308 {
4309 case SVGA3D_RS_ZENABLE: /* SVGA3dBool */
4310 enableCap = GL_DEPTH_TEST;
4311 val = pRenderState[i].uintValue;
4312 break;
4313
4314 case SVGA3D_RS_ZWRITEENABLE: /* SVGA3dBool */
4315 glDepthMask(!!pRenderState[i].uintValue);
4316 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4317 break;
4318
4319 case SVGA3D_RS_ALPHATESTENABLE: /* SVGA3dBool */
4320 enableCap = GL_ALPHA_TEST;
4321 val = pRenderState[i].uintValue;
4322 break;
4323
4324 case SVGA3D_RS_DITHERENABLE: /* SVGA3dBool */
4325 enableCap = GL_DITHER;
4326 val = pRenderState[i].uintValue;
4327 break;
4328
4329 case SVGA3D_RS_FOGENABLE: /* SVGA3dBool */
4330 enableCap = GL_FOG;
4331 val = pRenderState[i].uintValue;
4332 break;
4333
4334 case SVGA3D_RS_SPECULARENABLE: /* SVGA3dBool */
4335 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4336 break;
4337
4338 case SVGA3D_RS_LIGHTINGENABLE: /* SVGA3dBool */
4339 enableCap = GL_LIGHTING;
4340 val = pRenderState[i].uintValue;
4341 break;
4342
4343 case SVGA3D_RS_NORMALIZENORMALS: /* SVGA3dBool */
4344 /* not applicable */
4345 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4346 break;
4347
4348 case SVGA3D_RS_POINTSPRITEENABLE: /* SVGA3dBool */
4349 enableCap = GL_POINT_SPRITE_ARB;
4350 val = pRenderState[i].uintValue;
4351 break;
4352
4353 case SVGA3D_RS_POINTSIZE: /* float */
4354 /** @todo we need to apply scaling for point sizes below the min or above the max; see Wine) */
4355 if (pRenderState[i].floatValue < pState->caps.flPointSize[0])
4356 pRenderState[i].floatValue = pState->caps.flPointSize[0];
4357 if (pRenderState[i].floatValue > pState->caps.flPointSize[1])
4358 pRenderState[i].floatValue = pState->caps.flPointSize[1];
4359
4360 glPointSize(pRenderState[i].floatValue);
4361 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4362 Log(("SVGA3D_RS_POINTSIZE: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4363 break;
4364
4365 case SVGA3D_RS_POINTSIZEMIN: /* float */
4366 pState->ext.glPointParameterf(GL_POINT_SIZE_MIN, pRenderState[i].floatValue);
4367 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4368 Log(("SVGA3D_RS_POINTSIZEMIN: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4369 break;
4370
4371 case SVGA3D_RS_POINTSIZEMAX: /* float */
4372 pState->ext.glPointParameterf(GL_POINT_SIZE_MAX, pRenderState[i].floatValue);
4373 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4374 Log(("SVGA3D_RS_POINTSIZEMAX: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4375 break;
4376
4377 case SVGA3D_RS_POINTSCALEENABLE: /* SVGA3dBool */
4378 case SVGA3D_RS_POINTSCALE_A: /* float */
4379 case SVGA3D_RS_POINTSCALE_B: /* float */
4380 case SVGA3D_RS_POINTSCALE_C: /* float */
4381 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4382 break;
4383
4384 case SVGA3D_RS_AMBIENT: /* SVGA3dColor */
4385 {
4386 GLfloat color[4]; /* red, green, blue, alpha */
4387
4388 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4389
4390 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, color);
4391 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4392 break;
4393 }
4394
4395 case SVGA3D_RS_CLIPPLANEENABLE: /* SVGA3dClipPlanes */
4396 {
4397 AssertCompile(SVGA3D_CLIPPLANE_MAX == (1 << 5));
4398 for (uint32_t j = 0; j <= 5; j++)
4399 {
4400 if (pRenderState[i].uintValue & RT_BIT(j))
4401 glEnable(GL_CLIP_PLANE0 + j);
4402 else
4403 glDisable(GL_CLIP_PLANE0 + j);
4404 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4405 }
4406 break;
4407 }
4408
4409 case SVGA3D_RS_FOGCOLOR: /* SVGA3dColor */
4410 {
4411 GLfloat color[4]; /* red, green, blue, alpha */
4412
4413 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4414
4415 glFogfv(GL_FOG_COLOR, color);
4416 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4417 break;
4418 }
4419
4420 case SVGA3D_RS_FOGSTART: /* float */
4421 glFogf(GL_FOG_START, pRenderState[i].floatValue);
4422 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4423 break;
4424
4425 case SVGA3D_RS_FOGEND: /* float */
4426 glFogf(GL_FOG_END, pRenderState[i].floatValue);
4427 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4428 break;
4429
4430 case SVGA3D_RS_FOGDENSITY: /* float */
4431 glFogf(GL_FOG_DENSITY, pRenderState[i].floatValue);
4432 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4433 break;
4434
4435 case SVGA3D_RS_RANGEFOGENABLE: /* SVGA3dBool */
4436 glFogi(GL_FOG_COORD_SRC, (pRenderState[i].uintValue) ? GL_FOG_COORD : GL_FRAGMENT_DEPTH);
4437 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4438 break;
4439
4440 case SVGA3D_RS_FOGMODE: /* SVGA3dFogMode */
4441 {
4442 SVGA3dFogMode mode;
4443 mode.uintValue = pRenderState[i].uintValue;
4444
4445 enableCap = GL_FOG_MODE;
4446 switch (mode.s.function)
4447 {
4448 case SVGA3D_FOGFUNC_EXP:
4449 val = GL_EXP;
4450 break;
4451 case SVGA3D_FOGFUNC_EXP2:
4452 val = GL_EXP2;
4453 break;
4454 case SVGA3D_FOGFUNC_LINEAR:
4455 val = GL_LINEAR;
4456 break;
4457 default:
4458 AssertMsgFailedReturn(("Unexpected fog function %d\n", mode.s.function), VERR_INTERNAL_ERROR);
4459 break;
4460 }
4461
4462 /** @todo how to switch between vertex and pixel fog modes??? */
4463 Assert(mode.s.type == SVGA3D_FOGTYPE_PIXEL);
4464#if 0
4465 /* The fog type determines the render state. */
4466 switch (mode.s.type)
4467 {
4468 case SVGA3D_FOGTYPE_VERTEX:
4469 renderState = D3DRS_FOGVERTEXMODE;
4470 break;
4471 case SVGA3D_FOGTYPE_PIXEL:
4472 renderState = D3DRS_FOGTABLEMODE;
4473 break;
4474 default:
4475 AssertMsgFailedReturn(("Unexpected fog type %d\n", mode.s.type), VERR_INTERNAL_ERROR);
4476 break;
4477 }
4478#endif
4479
4480 /* Set the fog base to depth or range. */
4481 switch (mode.s.base)
4482 {
4483 case SVGA3D_FOGBASE_DEPTHBASED:
4484 glFogi(GL_FOG_COORD_SRC, GL_FRAGMENT_DEPTH);
4485 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4486 break;
4487 case SVGA3D_FOGBASE_RANGEBASED:
4488 glFogi(GL_FOG_COORD_SRC, GL_FOG_COORD);
4489 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4490 break;
4491 default:
4492 /* ignore */
4493 AssertMsgFailed(("Unexpected fog base %d\n", mode.s.base));
4494 break;
4495 }
4496 break;
4497 }
4498
4499 case SVGA3D_RS_FILLMODE: /* SVGA3dFillMode */
4500 {
4501 SVGA3dFillMode mode;
4502
4503 mode.uintValue = pRenderState[i].uintValue;
4504
4505 switch (mode.s.mode)
4506 {
4507 case SVGA3D_FILLMODE_POINT:
4508 val = GL_POINT;
4509 break;
4510 case SVGA3D_FILLMODE_LINE:
4511 val = GL_LINE;
4512 break;
4513 case SVGA3D_FILLMODE_FILL:
4514 val = GL_FILL;
4515 break;
4516 default:
4517 AssertMsgFailedReturn(("Unexpected fill mode %d\n", mode.s.mode), VERR_INTERNAL_ERROR);
4518 break;
4519 }
4520 /* @note only front and back faces */
4521 Assert(mode.s.face == SVGA3D_FACE_FRONT_BACK);
4522 glPolygonMode(GL_FRONT_AND_BACK, val);
4523 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4524 break;
4525 }
4526
4527 case SVGA3D_RS_SHADEMODE: /* SVGA3dShadeMode */
4528 switch (pRenderState[i].uintValue)
4529 {
4530 case SVGA3D_SHADEMODE_FLAT:
4531 val = GL_FLAT;
4532 break;
4533
4534 case SVGA3D_SHADEMODE_SMOOTH:
4535 val = GL_SMOOTH;
4536 break;
4537
4538 default:
4539 AssertMsgFailedReturn(("Unexpected shade mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4540 break;
4541 }
4542
4543 glShadeModel(val);
4544 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4545 break;
4546
4547 case SVGA3D_RS_LINEPATTERN: /* SVGA3dLinePattern */
4548 /* No longer supported by d3d; mesagl comments suggest not all backends support it */
4549 /** @todo */
4550 Log(("WARNING: SVGA3D_RS_LINEPATTERN %x not supported!!\n", pRenderState[i].uintValue));
4551 /*
4552 renderState = D3DRS_LINEPATTERN;
4553 val = pRenderState[i].uintValue;
4554 */
4555 break;
4556
4557 case SVGA3D_RS_LINEAA: /* SVGA3dBool */
4558 enableCap = GL_LINE_SMOOTH;
4559 val = pRenderState[i].uintValue;
4560 break;
4561
4562 case SVGA3D_RS_LINEWIDTH: /* float */
4563 glLineWidth(pRenderState[i].floatValue);
4564 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4565 break;
4566
4567 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
4568 {
4569 /* Refresh the blending state based on the new enable setting.
4570 * This will take existing states and set them using either glBlend* or glBlend*Separate.
4571 */
4572 static SVGA3dRenderStateName const saRefreshState[] =
4573 {
4574 SVGA3D_RS_SRCBLEND,
4575 SVGA3D_RS_BLENDEQUATION
4576 };
4577 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4578 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4579 {
4580 renderstate[j].state = saRefreshState[j];
4581 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4582 }
4583
4584 rc = vmsvga3dSetRenderState(pThisCC, cid, 2, renderstate);
4585 AssertRCReturn(rc, rc);
4586
4587 if (pContext->state.aRenderState[SVGA3D_RS_BLENDENABLE].uintValue != 0)
4588 continue; /* Ignore if blend is enabled */
4589 /* Apply SVGA3D_RS_SEPARATEALPHABLENDENABLE as SVGA3D_RS_BLENDENABLE */
4590 } RT_FALL_THRU();
4591
4592 case SVGA3D_RS_BLENDENABLE: /* SVGA3dBool */
4593 enableCap = GL_BLEND;
4594 val = pRenderState[i].uintValue;
4595 break;
4596
4597 case SVGA3D_RS_SRCBLENDALPHA: /* SVGA3dBlendOp */
4598 case SVGA3D_RS_DSTBLENDALPHA: /* SVGA3dBlendOp */
4599 case SVGA3D_RS_SRCBLEND: /* SVGA3dBlendOp */
4600 case SVGA3D_RS_DSTBLEND: /* SVGA3dBlendOp */
4601 {
4602 GLint srcRGB, srcAlpha, dstRGB, dstAlpha;
4603 GLint blendop = vmsvga3dBlendOp2GL(pRenderState[i].uintValue);
4604
4605 glGetIntegerv(GL_BLEND_SRC_RGB, &srcRGB);
4606 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4607 glGetIntegerv(GL_BLEND_DST_RGB, &dstRGB);
4608 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4609 glGetIntegerv(GL_BLEND_DST_ALPHA, &dstAlpha);
4610 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4611 glGetIntegerv(GL_BLEND_SRC_ALPHA, &srcAlpha);
4612 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4613
4614 switch (pRenderState[i].state)
4615 {
4616 case SVGA3D_RS_SRCBLEND:
4617 srcRGB = blendop;
4618 break;
4619 case SVGA3D_RS_DSTBLEND:
4620 dstRGB = blendop;
4621 break;
4622 case SVGA3D_RS_SRCBLENDALPHA:
4623 srcAlpha = blendop;
4624 break;
4625 case SVGA3D_RS_DSTBLENDALPHA:
4626 dstAlpha = blendop;
4627 break;
4628 default:
4629 /* not possible; shut up gcc */
4630 AssertFailed();
4631 break;
4632 }
4633
4634 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4635 pState->ext.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
4636 else
4637 glBlendFunc(srcRGB, dstRGB);
4638 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4639 break;
4640 }
4641
4642 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
4643 case SVGA3D_RS_BLENDEQUATION: /* SVGA3dBlendEquation */
4644 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4645 {
4646 GLenum const modeRGB = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATION].uintValue);
4647 GLenum const modeAlpha = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATIONALPHA].uintValue);
4648 pState->ext.glBlendEquationSeparate(modeRGB, modeAlpha);
4649 }
4650 else
4651 {
4652#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4653 glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4654#else
4655 pState->ext.glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4656#endif
4657 }
4658 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4659 break;
4660
4661 case SVGA3D_RS_BLENDCOLOR: /* SVGA3dColor */
4662 {
4663 GLfloat red, green, blue, alpha;
4664
4665 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &red, &green, &blue, &alpha);
4666
4667#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4668 glBlendColor(red, green, blue, alpha);
4669#else
4670 pState->ext.glBlendColor(red, green, blue, alpha);
4671#endif
4672 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4673 break;
4674 }
4675
4676 case SVGA3D_RS_CULLMODE: /* SVGA3dFace */
4677 {
4678 GLenum mode = GL_BACK; /* default for OpenGL */
4679
4680 switch (pRenderState[i].uintValue)
4681 {
4682 case SVGA3D_FACE_NONE:
4683 break;
4684 case SVGA3D_FACE_FRONT:
4685 mode = GL_FRONT;
4686 break;
4687 case SVGA3D_FACE_BACK:
4688 mode = GL_BACK;
4689 break;
4690 case SVGA3D_FACE_FRONT_BACK:
4691 mode = GL_FRONT_AND_BACK;
4692 break;
4693 default:
4694 AssertMsgFailedReturn(("Unexpected cull mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4695 break;
4696 }
4697 enableCap = GL_CULL_FACE;
4698 if (pRenderState[i].uintValue != SVGA3D_FACE_NONE)
4699 {
4700 glCullFace(mode);
4701 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4702 val = 1;
4703 }
4704 else
4705 val = 0;
4706 break;
4707 }
4708
4709 case SVGA3D_RS_ZFUNC: /* SVGA3dCmpFunc */
4710 glDepthFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue));
4711 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4712 break;
4713
4714 case SVGA3D_RS_ALPHAFUNC: /* SVGA3dCmpFunc */
4715 {
4716 GLclampf ref;
4717
4718 glGetFloatv(GL_ALPHA_TEST_REF, &ref);
4719 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4720 glAlphaFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue), ref);
4721 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4722 break;
4723 }
4724
4725 case SVGA3D_RS_ALPHAREF: /* float (0.0 .. 1.0) */
4726 {
4727 GLint func;
4728
4729 glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
4730 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4731 glAlphaFunc(func, pRenderState[i].floatValue);
4732 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4733 break;
4734 }
4735
4736 case SVGA3D_RS_STENCILENABLE2SIDED: /* SVGA3dBool */
4737 {
4738 /* Refresh the stencil state based on the new enable setting.
4739 * This will take existing states and set them using either glStencil or glStencil*Separate.
4740 */
4741 static SVGA3dRenderStateName const saRefreshState[] =
4742 {
4743 SVGA3D_RS_STENCILFUNC,
4744 SVGA3D_RS_STENCILFAIL,
4745 SVGA3D_RS_CCWSTENCILFUNC,
4746 SVGA3D_RS_CCWSTENCILFAIL
4747 };
4748 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4749 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4750 {
4751 renderstate[j].state = saRefreshState[j];
4752 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4753 }
4754
4755 rc = vmsvga3dSetRenderState(pThisCC, cid, RT_ELEMENTS(renderstate), renderstate);
4756 AssertRCReturn(rc, rc);
4757
4758 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE].uintValue != 0)
4759 continue; /* Ignore if stencil is enabled */
4760 /* Apply SVGA3D_RS_STENCILENABLE2SIDED as SVGA3D_RS_STENCILENABLE. */
4761 } RT_FALL_THRU();
4762
4763 case SVGA3D_RS_STENCILENABLE: /* SVGA3dBool */
4764 enableCap = GL_STENCIL_TEST;
4765 val = pRenderState[i].uintValue;
4766 break;
4767
4768 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4769 case SVGA3D_RS_STENCILREF: /* uint32_t */
4770 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4771 {
4772 GLint func, ref;
4773 GLuint mask;
4774
4775 /* Query current values to have all parameters for glStencilFunc[Separate]. */
4776 glGetIntegerv(GL_STENCIL_FUNC, &func);
4777 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4778 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4779 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4780 glGetIntegerv(GL_STENCIL_REF, &ref);
4781 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4782
4783 /* Update the changed value. */
4784 switch (pRenderState[i].state)
4785 {
4786 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4787 func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4788 break;
4789
4790 case SVGA3D_RS_STENCILREF: /* uint32_t */
4791 ref = pRenderState[i].uintValue;
4792 break;
4793
4794 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4795 mask = pRenderState[i].uintValue;
4796 break;
4797
4798 default:
4799 /* not possible; shut up gcc */
4800 AssertFailed();
4801 break;
4802 }
4803
4804 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4805 {
4806 pState->ext.glStencilFuncSeparate(GL_FRONT, func, ref, mask);
4807 }
4808 else
4809 {
4810 glStencilFunc(func, ref, mask);
4811 }
4812 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4813 break;
4814 }
4815
4816 case SVGA3D_RS_STENCILWRITEMASK: /* uint32_t */
4817 glStencilMask(pRenderState[i].uintValue);
4818 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4819 break;
4820
4821 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4822 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4823 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4824 {
4825 GLint sfail, dpfail, dppass;
4826 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4827
4828 glGetIntegerv(GL_STENCIL_FAIL, &sfail);
4829 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4830 glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail);
4831 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4832 glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass);
4833 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4834
4835 switch (pRenderState[i].state)
4836 {
4837 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4838 sfail = stencilop;
4839 break;
4840 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4841 dpfail = stencilop;
4842 break;
4843 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4844 dppass = stencilop;
4845 break;
4846 default:
4847 /* not possible; shut up gcc */
4848 AssertFailed();
4849 break;
4850 }
4851 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4852 {
4853 pState->ext.glStencilOpSeparate(GL_FRONT, sfail, dpfail, dppass);
4854 }
4855 else
4856 {
4857 glStencilOp(sfail, dpfail, dppass);
4858 }
4859 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4860 break;
4861 }
4862
4863 case SVGA3D_RS_CCWSTENCILFUNC: /* SVGA3dCmpFunc */
4864 {
4865 GLint ref;
4866 GLuint mask;
4867 GLint const func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4868
4869 /* GL_STENCIL_VALUE_MASK and GL_STENCIL_REF are the same for both GL_FRONT and GL_BACK. */
4870 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4871 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4872 glGetIntegerv(GL_STENCIL_REF, &ref);
4873 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4874
4875 pState->ext.glStencilFuncSeparate(GL_BACK, func, ref, mask);
4876 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4877 break;
4878 }
4879
4880 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
4881 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
4882 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
4883 {
4884 GLint sfail, dpfail, dppass;
4885 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4886
4887 glGetIntegerv(GL_STENCIL_BACK_FAIL, &sfail);
4888 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4889 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail);
4890 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4891 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass);
4892 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4893
4894 switch (pRenderState[i].state)
4895 {
4896 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
4897 sfail = stencilop;
4898 break;
4899 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
4900 dpfail = stencilop;
4901 break;
4902 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
4903 dppass = stencilop;
4904 break;
4905 default:
4906 /* not possible; shut up gcc */
4907 AssertFailed();
4908 break;
4909 }
4910 pState->ext.glStencilOpSeparate(GL_BACK, sfail, dpfail, dppass);
4911 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4912 break;
4913 }
4914
4915 case SVGA3D_RS_ZBIAS: /* float */
4916 /** @todo unknown meaning; depth bias is not identical
4917 renderState = D3DRS_DEPTHBIAS;
4918 val = pRenderState[i].uintValue;
4919 */
4920 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_RS_ZBIAS\n"));
4921 break;
4922
4923 case SVGA3D_RS_DEPTHBIAS: /* float */
4924 {
4925 GLfloat factor;
4926
4927 /** @todo not sure if the d3d & ogl definitions are identical. */
4928
4929 /* Do not change the factor part. */
4930 glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor);
4931 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4932
4933 glPolygonOffset(factor, pRenderState[i].floatValue);
4934 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4935 break;
4936 }
4937
4938 case SVGA3D_RS_SLOPESCALEDEPTHBIAS: /* float */
4939 {
4940 GLfloat units;
4941
4942 /** @todo not sure if the d3d & ogl definitions are identical. */
4943
4944 /* Do not change the factor part. */
4945 glGetFloatv(GL_POLYGON_OFFSET_UNITS, &units);
4946 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4947
4948 glPolygonOffset(pRenderState[i].floatValue, units);
4949 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4950 break;
4951 }
4952
4953 case SVGA3D_RS_COLORWRITEENABLE: /* SVGA3dColorMask */
4954 {
4955 GLboolean red, green, blue, alpha;
4956 SVGA3dColorMask mask;
4957
4958 mask.uintValue = pRenderState[i].uintValue;
4959
4960 red = mask.s.red;
4961 green = mask.s.green;
4962 blue = mask.s.blue;
4963 alpha = mask.s.alpha;
4964
4965 glColorMask(red, green, blue, alpha);
4966 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4967 break;
4968 }
4969
4970 case SVGA3D_RS_COLORWRITEENABLE1: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4971 case SVGA3D_RS_COLORWRITEENABLE2: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4972 case SVGA3D_RS_COLORWRITEENABLE3: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
4973 Log(("vmsvga3dSetRenderState: WARNING SVGA3D_RS_COLORWRITEENABLEx not supported!!\n"));
4974 break;
4975
4976 case SVGA3D_RS_SCISSORTESTENABLE: /* SVGA3dBool */
4977 enableCap = GL_SCISSOR_TEST;
4978 val = pRenderState[i].uintValue;
4979 break;
4980
4981#if 0
4982 case SVGA3D_RS_DIFFUSEMATERIALSOURCE: /* SVGA3dVertexMaterial */
4983 AssertCompile(D3DMCS_COLOR2 == SVGA3D_VERTEXMATERIAL_SPECULAR);
4984 renderState = D3DRS_DIFFUSEMATERIALSOURCE;
4985 val = pRenderState[i].uintValue;
4986 break;
4987
4988 case SVGA3D_RS_SPECULARMATERIALSOURCE: /* SVGA3dVertexMaterial */
4989 renderState = D3DRS_SPECULARMATERIALSOURCE;
4990 val = pRenderState[i].uintValue;
4991 break;
4992
4993 case SVGA3D_RS_AMBIENTMATERIALSOURCE: /* SVGA3dVertexMaterial */
4994 renderState = D3DRS_AMBIENTMATERIALSOURCE;
4995 val = pRenderState[i].uintValue;
4996 break;
4997
4998 case SVGA3D_RS_EMISSIVEMATERIALSOURCE: /* SVGA3dVertexMaterial */
4999 renderState = D3DRS_EMISSIVEMATERIALSOURCE;
5000 val = pRenderState[i].uintValue;
5001 break;
5002#endif
5003
5004 case SVGA3D_RS_WRAP3: /* SVGA3dWrapFlags */
5005 case SVGA3D_RS_WRAP4: /* SVGA3dWrapFlags */
5006 case SVGA3D_RS_WRAP5: /* SVGA3dWrapFlags */
5007 case SVGA3D_RS_WRAP6: /* SVGA3dWrapFlags */
5008 case SVGA3D_RS_WRAP7: /* SVGA3dWrapFlags */
5009 case SVGA3D_RS_WRAP8: /* SVGA3dWrapFlags */
5010 case SVGA3D_RS_WRAP9: /* SVGA3dWrapFlags */
5011 case SVGA3D_RS_WRAP10: /* SVGA3dWrapFlags */
5012 case SVGA3D_RS_WRAP11: /* SVGA3dWrapFlags */
5013 case SVGA3D_RS_WRAP12: /* SVGA3dWrapFlags */
5014 case SVGA3D_RS_WRAP13: /* SVGA3dWrapFlags */
5015 case SVGA3D_RS_WRAP14: /* SVGA3dWrapFlags */
5016 case SVGA3D_RS_WRAP15: /* SVGA3dWrapFlags */
5017 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_WRAPx (x >= 3)\n"));
5018 break;
5019
5020 case SVGA3D_RS_LASTPIXEL: /* SVGA3dBool */
5021 case SVGA3D_RS_TWEENFACTOR: /* float */
5022 case SVGA3D_RS_INDEXEDVERTEXBLENDENABLE: /* SVGA3dBool */
5023 case SVGA3D_RS_VERTEXBLEND: /* SVGA3dVertexBlendFlags */
5024 Log(("vmsvga3dSetRenderState: WARNING not applicable!!\n"));
5025 break;
5026
5027 case SVGA3D_RS_MULTISAMPLEANTIALIAS: /* SVGA3dBool */
5028 enableCap = GL_MULTISAMPLE;
5029 val = pRenderState[i].uintValue;
5030 break;
5031
5032 case SVGA3D_RS_MULTISAMPLEMASK: /* uint32_t */
5033 case SVGA3D_RS_ANTIALIASEDLINEENABLE: /* SVGA3dBool */
5034 Log(("vmsvga3dSetRenderState: WARNING not applicable??!!\n"));
5035 break;
5036
5037 case SVGA3D_RS_COORDINATETYPE: /* SVGA3dCoordinateType */
5038 Assert(pRenderState[i].uintValue == SVGA3D_COORDINATE_LEFTHANDED);
5039 /** @todo setup a view matrix to scale the world space by -1 in the z-direction for right handed coordinates. */
5040 /*
5041 renderState = D3DRS_COORDINATETYPE;
5042 val = pRenderState[i].uintValue;
5043 */
5044 break;
5045
5046 case SVGA3D_RS_FRONTWINDING: /* SVGA3dFrontWinding */
5047 Assert(pRenderState[i].uintValue == SVGA3D_FRONTWINDING_CW);
5048 /* Invert the selected mode because of y-inversion (?) */
5049 glFrontFace((pRenderState[i].uintValue != SVGA3D_FRONTWINDING_CW) ? GL_CW : GL_CCW);
5050 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5051 break;
5052
5053 case SVGA3D_RS_OUTPUTGAMMA: /* float */
5054 //AssertFailed();
5055 /*
5056 D3DRS_SRGBWRITEENABLE ??
5057 renderState = D3DRS_OUTPUTGAMMA;
5058 val = pRenderState[i].uintValue;
5059 */
5060 break;
5061
5062#if 0
5063
5064 case SVGA3D_RS_VERTEXMATERIALENABLE: /* SVGA3dBool */
5065 //AssertFailed();
5066 renderState = D3DRS_INDEXEDVERTEXBLENDENABLE; /* correct?? */
5067 val = pRenderState[i].uintValue;
5068 break;
5069
5070 case SVGA3D_RS_TEXTUREFACTOR: /* SVGA3dColor */
5071 renderState = D3DRS_TEXTUREFACTOR;
5072 val = pRenderState[i].uintValue;
5073 break;
5074
5075 case SVGA3D_RS_LOCALVIEWER: /* SVGA3dBool */
5076 renderState = D3DRS_LOCALVIEWER;
5077 val = pRenderState[i].uintValue;
5078 break;
5079
5080 case SVGA3D_RS_ZVISIBLE: /* SVGA3dBool */
5081 AssertFailed();
5082 /*
5083 renderState = D3DRS_ZVISIBLE;
5084 val = pRenderState[i].uintValue;
5085 */
5086 break;
5087
5088 case SVGA3D_RS_CLIPPING: /* SVGA3dBool */
5089 renderState = D3DRS_CLIPPING;
5090 val = pRenderState[i].uintValue;
5091 break;
5092
5093 case SVGA3D_RS_WRAP0: /* SVGA3dWrapFlags */
5094 glTexParameter GL_TEXTURE_WRAP_S
5095 Assert(SVGA3D_WRAPCOORD_3 == D3DWRAPCOORD_3);
5096 renderState = D3DRS_WRAP0;
5097 val = pRenderState[i].uintValue;
5098 break;
5099
5100 case SVGA3D_RS_WRAP1: /* SVGA3dWrapFlags */
5101 glTexParameter GL_TEXTURE_WRAP_T
5102 renderState = D3DRS_WRAP1;
5103 val = pRenderState[i].uintValue;
5104 break;
5105
5106 case SVGA3D_RS_WRAP2: /* SVGA3dWrapFlags */
5107 glTexParameter GL_TEXTURE_WRAP_R
5108 renderState = D3DRS_WRAP2;
5109 val = pRenderState[i].uintValue;
5110 break;
5111
5112
5113 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
5114 renderState = D3DRS_SEPARATEALPHABLENDENABLE;
5115 val = pRenderState[i].uintValue;
5116 break;
5117
5118
5119 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
5120 renderState = D3DRS_BLENDOPALPHA;
5121 val = pRenderState[i].uintValue;
5122 break;
5123
5124 case SVGA3D_RS_TRANSPARENCYANTIALIAS: /* SVGA3dTransparencyAntialiasType */
5125 AssertFailed();
5126 /*
5127 renderState = D3DRS_TRANSPARENCYANTIALIAS;
5128 val = pRenderState[i].uintValue;
5129 */
5130 break;
5131
5132#endif
5133 default:
5134 AssertFailed();
5135 break;
5136 }
5137
5138 if (enableCap != ~(GLenum)0)
5139 {
5140 if (val)
5141 glEnable(enableCap);
5142 else
5143 glDisable(enableCap);
5144 }
5145 }
5146
5147 return VINF_SUCCESS;
5148}
5149
5150int vmsvga3dSetRenderTarget(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRenderTargetType type, SVGA3dSurfaceImageId target)
5151{
5152 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5153
5154 AssertReturn(pState, VERR_NO_MEMORY);
5155 AssertReturn((unsigned)type < SVGA3D_RT_MAX, VERR_INVALID_PARAMETER);
5156
5157 LogFunc(("cid=%u type=%x sid=%u\n", cid, type, target.sid));
5158
5159 PVMSVGA3DCONTEXT pContext;
5160 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5161 AssertRCReturn(rc, rc);
5162
5163 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5164
5165 /* Save for vm state save/restore. */
5166 pContext->state.aRenderTargets[type] = target.sid;
5167
5168 if (target.sid == SVGA3D_INVALID_ID)
5169 {
5170 /* Disable render target. */
5171 switch (type)
5172 {
5173 case SVGA3D_RT_DEPTH:
5174 case SVGA3D_RT_STENCIL:
5175 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER, (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
5176 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5177 break;
5178
5179 case SVGA3D_RT_COLOR0:
5180 case SVGA3D_RT_COLOR1:
5181 case SVGA3D_RT_COLOR2:
5182 case SVGA3D_RT_COLOR3:
5183 case SVGA3D_RT_COLOR4:
5184 case SVGA3D_RT_COLOR5:
5185 case SVGA3D_RT_COLOR6:
5186 case SVGA3D_RT_COLOR7:
5187 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0, 0, 0, 0);
5188 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5189 break;
5190
5191 default:
5192 AssertFailedReturn(VERR_INVALID_PARAMETER);
5193 }
5194 return VINF_SUCCESS;
5195 }
5196
5197 PVMSVGA3DSURFACE pRenderTarget;
5198 rc = vmsvga3dSurfaceFromSid(pState, target.sid, &pRenderTarget);
5199 AssertRCReturn(rc, rc);
5200
5201 switch (type)
5202 {
5203 case SVGA3D_RT_DEPTH:
5204 case SVGA3D_RT_STENCIL:
5205#if 1
5206 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5207 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5208 {
5209 LogFunc(("create depth texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n",
5210 target.sid, pRenderTarget->surfaceFlags, pRenderTarget->format));
5211 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pRenderTarget);
5212 AssertRCReturn(rc, rc);
5213 }
5214
5215 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5216 Assert(!pRenderTarget->fDirty);
5217
5218 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5219
5220 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER,
5221 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5222 GL_TEXTURE_2D, pRenderTarget->oglId.texture, target.mipmap);
5223 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5224#else
5225 AssertReturn(target.mipmap == 0, VERR_INVALID_PARAMETER);
5226 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5227 {
5228 Log(("vmsvga3dSetRenderTarget: create renderbuffer to be used as render target; surface id=%x type=%d format=%d\n", target.sid, pRenderTarget->surfaceFlags, pRenderTarget->internalFormatGL));
5229 pContext = &pState->SharedCtx;
5230 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5231
5232 pState->ext.glGenRenderbuffers(1, &pRenderTarget->oglId.renderbuffer);
5233 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5234 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_RENDERBUFFER;
5235
5236 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5237 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5238
5239 pState->ext.glRenderbufferStorage(GL_RENDERBUFFER,
5240 pRenderTarget->internalFormatGL,
5241 pRenderTarget->paMipmapLevels[0].mipmapSize.width,
5242 pRenderTarget->paMipmapLevels[0].mipmapSize.height);
5243 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5244
5245 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, OPENGL_INVALID_ID);
5246 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5247
5248 pContext = pState->papContexts[cid];
5249 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5250 pRenderTarget->idWeakContextAssociation = cid;
5251 }
5252
5253 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5254 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5255 Assert(!pRenderTarget->fDirty);
5256 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5257
5258 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5259
5260 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
5261 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5262 GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5263 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5264#endif
5265 break;
5266
5267 case SVGA3D_RT_COLOR0:
5268 case SVGA3D_RT_COLOR1:
5269 case SVGA3D_RT_COLOR2:
5270 case SVGA3D_RT_COLOR3:
5271 case SVGA3D_RT_COLOR4:
5272 case SVGA3D_RT_COLOR5:
5273 case SVGA3D_RT_COLOR6:
5274 case SVGA3D_RT_COLOR7:
5275 {
5276 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5277 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5278 {
5279 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));
5280 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pRenderTarget);
5281 AssertRCReturn(rc, rc);
5282 }
5283
5284 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5285 Assert(!pRenderTarget->fDirty);
5286
5287 pRenderTarget->surfaceFlags |= SVGA3D_SURFACE_HINT_RENDERTARGET;
5288
5289 GLenum textarget;
5290 if (pRenderTarget->surfaceFlags & SVGA3D_SURFACE_CUBEMAP)
5291 textarget = vmsvga3dCubemapFaceFromIndex(target.face);
5292 else
5293 textarget = GL_TEXTURE_2D;
5294 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0,
5295 textarget, pRenderTarget->oglId.texture, target.mipmap);
5296 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5297
5298#ifdef DEBUG
5299 GLenum status = pState->ext.glCheckFramebufferStatus(GL_FRAMEBUFFER);
5300 if (status != GL_FRAMEBUFFER_COMPLETE)
5301 Log(("vmsvga3dSetRenderTarget: WARNING: glCheckFramebufferStatus returned %x\n", status));
5302#endif
5303 /** @todo use glDrawBuffers too? */
5304 break;
5305 }
5306
5307 default:
5308 AssertFailedReturn(VERR_INVALID_PARAMETER);
5309 }
5310
5311 return VINF_SUCCESS;
5312}
5313
5314#if 0
5315/**
5316 * Convert SVGA texture combiner value to its D3D equivalent
5317 */
5318static DWORD vmsvga3dTextureCombiner2D3D(uint32_t value)
5319{
5320 switch (value)
5321 {
5322 case SVGA3D_TC_DISABLE:
5323 return D3DTOP_DISABLE;
5324 case SVGA3D_TC_SELECTARG1:
5325 return D3DTOP_SELECTARG1;
5326 case SVGA3D_TC_SELECTARG2:
5327 return D3DTOP_SELECTARG2;
5328 case SVGA3D_TC_MODULATE:
5329 return D3DTOP_MODULATE;
5330 case SVGA3D_TC_ADD:
5331 return D3DTOP_ADD;
5332 case SVGA3D_TC_ADDSIGNED:
5333 return D3DTOP_ADDSIGNED;
5334 case SVGA3D_TC_SUBTRACT:
5335 return D3DTOP_SUBTRACT;
5336 case SVGA3D_TC_BLENDTEXTUREALPHA:
5337 return D3DTOP_BLENDTEXTUREALPHA;
5338 case SVGA3D_TC_BLENDDIFFUSEALPHA:
5339 return D3DTOP_BLENDDIFFUSEALPHA;
5340 case SVGA3D_TC_BLENDCURRENTALPHA:
5341 return D3DTOP_BLENDCURRENTALPHA;
5342 case SVGA3D_TC_BLENDFACTORALPHA:
5343 return D3DTOP_BLENDFACTORALPHA;
5344 case SVGA3D_TC_MODULATE2X:
5345 return D3DTOP_MODULATE2X;
5346 case SVGA3D_TC_MODULATE4X:
5347 return D3DTOP_MODULATE4X;
5348 case SVGA3D_TC_DSDT:
5349 AssertFailed(); /** @todo ??? */
5350 return D3DTOP_DISABLE;
5351 case SVGA3D_TC_DOTPRODUCT3:
5352 return D3DTOP_DOTPRODUCT3;
5353 case SVGA3D_TC_BLENDTEXTUREALPHAPM:
5354 return D3DTOP_BLENDTEXTUREALPHAPM;
5355 case SVGA3D_TC_ADDSIGNED2X:
5356 return D3DTOP_ADDSIGNED2X;
5357 case SVGA3D_TC_ADDSMOOTH:
5358 return D3DTOP_ADDSMOOTH;
5359 case SVGA3D_TC_PREMODULATE:
5360 return D3DTOP_PREMODULATE;
5361 case SVGA3D_TC_MODULATEALPHA_ADDCOLOR:
5362 return D3DTOP_MODULATEALPHA_ADDCOLOR;
5363 case SVGA3D_TC_MODULATECOLOR_ADDALPHA:
5364 return D3DTOP_MODULATECOLOR_ADDALPHA;
5365 case SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR:
5366 return D3DTOP_MODULATEINVALPHA_ADDCOLOR;
5367 case SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA:
5368 return D3DTOP_MODULATEINVCOLOR_ADDALPHA;
5369 case SVGA3D_TC_BUMPENVMAPLUMINANCE:
5370 return D3DTOP_BUMPENVMAPLUMINANCE;
5371 case SVGA3D_TC_MULTIPLYADD:
5372 return D3DTOP_MULTIPLYADD;
5373 case SVGA3D_TC_LERP:
5374 return D3DTOP_LERP;
5375 default:
5376 AssertFailed();
5377 return D3DTOP_DISABLE;
5378 }
5379}
5380
5381/**
5382 * Convert SVGA texture arg data value to its D3D equivalent
5383 */
5384static DWORD vmsvga3dTextureArgData2D3D(uint32_t value)
5385{
5386 switch (value)
5387 {
5388 case SVGA3D_TA_CONSTANT:
5389 return D3DTA_CONSTANT;
5390 case SVGA3D_TA_PREVIOUS:
5391 return D3DTA_CURRENT; /* current = previous */
5392 case SVGA3D_TA_DIFFUSE:
5393 return D3DTA_DIFFUSE;
5394 case SVGA3D_TA_TEXTURE:
5395 return D3DTA_TEXTURE;
5396 case SVGA3D_TA_SPECULAR:
5397 return D3DTA_SPECULAR;
5398 default:
5399 AssertFailed();
5400 return 0;
5401 }
5402}
5403
5404/**
5405 * Convert SVGA texture transform flag value to its D3D equivalent
5406 */
5407static DWORD vmsvga3dTextTransformFlags2D3D(uint32_t value)
5408{
5409 switch (value)
5410 {
5411 case SVGA3D_TEX_TRANSFORM_OFF:
5412 return D3DTTFF_DISABLE;
5413 case SVGA3D_TEX_TRANSFORM_S:
5414 return D3DTTFF_COUNT1; /** @todo correct? */
5415 case SVGA3D_TEX_TRANSFORM_T:
5416 return D3DTTFF_COUNT2; /** @todo correct? */
5417 case SVGA3D_TEX_TRANSFORM_R:
5418 return D3DTTFF_COUNT3; /** @todo correct? */
5419 case SVGA3D_TEX_TRANSFORM_Q:
5420 return D3DTTFF_COUNT4; /** @todo correct? */
5421 case SVGA3D_TEX_PROJECTED:
5422 return D3DTTFF_PROJECTED;
5423 default:
5424 AssertFailed();
5425 return 0;
5426 }
5427}
5428#endif
5429
5430static GLenum vmsvga3dTextureAddress2OGL(SVGA3dTextureAddress value)
5431{
5432 switch (value)
5433 {
5434 case SVGA3D_TEX_ADDRESS_WRAP:
5435 return GL_REPEAT;
5436 case SVGA3D_TEX_ADDRESS_MIRROR:
5437 return GL_MIRRORED_REPEAT;
5438 case SVGA3D_TEX_ADDRESS_CLAMP:
5439 return GL_CLAMP_TO_EDGE;
5440 case SVGA3D_TEX_ADDRESS_BORDER:
5441 return GL_CLAMP_TO_BORDER;
5442 case SVGA3D_TEX_ADDRESS_MIRRORONCE:
5443 AssertFailed();
5444 return GL_CLAMP_TO_EDGE_SGIS; /** @todo correct? */
5445
5446 case SVGA3D_TEX_ADDRESS_EDGE:
5447 case SVGA3D_TEX_ADDRESS_INVALID:
5448 default:
5449 AssertFailed();
5450 return GL_REPEAT; /* default */
5451 }
5452}
5453
5454static GLenum vmsvga3dTextureFilter2OGL(SVGA3dTextureFilter value)
5455{
5456 switch (value)
5457 {
5458 case SVGA3D_TEX_FILTER_NONE:
5459 case SVGA3D_TEX_FILTER_LINEAR:
5460 case SVGA3D_TEX_FILTER_ANISOTROPIC: /* Anisotropic filtering is controlled by SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL */
5461 return GL_LINEAR;
5462 case SVGA3D_TEX_FILTER_NEAREST:
5463 return GL_NEAREST;
5464 case SVGA3D_TEX_FILTER_FLATCUBIC: // Deprecated, not implemented
5465 case SVGA3D_TEX_FILTER_GAUSSIANCUBIC: // Deprecated, not implemented
5466 case SVGA3D_TEX_FILTER_PYRAMIDALQUAD: // Not currently implemented
5467 case SVGA3D_TEX_FILTER_GAUSSIANQUAD: // Not currently implemented
5468 default:
5469 AssertFailed();
5470 return GL_LINEAR; /* default */
5471 }
5472}
5473
5474uint32_t vmsvga3dSVGA3dColor2RGBA(SVGA3dColor value)
5475{
5476 /* flip the red and blue bytes */
5477 uint8_t blue = value & 0xff;
5478 uint8_t red = (value >> 16) & 0xff;
5479 return (value & 0xff00ff00) | red | (blue << 16);
5480}
5481
5482int vmsvga3dSetTextureState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cTextureStates, SVGA3dTextureState *pTextureState)
5483{
5484 GLenum val = ~(GLenum)0; /* Shut up MSC. */
5485 GLenum currentStage = ~(GLenum)0;
5486 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5487 AssertReturn(pState, VERR_NO_MEMORY);
5488
5489 Log(("vmsvga3dSetTextureState %x cTextureState=%d\n", cid, cTextureStates));
5490
5491 PVMSVGA3DCONTEXT pContext;
5492 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5493 AssertRCReturn(rc, rc);
5494
5495 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5496
5497 /* Which texture is active for the current stage. Needed to use right OpenGL target when setting parameters. */
5498 PVMSVGA3DSURFACE pCurrentTextureSurface = NULL;
5499
5500 for (uint32_t i = 0; i < cTextureStates; ++i)
5501 {
5502 GLenum textureType = ~(GLenum)0;
5503#if 0
5504 GLenum samplerType = ~(GLenum)0;
5505#endif
5506
5507 LogFunc(("cid=%u stage=%d type=%s (%x) val=%x\n",
5508 cid, pTextureState[i].stage, vmsvga3dTextureStateToString(pTextureState[i].name), pTextureState[i].name, pTextureState[i].value));
5509
5510 /* Record the texture state for vm state saving. */
5511 if ( pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates)
5512 && (unsigned)pTextureState[i].name < RT_ELEMENTS(pContext->state.aTextureStates[0]))
5513 {
5514 pContext->state.aTextureStates[pTextureState[i].stage][pTextureState[i].name] = pTextureState[i];
5515 }
5516
5517 /* Activate the right texture unit for subsequent texture state changes. */
5518 if (pTextureState[i].stage != currentStage || i == 0)
5519 {
5520 /** @todo Is this the appropriate limit for all kinds of textures? It is the
5521 * size of aSidActiveTextures and for binding/unbinding we cannot exceed it. */
5522 if (pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates))
5523 {
5524 pState->ext.glActiveTexture(GL_TEXTURE0 + pTextureState[i].stage);
5525 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5526 currentStage = pTextureState[i].stage;
5527 }
5528 else
5529 {
5530 AssertMsgFailed(("pTextureState[%d].stage=%#x name=%#x\n", i, pTextureState[i].stage, pTextureState[i].name));
5531 continue;
5532 }
5533
5534 if (pContext->aSidActiveTextures[currentStage] != SVGA3D_INVALID_ID)
5535 {
5536 rc = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[currentStage], &pCurrentTextureSurface);
5537 AssertRCReturn(rc, rc);
5538 }
5539 else
5540 pCurrentTextureSurface = NULL; /* Make sure that no stale pointer is used. */
5541 }
5542
5543 switch (pTextureState[i].name)
5544 {
5545 case SVGA3D_TS_BUMPENVMAT00: /* float */
5546 case SVGA3D_TS_BUMPENVMAT01: /* float */
5547 case SVGA3D_TS_BUMPENVMAT10: /* float */
5548 case SVGA3D_TS_BUMPENVMAT11: /* float */
5549 case SVGA3D_TS_BUMPENVLSCALE: /* float */
5550 case SVGA3D_TS_BUMPENVLOFFSET: /* float */
5551 Log(("vmsvga3dSetTextureState: bump mapping texture options not supported!!\n"));
5552 break;
5553
5554 case SVGA3D_TS_COLOROP: /* SVGA3dTextureCombiner */
5555 case SVGA3D_TS_COLORARG0: /* SVGA3dTextureArgData */
5556 case SVGA3D_TS_COLORARG1: /* SVGA3dTextureArgData */
5557 case SVGA3D_TS_COLORARG2: /* SVGA3dTextureArgData */
5558 case SVGA3D_TS_ALPHAOP: /* SVGA3dTextureCombiner */
5559 case SVGA3D_TS_ALPHAARG0: /* SVGA3dTextureArgData */
5560 case SVGA3D_TS_ALPHAARG1: /* SVGA3dTextureArgData */
5561 case SVGA3D_TS_ALPHAARG2: /* SVGA3dTextureArgData */
5562 /** @todo not used by MesaGL */
5563 Log(("vmsvga3dSetTextureState: colorop/alphaop not yet supported!!\n"));
5564 break;
5565#if 0
5566
5567 case SVGA3D_TS_TEXCOORDINDEX: /* uint32_t */
5568 textureType = D3DTSS_TEXCOORDINDEX;
5569 val = pTextureState[i].value;
5570 break;
5571
5572 case SVGA3D_TS_TEXTURETRANSFORMFLAGS: /* SVGA3dTexTransformFlags */
5573 textureType = D3DTSS_TEXTURETRANSFORMFLAGS;
5574 val = vmsvga3dTextTransformFlags2D3D(pTextureState[i].value);
5575 break;
5576#endif
5577
5578 case SVGA3D_TS_BIND_TEXTURE: /* SVGA3dSurfaceId */
5579 {
5580 uint32_t const sid = pTextureState[i].value;
5581
5582 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u replacing sid=%u\n",
5583 currentStage, sid, pContext->aSidActiveTextures[currentStage]));
5584
5585 /* Only if texture actually changed. */ /// @todo needs testing.
5586 if (pContext->aSidActiveTextures[currentStage] != sid)
5587 {
5588 if (pCurrentTextureSurface)
5589 {
5590 /* Unselect the currently associated texture. */
5591 glBindTexture(pCurrentTextureSurface->targetGL, 0);
5592 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5593
5594 if (currentStage < 8)
5595 {
5596 /* Necessary for the fixed pipeline. */
5597 glDisable(pCurrentTextureSurface->targetGL);
5598 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5599 }
5600
5601 pCurrentTextureSurface = NULL;
5602 }
5603
5604 if (sid == SVGA3D_INVALID_ID)
5605 {
5606 Assert(pCurrentTextureSurface == NULL);
5607 }
5608 else
5609 {
5610 PVMSVGA3DSURFACE pSurface;
5611 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
5612 AssertRCReturn(rc, rc);
5613
5614 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u (%d,%d) replacing sid=%u\n",
5615 currentStage, sid, pSurface->paMipmapLevels[0].mipmapSize.width,
5616 pSurface->paMipmapLevels[0].mipmapSize.height, pContext->aSidActiveTextures[currentStage]));
5617
5618 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
5619 {
5620 Log(("CreateTexture (%d,%d) levels=%d\n",
5621 pSurface->paMipmapLevels[0].mipmapSize.width, pSurface->paMipmapLevels[0].mipmapSize.height, pSurface->faces[0].numMipLevels));
5622 rc = vmsvga3dBackCreateTexture(pState, pContext, cid, pSurface);
5623 AssertRCReturn(rc, rc);
5624 }
5625
5626 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
5627 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5628
5629 if (currentStage < 8)
5630 {
5631 /* Necessary for the fixed pipeline. */
5632 glEnable(pSurface->targetGL);
5633 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5634 }
5635
5636 /* Remember the currently active texture. */
5637 pCurrentTextureSurface = pSurface;
5638
5639 /* Recreate the texture state as glBindTexture resets them all (sigh). */
5640 for (uint32_t iStage = 0; iStage < RT_ELEMENTS(pContext->state.aTextureStates); iStage++)
5641 {
5642 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aTextureStates[0]); j++)
5643 {
5644 SVGA3dTextureState *pTextureStateIter = &pContext->state.aTextureStates[iStage][j];
5645
5646 if ( pTextureStateIter->name != SVGA3D_TS_INVALID
5647 && pTextureStateIter->name != SVGA3D_TS_BIND_TEXTURE)
5648 vmsvga3dSetTextureState(pThisCC, pContext->id, 1, pTextureStateIter);
5649 }
5650 }
5651 }
5652
5653 pContext->aSidActiveTextures[currentStage] = sid;
5654 }
5655
5656 /* Finished; continue with the next one. */
5657 continue;
5658 }
5659
5660 case SVGA3D_TS_ADDRESSW: /* SVGA3dTextureAddress */
5661 textureType = GL_TEXTURE_WRAP_R; /* R = W */
5662 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5663 break;
5664
5665 case SVGA3D_TS_ADDRESSU: /* SVGA3dTextureAddress */
5666 textureType = GL_TEXTURE_WRAP_S; /* S = U */
5667 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5668 break;
5669
5670 case SVGA3D_TS_ADDRESSV: /* SVGA3dTextureAddress */
5671 textureType = GL_TEXTURE_WRAP_T; /* T = V */
5672 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5673 break;
5674
5675 case SVGA3D_TS_MIPFILTER: /* SVGA3dTextureFilter */
5676 case SVGA3D_TS_MINFILTER: /* SVGA3dTextureFilter */
5677 {
5678 uint32_t mipFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MIPFILTER].value;
5679 uint32_t minFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MINFILTER].value;
5680
5681 /* If SVGA3D_TS_MIPFILTER is set to NONE, then use SVGA3D_TS_MIPFILTER, otherwise SVGA3D_TS_MIPFILTER enables mipmap minification. */
5682 textureType = GL_TEXTURE_MIN_FILTER;
5683 if (mipFilter != SVGA3D_TEX_FILTER_NONE)
5684 {
5685 if (minFilter == SVGA3D_TEX_FILTER_NEAREST)
5686 {
5687 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5688 val = GL_NEAREST_MIPMAP_LINEAR;
5689 else
5690 val = GL_NEAREST_MIPMAP_NEAREST;
5691 }
5692 else
5693 {
5694 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5695 val = GL_LINEAR_MIPMAP_LINEAR;
5696 else
5697 val = GL_LINEAR_MIPMAP_NEAREST;
5698 }
5699 }
5700 else
5701 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)minFilter);
5702 break;
5703 }
5704
5705 case SVGA3D_TS_MAGFILTER: /* SVGA3dTextureFilter */
5706 textureType = GL_TEXTURE_MAG_FILTER;
5707 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)pTextureState[i].value);
5708 Assert(val == GL_NEAREST || val == GL_LINEAR);
5709 break;
5710
5711 case SVGA3D_TS_BORDERCOLOR: /* SVGA3dColor */
5712 {
5713 GLfloat color[4]; /* red, green, blue, alpha */
5714 vmsvgaColor2GLFloatArray(pTextureState[i].value, &color[0], &color[1], &color[2], &color[3]);
5715
5716 GLenum targetGL;
5717 if (pCurrentTextureSurface)
5718 targetGL = pCurrentTextureSurface->targetGL;
5719 else
5720 {
5721 /* No texture bound, assume 2D. */
5722 targetGL = GL_TEXTURE_2D;
5723 }
5724
5725 glTexParameterfv(targetGL, GL_TEXTURE_BORDER_COLOR, color); /* Identical; default 0.0 identical too */
5726 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5727 break;
5728 }
5729
5730 case SVGA3D_TS_TEXTURE_LOD_BIAS: /* float */
5731 {
5732 GLenum targetGL;
5733 if (pCurrentTextureSurface)
5734 targetGL = pCurrentTextureSurface->targetGL;
5735 else
5736 {
5737 /* No texture bound, assume 2D. */
5738 targetGL = GL_TEXTURE_2D;
5739 }
5740
5741 glTexParameterf(targetGL, GL_TEXTURE_LOD_BIAS, pTextureState[i].floatValue); /* Identical; default 0.0 identical too */
5742 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5743 break;
5744 }
5745
5746 case SVGA3D_TS_TEXTURE_MIPMAP_LEVEL: /* uint32_t */
5747 textureType = GL_TEXTURE_BASE_LEVEL;
5748 val = pTextureState[i].value;
5749 break;
5750
5751 case SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL: /* uint32_t */
5752 if (pState->caps.fTextureFilterAnisotropicSupported)
5753 {
5754 textureType = GL_TEXTURE_MAX_ANISOTROPY_EXT;
5755 val = RT_MIN((GLint)pTextureState[i].value, pState->caps.maxTextureAnisotropy);
5756 } /* otherwise ignore. */
5757 break;
5758
5759#if 0
5760 case SVGA3D_TS_GAMMA: /* float */
5761 samplerType = D3DSAMP_SRGBTEXTURE;
5762 /* Boolean in D3D */
5763 if (pTextureState[i].floatValue == 1.0f)
5764 val = FALSE;
5765 else
5766 val = TRUE;
5767 break;
5768#endif
5769 /* Internal commands, that don't map directly to the SetTextureStageState API. */
5770 case SVGA3D_TS_TEXCOORDGEN: /* SVGA3dTextureCoordGen */
5771 AssertFailed();
5772 break;
5773
5774 default:
5775 //AssertFailed();
5776 break;
5777 }
5778
5779 if (textureType != ~(GLenum)0)
5780 {
5781 GLenum targetGL;
5782 if (pCurrentTextureSurface)
5783 targetGL = pCurrentTextureSurface->targetGL;
5784 else
5785 {
5786 /* No texture bound, assume 2D. */
5787 targetGL = GL_TEXTURE_2D;
5788 }
5789
5790 switch (pTextureState[i].name)
5791 {
5792 case SVGA3D_TS_MINFILTER:
5793 case SVGA3D_TS_MAGFILTER:
5794 {
5795 if (pState->caps.fTextureFilterAnisotropicSupported)
5796 {
5797 uint32_t const anisotropyLevel = (SVGA3dTextureFilter)pTextureState[i].value == SVGA3D_TEX_FILTER_ANISOTROPIC
5798 ? RT_MAX(1, pContext->state.aTextureStates[currentStage][SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL].value)
5799 : 1;
5800 glTexParameteri(targetGL, GL_TEXTURE_MAX_ANISOTROPY_EXT, RT_MIN((GLint)anisotropyLevel, pState->caps.maxTextureAnisotropy));
5801 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5802 }
5803 } break;
5804
5805 default: break;
5806 }
5807
5808 glTexParameteri(targetGL, textureType, val);
5809 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5810 }
5811 }
5812
5813 return VINF_SUCCESS;
5814}
5815
5816int vmsvga3dSetMaterial(PVGASTATECC pThisCC, uint32_t cid, SVGA3dFace face, SVGA3dMaterial *pMaterial)
5817{
5818 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5819 AssertReturn(pState, VERR_NO_MEMORY);
5820
5821 LogFunc(("cid=%u face %d\n", cid, face));
5822
5823 PVMSVGA3DCONTEXT pContext;
5824 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5825 AssertRCReturn(rc, rc);
5826
5827 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5828
5829 GLenum oglFace;
5830 switch (face)
5831 {
5832 case SVGA3D_FACE_NONE:
5833 case SVGA3D_FACE_FRONT:
5834 oglFace = GL_FRONT;
5835 break;
5836
5837 case SVGA3D_FACE_BACK:
5838 oglFace = GL_BACK;
5839 break;
5840
5841 case SVGA3D_FACE_FRONT_BACK:
5842 oglFace = GL_FRONT_AND_BACK;
5843 break;
5844
5845 default:
5846 AssertFailedReturn(VERR_INVALID_PARAMETER);
5847 }
5848
5849 /* Save for vm state save/restore. */
5850 pContext->state.aMaterial[face].fValid = true;
5851 pContext->state.aMaterial[face].material = *pMaterial;
5852 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_MATERIAL;
5853
5854 glMaterialfv(oglFace, GL_DIFFUSE, pMaterial->diffuse);
5855 glMaterialfv(oglFace, GL_AMBIENT, pMaterial->ambient);
5856 glMaterialfv(oglFace, GL_SPECULAR, pMaterial->specular);
5857 glMaterialfv(oglFace, GL_EMISSION, pMaterial->emissive);
5858 glMaterialfv(oglFace, GL_SHININESS, &pMaterial->shininess);
5859 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5860
5861 return VINF_SUCCESS;
5862}
5863
5864/** @todo Move into separate library as we are using logic from Wine here. */
5865int vmsvga3dSetLightData(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, SVGA3dLightData *pData)
5866{
5867 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5868 AssertReturn(pState, VERR_NO_MEMORY);
5869
5870 LogFunc(("vmsvga3dSetLightData cid=%u index=%d type=%d\n", cid, index, pData->type));
5871 ASSERT_GUEST_RETURN(index < SVGA3D_MAX_LIGHTS, VERR_INVALID_PARAMETER);
5872
5873 PVMSVGA3DCONTEXT pContext;
5874 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5875 AssertRCReturn(rc, rc);
5876
5877 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5878
5879 /* Store for vm state save/restore */
5880 pContext->state.aLightData[index].fValidData = true;
5881 pContext->state.aLightData[index].data = *pData;
5882
5883 if ( pData->attenuation0 < 0.0f
5884 || pData->attenuation1 < 0.0f
5885 || pData->attenuation2 < 0.0f)
5886 {
5887 Log(("vmsvga3dSetLightData: invalid negative attenuation values!!\n"));
5888 return VINF_SUCCESS; /* ignore; could crash the GL driver */
5889 }
5890
5891 /* Light settings are affected by the model view in OpenGL, the View transform in direct3d */
5892 glMatrixMode(GL_MODELVIEW);
5893 glPushMatrix();
5894 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
5895
5896 glLightfv(GL_LIGHT0 + index, GL_DIFFUSE, pData->diffuse);
5897 glLightfv(GL_LIGHT0 + index, GL_SPECULAR, pData->specular);
5898 glLightfv(GL_LIGHT0 + index, GL_AMBIENT, pData->ambient);
5899
5900 float QuadAttenuation;
5901 if (pData->range * pData->range >= FLT_MIN)
5902 QuadAttenuation = 1.4f / (pData->range * pData->range);
5903 else
5904 QuadAttenuation = 0.0f;
5905
5906 switch (pData->type)
5907 {
5908 case SVGA3D_LIGHTTYPE_POINT:
5909 {
5910 GLfloat position[4];
5911
5912 position[0] = pData->position[0];
5913 position[1] = pData->position[1];
5914 position[2] = pData->position[2];
5915 position[3] = 1.0f;
5916
5917 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
5918 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5919
5920 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
5921 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5922
5923 /* Attenuation - Are these right? guessing... */
5924 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
5925 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5926
5927 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
5928 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5929
5930 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
5931 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5932
5933 /** @todo range */
5934 break;
5935 }
5936
5937 case SVGA3D_LIGHTTYPE_SPOT1:
5938 {
5939 GLfloat exponent;
5940 GLfloat position[4];
5941 const GLfloat pi = 4.0f * atanf(1.0f);
5942
5943 position[0] = pData->position[0];
5944 position[1] = pData->position[1];
5945 position[2] = pData->position[2];
5946 position[3] = 1.0f;
5947
5948 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
5949 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5950
5951 position[0] = pData->direction[0];
5952 position[1] = pData->direction[1];
5953 position[2] = pData->direction[2];
5954 position[3] = 1.0f;
5955
5956 glLightfv(GL_LIGHT0 + index, GL_SPOT_DIRECTION, position);
5957 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5958
5959 /*
5960 * opengl-ish and d3d-ish spot lights use too different models for the
5961 * light "intensity" as a function of the angle towards the main light direction,
5962 * so we only can approximate very roughly.
5963 * however spot lights are rather rarely used in games (if ever used at all).
5964 * furthermore if still used, probably nobody pays attention to such details.
5965 */
5966 if (pData->falloff == 0)
5967 {
5968 /* Falloff = 0 is easy, because d3d's and opengl's spot light equations have the
5969 * falloff resp. exponent parameter as an exponent, so the spot light lighting
5970 * will always be 1.0 for both of them, and we don't have to care for the
5971 * rest of the rather complex calculation
5972 */
5973 exponent = 0.0f;
5974 }
5975 else
5976 {
5977 float rho = pData->theta + (pData->phi - pData->theta) / (2 * pData->falloff);
5978 if (rho < 0.0001f)
5979 rho = 0.0001f;
5980 exponent = -0.3f/log(cos(rho/2));
5981 }
5982 if (exponent > 128.0f)
5983 exponent = 128.0f;
5984
5985 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, exponent);
5986 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5987
5988 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, pData->phi * 90.0 / pi);
5989 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5990
5991 /* Attenuation - Are these right? guessing... */
5992 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
5993 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5994
5995 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
5996 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
5997
5998 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
5999 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6000
6001 /** @todo range */
6002 break;
6003 }
6004
6005 case SVGA3D_LIGHTTYPE_DIRECTIONAL:
6006 {
6007 GLfloat position[4];
6008
6009 position[0] = -pData->direction[0];
6010 position[1] = -pData->direction[1];
6011 position[2] = -pData->direction[2];
6012 position[3] = 0.0f;
6013
6014 glLightfv(GL_LIGHT0 + index, GL_POSITION, position); /* Note gl uses w position of 0 for direction! */
6015 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6016
6017 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6018 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6019
6020 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, 0.0f);
6021 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6022 break;
6023 }
6024
6025 case SVGA3D_LIGHTTYPE_SPOT2:
6026 default:
6027 Log(("Unsupported light type!!\n"));
6028 rc = VERR_INVALID_PARAMETER;
6029 break;
6030 }
6031
6032 /* Restore the modelview matrix */
6033 glPopMatrix();
6034
6035 return rc;
6036}
6037
6038int vmsvga3dSetLightEnabled(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, uint32_t enabled)
6039{
6040 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6041 AssertReturn(pState, VERR_NO_MEMORY);
6042
6043 LogFunc(("cid=%u %d -> %d\n", cid, index, enabled));
6044
6045 PVMSVGA3DCONTEXT pContext;
6046 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6047 AssertRCReturn(rc, rc);
6048
6049 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6050
6051 /* Store for vm state save/restore */
6052 if (index < SVGA3D_MAX_LIGHTS)
6053 pContext->state.aLightData[index].fEnabled = !!enabled;
6054 else
6055 AssertFailed();
6056
6057 if (enabled)
6058 {
6059 if (index < SVGA3D_MAX_LIGHTS)
6060 {
6061 /* Load the default settings if none have been set yet. */
6062 if (!pContext->state.aLightData[index].fValidData)
6063 vmsvga3dSetLightData(pThisCC, cid, index, (SVGA3dLightData *)&vmsvga3d_default_light);
6064 }
6065 glEnable(GL_LIGHT0 + index);
6066 }
6067 else
6068 glDisable(GL_LIGHT0 + index);
6069
6070 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6071 return VINF_SUCCESS;
6072}
6073
6074int vmsvga3dSetViewPort(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6075{
6076 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6077 AssertReturn(pState, VERR_NO_MEMORY);
6078
6079 Log(("vmsvga3dSetViewPort cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6080
6081 PVMSVGA3DCONTEXT pContext;
6082 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6083 AssertRCReturn(rc, rc);
6084
6085 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6086
6087 /* Save for vm state save/restore. */
6088 pContext->state.RectViewPort = *pRect;
6089 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VIEWPORT;
6090
6091 /** @todo y-inversion for partial viewport coordinates? */
6092 glViewport(pRect->x, pRect->y, pRect->w, pRect->h);
6093 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6094
6095 /* Reset the projection matrix as that relies on the viewport setting. */
6096 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6097 vmsvga3dSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION,
6098 pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6099 else
6100 {
6101 float matrix[16];
6102
6103 /* identity matrix if no matrix set. */
6104 memset(matrix, 0, sizeof(matrix));
6105 matrix[0] = 1.0;
6106 matrix[5] = 1.0;
6107 matrix[10] = 1.0;
6108 matrix[15] = 1.0;
6109 vmsvga3dSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION, matrix);
6110 }
6111
6112 return VINF_SUCCESS;
6113}
6114
6115int vmsvga3dSetClipPlane(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, float plane[4])
6116{
6117 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6118 AssertReturn(pState, VERR_NO_MEMORY);
6119 double oglPlane[4];
6120
6121 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)));
6122 AssertReturn(index < SVGA3D_CLIPPLANE_MAX, VERR_INVALID_PARAMETER);
6123
6124 PVMSVGA3DCONTEXT pContext;
6125 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6126 AssertRCReturn(rc, rc);
6127
6128 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6129
6130 /* Store for vm state save/restore. */
6131 pContext->state.aClipPlane[index].fValid = true;
6132 memcpy(pContext->state.aClipPlane[index].plane, plane, sizeof(pContext->state.aClipPlane[index].plane));
6133
6134 /** @todo clip plane affected by model view in OpenGL & view in D3D + vertex shader -> not transformed (see Wine; state.c clipplane) */
6135 oglPlane[0] = (double)plane[0];
6136 oglPlane[1] = (double)plane[1];
6137 oglPlane[2] = (double)plane[2];
6138 oglPlane[3] = (double)plane[3];
6139
6140 glClipPlane(GL_CLIP_PLANE0 + index, oglPlane);
6141 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6142
6143 return VINF_SUCCESS;
6144}
6145
6146int vmsvga3dSetScissorRect(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6147{
6148 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6149 AssertReturn(pState, VERR_NO_MEMORY);
6150
6151 Log(("vmsvga3dSetScissorRect cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6152
6153 PVMSVGA3DCONTEXT pContext;
6154 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6155 AssertRCReturn(rc, rc);
6156
6157 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6158
6159 /* Store for vm state save/restore. */
6160 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_SCISSORRECT;
6161 pContext->state.RectScissor = *pRect;
6162
6163 glScissor(pRect->x, pRect->y, pRect->w, pRect->h);
6164 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6165
6166 return VINF_SUCCESS;
6167}
6168
6169static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha)
6170{
6171 /* Convert byte color components to float (0-1.0) */
6172 *pAlpha = (GLfloat)(color >> 24) / 255.0;
6173 *pRed = (GLfloat)((color >> 16) & 0xff) / 255.0;
6174 *pGreen = (GLfloat)((color >> 8) & 0xff) / 255.0;
6175 *pBlue = (GLfloat)(color & 0xff) / 255.0;
6176}
6177
6178int vmsvga3dCommandClear(PVGASTATECC pThisCC, uint32_t cid, SVGA3dClearFlag clearFlag, uint32_t color, float depth, uint32_t stencil,
6179 uint32_t cRects, SVGA3dRect *pRect)
6180{
6181 GLbitfield mask = 0;
6182 GLbitfield restoreMask = 0;
6183 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6184 AssertReturn(pState, VERR_NO_MEMORY);
6185 GLboolean fDepthWriteEnabled = GL_FALSE;
6186 GLboolean afColorWriteEnabled[4] = { GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE };
6187
6188 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));
6189
6190 PVMSVGA3DCONTEXT pContext;
6191 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6192 AssertRCReturn(rc, rc);
6193
6194 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6195
6196 if (clearFlag & SVGA3D_CLEAR_COLOR)
6197 {
6198 GLfloat red, green, blue, alpha;
6199 vmsvgaColor2GLFloatArray(color, &red, &green, &blue, &alpha);
6200
6201 /* Set the color clear value. */
6202 glClearColor(red, green, blue, alpha);
6203 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6204
6205 mask |= GL_COLOR_BUFFER_BIT;
6206
6207 /* glClear will not clear the color buffer if writing is disabled. */
6208 glGetBooleanv(GL_COLOR_WRITEMASK, afColorWriteEnabled);
6209 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6210 if ( afColorWriteEnabled[0] == GL_FALSE
6211 || afColorWriteEnabled[1] == GL_FALSE
6212 || afColorWriteEnabled[2] == GL_FALSE
6213 || afColorWriteEnabled[3] == GL_FALSE)
6214 {
6215 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
6216 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6217
6218 restoreMask |= GL_COLOR_BUFFER_BIT;
6219 }
6220
6221 }
6222
6223 if (clearFlag & SVGA3D_CLEAR_STENCIL)
6224 {
6225 /** @todo possibly the same problem as with glDepthMask */
6226 glClearStencil(stencil);
6227 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6228
6229 mask |= GL_STENCIL_BUFFER_BIT;
6230 }
6231
6232 if (clearFlag & SVGA3D_CLEAR_DEPTH)
6233 {
6234 glClearDepth((GLdouble)depth);
6235 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6236
6237 mask |= GL_DEPTH_BUFFER_BIT;
6238
6239 /* glClear will not clear the depth buffer if writing is disabled. */
6240 glGetBooleanv(GL_DEPTH_WRITEMASK, &fDepthWriteEnabled);
6241 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6242 if (fDepthWriteEnabled == GL_FALSE)
6243 {
6244 glDepthMask(GL_TRUE);
6245 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6246
6247 restoreMask |= GL_DEPTH_BUFFER_BIT;
6248 }
6249 }
6250
6251 /* Save the current scissor test bit and scissor box. */
6252 glPushAttrib(GL_SCISSOR_BIT);
6253 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6254
6255 if (cRects)
6256 {
6257 glEnable(GL_SCISSOR_TEST);
6258 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6259
6260 for (uint32_t i = 0; i < cRects; ++i)
6261 {
6262 LogFunc(("rect [%d] %d,%d %dx%d)\n", i, pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h));
6263 glScissor(pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h);
6264 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6265
6266 glClear(mask);
6267 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6268 }
6269 }
6270 else
6271 {
6272 glDisable(GL_SCISSOR_TEST);
6273 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6274
6275 glClear(mask);
6276 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6277 }
6278
6279 /* Restore the old scissor test bit and box */
6280 glPopAttrib();
6281 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6282
6283 /* Restore the write states. */
6284 if (restoreMask & GL_COLOR_BUFFER_BIT)
6285 {
6286 glColorMask(afColorWriteEnabled[0],
6287 afColorWriteEnabled[1],
6288 afColorWriteEnabled[2],
6289 afColorWriteEnabled[3]);
6290 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6291 }
6292
6293 if (restoreMask & GL_DEPTH_BUFFER_BIT)
6294 {
6295 glDepthMask(fDepthWriteEnabled);
6296 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6297 }
6298
6299 return VINF_SUCCESS;
6300}
6301
6302/* Convert VMWare vertex declaration to its OpenGL equivalent. */
6303int vmsvga3dVertexDecl2OGL(SVGA3dVertexArrayIdentity &identity, GLint &size, GLenum &type, GLboolean &normalized, uint32_t &cbAttrib)
6304{
6305 normalized = GL_FALSE;
6306 switch (identity.type)
6307 {
6308 case SVGA3D_DECLTYPE_FLOAT1:
6309 size = 1;
6310 type = GL_FLOAT;
6311 cbAttrib = sizeof(float);
6312 break;
6313 case SVGA3D_DECLTYPE_FLOAT2:
6314 size = 2;
6315 type = GL_FLOAT;
6316 cbAttrib = 2 * sizeof(float);
6317 break;
6318 case SVGA3D_DECLTYPE_FLOAT3:
6319 size = 3;
6320 type = GL_FLOAT;
6321 cbAttrib = 3 * sizeof(float);
6322 break;
6323 case SVGA3D_DECLTYPE_FLOAT4:
6324 size = 4;
6325 type = GL_FLOAT;
6326 cbAttrib = 4 * sizeof(float);
6327 break;
6328
6329 case SVGA3D_DECLTYPE_D3DCOLOR:
6330 size = GL_BGRA; /* @note requires GL_ARB_vertex_array_bgra */
6331 type = GL_UNSIGNED_BYTE;
6332 normalized = GL_TRUE; /* glVertexAttribPointer fails otherwise */
6333 cbAttrib = sizeof(uint32_t);
6334 break;
6335
6336 case SVGA3D_DECLTYPE_UBYTE4N:
6337 normalized = GL_TRUE;
6338 RT_FALL_THRU();
6339 case SVGA3D_DECLTYPE_UBYTE4:
6340 size = 4;
6341 type = GL_UNSIGNED_BYTE;
6342 cbAttrib = sizeof(uint32_t);
6343 break;
6344
6345 case SVGA3D_DECLTYPE_SHORT2N:
6346 normalized = GL_TRUE;
6347 RT_FALL_THRU();
6348 case SVGA3D_DECLTYPE_SHORT2:
6349 size = 2;
6350 type = GL_SHORT;
6351 cbAttrib = 2 * sizeof(uint16_t);
6352 break;
6353
6354 case SVGA3D_DECLTYPE_SHORT4N:
6355 normalized = GL_TRUE;
6356 RT_FALL_THRU();
6357 case SVGA3D_DECLTYPE_SHORT4:
6358 size = 4;
6359 type = GL_SHORT;
6360 cbAttrib = 4 * sizeof(uint16_t);
6361 break;
6362
6363 case SVGA3D_DECLTYPE_USHORT4N:
6364 normalized = GL_TRUE;
6365 size = 4;
6366 type = GL_UNSIGNED_SHORT;
6367 cbAttrib = 4 * sizeof(uint16_t);
6368 break;
6369
6370 case SVGA3D_DECLTYPE_USHORT2N:
6371 normalized = GL_TRUE;
6372 size = 2;
6373 type = GL_UNSIGNED_SHORT;
6374 cbAttrib = 2 * sizeof(uint16_t);
6375 break;
6376
6377 case SVGA3D_DECLTYPE_UDEC3:
6378 size = 3;
6379 type = GL_UNSIGNED_INT_2_10_10_10_REV; /** @todo correct? */
6380 cbAttrib = sizeof(uint32_t);
6381 break;
6382
6383 case SVGA3D_DECLTYPE_DEC3N:
6384 normalized = true;
6385 size = 3;
6386 type = GL_INT_2_10_10_10_REV; /** @todo correct? */
6387 cbAttrib = sizeof(uint32_t);
6388 break;
6389
6390 case SVGA3D_DECLTYPE_FLOAT16_2:
6391 size = 2;
6392 type = GL_HALF_FLOAT;
6393 cbAttrib = 2 * sizeof(uint16_t);
6394 break;
6395 case SVGA3D_DECLTYPE_FLOAT16_4:
6396 size = 4;
6397 type = GL_HALF_FLOAT;
6398 cbAttrib = 4 * sizeof(uint16_t);
6399 break;
6400 default:
6401 AssertFailedReturn(VERR_INVALID_PARAMETER);
6402 }
6403
6404 //pVertexElement->Method = identity.method;
6405 //pVertexElement->Usage = identity.usage;
6406
6407 return VINF_SUCCESS;
6408}
6409
6410static float vmsvga3dFloat16To32(uint16_t f16)
6411{
6412 /* From Wiki */
6413#ifndef INFINITY
6414 static uint32_t const sBitsINFINITY = UINT32_C(0x7f800000);
6415 #define INFINITY (*(float const *)&sBitsINFINITY)
6416#endif
6417#ifndef NAN
6418 static uint32_t const sBitsNAN = UINT32_C(0x7fc00000);
6419 #define NAN (*(float const *)&sBitsNAN)
6420#endif
6421
6422 uint16_t const s = (f16 >> UINT16_C(15)) & UINT16_C(0x1);
6423 uint16_t const e = (f16 >> UINT16_C(10)) & UINT16_C(0x1f);
6424 uint16_t const m = (f16 ) & UINT16_C(0x3ff);
6425
6426 float result = s ? 1.0f : -1.0f;
6427 if (e == 0)
6428 {
6429 if (m == 0)
6430 result *= 0.0f; /* zero, -0 */
6431 else
6432 result *= (float)m / 1024.0f / 16384.0f; /* subnormal numbers: sign * 2^-14 * 0.m */
6433 }
6434 else if (e == 0x1f)
6435 {
6436 if (m == 0)
6437 result *= INFINITY; /* +-infinity */
6438 else
6439 result = NAN; /* NAN */
6440 }
6441 else
6442 {
6443 result *= powf(2.0f, (float)e - 15.0f) * (1.0f + (float)m / 1024.0f); /* sign * 2^(e-15) * 1.m */
6444 }
6445
6446 return result;
6447}
6448
6449/* Set a vertex attribute according to VMSVGA vertex declaration. */
6450static int vmsvga3dSetVertexAttrib(PVMSVGA3DSTATE pState, GLuint index, SVGA3dVertexArrayIdentity const *pIdentity, GLvoid const *pv)
6451{
6452 switch (pIdentity->type)
6453 {
6454 case SVGA3D_DECLTYPE_FLOAT1:
6455 {
6456 /* "One-component float expanded to (float, 0, 0, 1)." */
6457 GLfloat const *p = (GLfloat *)pv;
6458 GLfloat const v[4] = { p[0], 0.0f, 0.0f, 1.0f };
6459 pState->ext.glVertexAttrib4fv(index, v);
6460 break;
6461 }
6462 case SVGA3D_DECLTYPE_FLOAT2:
6463 {
6464 /* "Two-component float expanded to (float, float, 0, 1)." */
6465 GLfloat const *p = (GLfloat *)pv;
6466 GLfloat const v[4] = { p[0], p[1], 0.0f, 1.0f };
6467 pState->ext.glVertexAttrib4fv(index, v);
6468 break;
6469 }
6470 case SVGA3D_DECLTYPE_FLOAT3:
6471 {
6472 /* "Three-component float expanded to (float, float, float, 1)." */
6473 GLfloat const *p = (GLfloat *)pv;
6474 GLfloat const v[4] = { p[0], p[1], p[2], 1.0f };
6475 pState->ext.glVertexAttrib4fv(index, v);
6476 break;
6477 }
6478 case SVGA3D_DECLTYPE_FLOAT4:
6479 pState->ext.glVertexAttrib4fv(index, (GLfloat const *)pv);
6480 break;
6481 case SVGA3D_DECLTYPE_D3DCOLOR:
6482 /** @todo Need to swap bytes? */
6483 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6484 break;
6485 case SVGA3D_DECLTYPE_UBYTE4:
6486 pState->ext.glVertexAttrib4ubv(index, (GLubyte const *)pv);
6487 break;
6488 case SVGA3D_DECLTYPE_SHORT2:
6489 {
6490 /* "Two-component, signed short expanded to (value, value, 0, 1)." */
6491 GLshort const *p = (GLshort const *)pv;
6492 GLshort const v[4] = { p[0], p[1], 0, 1 };
6493 pState->ext.glVertexAttrib4sv(index, v);
6494 break;
6495 }
6496 case SVGA3D_DECLTYPE_SHORT4:
6497 pState->ext.glVertexAttrib4sv(index, (GLshort const *)pv);
6498 break;
6499 case SVGA3D_DECLTYPE_UBYTE4N:
6500 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6501 break;
6502 case SVGA3D_DECLTYPE_SHORT2N:
6503 {
6504 /* "Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1)." */
6505 GLshort const *p = (GLshort const *)pv;
6506 GLshort const v[4] = { p[0], p[1], 0, 1 };
6507 pState->ext.glVertexAttrib4Nsv(index, v);
6508 break;
6509 }
6510 case SVGA3D_DECLTYPE_SHORT4N:
6511 pState->ext.glVertexAttrib4Nsv(index, (GLshort const *)pv);
6512 break;
6513 case SVGA3D_DECLTYPE_USHORT2N:
6514 {
6515 GLushort const *p = (GLushort const *)pv;
6516 GLushort const v[4] = { p[0], p[1], 0, 1 };
6517 pState->ext.glVertexAttrib4Nusv(index, v);
6518 break;
6519 }
6520 case SVGA3D_DECLTYPE_USHORT4N:
6521 pState->ext.glVertexAttrib4Nusv(index, (GLushort const *)pv);
6522 break;
6523 case SVGA3D_DECLTYPE_UDEC3:
6524 {
6525 /** @todo Test */
6526 /* "Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1)." */
6527 uint32_t const u32 = *(uint32_t *)pv;
6528 GLfloat const v[4] = { (float)(u32 & 0x3ff), (float)((u32 >> 10) & 0x3ff), (float)((u32 >> 20) & 0x3ff), 1.0f };
6529 pState->ext.glVertexAttrib4fv(index, v);
6530 break;
6531 }
6532 case SVGA3D_DECLTYPE_DEC3N:
6533 {
6534 /** @todo Test */
6535 /* "Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)." */
6536 uint32_t const u32 = *(uint32_t *)pv;
6537 GLfloat const v[4] = { (u32 & 0x3ff) / 511.0f, ((u32 >> 10) & 0x3ff) / 511.0f, ((u32 >> 20) & 0x3ff) / 511.0f, 1.0f };
6538 pState->ext.glVertexAttrib4fv(index, v);
6539 break;
6540 }
6541 case SVGA3D_DECLTYPE_FLOAT16_2:
6542 {
6543 /** @todo Test */
6544 /* "Two-component, 16-bit, floating point expanded to (value, value, 0, 1)." */
6545 uint16_t const *p = (uint16_t *)pv;
6546 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]), 0.0f, 1.0f };
6547 pState->ext.glVertexAttrib4fv(index, v);
6548 break;
6549 }
6550 case SVGA3D_DECLTYPE_FLOAT16_4:
6551 {
6552 /** @todo Test */
6553 uint16_t const *p = (uint16_t *)pv;
6554 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]),
6555 vmsvga3dFloat16To32(p[2]), vmsvga3dFloat16To32(p[3]) };
6556 pState->ext.glVertexAttrib4fv(index, v);
6557 break;
6558 }
6559 default:
6560 AssertFailedReturn(VERR_INVALID_PARAMETER);
6561 }
6562
6563 return VINF_SUCCESS;
6564}
6565
6566/* Convert VMWare primitive type to its OpenGL equivalent. */
6567/* Calculate the vertex count based on the primitive type and nr of primitives. */
6568int vmsvga3dPrimitiveType2OGL(SVGA3dPrimitiveType PrimitiveType, GLenum *pMode, uint32_t cPrimitiveCount, uint32_t *pcVertices)
6569{
6570 switch (PrimitiveType)
6571 {
6572 case SVGA3D_PRIMITIVE_TRIANGLELIST:
6573 *pMode = GL_TRIANGLES;
6574 *pcVertices = cPrimitiveCount * 3;
6575 break;
6576 case SVGA3D_PRIMITIVE_POINTLIST:
6577 *pMode = GL_POINTS;
6578 *pcVertices = cPrimitiveCount;
6579 break;
6580 case SVGA3D_PRIMITIVE_LINELIST:
6581 *pMode = GL_LINES;
6582 *pcVertices = cPrimitiveCount * 2;
6583 break;
6584 case SVGA3D_PRIMITIVE_LINESTRIP:
6585 *pMode = GL_LINE_STRIP;
6586 *pcVertices = cPrimitiveCount + 1;
6587 break;
6588 case SVGA3D_PRIMITIVE_TRIANGLESTRIP:
6589 *pMode = GL_TRIANGLE_STRIP;
6590 *pcVertices = cPrimitiveCount + 2;
6591 break;
6592 case SVGA3D_PRIMITIVE_TRIANGLEFAN:
6593 *pMode = GL_TRIANGLE_FAN;
6594 *pcVertices = cPrimitiveCount + 2;
6595 break;
6596 default:
6597 return VERR_INVALID_PARAMETER;
6598 }
6599 return VINF_SUCCESS;
6600}
6601
6602static int vmsvga3dResetTransformMatrices(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
6603{
6604 int rc;
6605
6606 /* Reset the view matrix (also takes the world matrix into account). */
6607 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid == true)
6608 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW,
6609 pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6610 else
6611 {
6612 float matrix[16];
6613
6614 /* identity matrix if no matrix set. */
6615 memset(matrix, 0, sizeof(matrix));
6616 matrix[0] = 1.0;
6617 matrix[5] = 1.0;
6618 matrix[10] = 1.0;
6619 matrix[15] = 1.0;
6620 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW, matrix);
6621 }
6622
6623 /* Reset the projection matrix. */
6624 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6625 {
6626 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6627 }
6628 else
6629 {
6630 float matrix[16];
6631
6632 /* identity matrix if no matrix set. */
6633 memset(matrix, 0, sizeof(matrix));
6634 matrix[0] = 1.0;
6635 matrix[5] = 1.0;
6636 matrix[10] = 1.0;
6637 matrix[15] = 1.0;
6638 rc = vmsvga3dSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, matrix);
6639 }
6640 AssertRC(rc);
6641 return rc;
6642}
6643
6644static int vmsvga3dDrawPrimitivesProcessVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext,
6645 uint32_t iVertexDeclBase, uint32_t numVertexDecls,
6646 SVGA3dVertexDecl *pVertexDecl,
6647 SVGA3dVertexDivisor const *paVertexDivisors)
6648{
6649 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6650 unsigned const sidVertex = pVertexDecl[0].array.surfaceId;
6651
6652 PVMSVGA3DSURFACE pVertexSurface;
6653 int rc = vmsvga3dSurfaceFromSid(pState, sidVertex, &pVertexSurface);
6654 AssertRCReturn(rc, rc);
6655
6656 Log(("vmsvga3dDrawPrimitives: vertex surface sid=%u\n", sidVertex));
6657
6658 /* Create and/or bind the vertex buffer. */
6659 if (pVertexSurface->oglId.buffer == OPENGL_INVALID_ID)
6660 {
6661 Log(("vmsvga3dDrawPrimitives: create vertex buffer fDirty=%d size=%x bytes\n", pVertexSurface->fDirty, pVertexSurface->paMipmapLevels[0].cbSurface));
6662 PVMSVGA3DCONTEXT pSavedCtx = pContext;
6663 pContext = &pState->SharedCtx;
6664 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6665
6666 pState->ext.glGenBuffers(1, &pVertexSurface->oglId.buffer);
6667 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6668 pVertexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
6669
6670 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6671 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6672
6673 Assert(pVertexSurface->fDirty);
6674 /** @todo rethink usage dynamic/static */
6675 pState->ext.glBufferData(GL_ARRAY_BUFFER, pVertexSurface->paMipmapLevels[0].cbSurface, pVertexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
6676 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6677
6678 pVertexSurface->paMipmapLevels[0].fDirty = false;
6679 pVertexSurface->fDirty = false;
6680
6681 pVertexSurface->surfaceFlags |= SVGA3D_SURFACE_HINT_VERTEXBUFFER;
6682
6683 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, OPENGL_INVALID_ID);
6684 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6685
6686 pContext = pSavedCtx;
6687 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6688 }
6689
6690 Assert(pVertexSurface->fDirty == false);
6691 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6692 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6693
6694 /* Setup the vertex declarations. */
6695 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6696 {
6697 GLint size;
6698 GLenum type;
6699 GLboolean normalized;
6700 uint32_t cbAttrib;
6701 GLuint index = iVertexDeclBase + iVertex;
6702
6703 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));
6704
6705 rc = vmsvga3dVertexDecl2OGL(pVertexDecl[iVertex].identity, size, type, normalized, cbAttrib);
6706 AssertRCReturn(rc, rc);
6707
6708 ASSERT_GUEST_RETURN( pVertexSurface->paMipmapLevels[0].cbSurface >= pVertexDecl[iVertex].array.offset
6709 && pVertexSurface->paMipmapLevels[0].cbSurface - pVertexDecl[iVertex].array.offset >= cbAttrib,
6710 VERR_INVALID_PARAMETER);
6711 RT_UNTRUSTED_VALIDATED_FENCE();
6712
6713 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6714 {
6715 /* Use numbered vertex arrays (or attributes) when shaders are active. */
6716 if (pVertexDecl[iVertex].array.stride)
6717 {
6718 pState->ext.glEnableVertexAttribArray(index);
6719 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6720 pState->ext.glVertexAttribPointer(index, size, type, normalized, pVertexDecl[iVertex].array.stride,
6721 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6722 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6723
6724 GLuint divisor = paVertexDivisors && paVertexDivisors[index].s.instanceData ? 1 : 0;
6725 pState->ext.glVertexAttribDivisor(index, divisor);
6726 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6727
6728 /** @todo case SVGA3D_DECLUSAGE_COLOR: color component order not identical!! test GL_BGRA!! */
6729 }
6730 else
6731 {
6732 /*
6733 * D3D and OpenGL have a different meaning of value zero for the vertex array stride:
6734 * - D3D (VMSVGA): "use a zero stride to tell the runtime not to increment the vertex buffer offset."
6735 * - OpenGL: "If stride is 0, the generic vertex attributes are understood to be tightly packed in the array."
6736 * VMSVGA uses the D3D semantics.
6737 *
6738 * Use glVertexAttrib in order to tell OpenGL to reuse the zero stride attributes for each vertex.
6739 */
6740 pState->ext.glDisableVertexAttribArray(index);
6741 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6742
6743 const GLvoid *v = (uint8_t *)pVertexSurface->paMipmapLevels[0].pSurfaceData + pVertexDecl[iVertex].array.offset;
6744 vmsvga3dSetVertexAttrib(pState, index, &pVertexDecl[iVertex].identity, v);
6745 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6746 }
6747 }
6748 else
6749 {
6750 if (pVertexDecl[iVertex].array.stride == 0)
6751 {
6752 /* Zero stride means that the attribute pointer must not be increased.
6753 * See comment about stride in vmsvga3dDrawPrimitives.
6754 */
6755 LogRelMax(8, ("VMSVGA: Warning: zero stride array in fixed function pipeline\n"));
6756 AssertFailed();
6757 }
6758
6759 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6760 switch (pVertexDecl[iVertex].identity.usage)
6761 {
6762 case SVGA3D_DECLUSAGE_POSITIONT:
6763 case SVGA3D_DECLUSAGE_POSITION:
6764 {
6765 glEnableClientState(GL_VERTEX_ARRAY);
6766 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6767 glVertexPointer(size, type, pVertexDecl[iVertex].array.stride,
6768 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6769 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6770 break;
6771 }
6772 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6773 AssertFailed();
6774 break;
6775 case SVGA3D_DECLUSAGE_BLENDINDICES:
6776 AssertFailed();
6777 break;
6778 case SVGA3D_DECLUSAGE_NORMAL:
6779 glEnableClientState(GL_NORMAL_ARRAY);
6780 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6781 glNormalPointer(type, pVertexDecl[iVertex].array.stride,
6782 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6783 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6784 break;
6785 case SVGA3D_DECLUSAGE_PSIZE:
6786 AssertFailed();
6787 break;
6788 case SVGA3D_DECLUSAGE_TEXCOORD:
6789 /* Specify the affected texture unit. */
6790#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6791 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6792#else
6793 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6794#endif
6795 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
6796 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6797 glTexCoordPointer(size, type, pVertexDecl[iVertex].array.stride,
6798 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6799 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6800 break;
6801 case SVGA3D_DECLUSAGE_TANGENT:
6802 AssertFailed();
6803 break;
6804 case SVGA3D_DECLUSAGE_BINORMAL:
6805 AssertFailed();
6806 break;
6807 case SVGA3D_DECLUSAGE_TESSFACTOR:
6808 AssertFailed();
6809 break;
6810 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! test GL_BGRA!! */
6811 glEnableClientState(GL_COLOR_ARRAY);
6812 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6813 glColorPointer(size, type, pVertexDecl[iVertex].array.stride,
6814 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6815 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6816 break;
6817 case SVGA3D_DECLUSAGE_FOG:
6818 glEnableClientState(GL_FOG_COORD_ARRAY);
6819 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6820 pState->ext.glFogCoordPointer(type, pVertexDecl[iVertex].array.stride,
6821 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6822 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6823 break;
6824 case SVGA3D_DECLUSAGE_DEPTH:
6825 AssertFailed();
6826 break;
6827 case SVGA3D_DECLUSAGE_SAMPLE:
6828 AssertFailed();
6829 break;
6830 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
6831 }
6832 }
6833
6834#ifdef LOG_ENABLED
6835 if (pVertexDecl[iVertex].array.stride == 0)
6836 Log(("vmsvga3dDrawPrimitives: stride == 0! Can be valid\n"));
6837#endif
6838 }
6839
6840 return VINF_SUCCESS;
6841}
6842
6843static int vmsvga3dDrawPrimitivesCleanupVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t iVertexDeclBase,
6844 uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl)
6845{
6846 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6847
6848 /* Clean up the vertex declarations. */
6849 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6850 {
6851 if (pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT)
6852 {
6853 /* Reset the transformation matrices in case of a switch back from pretransformed mode. */
6854 Log(("vmsvga3dDrawPrimitivesCleanupVertexDecls: reset world and projection matrices after transformation reset (pre-transformed -> transformed)\n"));
6855 vmsvga3dResetTransformMatrices(pThisCC, pContext);
6856 }
6857
6858 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6859 {
6860 /* Use numbered vertex arrays when shaders are active. */
6861 pState->ext.glVertexAttribDivisor(iVertexDeclBase + iVertex, 0);
6862 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6863 pState->ext.glDisableVertexAttribArray(iVertexDeclBase + iVertex);
6864 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6865 }
6866 else
6867 {
6868 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6869 switch (pVertexDecl[iVertex].identity.usage)
6870 {
6871 case SVGA3D_DECLUSAGE_POSITION:
6872 case SVGA3D_DECLUSAGE_POSITIONT:
6873 glDisableClientState(GL_VERTEX_ARRAY);
6874 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6875 break;
6876 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6877 break;
6878 case SVGA3D_DECLUSAGE_BLENDINDICES:
6879 break;
6880 case SVGA3D_DECLUSAGE_NORMAL:
6881 glDisableClientState(GL_NORMAL_ARRAY);
6882 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6883 break;
6884 case SVGA3D_DECLUSAGE_PSIZE:
6885 break;
6886 case SVGA3D_DECLUSAGE_TEXCOORD:
6887 /* Specify the affected texture unit. */
6888#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6889 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6890#else
6891 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6892#endif
6893 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
6894 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6895 break;
6896 case SVGA3D_DECLUSAGE_TANGENT:
6897 break;
6898 case SVGA3D_DECLUSAGE_BINORMAL:
6899 break;
6900 case SVGA3D_DECLUSAGE_TESSFACTOR:
6901 break;
6902 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! */
6903 glDisableClientState(GL_COLOR_ARRAY);
6904 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6905 break;
6906 case SVGA3D_DECLUSAGE_FOG:
6907 glDisableClientState(GL_FOG_COORD_ARRAY);
6908 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6909 break;
6910 case SVGA3D_DECLUSAGE_DEPTH:
6911 break;
6912 case SVGA3D_DECLUSAGE_SAMPLE:
6913 break;
6914 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
6915 }
6916 }
6917 }
6918 /* Unbind the vertex buffer after usage. */
6919 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
6920 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6921 return VINF_SUCCESS;
6922}
6923
6924int vmsvga3dDrawPrimitives(PVGASTATECC pThisCC, uint32_t cid, uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl,
6925 uint32_t numRanges, SVGA3dPrimitiveRange *pRange, uint32_t cVertexDivisor,
6926 SVGA3dVertexDivisor *pVertexDivisor)
6927{
6928 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6929 AssertReturn(pState, VERR_INTERNAL_ERROR);
6930 uint32_t iCurrentVertex;
6931
6932 Log(("vmsvga3dDrawPrimitives cid=%u numVertexDecls=%d numRanges=%d, cVertexDivisor=%d\n", cid, numVertexDecls, numRanges, cVertexDivisor));
6933
6934 /* Caller already check these, but it cannot hurt to check again... */
6935 AssertReturn(numVertexDecls && numVertexDecls <= SVGA3D_MAX_VERTEX_ARRAYS, VERR_INVALID_PARAMETER);
6936 AssertReturn(numRanges && numRanges <= SVGA3D_MAX_DRAW_PRIMITIVE_RANGES, VERR_INVALID_PARAMETER);
6937 AssertReturn(!cVertexDivisor || cVertexDivisor == numVertexDecls, VERR_INVALID_PARAMETER);
6938
6939 if (!cVertexDivisor)
6940 pVertexDivisor = NULL; /* Be sure. */
6941
6942 PVMSVGA3DCONTEXT pContext;
6943 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6944 AssertRCReturn(rc, rc);
6945
6946 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6947
6948 /* Check for pretransformed vertex declarations. */
6949 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6950 {
6951 switch (pVertexDecl[iVertex].identity.usage)
6952 {
6953 case SVGA3D_DECLUSAGE_POSITIONT:
6954 Log(("ShaderSetPositionTransformed: (%d,%d)\n", pContext->state.RectViewPort.w, pContext->state.RectViewPort.h));
6955 RT_FALL_THRU();
6956 case SVGA3D_DECLUSAGE_POSITION:
6957 ShaderSetPositionTransformed(pContext->pShaderContext, pContext->state.RectViewPort.w,
6958 pContext->state.RectViewPort.h,
6959 pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT);
6960 break;
6961 default: /* Shut up MSC. */ break;
6962 }
6963 }
6964
6965 /* Flush any shader changes; after (!) checking the vertex declarations to deal with pre-transformed vertices. */
6966 if (pContext->pShaderContext)
6967 {
6968 uint32_t rtHeight = 0;
6969
6970 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA_ID_INVALID)
6971 {
6972 PVMSVGA3DSURFACE pRenderTarget;
6973 rc = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pRenderTarget);
6974 AssertRCReturn(rc, rc);
6975
6976 rtHeight = pRenderTarget->paMipmapLevels[0].mipmapSize.height;
6977 }
6978
6979 ShaderUpdateState(pContext->pShaderContext, rtHeight);
6980 }
6981
6982 /* Try to figure out if instancing is used.
6983 * Support simple instancing case with one set of indexed data and one set per-instance data.
6984 */
6985 uint32_t cInstances = 0;
6986 for (uint32_t iVertexDivisor = 0; iVertexDivisor < cVertexDivisor; ++iVertexDivisor)
6987 {
6988 if (pVertexDivisor[iVertexDivisor].s.indexedData)
6989 {
6990 if (cInstances == 0)
6991 cInstances = pVertexDivisor[iVertexDivisor].s.count;
6992 else
6993 Assert(cInstances == pVertexDivisor[iVertexDivisor].s.count);
6994 }
6995 else if (pVertexDivisor[iVertexDivisor].s.instanceData)
6996 {
6997 Assert(pVertexDivisor[iVertexDivisor].s.count == 1);
6998 }
6999 }
7000
7001 /* Process all vertex declarations. Each vertex buffer is represented by one stream. */
7002 iCurrentVertex = 0;
7003 while (iCurrentVertex < numVertexDecls)
7004 {
7005 uint32_t sidVertex = SVGA_ID_INVALID;
7006 uint32_t iVertex;
7007
7008 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7009 {
7010 if ( sidVertex != SVGA_ID_INVALID
7011 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7012 )
7013 break;
7014 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7015 }
7016
7017 rc = vmsvga3dDrawPrimitivesProcessVertexDecls(pThisCC, pContext, iCurrentVertex, iVertex - iCurrentVertex,
7018 &pVertexDecl[iCurrentVertex], pVertexDivisor);
7019 AssertRCReturn(rc, rc);
7020
7021 iCurrentVertex = iVertex;
7022 }
7023
7024 /* Now draw the primitives. */
7025 for (unsigned iPrimitive = 0; iPrimitive < numRanges; iPrimitive++)
7026 {
7027 GLenum modeDraw;
7028 unsigned const sidIndex = pRange[iPrimitive].indexArray.surfaceId;
7029 PVMSVGA3DSURFACE pIndexSurface = NULL;
7030 unsigned cVertices;
7031
7032 Log(("Primitive %d: type %s\n", iPrimitive, vmsvga3dPrimitiveType2String(pRange[iPrimitive].primType)));
7033 rc = vmsvga3dPrimitiveType2OGL(pRange[iPrimitive].primType, &modeDraw, pRange[iPrimitive].primitiveCount, &cVertices);
7034 if (RT_FAILURE(rc))
7035 {
7036 AssertRC(rc);
7037 goto internal_error;
7038 }
7039
7040 if (sidIndex != SVGA3D_INVALID_ID)
7041 {
7042 AssertMsg(pRange[iPrimitive].indexWidth == sizeof(uint32_t) || pRange[iPrimitive].indexWidth == sizeof(uint16_t), ("Unsupported primitive width %d\n", pRange[iPrimitive].indexWidth));
7043
7044 rc = vmsvga3dSurfaceFromSid(pState, sidIndex, &pIndexSurface);
7045 if (RT_FAILURE(rc))
7046 {
7047 AssertRC(rc);
7048 goto internal_error;
7049 }
7050
7051 Log(("vmsvga3dDrawPrimitives: index surface sid=%u\n", sidIndex));
7052
7053 if (pIndexSurface->oglId.buffer == OPENGL_INVALID_ID)
7054 {
7055 Log(("vmsvga3dDrawPrimitives: create index buffer fDirty=%d size=%x bytes\n", pIndexSurface->fDirty, pIndexSurface->paMipmapLevels[0].cbSurface));
7056 pContext = &pState->SharedCtx;
7057 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7058
7059 pState->ext.glGenBuffers(1, &pIndexSurface->oglId.buffer);
7060 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7061 pIndexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
7062
7063 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7064 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7065
7066 Assert(pIndexSurface->fDirty);
7067
7068 /** @todo rethink usage dynamic/static */
7069 pState->ext.glBufferData(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->paMipmapLevels[0].cbSurface, pIndexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
7070 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7071
7072 pIndexSurface->paMipmapLevels[0].fDirty = false;
7073 pIndexSurface->fDirty = false;
7074
7075 pIndexSurface->surfaceFlags |= SVGA3D_SURFACE_HINT_INDEXBUFFER;
7076
7077 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, OPENGL_INVALID_ID);
7078 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7079
7080 pContext = pState->papContexts[cid];
7081 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7082 }
7083 Assert(pIndexSurface->fDirty == false);
7084
7085 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7086 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7087 }
7088
7089 if (!pIndexSurface)
7090 {
7091 /* Render without an index buffer */
7092 Log(("DrawPrimitive %d cPrimitives=%d cVertices=%d index index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pRange[iPrimitive].indexBias, cInstances));
7093 if (cInstances == 0)
7094 {
7095 glDrawArrays(modeDraw, pRange[iPrimitive].indexBias, cVertices);
7096 }
7097 else
7098 {
7099 pState->ext.glDrawArraysInstanced(modeDraw, pRange[iPrimitive].indexBias, cVertices, cInstances);
7100 }
7101 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7102 }
7103 else
7104 {
7105 Assert(pRange[iPrimitive].indexWidth == pRange[iPrimitive].indexArray.stride);
7106
7107 GLenum indexType;
7108 switch (pRange[iPrimitive].indexWidth)
7109 {
7110 case 1: indexType = GL_UNSIGNED_BYTE; break;
7111 case 2: indexType = GL_UNSIGNED_SHORT; break;
7112 default: AssertMsgFailed(("indexWidth %d\n", pRange[iPrimitive].indexWidth));
7113 RT_FALL_THROUGH();
7114 case 4: indexType = GL_UNSIGNED_INT; break;
7115 }
7116
7117 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));
7118 if (cInstances == 0)
7119 {
7120 /* Render with an index buffer */
7121 if (pRange[iPrimitive].indexBias == 0)
7122 glDrawElements(modeDraw,
7123 cVertices,
7124 indexType,
7125 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset); /* byte offset in indices buffer */
7126 else
7127 pState->ext.glDrawElementsBaseVertex(modeDraw,
7128 cVertices,
7129 indexType,
7130 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7131 pRange[iPrimitive].indexBias); /* basevertex */
7132 }
7133 else
7134 {
7135 /* Render with an index buffer */
7136 if (pRange[iPrimitive].indexBias == 0)
7137 pState->ext.glDrawElementsInstanced(modeDraw,
7138 cVertices,
7139 indexType,
7140 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7141 cInstances);
7142 else
7143 pState->ext.glDrawElementsInstancedBaseVertex(modeDraw,
7144 cVertices,
7145 indexType,
7146 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7147 cInstances,
7148 pRange[iPrimitive].indexBias); /* basevertex */
7149 }
7150 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7151
7152 /* Unbind the index buffer after usage. */
7153 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
7154 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7155 }
7156 }
7157
7158internal_error:
7159
7160 /* Deactivate the vertex declarations. */
7161 iCurrentVertex = 0;
7162 while (iCurrentVertex < numVertexDecls)
7163 {
7164 uint32_t sidVertex = SVGA_ID_INVALID;
7165 uint32_t iVertex;
7166
7167 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7168 {
7169 if ( sidVertex != SVGA_ID_INVALID
7170 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7171 )
7172 break;
7173 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7174 }
7175
7176 rc = vmsvga3dDrawPrimitivesCleanupVertexDecls(pThisCC, pContext, iCurrentVertex,
7177 iVertex - iCurrentVertex, &pVertexDecl[iCurrentVertex]);
7178 AssertRCReturn(rc, rc);
7179
7180 iCurrentVertex = iVertex;
7181 }
7182
7183#ifdef DEBUG
7184 /* Check whether 'activeTexture' on texture unit 'i' matches what we expect. */
7185 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); ++i)
7186 {
7187 if (pContext->aSidActiveTextures[i] != SVGA3D_INVALID_ID)
7188 {
7189 PVMSVGA3DSURFACE pTexture;
7190 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[i], &pTexture);
7191 AssertContinue(RT_SUCCESS(rc2));
7192
7193 GLint activeTextureUnit = 0;
7194 glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTextureUnit);
7195 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7196
7197 pState->ext.glActiveTexture(GL_TEXTURE0 + i);
7198 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7199
7200 GLint activeTexture = 0;
7201 glGetIntegerv(pTexture->bindingGL, &activeTexture);
7202 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7203
7204 pState->ext.glActiveTexture(activeTextureUnit);
7205 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7206
7207 AssertMsg(pTexture->oglId.texture == (GLuint)activeTexture,
7208 ("%d vs %d unit %d (active unit %d) sid=%u\n", pTexture->oglId.texture, activeTexture, i,
7209 activeTextureUnit - GL_TEXTURE0, pContext->aSidActiveTextures[i]));
7210 }
7211 }
7212#endif
7213
7214#if 0
7215 /* Dump render target to a bitmap. */
7216 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA3D_INVALID_ID)
7217 {
7218 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0]);
7219 PVMSVGA3DSURFACE pSurface;
7220 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pSurface);
7221 if (RT_SUCCESS(rc2))
7222 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post");
7223# if 0
7224 /* Stage 0 texture. */
7225 if (pContext->aSidActiveTextures[0] != SVGA3D_INVALID_ID)
7226 {
7227 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->aSidActiveTextures[0]);
7228 rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[0], &pSurface);
7229 if (RT_SUCCESS(rc2))
7230 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post-tx");
7231 }
7232# endif
7233 }
7234#endif
7235
7236 return rc;
7237}
7238
7239
7240int vmsvga3dShaderDefine(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type, uint32_t cbData, uint32_t *pShaderData)
7241{
7242 PVMSVGA3DSHADER pShader;
7243 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7244 AssertReturn(pState, VERR_NO_MEMORY);
7245
7246 Log(("vmsvga3dShaderDefine cid=%u shid=%d type=%s cbData=0x%x\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cbData));
7247
7248 PVMSVGA3DCONTEXT pContext;
7249 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7250 AssertRCReturn(rc, rc);
7251
7252 AssertReturn(shid < SVGA3D_MAX_SHADER_IDS, VERR_INVALID_PARAMETER);
7253
7254 rc = vmsvga3dShaderParse(cbData, pShaderData);
7255 if (RT_FAILURE(rc))
7256 {
7257 AssertRC(rc);
7258 vmsvga3dShaderLogRel("Failed to parse", type, cbData, pShaderData);
7259 return rc;
7260 }
7261
7262 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7263
7264 if (type == SVGA3D_SHADERTYPE_VS)
7265 {
7266 if (shid >= pContext->cVertexShaders)
7267 {
7268 void *pvNew = RTMemRealloc(pContext->paVertexShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7269 AssertReturn(pvNew, VERR_NO_MEMORY);
7270 pContext->paVertexShader = (PVMSVGA3DSHADER)pvNew;
7271 memset(&pContext->paVertexShader[pContext->cVertexShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cVertexShaders));
7272 for (uint32_t i = pContext->cVertexShaders; i < shid + 1; i++)
7273 pContext->paVertexShader[i].id = SVGA3D_INVALID_ID;
7274 pContext->cVertexShaders = shid + 1;
7275 }
7276 /* If one already exists with this id, then destroy it now. */
7277 if (pContext->paVertexShader[shid].id != SVGA3D_INVALID_ID)
7278 vmsvga3dShaderDestroy(pThisCC, cid, shid, pContext->paVertexShader[shid].type);
7279
7280 pShader = &pContext->paVertexShader[shid];
7281 }
7282 else
7283 {
7284 Assert(type == SVGA3D_SHADERTYPE_PS);
7285 if (shid >= pContext->cPixelShaders)
7286 {
7287 void *pvNew = RTMemRealloc(pContext->paPixelShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7288 AssertReturn(pvNew, VERR_NO_MEMORY);
7289 pContext->paPixelShader = (PVMSVGA3DSHADER)pvNew;
7290 memset(&pContext->paPixelShader[pContext->cPixelShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cPixelShaders));
7291 for (uint32_t i = pContext->cPixelShaders; i < shid + 1; i++)
7292 pContext->paPixelShader[i].id = SVGA3D_INVALID_ID;
7293 pContext->cPixelShaders = shid + 1;
7294 }
7295 /* If one already exists with this id, then destroy it now. */
7296 if (pContext->paPixelShader[shid].id != SVGA3D_INVALID_ID)
7297 vmsvga3dShaderDestroy(pThisCC, cid, shid, pContext->paPixelShader[shid].type);
7298
7299 pShader = &pContext->paPixelShader[shid];
7300 }
7301
7302 memset(pShader, 0, sizeof(*pShader));
7303 pShader->id = shid;
7304 pShader->cid = cid;
7305 pShader->type = type;
7306 pShader->cbData = cbData;
7307 pShader->pShaderProgram = RTMemAllocZ(cbData);
7308 AssertReturn(pShader->pShaderProgram, VERR_NO_MEMORY);
7309 memcpy(pShader->pShaderProgram, pShaderData, cbData);
7310
7311#ifdef DUMP_SHADER_DISASSEMBLY
7312 LPD3DXBUFFER pDisassembly;
7313 HRESULT hr = D3DXDisassembleShader((const DWORD *)pShaderData, FALSE, NULL, &pDisassembly);
7314 if (hr == D3D_OK)
7315 {
7316 Log(("Shader disassembly:\n%s\n", pDisassembly->GetBufferPointer()));
7317 pDisassembly->Release();
7318 }
7319#endif
7320
7321 switch (type)
7322 {
7323 case SVGA3D_SHADERTYPE_VS:
7324 rc = ShaderCreateVertexShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pVertexShader);
7325 AssertRC(rc);
7326 break;
7327
7328 case SVGA3D_SHADERTYPE_PS:
7329 rc = ShaderCreatePixelShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pPixelShader);
7330 AssertRC(rc);
7331 break;
7332
7333 default:
7334 AssertFailedReturn(VERR_INVALID_PARAMETER);
7335 }
7336 if (rc != VINF_SUCCESS)
7337 {
7338 vmsvga3dShaderLogRel("Failed to create", type, cbData, pShaderData);
7339
7340 RTMemFree(pShader->pShaderProgram);
7341 memset(pShader, 0, sizeof(*pShader));
7342 pShader->id = SVGA3D_INVALID_ID;
7343 }
7344
7345 return rc;
7346}
7347
7348int vmsvga3dShaderDestroy(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type)
7349{
7350 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7351 AssertReturn(pState, VERR_NO_MEMORY);
7352 PVMSVGA3DSHADER pShader = NULL;
7353
7354 Log(("vmsvga3dShaderDestroy cid=%u shid=%d type=%s\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL"));
7355
7356 PVMSVGA3DCONTEXT pContext;
7357 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7358 AssertRCReturn(rc, rc);
7359
7360 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7361
7362 if (type == SVGA3D_SHADERTYPE_VS)
7363 {
7364 if ( shid < pContext->cVertexShaders
7365 && pContext->paVertexShader[shid].id == shid)
7366 {
7367 pShader = &pContext->paVertexShader[shid];
7368 rc = ShaderDestroyVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7369 AssertRC(rc);
7370 }
7371 }
7372 else
7373 {
7374 Assert(type == SVGA3D_SHADERTYPE_PS);
7375 if ( shid < pContext->cPixelShaders
7376 && pContext->paPixelShader[shid].id == shid)
7377 {
7378 pShader = &pContext->paPixelShader[shid];
7379 rc = ShaderDestroyPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7380 AssertRC(rc);
7381 }
7382 }
7383
7384 if (pShader)
7385 {
7386 if (pShader->pShaderProgram)
7387 RTMemFree(pShader->pShaderProgram);
7388 memset(pShader, 0, sizeof(*pShader));
7389 pShader->id = SVGA3D_INVALID_ID;
7390 }
7391 else
7392 AssertFailedReturn(VERR_INVALID_PARAMETER);
7393
7394 return VINF_SUCCESS;
7395}
7396
7397int vmsvga3dShaderSet(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid, SVGA3dShaderType type, uint32_t shid)
7398{
7399 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7400 AssertReturn(pState, VERR_NO_MEMORY);
7401 int rc;
7402
7403 Log(("vmsvga3dShaderSet cid=%u type=%s shid=%d\n", cid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", shid));
7404
7405 if (!pContext)
7406 {
7407 rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7408 AssertRCReturn(rc, rc);
7409 }
7410
7411 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7412
7413 if (type == SVGA3D_SHADERTYPE_VS)
7414 {
7415 /* Save for vm state save/restore. */
7416 pContext->state.shidVertex = shid;
7417 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VERTEXSHADER;
7418
7419 if ( shid < pContext->cVertexShaders
7420 && pContext->paVertexShader[shid].id == shid)
7421 {
7422 PVMSVGA3DSHADER pShader = &pContext->paVertexShader[shid];
7423 Assert(type == pShader->type);
7424
7425 rc = ShaderSetVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7426 AssertRCReturn(rc, rc);
7427 }
7428 else
7429 if (shid == SVGA_ID_INVALID)
7430 {
7431 /* Unselect shader. */
7432 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7433 AssertRCReturn(rc, rc);
7434 }
7435 else
7436 AssertFailedReturn(VERR_INVALID_PARAMETER);
7437 }
7438 else
7439 {
7440 /* Save for vm state save/restore. */
7441 pContext->state.shidPixel = shid;
7442 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_PIXELSHADER;
7443
7444 Assert(type == SVGA3D_SHADERTYPE_PS);
7445 if ( shid < pContext->cPixelShaders
7446 && pContext->paPixelShader[shid].id == shid)
7447 {
7448 PVMSVGA3DSHADER pShader = &pContext->paPixelShader[shid];
7449 Assert(type == pShader->type);
7450
7451 rc = ShaderSetPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7452 AssertRCReturn(rc, rc);
7453 }
7454 else
7455 if (shid == SVGA_ID_INVALID)
7456 {
7457 /* Unselect shader. */
7458 rc = ShaderSetPixelShader(pContext->pShaderContext, NULL);
7459 AssertRCReturn(rc, rc);
7460 }
7461 else
7462 AssertFailedReturn(VERR_INVALID_PARAMETER);
7463 }
7464
7465 return VINF_SUCCESS;
7466}
7467
7468int vmsvga3dShaderSetConst(PVGASTATECC pThisCC, uint32_t cid, uint32_t reg, SVGA3dShaderType type, SVGA3dShaderConstType ctype, uint32_t cRegisters, uint32_t *pValues)
7469{
7470 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7471 AssertReturn(pState, VERR_NO_MEMORY);
7472
7473 Log(("vmsvga3dShaderSetConst cid=%u reg=%x type=%s cregs=%d ctype=%x\n", cid, reg, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cRegisters, ctype));
7474
7475 PVMSVGA3DCONTEXT pContext;
7476 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7477 AssertRCReturn(rc, rc);
7478
7479 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7480
7481 for (uint32_t i = 0; i < cRegisters; i++)
7482 {
7483#ifdef LOG_ENABLED
7484 switch (ctype)
7485 {
7486 case SVGA3D_CONST_TYPE_FLOAT:
7487 {
7488 float *pValuesF = (float *)pValues;
7489 Log(("ConstantF %d: value=" FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR "\n",
7490 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])));
7491 break;
7492 }
7493
7494 case SVGA3D_CONST_TYPE_INT:
7495 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]));
7496 break;
7497
7498 case SVGA3D_CONST_TYPE_BOOL:
7499 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]));
7500 break;
7501 }
7502#endif
7503 vmsvga3dSaveShaderConst(pContext, reg + i, type, ctype, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]);
7504 }
7505
7506 switch (type)
7507 {
7508 case SVGA3D_SHADERTYPE_VS:
7509 switch (ctype)
7510 {
7511 case SVGA3D_CONST_TYPE_FLOAT:
7512 rc = ShaderSetVertexShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7513 break;
7514
7515 case SVGA3D_CONST_TYPE_INT:
7516 rc = ShaderSetVertexShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7517 break;
7518
7519 case SVGA3D_CONST_TYPE_BOOL:
7520 rc = ShaderSetVertexShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7521 break;
7522
7523 default:
7524 AssertFailedReturn(VERR_INVALID_PARAMETER);
7525 }
7526 AssertRCReturn(rc, rc);
7527 break;
7528
7529 case SVGA3D_SHADERTYPE_PS:
7530 switch (ctype)
7531 {
7532 case SVGA3D_CONST_TYPE_FLOAT:
7533 rc = ShaderSetPixelShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7534 break;
7535
7536 case SVGA3D_CONST_TYPE_INT:
7537 rc = ShaderSetPixelShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7538 break;
7539
7540 case SVGA3D_CONST_TYPE_BOOL:
7541 rc = ShaderSetPixelShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7542 break;
7543
7544 default:
7545 AssertFailedReturn(VERR_INVALID_PARAMETER);
7546 }
7547 AssertRCReturn(rc, rc);
7548 break;
7549
7550 default:
7551 AssertFailedReturn(VERR_INVALID_PARAMETER);
7552 }
7553
7554 return VINF_SUCCESS;
7555}
7556
7557int vmsvga3dOcclusionQueryCreate(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7558{
7559 AssertReturn(pState->ext.glGenQueries, VERR_NOT_SUPPORTED);
7560 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7561
7562 GLuint idQuery = 0;
7563 pState->ext.glGenQueries(1, &idQuery);
7564 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7565 AssertReturn(idQuery, VERR_INTERNAL_ERROR);
7566 pContext->occlusion.idQuery = idQuery;
7567 return VINF_SUCCESS;
7568}
7569
7570int vmsvga3dOcclusionQueryDelete(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7571{
7572 AssertReturn(pState->ext.glDeleteQueries, VERR_NOT_SUPPORTED);
7573 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7574
7575 if (pContext->occlusion.idQuery)
7576 {
7577 pState->ext.glDeleteQueries(1, &pContext->occlusion.idQuery);
7578 }
7579 return VINF_SUCCESS;
7580}
7581
7582int vmsvga3dOcclusionQueryBegin(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7583{
7584 AssertReturn(pState->ext.glBeginQuery, VERR_NOT_SUPPORTED);
7585 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7586
7587 pState->ext.glBeginQuery(GL_ANY_SAMPLES_PASSED, pContext->occlusion.idQuery);
7588 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7589 return VINF_SUCCESS;
7590}
7591
7592int vmsvga3dOcclusionQueryEnd(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
7593{
7594 AssertReturn(pState->ext.glEndQuery, VERR_NOT_SUPPORTED);
7595 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7596
7597 pState->ext.glEndQuery(GL_ANY_SAMPLES_PASSED);
7598 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7599 return VINF_SUCCESS;
7600}
7601
7602int vmsvga3dOcclusionQueryGetData(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, uint32_t *pu32Pixels)
7603{
7604 AssertReturn(pState->ext.glGetQueryObjectuiv, VERR_NOT_SUPPORTED);
7605 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7606
7607 GLuint pixels = 0;
7608 pState->ext.glGetQueryObjectuiv(pContext->occlusion.idQuery, GL_QUERY_RESULT, &pixels);
7609 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7610
7611 *pu32Pixels = (uint32_t)pixels;
7612 return VINF_SUCCESS;
7613}
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