-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
4139 lines (3376 loc) · 145 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 OpenXR playground, exercising many areas of the OpenXR API.
* Advanced version of the openxr-simple-example
* @author Christoph Haag <christoph.haag@collabora.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#ifdef __linux__
// Required headers for OpenGL rendering, as well as for including openxr_platform
#define GL_GLEXT_PROTOTYPES
#define GL3_PROTOTYPES
#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_headers/openxr.h"
#include "openxr_headers/openxr_platform.h"
#include "openxr_headers/openxr_reflection.h"
#else
#error Only Linux/XLib supported for now
#endif
#define __USE_XOPEN_EXTENDED // strdup
#include <string.h>
/*
This file contains expansion macros (X Macros) for OpenXR enumerations and structures.
Example of how to use expansion macros to make an enum-to-string function:
*/
#define XR_ENUM_CASE_STR(name, val) \
case name: \
return #name;
#define XR_ENUM_STR(enumType) \
const char* XrStr_##enumType(uint64_t e) \
{ \
switch (e) { \
XR_LIST_ENUM_##enumType(XR_ENUM_CASE_STR) default : return "Unknown"; \
} \
}
#define XR_STR_IF_ENUM(name, val) \
if (strcmp(#name, e) == 0) \
return val;
#define XR_STR_ENUM(enumType) \
uint64_t XrEnum_##enumType(const char* e) \
{ \
XR_LIST_ENUM_##enumType(XR_STR_IF_ENUM) return 0x7FFFFFFF; \
}
#define XR_PRINT_ENUM(name, val) \
if (val != 0x7FFFFFFF) \
printf("\t\t%s\n", #name);
#define XR_ENUM_PRINT_VALS(enumType) \
void XrPrintEnum_##enumType() \
{ \
XR_LIST_ENUM_##enumType(XR_PRINT_ENUM) \
}
// instead of invoking each of the macros for every type, make a meta macro
#define XR_MACROS(enumType) \
XR_ENUM_STR(enumType) \
XR_STR_ENUM(enumType) \
XR_ENUM_PRINT_VALS(enumType)
XR_MACROS(XrResult)
XR_MACROS(XrFormFactor)
XR_MACROS(XrReferenceSpaceType)
XR_MACROS(XrViewConfigurationType)
XR_MACROS(XrEnvironmentBlendMode)
typedef const char* (*XrStr_fn)(long value);
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>
#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
// UDP
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define RECEIVER_IP "127.0.0.1"
#define RECEIVER_PORT 12345
#define SENDER_PORT 54321
#define MAX_BUFFER_SIZE 65507
#define SCALE 0.92
#define JOINT_DEFAULT 100.0
typedef struct {
int width;
int height;
} TextureInfo;
struct MainArgs {
int argc;
char** argv;
};
TextureInfo textureInfo;
GLubyte* buffer_in = NULL;
size_t buffer_in_size = 0;
GLuint prev_frame_id = 0;
int skip_frame_count = 0;
// flags
int VR_initialized = 0;
int data_ready = 0;
int closing_app = 0;
typedef struct {
int hand;
int joint_index;
XrPosef pose;
} JointData;
GLubyte* buffer_out = NULL;
size_t buffer_out_size = 0;
// flag for printing
int flag = 0;
clock_t start_time, current_time;
int initialized_hand[HAND_COUNT] = {0};
JointData initial_data[HAND_COUNT];
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
// Define min/max macros
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// ============================================================================
// 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
// =============================================================================
struct gl_renderer_t
{
// 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* VAOs;
struct
{
bool initialized;
GLuint texture;
GLuint fbo;
} quad;
int modelLoc;
int colorLoc;
int textureLoc;
int viewLoc;
int projLoc;
};
struct hand_tracking_t;
#ifdef __linux__
bool
init_sdl_window(Display** xDisplay,
uint32_t* visualid,
GLXFBConfig* glxFBConfig,
GLXDrawable* glxDrawable,
GLXContext* glxContext,
int w,
int h);
int
init_gl(uint32_t view_count, uint32_t* swapchain_lengths, struct gl_renderer_t* gl_renderer);
struct ApplicationState;
void
render_frame(struct ApplicationState* app,
int w,
int h,
struct gl_renderer_t* gl_renderer,
uint32_t projection_index,
XrTime predictedDisplayTime,
int view_index,
XrSpaceLocation* hand_locations,
struct hand_tracking_t* hand_tracking,
XrView* view,
GLuint image,
bool depth_supported,
GLuint depthbuffer);
struct quad_layer_t;
void
render_quad(struct gl_renderer_t* gl_renderer,
struct quad_layer_t* quad,
uint32_t swapchain_index,
XrTime predictedDisplayTime);
#endif
// =============================================================================
// 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];
xrResultToString(instance, result, resultString);
char formatRes[XR_MAX_RESULT_STRING_SIZE + 1024];
snprintf(formatRes, XR_MAX_RESULT_STRING_SIZE + 1023, "%s [%s]\n", format, resultString);
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 = 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);
const XrBaseInStructure* next = system_properties->next;
while (next) {
if (next->type == XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT) {
XrSystemHandTrackingPropertiesEXT* ht = system_properties->next;
printf("\tHand Tracking : %d\n", ht->supportsHandTracking);
}
next = next->next;
}
}
static void
print_supported_view_configs(XrInstance instance, XrSystemId system_id)
{
XrResult result;
uint32_t view_config_count;
result = xrEnumerateViewConfigurations(instance, system_id, 0, &view_config_count, NULL);
if (!xr_check(instance, result, "Failed to get view configuration count"))
return;
printf("Runtime supports %d view configurations\n", view_config_count);
XrViewConfigurationType view_configs[view_config_count];
result = xrEnumerateViewConfigurations(instance, system_id, view_config_count, &view_config_count,
view_configs);
if (!xr_check(instance, result, "Failed to enumerate view configurations!"))
return;
for (uint32_t i = 0; i < view_config_count; ++i) {
XrViewConfigurationProperties props = {.type = XR_TYPE_VIEW_CONFIGURATION_PROPERTIES,
.next = NULL};
result = xrGetViewConfigurationProperties(instance, system_id, view_configs[i], &props);
if (!xr_check(instance, result, "Failed to get view configuration info %d!", i))
return;
printf("type %d: FOV mutable: %d\n", props.viewConfigurationType, props.fovMutable);
}
}
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);
}
}
static void
print_reference_spaces(XrInstance instance, XrSession session)
{
XrResult result;
uint32_t ref_space_count;
result = xrEnumerateReferenceSpaces(session, 0, &ref_space_count, NULL);
if (!xr_check(instance, result, "Getting number of reference spaces failed!"))
return;
XrReferenceSpaceType* ref_spaces = malloc(sizeof(XrReferenceSpaceType) * ref_space_count);
result = xrEnumerateReferenceSpaces(session, ref_space_count, &ref_space_count, ref_spaces);
if (!xr_check(instance, result, "Enumerating reference spaces failed!"))
return;
printf("Runtime supports %d reference spaces:\n", ref_space_count);
for (uint32_t i = 0; i < ref_space_count; i++) {
if (ref_spaces[i] == XR_REFERENCE_SPACE_TYPE_LOCAL) {
printf("\tXR_REFERENCE_SPACE_TYPE_LOCAL\n");
} else if (ref_spaces[i] == XR_REFERENCE_SPACE_TYPE_STAGE) {
printf("\tXR_REFERENCE_SPACE_TYPE_STAGE\n");
} else if (ref_spaces[i] == XR_REFERENCE_SPACE_TYPE_VIEW) {
printf("\tXR_REFERENCE_SPACE_TYPE_VIEW\n");
} else {
printf("\tOther (extension?) refspace %u\\n", ref_spaces[i]);
}
}
free(ref_spaces);
}
static bool
check_opengl_version(XrGraphicsRequirementsOpenGLKHR* opengl_reqs)
{
XrVersion desired_opengl_version = XR_MAKE_VERSION(3, 3, 0);
if (desired_opengl_version > opengl_reqs->maxApiVersionSupported ||
desired_opengl_version < opengl_reqs->minApiVersionSupported) {
printf(
"We want OpenGL %d.%d.%d, but runtime only supports OpenGL "
"%d.%d.%d - %d.%d.%d!\n",
XR_VERSION_MAJOR(desired_opengl_version), XR_VERSION_MINOR(desired_opengl_version),
XR_VERSION_PATCH(desired_opengl_version),
XR_VERSION_MAJOR(opengl_reqs->minApiVersionSupported),
XR_VERSION_MINOR(opengl_reqs->minApiVersionSupported),
XR_VERSION_PATCH(opengl_reqs->minApiVersionSupported),
XR_VERSION_MAJOR(opengl_reqs->maxApiVersionSupported),
XR_VERSION_MINOR(opengl_reqs->maxApiVersionSupported),
XR_VERSION_PATCH(opengl_reqs->maxApiVersionSupported));
return false;
}
return true;
}
// 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 = 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 = 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;
}
struct action_t
{
XrAction action;
XrActionType action_type;
union {
XrActionStateFloat float_;
XrActionStateBoolean boolean_;
XrActionStatePose pose_;
XrActionStateVector2f vec2f_;
} states[HAND_COUNT];
XrSpace pose_spaces[HAND_COUNT];
XrSpaceLocation pose_locations[HAND_COUNT];
XrSpaceVelocity pose_velocities[HAND_COUNT];
// the subaction paths this action was created with
XrPath* subaction_paths;
uint32_t subaction_path_count;
};
bool
create_action(XrInstance instance,
XrActionType type,
char* name,
char* localized_name,
XrActionSet set,
int subaction_path_count,
XrPath* subaction_paths,
struct action_t* out_action)
{
XrActionCreateInfo actionInfo = {.type = XR_TYPE_ACTION_CREATE_INFO,
.actionType = type,
.countSubactionPaths = subaction_path_count,
.subactionPaths = subaction_paths};
strcpy(actionInfo.actionName, name);
strcpy(actionInfo.localizedActionName, localized_name);
XrResult result = xrCreateAction(set, &actionInfo, &out_action->action);
if (!xr_check(instance, result, "Failed to create action %s", name))
return false;
out_action->action_type = type;
out_action->subaction_paths = subaction_paths;
out_action->subaction_path_count = subaction_path_count;
return true;
}
bool
create_action_space(XrInstance instance,
XrSession session,
struct action_t* action,
XrPath* subaction_paths,
uint32_t subaction_path_count)
{
// poses can't be queried directly, we need to create a space for each
for (uint32_t i = 0; i < subaction_path_count; i++) {
XrActionSpaceCreateInfo action_space_info = {.type = XR_TYPE_ACTION_SPACE_CREATE_INFO,
.next = NULL,
.action = action->action,
.poseInActionSpace = identity_pose,
.subactionPath = subaction_paths[i]};
XrResult result;
result = xrCreateActionSpace(session, &action_space_info, &action->pose_spaces[i]);
if (!xr_check(instance, result, "failed to create subaction path %d pose space", i))
return false;
}
return true;
}
struct base_extension_t
{
bool supported;
uint32_t version;
char* ext_name_string;
};
struct opengl_t
{
struct base_extension_t base;
// functions belonging to extensions must be loaded with xrGetInstanceProcAddr before use
PFN_xrGetOpenGLGraphicsRequirementsKHR xrGetOpenGLGraphicsRequirementsKHR;
};
struct hand_tracking_t
{
struct base_extension_t base;
// whether the current VR system in use has hand tracking
bool system_supported;
XrHandTrackerEXT trackers[HAND_COUNT];
// out data
XrHandJointLocationEXT joints[HAND_COUNT][XR_HAND_JOINT_COUNT_EXT];
XrHandJointLocationsEXT joint_locations[HAND_COUNT];
// optional
XrHandJointVelocitiesEXT joint_velocities[HAND_COUNT];
XrHandJointVelocityEXT joint_velocities_arr[HAND_COUNT][XR_HAND_JOINT_COUNT_EXT];
PFN_xrLocateHandJointsEXT xrLocateHandJointsEXT;
PFN_xrCreateHandTrackerEXT xrCreateHandTrackerEXT;
};
struct depth_t
{
struct base_extension_t base;
XrCompositionLayerDepthInfoKHR* infos;
};
struct refresh_rate_t
{
struct base_extension_t base;
PFN_xrEnumerateDisplayRefreshRatesFB xrEnumerateDisplayRefreshRatesFB;
PFN_xrGetDisplayRefreshRateFB xrGetDisplayRefreshRateFB;
PFN_xrRequestDisplayRefreshRateFB xrRequestDisplayRefreshRateFB;
};
static char* vive_tracker_role_str[] = {
"/user/vive_tracker_htcx/role/handheld_object", "/user/vive_tracker_htcx/role/left_foot",
"/user/vive_tracker_htcx/role/right_foot", "/user/vive_tracker_htcx/role/left_shoulder",
"/user/vive_tracker_htcx/role/right_shoulder", "/user/vive_tracker_htcx/role/left_elbow",
"/user/vive_tracker_htcx/role/right_elbow", "/user/vive_tracker_htcx/role/left_knee",
"/user/vive_tracker_htcx/role/right_knee", "/user/vive_tracker_htcx/role/waist",
"/user/vive_tracker_htcx/role/chest", "/user/vive_tracker_htcx/role/camera",
"/user/vive_tracker_htcx/role/keyboard",
};
#define VIVE_TRACKER_ROLE_COUNT (sizeof(vive_tracker_role_str) / sizeof(vive_tracker_role_str[0]))
struct known_vive_tracker
{
XrPath persistent_path;
XrPath role_path;
char* role_str;
// pointing to the pre-created per-role action. NULL if role_PATH == XR_NULL_PATH.
struct action_t action;
struct known_vive_tracker* next;
};
struct vive_tracker_t
{
struct base_extension_t base;
// dynamic list of trackers
struct known_vive_tracker* trackers;
PFN_xrEnumerateViveTrackerPathsHTCX pfnxrEnumerateViveTrackerPathsHTCX;
};
struct ext_t
{
struct opengl_t opengl;
struct depth_t depth;
struct hand_tracking_t hand_tracking;
struct refresh_rate_t refresh_rate;
struct vive_tracker_t vive_tracker;
};
struct OpenXRState
{
XrFormFactor form_factor;
XrViewConfigurationType view_type;
XrReferenceSpaceType play_space_type;
XrInstance instance;
XrSession session;
XrSystemId system_id;
XrSessionState state;
XrEnvironmentBlendMode blend_mode;
bool blend_mode_explicitly_set;
XrSpace play_space;
// Each physical Display/Eye is described by a view
uint32_t view_count;
XrViewConfigurationView* viewconfig_views;
XrCompositionLayerProjectionView* projection_views;
XrView* views;
XrViewState view_state;
};
struct ApplicationState
{
// have to define the names somewhere
struct ext_t ext;
struct OpenXRState oxr;
// use optional XrSpaceVelocity in xrLocateSpace for controllers and visualize linear velocity
bool query_hand_velocities;
// use optional XrSpaceVelocity in xrLocateHandJointsEXT and visualize linear velocity
bool query_joint_velocities;
struct
{
bool enabled;
// cube moves in `velocity` direction until it hits `center_pos +- `bouncing_lengths, then
// reverse `velocity
XrVector3f center_pos; // m
XrVector3f current_pos; // m
XrTime pos_ts; // ns
XrVector3f velocity; // m/s
XrVector3f bouncing_lengths; // m
} cube;
// Grabbing objects is not actually implemented in this demo, it only gives some haptic feebdack.
struct action_t grab_action;
// A 1D action that is fed by one axis of a 2D input (y axis of thumbstick).
struct action_t accelerate_action;
struct action_t hand_pose_action;
struct action_t aim_action;
struct action_t haptic_action;
XrSpace ref_local_space;
XrSpace ref_local_space_y1;
XrSpace ref_stage_space;
XrSpace ref_stage_space_y1;
XrSpace ref_view_space;
XrSpace ref_view_space_z1;
struct gl_renderer_t gl_renderer;
};
static char*
create_name_from_path(char* path)
{
char* name = strdup(path);
char* ptr = name;
while (*ptr != '\0') {
if (*ptr == '/') {
*ptr = '_';
}
ptr++;
}
return name;
}
static bool
create_vive_role_trackers(XrInstance instance,
XrSession session,
struct ext_t* ext,
XrActionSet actionset)
{
if (!ext->vive_tracker.base.supported) {
return XR_SUCCESS;
}
struct known_vive_tracker* curr_tracker = NULL;
for (uint32_t i = 0; i < VIVE_TRACKER_ROLE_COUNT; i++) {
struct known_vive_tracker* next_tracker = calloc(1, sizeof(struct known_vive_tracker));
next_tracker->action =
(struct action_t){.action = XR_NULL_HANDLE, .action_type = XR_ACTION_TYPE_POSE_INPUT};
next_tracker->role_path = XR_NULL_PATH;
next_tracker->role_str = (char*)vive_tracker_role_str[i];
XrResult result = xrStringToPath(instance, next_tracker->role_str, &next_tracker->role_path);
if (!xr_check(instance, result, "Failed to get XrPath for role %s!", next_tracker->role_path)) {
return false;
}
// frowned upon but do it anyway
char* name = create_name_from_path(next_tracker->role_str);
printf("Create action name %s with subaction path %s | %lu\n", name, next_tracker->role_str,
next_tracker->role_path);
if (!create_action(instance, XR_ACTION_TYPE_POSE_INPUT, name, name, actionset, 1,
&next_tracker->role_path, &next_tracker->action)) {
free(name);
return false;
}
free(name);
if (!create_action_space(instance, session, &next_tracker->action, &next_tracker->role_path,
1)) {
return false;