forked from ILLIXR/Monado_OpenXR_Simple_Example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
1914 lines (1594 loc) · 80 KB
/
main.c
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 2019-2021, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief A simple, commented, (almost) single file OpenXR example
* @author Christoph Haag <christoph.haag@collabora.com>
*/
#include <stdio.h>
#include <stdbool.h>
// Required headers for OpenGL rendering, as well as for including openxr_platform
#include <GL/gl.h>
#include <GL/glext.h>
// Required headers for windowing, as well as the XrGraphicsBindingOpenGLXlibKHR struct.
#include <X11/Xlib.h>
#include <GL/glx.h>
#define XR_USE_PLATFORM_XLIB
#define XR_USE_GRAPHICS_API_OPENGL
#include "openxr_includes/openxr.h"
#include "openxr_includes/openxr_platform.h"
#include "oxr/oxr_api_funcs.h"
#include "SDL.h"
#include "SDL_events.h"
#define GL_DECL(TYPE, FUNC) static TYPE FUNC = NULL;
#define LOAD_GL_FUNC(TYPE, FUNC) FUNC = (TYPE)SDL_GL_GetProcAddress(#FUNC);
#define FOR_EACH_GL_FUNC(_) \
_(PFNGLDELETEFRAMEBUFFERSPROC, glDeleteFramebuffers) \
_(PFNGLDEBUGMESSAGECALLBACKPROC, glDebugMessageCallback) \
_(PFNGLGENFRAMEBUFFERSPROC, glGenFramebuffers) \
_(PFNGLCREATESHADERPROC, glCreateShader) \
_(PFNGLSHADERSOURCEPROC, glShaderSource) \
_(PFNGLCOMPILESHADERPROC, glCompileShader) \
_(PFNGLGETSHADERIVPROC, glGetShaderiv) \
_(PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog) \
_(PFNGLCREATEPROGRAMPROC, glCreateProgram) \
_(PFNGLATTACHSHADERPROC, glAttachShader) \
_(PFNGLLINKPROGRAMPROC, glLinkProgram) \
_(PFNGLGETPROGRAMIVPROC, glGetProgramiv) \
_(PFNGLGETPROGRAMINFOLOGPROC, glGetProgramInfoLog) \
_(PFNGLDELETESHADERPROC, glDeleteShader) \
_(PFNGLGENBUFFERSPROC, glGenBuffers) \
_(PFNGLGENVERTEXARRAYSPROC, glGenVertexArrays) \
_(PFNGLBINDVERTEXARRAYPROC, glBindVertexArray) \
_(PFNGLBINDBUFFERPROC, glBindBuffer) \
_(PFNGLBUFFERDATAPROC, glBufferData) \
_(PFNGLVERTEXATTRIBPOINTERPROC, glVertexAttribPointer) \
_(PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray) \
_(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation) \
_(PFNGLBINDFRAMEBUFFERPROC, glBindFramebuffer) \
_(PFNGLFRAMEBUFFERTEXTURE2DPROC, glFramebufferTexture2D) \
_(PFNGLUSEPROGRAMPROC, glUseProgram) \
_(PFNGLUNIFORMMATRIX4FVPROC, glUniformMatrix4fv) \
_(PFNGLBLITNAMEDFRAMEBUFFERPROC, glBlitNamedFramebuffer) \
_(PFNGLUNIFORM3FPROC, glUniform3f) \
_(PFNGLUNIFORM4FPROC, glUniform4f)
// generates a global declaration for each gl func listed in FOR_EACH_GL_FUNC
FOR_EACH_GL_FUNC(GL_DECL)
static void
init_gl_funcs(void)
{
// initializes each global declaration using SDL_GL_GetProcAddress
FOR_EACH_GL_FUNC(LOAD_GL_FUNC)
}
#define degrees_to_radians(angle_degrees) ((angle_degrees) * M_PI / 180.0)
//#define radians_to_degrees(angle_radians) ((angle_radians) * 180.0 / M_PI)
// we need an identity pose for creating spaces without offsets
static XrPosef identity_pose = {.orientation = {.x = 0, .y = 0, .z = 0, .w = 1.0},
.position = {.x = 0, .y = 0, .z = 0}};
#define HAND_LEFT_INDEX 0
#define HAND_RIGHT_INDEX 1
#define HAND_COUNT 2
// =============================================================================
// math code adapted from
// https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/master/src/common/xr_linear.h
// Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2016 Oculus VR, LLC.
// SPDX-License-Identifier: Apache-2.0
// =============================================================================
typedef enum
{
GRAPHICS_VULKAN,
GRAPHICS_OPENGL,
GRAPHICS_OPENGL_ES
} GraphicsAPI;
typedef struct XrMatrix4x4f
{
float m[16];
} XrMatrix4x4f;
inline static void
XrMatrix4x4f_CreateProjectionFov(XrMatrix4x4f* result,
GraphicsAPI graphicsApi,
const XrFovf fov,
const float nearZ,
const float farZ)
{
const float tanAngleLeft = tanf(fov.angleLeft);
const float tanAngleRight = tanf(fov.angleRight);
const float tanAngleDown = tanf(fov.angleDown);
const float tanAngleUp = tanf(fov.angleUp);
const float tanAngleWidth = tanAngleRight - tanAngleLeft;
// Set to tanAngleDown - tanAngleUp for a clip space with positive Y
// down (Vulkan). Set to tanAngleUp - tanAngleDown for a clip space with
// positive Y up (OpenGL / D3D / Metal).
const float tanAngleHeight =
graphicsApi == GRAPHICS_VULKAN ? (tanAngleDown - tanAngleUp) : (tanAngleUp - tanAngleDown);
// Set to nearZ for a [-1,1] Z clip space (OpenGL / OpenGL ES).
// Set to zero for a [0,1] Z clip space (Vulkan / D3D / Metal).
const float offsetZ =
(graphicsApi == GRAPHICS_OPENGL || graphicsApi == GRAPHICS_OPENGL_ES) ? nearZ : 0;
if (farZ <= nearZ) {
// place the far plane at infinity
result->m[0] = 2 / tanAngleWidth;
result->m[4] = 0;
result->m[8] = (tanAngleRight + tanAngleLeft) / tanAngleWidth;
result->m[12] = 0;
result->m[1] = 0;
result->m[5] = 2 / tanAngleHeight;
result->m[9] = (tanAngleUp + tanAngleDown) / tanAngleHeight;
result->m[13] = 0;
result->m[2] = 0;
result->m[6] = 0;
result->m[10] = -1;
result->m[14] = -(nearZ + offsetZ);
result->m[3] = 0;
result->m[7] = 0;
result->m[11] = -1;
result->m[15] = 0;
} else {
// normal projection
result->m[0] = 2 / tanAngleWidth;
result->m[4] = 0;
result->m[8] = (tanAngleRight + tanAngleLeft) / tanAngleWidth;
result->m[12] = 0;
result->m[1] = 0;
result->m[5] = 2 / tanAngleHeight;
result->m[9] = (tanAngleUp + tanAngleDown) / tanAngleHeight;
result->m[13] = 0;
result->m[2] = 0;
result->m[6] = 0;
result->m[10] = -(farZ + offsetZ) / (farZ - nearZ);
result->m[14] = -(farZ * (nearZ + offsetZ)) / (farZ - nearZ);
result->m[3] = 0;
result->m[7] = 0;
result->m[11] = -1;
result->m[15] = 0;
}
}
inline static void
XrMatrix4x4f_CreateFromQuaternion(XrMatrix4x4f* result, const XrQuaternionf* quat)
{
const float x2 = quat->x + quat->x;
const float y2 = quat->y + quat->y;
const float z2 = quat->z + quat->z;
const float xx2 = quat->x * x2;
const float yy2 = quat->y * y2;
const float zz2 = quat->z * z2;
const float yz2 = quat->y * z2;
const float wx2 = quat->w * x2;
const float xy2 = quat->x * y2;
const float wz2 = quat->w * z2;
const float xz2 = quat->x * z2;
const float wy2 = quat->w * y2;
result->m[0] = 1.0f - yy2 - zz2;
result->m[1] = xy2 + wz2;
result->m[2] = xz2 - wy2;
result->m[3] = 0.0f;
result->m[4] = xy2 - wz2;
result->m[5] = 1.0f - xx2 - zz2;
result->m[6] = yz2 + wx2;
result->m[7] = 0.0f;
result->m[8] = xz2 + wy2;
result->m[9] = yz2 - wx2;
result->m[10] = 1.0f - xx2 - yy2;
result->m[11] = 0.0f;
result->m[12] = 0.0f;
result->m[13] = 0.0f;
result->m[14] = 0.0f;
result->m[15] = 1.0f;
}
inline static void
XrMatrix4x4f_CreateTranslation(XrMatrix4x4f* result, const float x, const float y, const float z)
{
result->m[0] = 1.0f;
result->m[1] = 0.0f;
result->m[2] = 0.0f;
result->m[3] = 0.0f;
result->m[4] = 0.0f;
result->m[5] = 1.0f;
result->m[6] = 0.0f;
result->m[7] = 0.0f;
result->m[8] = 0.0f;
result->m[9] = 0.0f;
result->m[10] = 1.0f;
result->m[11] = 0.0f;
result->m[12] = x;
result->m[13] = y;
result->m[14] = z;
result->m[15] = 1.0f;
}
inline static void
XrMatrix4x4f_Multiply(XrMatrix4x4f* result, const XrMatrix4x4f* a, const XrMatrix4x4f* b)
{
result->m[0] = a->m[0] * b->m[0] + a->m[4] * b->m[1] + a->m[8] * b->m[2] + a->m[12] * b->m[3];
result->m[1] = a->m[1] * b->m[0] + a->m[5] * b->m[1] + a->m[9] * b->m[2] + a->m[13] * b->m[3];
result->m[2] = a->m[2] * b->m[0] + a->m[6] * b->m[1] + a->m[10] * b->m[2] + a->m[14] * b->m[3];
result->m[3] = a->m[3] * b->m[0] + a->m[7] * b->m[1] + a->m[11] * b->m[2] + a->m[15] * b->m[3];
result->m[4] = a->m[0] * b->m[4] + a->m[4] * b->m[5] + a->m[8] * b->m[6] + a->m[12] * b->m[7];
result->m[5] = a->m[1] * b->m[4] + a->m[5] * b->m[5] + a->m[9] * b->m[6] + a->m[13] * b->m[7];
result->m[6] = a->m[2] * b->m[4] + a->m[6] * b->m[5] + a->m[10] * b->m[6] + a->m[14] * b->m[7];
result->m[7] = a->m[3] * b->m[4] + a->m[7] * b->m[5] + a->m[11] * b->m[6] + a->m[15] * b->m[7];
result->m[8] = a->m[0] * b->m[8] + a->m[4] * b->m[9] + a->m[8] * b->m[10] + a->m[12] * b->m[11];
result->m[9] = a->m[1] * b->m[8] + a->m[5] * b->m[9] + a->m[9] * b->m[10] + a->m[13] * b->m[11];
result->m[10] = a->m[2] * b->m[8] + a->m[6] * b->m[9] + a->m[10] * b->m[10] + a->m[14] * b->m[11];
result->m[11] = a->m[3] * b->m[8] + a->m[7] * b->m[9] + a->m[11] * b->m[10] + a->m[15] * b->m[11];
result->m[12] =
a->m[0] * b->m[12] + a->m[4] * b->m[13] + a->m[8] * b->m[14] + a->m[12] * b->m[15];
result->m[13] =
a->m[1] * b->m[12] + a->m[5] * b->m[13] + a->m[9] * b->m[14] + a->m[13] * b->m[15];
result->m[14] =
a->m[2] * b->m[12] + a->m[6] * b->m[13] + a->m[10] * b->m[14] + a->m[14] * b->m[15];
result->m[15] =
a->m[3] * b->m[12] + a->m[7] * b->m[13] + a->m[11] * b->m[14] + a->m[15] * b->m[15];
}
inline static void
XrMatrix4x4f_Invert(XrMatrix4x4f* result, const XrMatrix4x4f* src)
{
result->m[0] = src->m[0];
result->m[1] = src->m[4];
result->m[2] = src->m[8];
result->m[3] = 0.0f;
result->m[4] = src->m[1];
result->m[5] = src->m[5];
result->m[6] = src->m[9];
result->m[7] = 0.0f;
result->m[8] = src->m[2];
result->m[9] = src->m[6];
result->m[10] = src->m[10];
result->m[11] = 0.0f;
result->m[12] = -(src->m[0] * src->m[12] + src->m[1] * src->m[13] + src->m[2] * src->m[14]);
result->m[13] = -(src->m[4] * src->m[12] + src->m[5] * src->m[13] + src->m[6] * src->m[14]);
result->m[14] = -(src->m[8] * src->m[12] + src->m[9] * src->m[13] + src->m[10] * src->m[14]);
result->m[15] = 1.0f;
}
inline static void
XrMatrix4x4f_CreateViewMatrix(XrMatrix4x4f* result,
const XrVector3f* translation,
const XrQuaternionf* rotation)
{
XrMatrix4x4f rotationMatrix;
XrMatrix4x4f_CreateFromQuaternion(&rotationMatrix, rotation);
XrMatrix4x4f translationMatrix;
XrMatrix4x4f_CreateTranslation(&translationMatrix, translation->x, translation->y,
translation->z);
XrMatrix4x4f viewMatrix;
XrMatrix4x4f_Multiply(&viewMatrix, &translationMatrix, &rotationMatrix);
XrMatrix4x4f_Invert(result, &viewMatrix);
}
inline static void
XrMatrix4x4f_CreateScale(XrMatrix4x4f* result, const float x, const float y, const float z)
{
result->m[0] = x;
result->m[1] = 0.0f;
result->m[2] = 0.0f;
result->m[3] = 0.0f;
result->m[4] = 0.0f;
result->m[5] = y;
result->m[6] = 0.0f;
result->m[7] = 0.0f;
result->m[8] = 0.0f;
result->m[9] = 0.0f;
result->m[10] = z;
result->m[11] = 0.0f;
result->m[12] = 0.0f;
result->m[13] = 0.0f;
result->m[14] = 0.0f;
result->m[15] = 1.0f;
}
inline static void
XrMatrix4x4f_CreateModelMatrix(XrMatrix4x4f* result,
const XrVector3f* translation,
const XrQuaternionf* rotation,
const XrVector3f* scale)
{
XrMatrix4x4f scaleMatrix;
XrMatrix4x4f_CreateScale(&scaleMatrix, scale->x, scale->y, scale->z);
XrMatrix4x4f rotationMatrix;
XrMatrix4x4f_CreateFromQuaternion(&rotationMatrix, rotation);
XrMatrix4x4f translationMatrix;
XrMatrix4x4f_CreateTranslation(&translationMatrix, translation->x, translation->y,
translation->z);
XrMatrix4x4f combinedMatrix;
XrMatrix4x4f_Multiply(&combinedMatrix, &rotationMatrix, &scaleMatrix);
XrMatrix4x4f_Multiply(result, &translationMatrix, &combinedMatrix);
}
// =============================================================================
// =============================================================================
// OpenGL rendering code at the end of the file
// =============================================================================
#ifdef _WIN32
bool
init_sdl_window(HDC* xDisplay, HGLRC* glxContext, int w, int h);
#else
bool
init_sdl_window(Display** xDisplay,
uint32_t* visualid,
GLXFBConfig* glxFBConfig,
GLXDrawable* glxDrawable,
GLXContext* glxContext,
int w,
int h);
#endif
int
init_gl(uint32_t view_count,
uint32_t* swapchain_lengths,
GLuint*** framebuffers,
GLuint* shader_program_id,
GLuint* VAO);
void
render_frame(int w,
int h,
GLuint shader_program_id,
GLuint VAO,
XrTime predictedDisplayTime,
int view_index,
XrSpaceLocation* hand_locations,
XrMatrix4x4f projectionmatrix,
XrMatrix4x4f viewmatrix,
GLuint framebuffer,
GLuint image,
bool depth_supported,
GLuint depthbuffer);
// =============================================================================
// true if XrResult is a success code, else print error message and return false
bool
xr_check(XrInstance instance, XrResult result, const char* format, ...)
{
if (XR_SUCCEEDED(result))
return true;
char resultString[XR_MAX_RESULT_STRING_SIZE];
oxr_xrResultToString(instance, result, resultString);
char formatRes[XR_MAX_RESULT_STRING_SIZE + 1024];
snprintf(formatRes, XR_MAX_RESULT_STRING_SIZE + 1023, "%s [%s] (%d)\n", format, resultString,
result);
va_list args;
va_start(args, format);
vprintf(formatRes, args);
va_end(args);
return false;
}
static void
print_instance_properties(XrInstance instance)
{
XrResult result;
XrInstanceProperties instance_props = {
.type = XR_TYPE_INSTANCE_PROPERTIES,
.next = NULL,
};
result = oxr_xrGetInstanceProperties(instance, &instance_props);
if (!xr_check(NULL, result, "Failed to get instance info"))
return;
printf("Runtime Name: %s\n", instance_props.runtimeName);
printf("Runtime Version: %d.%d.%d\n", XR_VERSION_MAJOR(instance_props.runtimeVersion),
XR_VERSION_MINOR(instance_props.runtimeVersion),
XR_VERSION_PATCH(instance_props.runtimeVersion));
}
static void
print_system_properties(XrSystemProperties* system_properties)
{
printf("System properties for system %lu: \"%s\", vendor ID %d\n", system_properties->systemId,
system_properties->systemName, system_properties->vendorId);
printf("\tMax layers : %d\n", system_properties->graphicsProperties.maxLayerCount);
printf("\tMax swapchain height: %d\n",
system_properties->graphicsProperties.maxSwapchainImageHeight);
printf("\tMax swapchain width : %d\n",
system_properties->graphicsProperties.maxSwapchainImageWidth);
printf("\tOrientation Tracking: %d\n", system_properties->trackingProperties.orientationTracking);
printf("\tPosition Tracking : %d\n", system_properties->trackingProperties.positionTracking);
}
static void
print_viewconfig_view_info(uint32_t view_count, XrViewConfigurationView* viewconfig_views)
{
for (uint32_t i = 0; i < view_count; i++) {
printf("View Configuration View %d:\n", i);
printf("\tResolution : Recommended %dx%d, Max: %dx%d\n",
viewconfig_views[0].recommendedImageRectWidth,
viewconfig_views[0].recommendedImageRectHeight, viewconfig_views[0].maxImageRectWidth,
viewconfig_views[0].maxImageRectHeight);
printf("\tSwapchain Samples: Recommended: %d, Max: %d)\n",
viewconfig_views[0].recommendedSwapchainSampleCount,
viewconfig_views[0].maxSwapchainSampleCount);
}
}
// returns the preferred swapchain format if it is supported
// else:
// - if fallback is true, return the first supported format
// - if fallback is false, return -1
static int64_t
get_swapchain_format(XrInstance instance,
XrSession session,
int64_t preferred_format,
bool fallback)
{
XrResult result;
uint32_t swapchain_format_count;
result = oxr_xrEnumerateSwapchainFormats(session, 0, &swapchain_format_count, NULL);
if (!xr_check(instance, result, "Failed to get number of supported swapchain formats"))
return -1;
printf("Runtime supports %d swapchain formats\n", swapchain_format_count);
int64_t* swapchain_formats = malloc(sizeof(int64_t) * swapchain_format_count);
result = oxr_xrEnumerateSwapchainFormats(session, swapchain_format_count, &swapchain_format_count,
swapchain_formats);
if (!xr_check(instance, result, "Failed to enumerate swapchain formats"))
return -1;
int64_t chosen_format = fallback ? swapchain_formats[0] : -1;
for (uint32_t i = 0; i < swapchain_format_count; i++) {
printf("Supported GL format: %#lx\n", swapchain_formats[i]);
if (swapchain_formats[i] == preferred_format) {
chosen_format = swapchain_formats[i];
printf("Using preferred swapchain format %#lx\n", chosen_format);
break;
}
}
if (fallback && chosen_format != preferred_format) {
printf("Falling back to non preferred swapchain format %#lx\n", chosen_format);
}
free(swapchain_formats);
return chosen_format;
}
int
main(int argc, char** argv)
{
// Changing to HANDHELD_DISPLAY or a future form factor may work, but has not been tested.
XrFormFactor form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
// Changing the form_factor may require changing the view_type too.
XrViewConfigurationType view_type = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
// Typically STAGE for room scale/standing, LOCAL for seated
XrReferenceSpaceType play_space_type = XR_REFERENCE_SPACE_TYPE_LOCAL;
XrSpace play_space = XR_NULL_HANDLE;
// the instance handle can be thought of as the basic connection to the OpenXR runtime
XrInstance instance = XR_NULL_HANDLE;
// the system represents an (opaque) set of XR devices in use, managed by the runtime
XrSystemId system_id = XR_NULL_SYSTEM_ID;
// the session deals with the renderloop submitting frames to the runtime
XrSession session = XR_NULL_HANDLE;
// each graphics API requires the use of a specialized struct
#ifdef _WIN32
XrGraphicsBindingOpenGLWin32KHR graphics_binding_gl = {0};
#else
// The runtime interacts with the OpenGL images (textures) via a Swapchain.
XrGraphicsBindingOpenGLXlibKHR graphics_binding_gl = {0};
#endif
// each physical Display/Eye is described by a view.
// view_count usually depends on the form_factor / view_type.
// dynamically allocating all view related structs instead of assuming 2
// hopefully allows this app to scale easily to different view_counts.
uint32_t view_count = 0;
// the viewconfiguration views contain information like resolution about each view
XrViewConfigurationView* viewconfig_views = NULL;
// array of view_count containers for submitting swapchains with rendered VR frames
XrCompositionLayerProjectionView* projection_views = NULL;
// array of view_count views, filled by the runtime with current HMD display pose
XrView* views = NULL;
// array of view_count handles for swapchains.
// it is possible to use imageRect to render all views to different areas of the
// same texture, but in this example we use one swapchain per view
XrSwapchain* swapchains = NULL;
// array of view_count ints, storing the length of swapchains
uint32_t* swapchain_lengths = NULL;
// array of view_count array of swapchain_length containers holding an OpenGL texture
// that is allocated by the runtime
XrSwapchainImageOpenGLKHR** images = NULL;
// depth swapchain equivalent to the VR color swapchains
XrSwapchain* depth_swapchains = NULL;
uint32_t* depth_swapchain_lengths = NULL;
XrSwapchainImageOpenGLKHR** depth_images = NULL;
XrPath hand_paths[HAND_COUNT];
struct
{
// supporting depth layers is *optional* for runtimes
bool supported;
XrCompositionLayerDepthInfoKHR* infos;
} depth;
struct
{
// To render into a texture we need a framebuffer (one per texture to make it easy)
GLuint** framebuffers;
float near_z;
float far_z;
GLuint shader_program_id;
GLuint VAO;
} gl_rendering;
gl_rendering.near_z = 0.01f;
gl_rendering.far_z = 100.0f;
// reuse this variable for all our OpenXR return codes
XrResult result = XR_SUCCESS;
// xrEnumerate*() functions are usually called once with CapacityInput = 0.
// The function will write the required amount into CountOutput. We then have
// to allocate an array to hold CountOutput elements and call the function
// with CountOutput as CapacityInput.
uint32_t ext_count = 0;
result = oxr_xrEnumerateInstanceExtensionProperties(NULL, 0, &ext_count, NULL);
/* TODO: instance null will not be able to convert XrResult to string */
if (!xr_check(NULL, result, "Failed to enumerate number of extension properties"))
return 1;
XrExtensionProperties* ext_props = malloc(sizeof(XrExtensionProperties) * ext_count);
for (uint16_t i = 0; i < ext_count; i++) {
// we usually have to fill in the type (for validation) and set
// next to NULL (or a pointer to an extension specific struct)
ext_props[i].type = XR_TYPE_EXTENSION_PROPERTIES;
ext_props[i].next = NULL;
}
result = oxr_xrEnumerateInstanceExtensionProperties(NULL, ext_count, &ext_count, ext_props);
if (!xr_check(NULL, result, "Failed to enumerate extension properties"))
return 1;
bool opengl_supported = false;
printf("Runtime supports %d extensions\n", ext_count);
for (uint32_t i = 0; i < ext_count; i++) {
printf("\t%s v%d\n", ext_props[i].extensionName, ext_props[i].extensionVersion);
if (strcmp(XR_KHR_OPENGL_ENABLE_EXTENSION_NAME, ext_props[i].extensionName) == 0) {
opengl_supported = true;
}
if (strcmp(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME, ext_props[i].extensionName) == 0) {
depth.supported = true;
}
}
free(ext_props);
// A graphics extension like OpenGL is required to draw anything in VR
if (!opengl_supported) {
printf("Runtime does not support OpenGL extension!\n");
return 1;
}
// --- Create XrInstance
int enabled_ext_count = 1;
const char* enabled_exts[1] = {XR_KHR_OPENGL_ENABLE_EXTENSION_NAME};
// same can be done for API layers, but API layers can also be enabled by env var
XrInstanceCreateInfo instance_create_info = {
.type = XR_TYPE_INSTANCE_CREATE_INFO,
.next = NULL,
.createFlags = 0,
.enabledExtensionCount = enabled_ext_count,
.enabledExtensionNames = enabled_exts,
.enabledApiLayerCount = 0,
.enabledApiLayerNames = NULL,
.applicationInfo =
{
// some compilers have trouble with char* initialization
.applicationName = "",
.engineName = "",
.applicationVersion = 1,
.engineVersion = 0,
.apiVersion = XR_CURRENT_API_VERSION,
},
};
strncpy(instance_create_info.applicationInfo.applicationName, "OpenXR OpenGL Example",
XR_MAX_APPLICATION_NAME_SIZE);
strncpy(instance_create_info.applicationInfo.engineName, "Custom", XR_MAX_ENGINE_NAME_SIZE);
result = oxr_xrCreateInstance(&instance_create_info, &instance);
if (!xr_check(NULL, result, "Failed to create XR instance."))
return 1;
// Optionally get runtime name and version
print_instance_properties(instance);
// --- Get XrSystemId
XrSystemGetInfo system_get_info = {
.type = XR_TYPE_SYSTEM_GET_INFO, .formFactor = form_factor, .next = NULL};
result = oxr_xrGetSystem(instance, &system_get_info, &system_id);
if (!xr_check(instance, result, "Failed to get system for HMD form factor."))
return 1;
printf("Successfully got XrSystem with id %lu for HMD form factor\n", system_id);
{
XrSystemProperties system_props = {
.type = XR_TYPE_SYSTEM_PROPERTIES,
.next = NULL,
};
result = oxr_xrGetSystemProperties(instance, system_id, &system_props);
if (!xr_check(instance, result, "Failed to get System properties"))
return 1;
print_system_properties(&system_props);
}
result = oxr_xrEnumerateViewConfigurationViews(instance, system_id, view_type, 0, &view_count, NULL);
if (!xr_check(instance, result, "Failed to get view configuration view count!"))
return 1;
viewconfig_views = malloc(sizeof(XrViewConfigurationView) * view_count);
for (uint32_t i = 0; i < view_count; i++) {
viewconfig_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
viewconfig_views[i].next = NULL;
}
result = oxr_xrEnumerateViewConfigurationViews(instance, system_id, view_type, view_count,
&view_count, viewconfig_views);
if (!xr_check(instance, result, "Failed to enumerate view configuration views!"))
return 1;
print_viewconfig_view_info(view_count, viewconfig_views);
// OpenXR requires checking graphics requirements before creating a session.
XrGraphicsRequirementsOpenGLKHR opengl_reqs = {.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR,
.next = NULL};
// this function pointer was loaded with xrGetInstanceProcAddr
result = oxr_xrGetOpenGLGraphicsRequirementsKHR(instance, system_id, &opengl_reqs);
if (!xr_check(instance, result, "Failed to get OpenGL graphics requirements!"))
return 1;
/* Checking opengl_reqs.minApiVersionSupported and opengl_reqs.maxApiVersionSupported
* is not very useful, compatibility will depend on the OpenGL implementation and the
* OpenXR runtime much more than the OpenGL version.
* Other APIs have more useful verifiable requirements. */
// --- Create session
#ifdef _WIN32
graphics_binding_gl = (XrGraphicsBindingOpenGLWin32KHR){
.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR,
};
#else
graphics_binding_gl = (XrGraphicsBindingOpenGLXlibKHR){
.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR,
};
#endif
// create SDL window the size of the left eye & fill GL graphics binding info
#ifdef _WIN32
if (!init_sdl_window(&graphics_binding_gl.hDC, &graphics_binding_gl.hGLRC,
viewconfig_views[0].recommendedImageRectWidth,
viewconfig_views[0].recommendedImageRectHeight)) {
#else
if (!init_sdl_window(&graphics_binding_gl.xDisplay, &graphics_binding_gl.visualid,
&graphics_binding_gl.glxFBConfig, &graphics_binding_gl.glxDrawable,
&graphics_binding_gl.glxContext,
viewconfig_views[0].recommendedImageRectWidth,
viewconfig_views[0].recommendedImageRectHeight)) {
#endif
printf("GLX init failed!\n");
return 1;
}
printf("Using OpenGL version: %s\n", glGetString(GL_VERSION));
printf("Using OpenGL Renderer: %s\n", glGetString(GL_RENDERER));
XrSessionCreateInfo session_create_info = {
.type = XR_TYPE_SESSION_CREATE_INFO, .next = &graphics_binding_gl, .systemId = system_id};
result = oxr_xrCreateSession(instance, &session_create_info, &session);
if (!xr_check(instance, result, "Failed to create session"))
return 1;
printf("Successfully created a session with OpenGL!\n");
/* Many runtimes support at least STAGE and LOCAL but not all do.
* Sophisticated apps might check with xrEnumerateReferenceSpaces() if the
* chosen one is supported and try another one if not.
* Here we will get an error from xrCreateReferenceSpace() and exit. */
XrReferenceSpaceCreateInfo play_space_create_info = {.type = XR_TYPE_REFERENCE_SPACE_CREATE_INFO,
.next = NULL,
.referenceSpaceType = play_space_type,
.poseInReferenceSpace = identity_pose};
result = oxr_xrCreateReferenceSpace(session, &play_space_create_info, &play_space);
if (!xr_check(instance, result, "Failed to create play space!"))
return 1;
// --- Create Swapchains
uint32_t swapchain_format_count;
result = oxr_xrEnumerateSwapchainFormats(session, 0, &swapchain_format_count, NULL);
if (!xr_check(instance, result, "Failed to get number of supported swapchain formats"))
return 1;
printf("Runtime supports %d swapchain formats\n", swapchain_format_count);
int64_t swapchain_formats[swapchain_format_count];
result = oxr_xrEnumerateSwapchainFormats(session, swapchain_format_count, &swapchain_format_count,
swapchain_formats);
if (!xr_check(instance, result, "Failed to enumerate swapchain formats"))
return 1;
// SRGB is usually a better choice than linear
// a more sophisticated approach would iterate supported swapchain formats and choose from them
int64_t color_format = get_swapchain_format(instance, session, GL_SRGB8_ALPHA8_EXT, true);
// GL_DEPTH_COMPONENT16 is a good bet
// SteamVR 1.16.4 supports GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32
// but NOT GL_DEPTH_COMPONENT32F
int64_t depth_format = get_swapchain_format(instance, session, GL_DEPTH_COMPONENT16, false);
if (depth_format < 0) {
printf("Preferred depth format GL_DEPTH_COMPONENT16 not supported, disabling depth\n");
depth.supported = false;
}
// --- Create swapchain for main VR rendering
{
// In the frame loop we render into OpenGL textures we receive from the runtime here.
swapchains = malloc(sizeof(XrSwapchain) * view_count);
swapchain_lengths = malloc(sizeof(uint32_t) * view_count);
images = malloc(sizeof(XrSwapchainImageOpenGLKHR*) * view_count);
for (uint32_t i = 0; i < view_count; i++) {
XrSwapchainCreateInfo swapchain_create_info = {
.type = XR_TYPE_SWAPCHAIN_CREATE_INFO,
.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT,
.createFlags = 0,
.format = color_format,
.sampleCount = viewconfig_views[i].recommendedSwapchainSampleCount,
.width = viewconfig_views[i].recommendedImageRectWidth,
.height = viewconfig_views[i].recommendedImageRectHeight,
.faceCount = 1,
.arraySize = 1,
.mipCount = 1,
.next = NULL,
};
result = oxr_xrCreateSwapchain(session, &swapchain_create_info, &swapchains[i]);
if (!xr_check(instance, result, "Failed to create swapchain %d!", i))
return 1;
// The runtime controls how many textures we have to be able to render to
// (e.g. "triple buffering")
result = oxr_xrEnumerateSwapchainImages(swapchains[i], 0, &swapchain_lengths[i], NULL);
if (!xr_check(instance, result, "Failed to enumerate swapchains"))
return 1;
images[i] = malloc(sizeof(XrSwapchainImageOpenGLKHR) * swapchain_lengths[i]);
for (uint32_t j = 0; j < swapchain_lengths[i]; j++) {
images[i][j].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR;
images[i][j].next = NULL;
}
result =
oxr_xrEnumerateSwapchainImages(swapchains[i], swapchain_lengths[i], &swapchain_lengths[i],
(XrSwapchainImageBaseHeader*)images[i]);
if (!xr_check(instance, result, "Failed to enumerate swapchain images"))
return 1;
}
}
// --- Create swapchain for depth buffers if supported
{
if (depth.supported) {
depth_swapchains = malloc(sizeof(XrSwapchain) * view_count);
depth_swapchain_lengths = malloc(sizeof(uint32_t) * view_count);
depth_images = malloc(sizeof(XrSwapchainImageOpenGLKHR*) * view_count);
for (uint32_t i = 0; i < view_count; i++) {
XrSwapchainCreateInfo swapchain_create_info = {
.type = XR_TYPE_SWAPCHAIN_CREATE_INFO,
.usageFlags = XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
.createFlags = 0,
.format = depth_format,
.sampleCount = viewconfig_views[i].recommendedSwapchainSampleCount,
.width = viewconfig_views[i].recommendedImageRectWidth,
.height = viewconfig_views[i].recommendedImageRectHeight,
.faceCount = 1,
.arraySize = 1,
.mipCount = 1,
.next = NULL,
};
result = oxr_xrCreateSwapchain(session, &swapchain_create_info, &depth_swapchains[i]);
if (!xr_check(instance, result, "Failed to create swapchain %d!", i))
return 1;
result =
oxr_xrEnumerateSwapchainImages(depth_swapchains[i], 0, &depth_swapchain_lengths[i], NULL);
if (!xr_check(instance, result, "Failed to enumerate swapchains"))
return 1;
// these are wrappers for the actual OpenGL texture id
depth_images[i] = malloc(sizeof(XrSwapchainImageOpenGLKHR) * depth_swapchain_lengths[i]);
for (uint32_t j = 0; j < depth_swapchain_lengths[i]; j++) {
depth_images[i][j].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR;
depth_images[i][j].next = NULL;
}
result = oxr_xrEnumerateSwapchainImages(depth_swapchains[i], depth_swapchain_lengths[i],
&depth_swapchain_lengths[i],
(XrSwapchainImageBaseHeader*)depth_images[i]);
if (!xr_check(instance, result, "Failed to enumerate swapchain images"))
return 1;
}
}
}
// Do not allocate these every frame to save some resources
views = (XrView*)malloc(sizeof(XrView) * view_count);
for (uint32_t i = 0; i < view_count; i++) {
views[i].type = XR_TYPE_VIEW;
views[i].next = NULL;
}
projection_views = (XrCompositionLayerProjectionView*)malloc(
sizeof(XrCompositionLayerProjectionView) * view_count);
for (uint32_t i = 0; i < view_count; i++) {
projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
projection_views[i].next = NULL;
projection_views[i].subImage.swapchain = swapchains[i];
projection_views[i].subImage.imageArrayIndex = 0;
projection_views[i].subImage.imageRect.offset.x = 0;
projection_views[i].subImage.imageRect.offset.y = 0;
projection_views[i].subImage.imageRect.extent.width =
viewconfig_views[i].recommendedImageRectWidth;
projection_views[i].subImage.imageRect.extent.height =
viewconfig_views[i].recommendedImageRectHeight;
// projection_views[i].{pose, fov} have to be filled every frame in frame loop
}
if (depth.supported) {
depth.infos = (XrCompositionLayerDepthInfoKHR*)malloc(sizeof(XrCompositionLayerDepthInfoKHR) *
view_count);
for (uint32_t i = 0; i < view_count; i++) {
depth.infos[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR;
depth.infos[i].next = NULL;
depth.infos[i].minDepth = 0.f;
depth.infos[i].maxDepth = 1.f;
depth.infos[i].nearZ = gl_rendering.near_z;
depth.infos[i].farZ = gl_rendering.far_z;
depth.infos[i].subImage.swapchain = depth_swapchains[i];
depth.infos[i].subImage.imageArrayIndex = 0;
depth.infos[i].subImage.imageRect.offset.x = 0;
depth.infos[i].subImage.imageRect.offset.y = 0;
depth.infos[i].subImage.imageRect.extent.width =
viewconfig_views[i].recommendedImageRectWidth;
depth.infos[i].subImage.imageRect.extent.height =
viewconfig_views[i].recommendedImageRectHeight;
// depth is chained to projection, not submitted as separate layer
projection_views[i].next = &depth.infos[i];
}
}
// --- Set up input (actions)
oxr_xrStringToPath(instance, "/user/hand/left", &hand_paths[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right", &hand_paths[HAND_RIGHT_INDEX]);
XrPath select_click_path[HAND_COUNT];
oxr_xrStringToPath(instance, "/user/hand/left/input/select/click",
&select_click_path[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right/input/select/click",
&select_click_path[HAND_RIGHT_INDEX]);
XrPath trigger_value_path[HAND_COUNT];
oxr_xrStringToPath(instance, "/user/hand/left/input/trigger/value",
&trigger_value_path[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right/input/trigger/value",
&trigger_value_path[HAND_RIGHT_INDEX]);
XrPath thumbstick_y_path[HAND_COUNT];
oxr_xrStringToPath(instance, "/user/hand/left/input/thumbstick/y",
&thumbstick_y_path[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right/input/thumbstick/y",
&thumbstick_y_path[HAND_RIGHT_INDEX]);
XrPath grip_pose_path[HAND_COUNT];
oxr_xrStringToPath(instance, "/user/hand/left/input/grip/pose", &grip_pose_path[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right/input/grip/pose", &grip_pose_path[HAND_RIGHT_INDEX]);
XrPath haptic_path[HAND_COUNT];
oxr_xrStringToPath(instance, "/user/hand/left/output/haptic", &haptic_path[HAND_LEFT_INDEX]);
oxr_xrStringToPath(instance, "/user/hand/right/output/haptic", &haptic_path[HAND_RIGHT_INDEX]);
XrActionSetCreateInfo gameplay_actionset_info = {
.type = XR_TYPE_ACTION_SET_CREATE_INFO, .next = NULL, .priority = 0};
strcpy(gameplay_actionset_info.actionSetName, "gameplay_actionset");
strcpy(gameplay_actionset_info.localizedActionSetName, "Gameplay Actions");
XrActionSet gameplay_actionset;
result = oxr_xrCreateActionSet(instance, &gameplay_actionset_info, &gameplay_actionset);
if (!xr_check(instance, result, "failed to create actionset"))
return 1;
XrAction hand_pose_action;
{
XrActionCreateInfo action_info = {.type = XR_TYPE_ACTION_CREATE_INFO,
.next = NULL,
.actionType = XR_ACTION_TYPE_POSE_INPUT,
.countSubactionPaths = HAND_COUNT,