/
hellovr_vulkan_main.cpp
3803 lines (3312 loc) · 150 KB
/
hellovr_vulkan_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation ============//
#if defined( _WIN32 )
#define VK_USE_PLATFORM_WIN32_KHR
#else
#define SDL_VIDEO_DRIVER_X11
#define VK_USE_PLATFORM_XLIB_KHR
#endif
#include <vulkan/vulkan.h>
#include <SDL.h>
#include <SDL_syswm.h>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <inttypes.h>
#include <openvr.h>
#include <deque>
#include "shared/lodepng.h"
#include "shared/Matrices.h"
#include "shared/pathtools.h"
#if defined(POSIX)
#include "unistd.h"
#endif
#ifndef _countof
#define _countof(x) (sizeof(x)/sizeof((x)[0]))
#endif
void ThreadSleep( unsigned long nMilliseconds )
{
#if defined(_WIN32)
::Sleep( nMilliseconds );
#elif defined(POSIX)
usleep( nMilliseconds * 1000 );
#endif
}
// Pipeline state objects
enum PipelineStateObjectEnum_t
{
PSO_SCENE = 0,
PSO_AXES,
PSO_RENDERMODEL,
PSO_COMPANION,
PSO_COUNT
};
// Indices of descriptor sets for rendering
enum DescriptorSetIndex_t
{
DESCRIPTOR_SET_LEFT_EYE_SCENE = 0,
DESCRIPTOR_SET_RIGHT_EYE_SCENE,
DESCRIPTOR_SET_COMPANION_LEFT_TEXTURE,
DESCRIPTOR_SET_COMPANION_RIGHT_TEXTURE,
DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL0,
DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL_MAX = DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL0 + vr::k_unMaxTrackedDeviceCount,
DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL0,
DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL_MAX = DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL0 + vr::k_unMaxTrackedDeviceCount,
NUM_DESCRIPTOR_SETS
};
class VulkanRenderModel
{
public:
VulkanRenderModel( const std::string & sRenderModelName );
~VulkanRenderModel();
bool BInit( VkDevice pDevice, const VkPhysicalDeviceMemoryProperties &memoryProperties, VkCommandBuffer pCommandBuffer, vr::TrackedDeviceIndex_t unTrackedDeviceIndex, VkDescriptorSet pDescriptorSets[ 2 ], const vr::RenderModel_t & vrModel, const vr::RenderModel_TextureMap_t & vrDiffuseTexture );
void Cleanup();
void Draw( vr::EVREye nEye, VkCommandBuffer pCommandBuffer, VkPipelineLayout pPipelineLayout, const Matrix4 &matMVP );
const std::string & GetName() const { return m_sModelName; }
private:
VkDevice m_pDevice;
VkPhysicalDeviceMemoryProperties m_physicalDeviceMemoryProperties;
VkBuffer m_pVertexBuffer;
VkDeviceMemory m_pVertexBufferMemory;
VkBuffer m_pIndexBuffer;
VkDeviceMemory m_pIndexBufferMemory;
VkImage m_pImage;
VkDeviceMemory m_pImageMemory;
VkImageView m_pImageView;
VkBuffer m_pImageStagingBuffer;
VkDeviceMemory m_pImageStagingBufferMemory;
VkBuffer m_pConstantBuffer[ 2 ];
VkDeviceMemory m_pConstantBufferMemory[ 2 ];
void *m_pConstantBufferData[ 2 ];
VkDescriptorSet m_pDescriptorSets[ 2 ];
VkSampler m_pSampler;
size_t m_unVertexCount;
vr::TrackedDeviceIndex_t m_unTrackedDeviceIndex;
std::string m_sModelName;
};
static bool g_bPrintf = true;
// Vulkan extension entrypoints
static PFN_vkCreateDebugReportCallbackEXT g_pVkCreateDebugReportCallbackEXT = nullptr;
static PFN_vkDestroyDebugReportCallbackEXT g_pVkDestroyDebugReportCallbackEXT = nullptr;
//-----------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
class CMainApplication
{
public:
CMainApplication( int argc, char *argv[] );
virtual ~CMainApplication();
bool BInit();
bool BInitVulkan();
bool BInitVulkanInstance();
bool BInitVulkanDevice();
bool BInitVulkanSwapchain();
bool BInitCompositor();
bool GetVulkanInstanceExtensionsRequired( std::vector< std::string > &outInstanceExtensionList );
bool GetVulkanDeviceExtensionsRequired( VkPhysicalDevice pPhysicalDevice, std::vector< std::string > &outDeviceExtensionList );
void SetupRenderModels();
void Shutdown();
void RunMainLoop();
bool HandleInput();
void ProcessVREvent( const vr::VREvent_t & event );
void RenderFrame();
bool SetupTexturemaps();
static void GenMipMapRGBA( const uint8_t *pSrc, uint8_t *ppDst, int nSrcWidth, int nSrcHeight, int *pDstWidthOut, int *pDstHeightOut );
void SetupScene();
void AddCubeToScene( Matrix4 mat, std::vector<float> &vertdata );
void AddCubeVertex( float fl0, float fl1, float fl2, float fl3, float fl4, std::vector<float> &vertdata );
void UpdateControllerAxes();
bool SetupStereoRenderTargets();
void SetupCompanionWindow();
void SetupCameras();
void RenderStereoTargets();
void RenderCompanionWindow();
void RenderScene( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixPoseEye( vr::Hmd_Eye nEye );
Matrix4 GetCurrentViewProjectionMatrix( vr::Hmd_Eye nEye );
void UpdateHMDMatrixPose();
Matrix4 ConvertSteamVRMatrixToMatrix4( const vr::HmdMatrix34_t &matPose );
bool CreateAllShaders();
void CreateAllDescriptorSets();
void SetupRenderModelForTrackedDevice( vr::TrackedDeviceIndex_t unTrackedDeviceIndex );
VulkanRenderModel *FindOrLoadRenderModel( vr::TrackedDeviceIndex_t unTrackedDeviceIndex, const char *pchRenderModelName );
private:
bool m_bDebugVulkan;
bool m_bVerbose;
bool m_bPerf;
bool m_bVblank;
int m_nMSAASampleCount;
// Optional scaling factor to render with supersampling (defaults off, use -scale)
float m_flSuperSampleScale;
vr::IVRSystem *m_pHMD;
vr::IVRRenderModels *m_pRenderModels;
std::string m_strDriver;
std::string m_strDisplay;
vr::TrackedDevicePose_t m_rTrackedDevicePose[ vr::k_unMaxTrackedDeviceCount ];
Matrix4 m_rmat4DevicePose[ vr::k_unMaxTrackedDeviceCount ];
bool m_rbShowTrackedDevice[ vr::k_unMaxTrackedDeviceCount ];
private: // SDL bookkeeping
SDL_Window *m_pCompanionWindow;
uint32_t m_nCompanionWindowWidth;
uint32_t m_nCompanionWindowHeight;
private:
int m_iTrackedControllerCount;
int m_iTrackedControllerCount_Last;
int m_iValidPoseCount;
int m_iValidPoseCount_Last;
bool m_bShowCubes;
std::string m_strPoseClasses; // what classes we saw poses for this frame
char m_rDevClassChar[ vr::k_unMaxTrackedDeviceCount ]; // for each device, a character representing its class
int m_iSceneVolumeWidth;
int m_iSceneVolumeHeight;
int m_iSceneVolumeDepth;
float m_fScaleSpacing;
float m_fScale;
int m_iSceneVolumeInit; // if you want something other than the default 20x20x20
float m_fNearClip;
float m_fFarClip;
unsigned int m_uiVertcount;
unsigned int m_uiCompanionWindowIndexSize;
VkInstance m_pInstance;
VkDevice m_pDevice;
VkPhysicalDevice m_pPhysicalDevice;
VkQueue m_pQueue;
VkSurfaceKHR m_pSurface;
VkSwapchainKHR m_pSwapchain;
VkPhysicalDeviceProperties m_physicalDeviceProperties;
VkPhysicalDeviceMemoryProperties m_physicalDeviceMemoryProperties;
VkPhysicalDeviceFeatures m_physicalDeviceFeatures;
uint32_t m_nQueueFamilyIndex;
VkDebugReportCallbackEXT m_pDebugReportCallback;
uint32_t m_nSwapQueueImageCount;
uint32_t m_nFrameIndex;
uint32_t m_nCurrentSwapchainImage;
std::vector< VkImage > m_swapchainImages;
std::vector< VkImageView > m_pSwapchainImageViews;
std::vector< VkFramebuffer > m_pSwapchainFramebuffers;
std::vector< VkSemaphore > m_pSwapchainSemaphores;
VkRenderPass m_pSwapchainRenderPass;
VkCommandPool m_pCommandPool;
VkDescriptorPool m_pDescriptorPool;
VkDescriptorSet m_pDescriptorSets[ NUM_DESCRIPTOR_SETS ];
struct VulkanCommandBuffer_t
{
VkCommandBuffer m_pCommandBuffer;
VkFence m_pFence;
};
std::deque< VulkanCommandBuffer_t > m_commandBuffers;
VulkanCommandBuffer_t m_currentCommandBuffer;
VulkanCommandBuffer_t GetCommandBuffer();
// Scene resources
VkBuffer m_pSceneVertexBuffer;
VkDeviceMemory m_pSceneVertexBufferMemory;
VkBufferView m_pSceneVertexBufferView;
VkBuffer m_pSceneConstantBuffer[ 2 ];
VkDeviceMemory m_pSceneConstantBufferMemory[ 2 ];
void *m_pSceneConstantBufferData[ 2 ];
VkImage m_pSceneImage;
VkDeviceMemory m_pSceneImageMemory;
VkImageView m_pSceneImageView;
VkBuffer m_pSceneStagingBuffer;
VkDeviceMemory m_pSceneStagingBufferMemory;
VkSampler m_pSceneSampler;
// Storage for VS and PS for each PSO
VkShaderModule m_pShaderModules[ PSO_COUNT * 2 ];
VkPipeline m_pPipelines[ PSO_COUNT ];
VkDescriptorSetLayout m_pDescriptorSetLayout;
VkPipelineLayout m_pPipelineLayout;
VkPipelineCache m_pPipelineCache;
// Companion window resources
VkBuffer m_pCompanionWindowVertexBuffer;
VkDeviceMemory m_pCompanionWindowVertexBufferMemory;
VkBuffer m_pCompanionWindowIndexBuffer;
VkDeviceMemory m_pCompanionWindowIndexBufferMemory;
// Controller axes resources
VkBuffer m_pControllerAxesVertexBuffer;
VkDeviceMemory m_pControllerAxesVertexBufferMemory;
unsigned int m_uiControllerVertcount;
Matrix4 m_mat4HMDPose;
Matrix4 m_mat4eyePosLeft;
Matrix4 m_mat4eyePosRight;
Matrix4 m_mat4ProjectionCenter;
Matrix4 m_mat4ProjectionLeft;
Matrix4 m_mat4ProjectionRight;
struct VertexDataScene
{
Vector3 position;
Vector2 texCoord;
};
struct VertexDataWindow
{
Vector2 position;
Vector2 texCoord;
VertexDataWindow( const Vector2 & pos, const Vector2 tex ) : position(pos), texCoord(tex) { }
};
struct FramebufferDesc
{
VkImage m_pImage;
VkImageLayout m_nImageLayout;
VkDeviceMemory m_pDeviceMemory;
VkImageView m_pImageView;
VkImage m_pDepthStencilImage;
VkImageLayout m_nDepthStencilImageLayout;
VkDeviceMemory m_pDepthStencilDeviceMemory;
VkImageView m_pDepthStencilImageView;
VkRenderPass m_pRenderPass;
VkFramebuffer m_pFramebuffer;
};
FramebufferDesc m_leftEyeDesc;
FramebufferDesc m_rightEyeDesc;
bool CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc );
uint32_t m_nRenderWidth;
uint32_t m_nRenderHeight;
std::vector< VulkanRenderModel * > m_vecRenderModels;
VulkanRenderModel *m_rTrackedDeviceToRenderModel[ vr::k_unMaxTrackedDeviceCount ];
};
//-----------------------------------------------------------------------------
// Purpose: Outputs a set of optional arguments to debugging output, using
// the printf format setting specified in fmt*.
//-----------------------------------------------------------------------------
void dprintf( const char *fmt, ... )
{
va_list args;
char buffer[ 2048 ];
va_start( args, fmt );
vsnprintf( buffer, sizeof( buffer ), fmt, args );
va_end( args );
if ( g_bPrintf )
printf( "%s", buffer );
OutputDebugStringA( buffer );
}
//-----------------------------------------------------------------------------
// Purpose: VK_EXT_debug_report callback
//-----------------------------------------------------------------------------
static VkBool32 VKAPI_PTR VKDebugMessageCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object,
size_t location, int32_t messageCode, const char* pLayerPrefix, const char *pMessage, void *pUserData )
{
char buf[4096] = { 0 };
switch ( flags )
{
case VK_DEBUG_REPORT_ERROR_BIT_EXT:
sprintf( buf, "VK ERROR %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_WARNING_BIT_EXT:
sprintf( buf, "VK WARNING %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
sprintf( buf, "VK PERF %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
sprintf( buf, "VK INFO %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
sprintf( buf, "VK DEBUG %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
default:
break;
}
dprintf( "%s\n", buf );
return VK_FALSE;
}
//-----------------------------------------------------------------------------
// Purpose: Determine the memory type index from the memory requirements
// and type bits
//-----------------------------------------------------------------------------
static bool MemoryTypeFromProperties( const VkPhysicalDeviceMemoryProperties &memoryProperties, uint32_t nMemoryTypeBits, VkMemoryPropertyFlags nMemoryProperties, uint32_t *pTypeIndexOut )
{
for ( uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++ )
{
if ( ( nMemoryTypeBits & 1 ) == 1)
{
// Type is available, does it match user properties?
if ( ( memoryProperties.memoryTypes[i].propertyFlags & nMemoryProperties ) == nMemoryProperties )
{
*pTypeIndexOut = i;
return true;
}
}
nMemoryTypeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Helper function to create Vulkan static VB/IBs
//-----------------------------------------------------------------------------
static bool CreateVulkanBuffer( VkDevice pDevice, const VkPhysicalDeviceMemoryProperties &memoryProperties, const void *pBufferData, VkDeviceSize nSize, VkBufferUsageFlags nUsage, VkBuffer *ppBufferOut, VkDeviceMemory *ppDeviceMemoryOut )
{
// Create the vertex buffer and fill with data
VkBufferCreateInfo bufferCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferCreateInfo.size = nSize;
bufferCreateInfo.usage = nUsage;
VkResult nResult = vkCreateBuffer( pDevice, &bufferCreateInfo, nullptr, ppBufferOut );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkCreateBuffer failed with error %d\n", __FUNCTION__, nResult );
return false;
}
VkMemoryRequirements memoryRequirements = {};
vkGetBufferMemoryRequirements( pDevice, *ppBufferOut, &memoryRequirements );
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
if ( !MemoryTypeFromProperties( memoryProperties, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex ) )
{
dprintf( "%s - failed to find matching memoryTypeIndex for buffer\n", __FUNCTION__ );
return false;
}
allocInfo.allocationSize = memoryRequirements.size;
nResult = vkAllocateMemory( pDevice, &allocInfo, nullptr, ppDeviceMemoryOut );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkCreateBuffer failed with error %d\n", __FUNCTION__, nResult );
return false;
}
nResult = vkBindBufferMemory( pDevice, *ppBufferOut, *ppDeviceMemoryOut, 0 );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s vkBindBufferMemory failed with error %d\n", __FUNCTION__, nResult );
return false;
}
if ( pBufferData != nullptr )
{
void *pData;
nResult = vkMapMemory( pDevice, *ppDeviceMemoryOut, 0, VK_WHOLE_SIZE, 0, &pData );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkMapMemory returned error %d\n", __FUNCTION__, nResult );
return false;
}
memcpy( pData, pBufferData, nSize );
vkUnmapMemory( pDevice, *ppDeviceMemoryOut );
VkMappedMemoryRange memoryRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
memoryRange.memory = *ppDeviceMemoryOut;
memoryRange.size = VK_WHOLE_SIZE;
vkFlushMappedMemoryRanges( pDevice, 1, &memoryRange );
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMainApplication::CMainApplication( int argc, char *argv[] )
: m_pCompanionWindow(NULL)
, m_nCompanionWindowWidth( 640 )
, m_nCompanionWindowHeight( 320 )
, m_pHMD( NULL )
, m_pRenderModels( NULL )
, m_bDebugVulkan( false )
, m_bVerbose( false )
, m_bPerf( false )
, m_bVblank( false )
, m_nMSAASampleCount( 4 )
, m_flSuperSampleScale( 1.0f )
, m_iTrackedControllerCount( 0 )
, m_iTrackedControllerCount_Last( -1 )
, m_iValidPoseCount( 0 )
, m_iValidPoseCount_Last( -1 )
, m_iSceneVolumeInit( 20 )
, m_strPoseClasses("")
, m_bShowCubes( true )
, m_pInstance( VK_NULL_HANDLE )
, m_pDevice( VK_NULL_HANDLE )
, m_pPhysicalDevice( VK_NULL_HANDLE )
, m_pQueue( VK_NULL_HANDLE )
, m_pSurface( VK_NULL_HANDLE )
, m_pSwapchain( VK_NULL_HANDLE )
, m_pDebugReportCallback( VK_NULL_HANDLE )
, m_pCommandPool( VK_NULL_HANDLE )
, m_pDescriptorPool( VK_NULL_HANDLE )
, m_nSwapQueueImageCount( 0 )
, m_nFrameIndex( 0 )
, m_nCurrentSwapchainImage( 0 )
, m_pSceneVertexBuffer( VK_NULL_HANDLE )
, m_pSceneVertexBufferMemory( VK_NULL_HANDLE )
, m_pSceneVertexBufferView( VK_NULL_HANDLE )
, m_pSceneImage( VK_NULL_HANDLE )
, m_pSceneImageMemory( VK_NULL_HANDLE )
, m_pSceneImageView( VK_NULL_HANDLE )
, m_pSceneStagingBuffer( VK_NULL_HANDLE )
, m_pSceneStagingBufferMemory( VK_NULL_HANDLE )
, m_pSceneSampler( VK_NULL_HANDLE )
, m_pDescriptorSetLayout( VK_NULL_HANDLE )
, m_pPipelineLayout( VK_NULL_HANDLE )
, m_pPipelineCache( VK_NULL_HANDLE )
, m_pCompanionWindowVertexBuffer( VK_NULL_HANDLE )
, m_pCompanionWindowVertexBufferMemory( VK_NULL_HANDLE )
, m_pCompanionWindowIndexBuffer( VK_NULL_HANDLE )
, m_pCompanionWindowIndexBufferMemory( VK_NULL_HANDLE )
, m_pControllerAxesVertexBuffer( VK_NULL_HANDLE )
, m_pControllerAxesVertexBufferMemory( VK_NULL_HANDLE )
{
memset( &m_leftEyeDesc, 0, sizeof( m_leftEyeDesc ) );
memset( &m_rightEyeDesc, 0, sizeof( m_rightEyeDesc ) );
memset( &m_pShaderModules[ 0 ], 0, sizeof( m_pShaderModules ) );
memset( &m_pPipelines[ 0 ], 0, sizeof( m_pPipelines ) );
memset( m_pSceneConstantBufferData, 0, sizeof( m_pSceneConstantBufferData ) );
memset( m_pDescriptorSets, 0, sizeof( m_pDescriptorSets ) );
for( int i = 1; i < argc; i++ )
{
if( !stricmp( argv[i], "-vulkandebug" ) )
{
m_bDebugVulkan = true;
}
else if( !stricmp( argv[i], "-verbose" ) )
{
m_bVerbose = true;
}
else if( !stricmp( argv[i], "-novblank" ) )
{
m_bVblank = false;
}
else if ( !stricmp( argv[i], "-msaa" ) && ( argc > i + 1 ) && ( *argv[ i + 1 ] != '-' ) )
{
m_nMSAASampleCount = atoi( argv[ i + 1 ] );
i++;
}
else if ( !stricmp( argv[i], "-supersample" ) && ( argc > i + 1 ) && ( *argv[ i + 1 ] != '-' ) )
{
m_flSuperSampleScale = ( float )atof( argv[ i + 1 ] );
i++;
}
else if( !stricmp( argv[i], "-noprintf" ) )
{
g_bPrintf = false;
}
else if ( !stricmp( argv[i], "-cubevolume" ) && ( argc > i + 1 ) && ( *argv[ i + 1 ] != '-' ) )
{
m_iSceneVolumeInit = atoi( argv[ i + 1 ] );
i++;
}
}
// other initialization tasks are done in BInit
memset( m_rDevClassChar, 0, sizeof( m_rDevClassChar ) );
};
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CMainApplication::~CMainApplication()
{
// work is done in Shutdown
dprintf( "Shutdown" );
}
//-----------------------------------------------------------------------------
// Purpose: Helper to get a string from a tracked device property and turn it
// into a std::string
//-----------------------------------------------------------------------------
std::string GetTrackedDeviceString( vr::IVRSystem *pHmd, vr::TrackedDeviceIndex_t unDevice, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError *peError = NULL )
{
uint32_t unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, NULL, 0, peError );
if( unRequiredBufferLen == 0 )
return "";
char *pchBuffer = new char[ unRequiredBufferLen ];
unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, pchBuffer, unRequiredBufferLen, peError );
std::string sResult = pchBuffer;
delete [] pchBuffer;
return sResult;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInit()
{
if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
{
dprintf("%s - SDL could not initialize! SDL Error: %s\n", __FUNCTION__, SDL_GetError());
return false;
}
// Loading the SteamVR Runtime
vr::EVRInitError eError = vr::VRInitError_None;
m_pHMD = vr::VR_Init( &eError, vr::VRApplication_Scene );
if ( eError != vr::VRInitError_None )
{
m_pHMD = NULL;
char buf[1024];
sprintf_s( buf, sizeof( buf ), "Unable to init VR runtime: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
return false;
}
m_pRenderModels = (vr::IVRRenderModels *)vr::VR_GetGenericInterface( vr::IVRRenderModels_Version, &eError );
if( !m_pRenderModels )
{
m_pHMD = NULL;
vr::VR_Shutdown();
char buf[1024];
sprintf_s( buf, sizeof( buf ), "Unable to get render model interface: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
return false;
}
int nWindowPosX = 700;
int nWindowPosY = 100;
Uint32 unWindowFlags = SDL_WINDOW_SHOWN;
m_pCompanionWindow = SDL_CreateWindow( "hellovr [Vulkan]", nWindowPosX, nWindowPosY, m_nCompanionWindowWidth, m_nCompanionWindowHeight, unWindowFlags );
if (m_pCompanionWindow == NULL)
{
dprintf( "%s - Window could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
return false;
}
m_strDriver = "No Driver";
m_strDisplay = "No Display";
m_strDriver = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String );
m_strDisplay = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String );
std::string strWindowTitle = "hellovr [Vulkan] - " + m_strDriver + " " + m_strDisplay;
SDL_SetWindowTitle( m_pCompanionWindow, strWindowTitle.c_str() );
// cube array
m_iSceneVolumeWidth = m_iSceneVolumeInit;
m_iSceneVolumeHeight = m_iSceneVolumeInit;
m_iSceneVolumeDepth = m_iSceneVolumeInit;
m_fScale = 0.3f;
m_fScaleSpacing = 4.0f;
m_fNearClip = 0.1f;
m_fFarClip = 30.0f;
m_uiVertcount = 0;
m_uiCompanionWindowIndexSize = 0;
if ( !BInitVulkan() )
{
dprintf( "%s - Unable to initialize Vulkan!\n", __FUNCTION__ );
return false;
}
if ( !BInitCompositor() )
{
dprintf( "%s - Failed to initialize VR Compositor!\n", __FUNCTION__ );
return false;
}
return true;
}
//--------------------------------------------------------------------------------------
// Ask OpenVR for the list of instance extensions required
//--------------------------------------------------------------------------------------
bool CMainApplication::GetVulkanInstanceExtensionsRequired( std::vector< std::string > &outInstanceExtensionList )
{
if ( !vr::VRCompositor() )
{
return false;
}
outInstanceExtensionList.clear();
uint32_t nBufferSize = vr::VRCompositor()->GetVulkanInstanceExtensionsRequired( nullptr, 0 );
if ( nBufferSize > 0 )
{
// Allocate memory for the space separated list and query for it
char *pExtensionStr = new char[ nBufferSize ];
pExtensionStr[0] = 0;
vr::VRCompositor()->GetVulkanInstanceExtensionsRequired( pExtensionStr, nBufferSize );
// Break up the space separated list into entries on the CUtlStringList
std::string curExtStr;
uint32_t nIndex = 0;
while ( pExtensionStr[ nIndex ] != 0 && ( nIndex < nBufferSize ) )
{
if ( pExtensionStr[ nIndex ] == ' ' )
{
outInstanceExtensionList.push_back( curExtStr );
curExtStr.clear();
}
else
{
curExtStr += pExtensionStr[ nIndex ];
}
nIndex++;
}
if ( curExtStr.size() > 0 )
{
outInstanceExtensionList.push_back( curExtStr );
}
delete [] pExtensionStr;
}
return true;
}
//--------------------------------------------------------------------------------------
// Ask OpenVR for the list of device extensions required
//--------------------------------------------------------------------------------------
bool CMainApplication::GetVulkanDeviceExtensionsRequired( VkPhysicalDevice pPhysicalDevice, std::vector< std::string > &outDeviceExtensionList )
{
if ( !vr::VRCompositor() )
{
return false;
}
outDeviceExtensionList.clear();
uint32_t nBufferSize = vr::VRCompositor()->GetVulkanDeviceExtensionsRequired( ( VkPhysicalDevice_T * ) pPhysicalDevice, nullptr, 0 );
if ( nBufferSize > 0 )
{
// Allocate memory for the space separated list and query for it
char *pExtensionStr = new char[ nBufferSize ];
pExtensionStr[0] = 0;
vr::VRCompositor()->GetVulkanDeviceExtensionsRequired( ( VkPhysicalDevice_T * ) pPhysicalDevice, pExtensionStr, nBufferSize );
// Break up the space separated list into entries on the CUtlStringList
std::string curExtStr;
uint32_t nIndex = 0;
while ( pExtensionStr[ nIndex ] != 0 && ( nIndex < nBufferSize ) )
{
if ( pExtensionStr[ nIndex ] == ' ' )
{
outDeviceExtensionList.push_back( curExtStr );
curExtStr.clear();
}
else
{
curExtStr += pExtensionStr[ nIndex ];
}
nIndex++;
}
if ( curExtStr.size() > 0 )
{
outDeviceExtensionList.push_back( curExtStr );
}
delete [] pExtensionStr;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Initialize Vulkan VkInstance
//-----------------------------------------------------------------------------
bool CMainApplication::BInitVulkanInstance()
{
VkResult nResult;
//----------------------//
// VkInstance creation //
//----------------------//
// Query OpenVR to determine which instance extensions need to be enabled before creating the instance
std::vector< std::string > requiredInstanceExtensions;
if ( !GetVulkanInstanceExtensionsRequired( requiredInstanceExtensions ) )
{
dprintf( "Could not determine OpenVR Vulkan instance extensions.\n" );
return false;
}
// Additional required instance extensions
requiredInstanceExtensions.push_back( VK_KHR_SURFACE_EXTENSION_NAME );
#if defined ( _WIN32 )
requiredInstanceExtensions.push_back( VK_KHR_WIN32_SURFACE_EXTENSION_NAME );
#else
requiredInstanceExtensions.push_back( VK_KHR_XLIB_SURFACE_EXTENSION_NAME );
#endif
uint32_t nEnabledLayerCount = 0;
VkLayerProperties *pLayerProperties = nullptr;
char **ppEnabledLayerNames = nullptr;
// Enable validation layers
if ( m_bDebugVulkan )
{
// OpenVR: no unique_objects when using validation with SteamVR
char const *pInstanceValidationLayers[] =
{
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_swapchain"
};
uint32_t nInstanceLayerCount = 0;
VkResult nResult = vkEnumerateInstanceLayerProperties( &nInstanceLayerCount, nullptr );
if ( nResult == VK_SUCCESS && nInstanceLayerCount > 0 )
{
pLayerProperties = new VkLayerProperties[ nInstanceLayerCount ];
ppEnabledLayerNames = new char*[ nInstanceLayerCount ];
nResult = vkEnumerateInstanceLayerProperties( &nInstanceLayerCount, pLayerProperties );
if ( nResult != VK_SUCCESS )
{
dprintf( "Error vkEnumerateInstanceLayerProperties in %d\n", nResult );
return false;
}
uint32_t nLayerIndex = 0;
for ( nLayerIndex = 0; nLayerIndex < nInstanceLayerCount; nLayerIndex++ )
{
for ( uint32_t nLayer = 0; nLayer < _countof( pInstanceValidationLayers ); nLayer++ )
{
if ( strstr( pLayerProperties[ nLayerIndex ].layerName, pInstanceValidationLayers[ nLayer ] ) != NULL )
{
ppEnabledLayerNames[ nEnabledLayerCount++ ] = pLayerProperties[ nLayerIndex ].layerName;
}
}
}
requiredInstanceExtensions.push_back( VK_EXT_DEBUG_REPORT_EXTENSION_NAME );
}
}
uint32_t nInstanceExtensionCount = 0;
nResult = vkEnumerateInstanceExtensionProperties( NULL, &nInstanceExtensionCount, NULL );
if ( nResult != VK_SUCCESS )
{
dprintf( "vkEnumerateInstanceExtensionProperties failed with error %d\n", nResult );
return false;
}
// Allocate enough ExtensionProperties to support all extensions being enabled
char** ppEnableInstanceExtensionNames = new char*[ requiredInstanceExtensions.size() ];
int32_t nEnableInstanceExtensionNamesCount = 0;
VkExtensionProperties *pExtensionProperties = new VkExtensionProperties[ nInstanceExtensionCount ];
if ( nInstanceExtensionCount > 0 )
{
nResult = vkEnumerateInstanceExtensionProperties( NULL, &nInstanceExtensionCount, pExtensionProperties );
if ( nResult != VK_SUCCESS )
{
dprintf( "vkEnumerateInstanceExtensionProperties failed with error %d\n", nResult );
return false;
}
for ( size_t nExt = 0; nExt < requiredInstanceExtensions.size(); nExt++ )
{
bool bFound = false;
uint32_t nExtIndex = 0;
for ( nExtIndex = 0; nExtIndex < nInstanceExtensionCount; nExtIndex++ )
{
if ( strcmp( requiredInstanceExtensions[ nExt ].c_str(), pExtensionProperties[ nExtIndex ].extensionName ) == 0 )
{
bFound = true;
ppEnableInstanceExtensionNames[ nEnableInstanceExtensionNamesCount++ ] = pExtensionProperties[ nExtIndex ].extensionName;
break;
}
}
if ( !bFound )
{
dprintf( "Vulkan missing requested extension '%s'.\n", requiredInstanceExtensions[ nExt ] );
}
}
if ( nEnableInstanceExtensionNamesCount != requiredInstanceExtensions.size() )
{
return false;
}
}
VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
appInfo.pApplicationName = "hellovr_vulkan";
appInfo.applicationVersion = 1;
appInfo.pEngineName = nullptr;
appInfo.engineVersion = 1;
appInfo.apiVersion = VK_MAKE_VERSION( 1, 0, 0 );
// Create the instance
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pNext = NULL;
instanceCreateInfo.pApplicationInfo = &appInfo;
instanceCreateInfo.enabledExtensionCount = nEnableInstanceExtensionNamesCount;
instanceCreateInfo.ppEnabledExtensionNames = ppEnableInstanceExtensionNames;
instanceCreateInfo.enabledLayerCount = nEnabledLayerCount;
instanceCreateInfo.ppEnabledLayerNames = ppEnabledLayerNames;
nResult = vkCreateInstance( &instanceCreateInfo, nullptr, &m_pInstance );
if ( nResult != VK_SUCCESS )
{
dprintf( "vkCreateInstance failed with error %d\n", nResult );
return false;
}
// Enable debug report extension
if ( m_bDebugVulkan )
{
g_pVkCreateDebugReportCallbackEXT = ( PFN_vkCreateDebugReportCallbackEXT ) vkGetInstanceProcAddr( m_pInstance, "vkCreateDebugReportCallbackEXT" );
g_pVkDestroyDebugReportCallbackEXT = ( PFN_vkDestroyDebugReportCallbackEXT ) vkGetInstanceProcAddr( m_pInstance, "vkDestroyDebugReportCallbackEXT" );
VkDebugReportCallbackCreateInfoEXT debugReportCreateInfo = {};
debugReportCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
debugReportCreateInfo.pNext = NULL;
debugReportCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT;
debugReportCreateInfo.pfnCallback = VKDebugMessageCallback;
debugReportCreateInfo.pUserData = NULL;
g_pVkCreateDebugReportCallbackEXT( m_pInstance, &debugReportCreateInfo, NULL, &m_pDebugReportCallback );
}
delete [] ppEnableInstanceExtensionNames;
delete [] ppEnabledLayerNames;
delete [] pLayerProperties;
delete [] pExtensionProperties;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Initialize Vulkan VkDevice
//-----------------------------------------------------------------------------
bool CMainApplication::BInitVulkanDevice()
{
uint32_t nDeviceCount = 0;
VkResult nResult = vkEnumeratePhysicalDevices( m_pInstance, &nDeviceCount, NULL );
if ( nResult != VK_SUCCESS || nDeviceCount == 0 )
{
dprintf( "vkEnumeratePhysicalDevices failed, unable to init and enumerate GPUs with Vulkan.\n" );
return false;
}
VkPhysicalDevice *pPhysicalDevices = new VkPhysicalDevice[ nDeviceCount ];
nResult = vkEnumeratePhysicalDevices( m_pInstance, &nDeviceCount, pPhysicalDevices );
if ( nResult != VK_SUCCESS || nDeviceCount == 0 )
{
dprintf( "vkEnumeratePhysicalDevices failed, unable to init and enumerate GPUs with Vulkan.\n" );
return false;
}
// Query OpenVR for the physical device to use
uint64_t pHMDPhysicalDevice = 0;
m_pHMD->GetOutputDevice( &pHMDPhysicalDevice, vr::TextureType_Vulkan, ( VkInstance_T * ) m_pInstance );
// Select the HMD physical device
m_pPhysicalDevice = VK_NULL_HANDLE;
for ( uint32_t nPhysicalDevice = 0; nPhysicalDevice < nDeviceCount; nPhysicalDevice++ )
{
if ( ( ( VkPhysicalDevice ) pHMDPhysicalDevice ) == pPhysicalDevices[ nPhysicalDevice ] )
{
m_pPhysicalDevice = ( VkPhysicalDevice ) pHMDPhysicalDevice;
break;
}
}
if ( m_pPhysicalDevice == VK_NULL_HANDLE )
{
// Fallback: Grab the first physical device
dprintf( "Failed to find GetOutputDevice VkPhysicalDevice, falling back to choosing first device.\n" );
m_pPhysicalDevice = pPhysicalDevices[ 0 ];
}
delete [] pPhysicalDevices;
vkGetPhysicalDeviceProperties( m_pPhysicalDevice, &m_physicalDeviceProperties );
vkGetPhysicalDeviceMemoryProperties( m_pPhysicalDevice, &m_physicalDeviceMemoryProperties );
vkGetPhysicalDeviceFeatures( m_pPhysicalDevice, &m_physicalDeviceFeatures );
//--------------------//
// VkDevice creation //
//--------------------//
// Query OpenVR for the required device extensions for this physical device
std::vector< std::string > requiredDeviceExtensions;
GetVulkanDeviceExtensionsRequired( m_pPhysicalDevice, requiredDeviceExtensions );
// Add additional required extensions
requiredDeviceExtensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
// Find the first graphics queue
uint32_t nQueueCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties( m_pPhysicalDevice, &nQueueCount, 0 );
VkQueueFamilyProperties *pQueueFamilyProperties = new VkQueueFamilyProperties[ nQueueCount ];
vkGetPhysicalDeviceQueueFamilyProperties( m_pPhysicalDevice, &nQueueCount, pQueueFamilyProperties );
if ( nQueueCount == 0 )
{
dprintf( "Failed to get queue properties.\n" );
return false;
}
uint32_t nGraphicsQueueIndex = 0;
for ( nGraphicsQueueIndex = 0; nGraphicsQueueIndex < nQueueCount; nGraphicsQueueIndex++ )
{
if ( pQueueFamilyProperties[ nGraphicsQueueIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT )
{
break;
}