File: vtkOpenXRManager.cxx

package info (click to toggle)
paraview 5.11.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 497,236 kB
  • sloc: cpp: 3,171,290; ansic: 1,315,072; python: 134,290; xml: 103,324; sql: 65,887; sh: 5,286; javascript: 4,901; yacc: 4,383; java: 3,977; perl: 2,363; lex: 1,909; f90: 1,255; objc: 143; makefile: 119; tcl: 59; pascal: 50; fortran: 29
file content (1391 lines) | stat: -rw-r--r-- 52,830 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenXRManager.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOpenXRManager.h"

#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenXRManagerOpenGLGraphics.h"
#include "vtkOpenXRUtilities.h"
#include "vtkWindows.h" // Does nothing if we are not on windows

#define VTK_CHECK_NULL_XRHANDLE(handle, msg)                                                       \
  if (handle == XR_NULL_HANDLE)                                                                    \
  {                                                                                                \
    vtkErrorWithObjectMacro(nullptr, << msg << " is a null handle.");                              \
    return false;                                                                                  \
  }

VTK_ABI_NAMESPACE_BEGIN
//------------------------------------------------------------------------------
vtkOpenXRManager::vtkOpenXRManager()
{
  // Use OpenGL as default backend
  this->GraphicsStrategy = vtkSmartPointer<vtkOpenXRManagerOpenGLGraphics>::New();

  // Use no-op connection strategy as default
  this->ConnectionStrategy = vtkSmartPointer<vtkOpenXRManagerConnection>::New();
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::Initialize(vtkOpenGLRenderWindow* helperWindow)
{
  if (!this->ConnectionStrategy->Initialize())
  {
    vtkWarningWithObjectMacro(nullptr, "Failed to initialize connection strategy.");
    return false;
  }

  if (!this->CreateInstance())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateInstance");
    return false;
  }

  // Create the SubactionPaths (left / right hand and head)
  if (!this->CreateSubactionPaths())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateSubactionPaths");
    return false;
  }

  if (!this->CreateSystem())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateSystem");
    return false;
  }

  if (!this->GraphicsStrategy->CheckGraphicsRequirements(this->Instance, this->SystemId))
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed in CheckGraphicsRequirements");
    return false;
  }

  if (!this->GraphicsStrategy->CreateGraphicsBinding(helperWindow))
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateGraphicsBinding");
    return false;
  }

  // When using remoting, the connection must be established before creating the session
  if (!this->ConnectionStrategy->ConnectToRemote(this->Instance, this->SystemId))
  {
    vtkWarningWithObjectMacro(nullptr, "Failed to connect.");
    return false;
  }

  if (!this->CreateSession())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateSession");
    return false;
  }

  // System properties use the following functions that must be called after
  // the connection has succeeded when using remoting:
  // xrEnumerateViewConfigurations, xrGetViewConfigurationProperties,
  // xrEnumerateEnvironmentBlendModes, xrGetSystemProperties.
  if (!this->CreateSystemProperties())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateSystemProperties");
    return false;
  }

  if (!this->CreateReferenceSpace())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateReferenceSpace");
    return false;
  }

  if (!this->CreateSwapchains())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to CreateSwapChains");
    return false;
  }

  if (!this->LoadControllerModels())
  {
    vtkWarningWithObjectMacro(nullptr, "Initialize failed to LoadController Models");
    return false;
  }

  return true;
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::Finalize()
{
  this->DestroyActionSets();
  xrEndSession(this->Session);
  xrDestroySession(this->Session);
  xrDestroyInstance(this->Instance);
}

//------------------------------------------------------------------------------
std::tuple<uint32_t, uint32_t> vtkOpenXRManager::GetRecommendedImageRectSize()
{
  if (this->RenderResources->ConfigViews.size() == 0)
  {
    return std::make_tuple(0, 0);
  }
  return std::make_tuple(this->RenderResources->ConfigViews[0].recommendedImageRectWidth,
    this->RenderResources->ConfigViews[0].recommendedImageRectHeight);
}

//------------------------------------------------------------------------------
uint32_t vtkOpenXRManager::GetRecommendedSampleCount()
{
  if (this->RenderResources->ConfigViews.size() == 0)
  {
    return 0;
  }
  return this->RenderResources->ConfigViews[0].recommendedSwapchainSampleCount;
}

//------------------------------------------------------------------------------
std::string vtkOpenXRManager::GetOpenXRPropertiesAsString()
{
  XrInstanceProperties instanceProperties = {
    XR_TYPE_INSTANCE_PROPERTIES, // .type
    nullptr,                     // .next
  };
  if (!this->XrCheckWarn(xrGetInstanceProperties(this->Instance, &instanceProperties),
        "Failed to get instance info"))
  {
    return "";
  }

  std::string properties = std::string(instanceProperties.runtimeName) + " " +
    std::to_string(XR_VERSION_MAJOR(instanceProperties.runtimeVersion)) + "." +
    std::to_string(XR_VERSION_MINOR(instanceProperties.runtimeVersion)) + "." +
    std::to_string(XR_VERSION_PATCH(instanceProperties.runtimeVersion));

  return properties;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::BeginSession()
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::BeginSession, Session");

  XrSessionBeginInfo session_begin_info = {
    XR_TYPE_SESSION_BEGIN_INFO, // .type
    nullptr,                    // .next
    this->ViewType              // .primaryViewConfigurationType
  };
  if (!this->XrCheckWarn(
        xrBeginSession(this->Session, &session_begin_info), "Failed to begin session!"))
  {
    return false;
  }

  vtkDebugWithObjectMacro(nullptr, "Session started.");

  this->SessionRunning = true;

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::WaitAndBeginFrame()
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::WaitAndBeginFrame, Session");

  // Wait frame
  XrFrameWaitInfo frameWaitInfo{ XR_TYPE_FRAME_WAIT_INFO };
  XrFrameState frameState{ XR_TYPE_FRAME_STATE };

  if (!this->XrCheckError(
        xrWaitFrame(this->Session, &frameWaitInfo, &frameState), "Failed to wait frame."))
  {
    return false;
  }

  // Begin frame
  XrFrameBeginInfo frameBeginInfo{ XR_TYPE_FRAME_BEGIN_INFO };
  if (!this->XrCheckError(xrBeginFrame(this->Session, &frameBeginInfo), "Failed to begin frame."))
  {
    return false;
  }

  // Store the value of shouldRender to avoid a render
  this->ShouldRenderCurrentFrame = frameState.shouldRender;

  // Store the value of frame predicted display time that is used in EndFrame
  this->PredictedDisplayTime = frameState.predictedDisplayTime;

  if (this->ShouldRenderCurrentFrame)
  {
    // Locate the views : this will update view pose and projection fov for each view
    XrViewLocateInfo viewLocateInfo{ XR_TYPE_VIEW_LOCATE_INFO };
    viewLocateInfo.viewConfigurationType = this->ViewType;
    viewLocateInfo.displayTime = frameState.predictedDisplayTime;
    viewLocateInfo.space = this->ReferenceSpace;
    const uint32_t viewCount = this->GetViewCount();
    uint32_t viewCountOutput;
    if (!this->XrCheckError(
          xrLocateViews(this->Session, &viewLocateInfo, &this->RenderResources->ViewState,
            viewCount, &viewCountOutput, this->RenderResources->Views.data()),
          "Failed to locate views !"))
    {
      return false;
    }

    if (viewCountOutput != viewCount)
    {
      vtkWarningWithObjectMacro(nullptr, << "ViewCountOutput (" << viewCountOutput
                                         << ") is different than ViewCount (" << viewCount
                                         << ") !");
    }
  }

  return true;
}

// loads the controller models using an extension if it is present.
// todo needs to be tied into the models class and
// the gltf conversion completed right now it is here as an example
// to start from.
bool vtkOpenXRManager::LoadControllerModels()
{
  if (!this->OptionalExtensions.ControllerModelExtensionSupported)
  {
    return true;
  }

  // Controllers are not loaded when remoting to the hololens.
  // TODO: handle hand mesh tracking using XR_MSFT_hand_tracking_mesh extension.
  if (this->OptionalExtensions.RemotingSupported)
  {
    return true;
  }

  auto lPath = this->GetXrPath("/user/hand/left");

  xr::ExtensionDispatchTable extensions;
  // Define the pointer function of enabled extensions (see XrExtensions.h)
  extensions.PopulateDispatchTable(this->Instance);

  XrControllerModelKeyStateMSFT controllerModelKeyState;
  this->XrCheckError(
    extensions.xrGetControllerModelKeyMSFT(this->Session, lPath, &controllerModelKeyState),
    "Failed to get controller model key!");

  // get the size
  uint32_t bufferCountOutput = 0;
  this->XrCheckError(extensions.xrLoadControllerModelMSFT(this->Session,
                       controllerModelKeyState.modelKey, 0, &bufferCountOutput, nullptr),
    "Failed to get controller model size!");

  // get the data
  uint32_t bufferCapacityInput = bufferCountOutput;
  uint8_t* buffer = new uint8_t[bufferCountOutput];
  this->XrCheckError(
    extensions.xrLoadControllerModelMSFT(this->Session, controllerModelKeyState.modelKey,
      bufferCapacityInput, &bufferCountOutput, buffer),
    "Failed to get controller model!");

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::PrepareRendering(uint32_t eye, void* colorTextureId, void* depthTextureId)
{
  const vtkOpenXRManager::Swapchain_t& colorSwapchain = this->RenderResources->ColorSwapchains[eye];
  const vtkOpenXRManager::Swapchain_t& depthSwapchain = this->RenderResources->DepthSwapchains[eye];

  // Use the full size of the allocated swapchain image (could render smaller some frames to hit
  // framerate)
  const XrRect2Di imageRect = { { 0, 0 },
    { (int32_t)colorSwapchain.Width, (int32_t)colorSwapchain.Height } };

  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    if (colorSwapchain.Width != depthSwapchain.Width)
    {
      vtkErrorWithObjectMacro(nullptr, << "Color swapchain width (" << colorSwapchain.Width
                                       << ") differs from depth swapchain width ("
                                       << depthSwapchain.Width << ").");
      return false;
    }
    if (colorSwapchain.Height != depthSwapchain.Height)
    {
      vtkErrorWithObjectMacro(nullptr, << "Color swapchain height (" << colorSwapchain.Height
                                       << ") differs from depth swapchain height ("
                                       << depthSwapchain.Height << ").");
      return false;
    }
  }

  // Store the texture to render into it during the render method
  const uint32_t colorSwapchainImageIndex =
    this->WaitAndAcquireSwapchainImage(colorSwapchain.Swapchain);

  this->GraphicsStrategy->GetColorSwapchainImage(eye, colorSwapchainImageIndex, colorTextureId);

  this->RenderResources->ProjectionLayerViews[eye] = { XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW };
  this->RenderResources->ProjectionLayerViews[eye].pose = this->RenderResources->Views[eye].pose;
  this->RenderResources->ProjectionLayerViews[eye].fov = this->RenderResources->Views[eye].fov;
  this->RenderResources->ProjectionLayerViews[eye].subImage.swapchain = colorSwapchain.Swapchain;
  this->RenderResources->ProjectionLayerViews[eye].subImage.imageRect = imageRect;
  this->RenderResources->ProjectionLayerViews[eye].subImage.imageArrayIndex = 0;

  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    const uint32_t depthSwapchainImageIndex =
      this->WaitAndAcquireSwapchainImage(depthSwapchain.Swapchain);

    this->GraphicsStrategy->GetDepthSwapchainImage(eye, depthSwapchainImageIndex, depthTextureId);

    this->RenderResources->DepthInfoViews[eye] = { XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR };
    this->RenderResources->DepthInfoViews[eye].minDepth = 0;
    this->RenderResources->DepthInfoViews[eye].maxDepth = 1;
    this->RenderResources->DepthInfoViews[eye].nearZ = 0.1;
    this->RenderResources->DepthInfoViews[eye].farZ = 20.0;
    this->RenderResources->DepthInfoViews[eye].subImage.swapchain = depthSwapchain.Swapchain;
    this->RenderResources->DepthInfoViews[eye].subImage.imageRect = imageRect;
    this->RenderResources->DepthInfoViews[eye].subImage.imageArrayIndex = 0;

    // Chain depth info struct to the corresponding projection layer view's next pointer
    this->RenderResources->ProjectionLayerViews[eye].next =
      &this->RenderResources->DepthInfoViews[eye];
  }

  return true;
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::ReleaseSwapchainImage(uint32_t eye)
{
  XrSwapchainImageReleaseInfo releaseInfo{ XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO };

  this->XrCheckError(
    xrReleaseSwapchainImage(this->RenderResources->ColorSwapchains[eye].Swapchain, &releaseInfo),
    "Failed to release color swapchain image!");

  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    this->XrCheckError(
      xrReleaseSwapchainImage(this->RenderResources->DepthSwapchains[eye].Swapchain, &releaseInfo),
      "Failed to release depth swapchain image!");
  }
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::EndFrame()
{
  // The projection layer consists of projection layer views.
  XrCompositionLayerProjection layer{ XR_TYPE_COMPOSITION_LAYER_PROJECTION };
  std::vector<XrCompositionLayerBaseHeader*> layers;

  // If the frame has been rendered, then we must submit the ProjectionLayerViews:
  if (this->ShouldRenderCurrentFrame)
  {
    // Inform the runtime that the app's submitted alpha channel has valid data for use during
    // composition. The primary display on HoloLens has an additive environment blend mode. It will
    // ignore the alpha channel. However, mixed reality capture uses the alpha channel if this bit
    // is set to blend content with the environment.
    layer.layerFlags = this->OptionalExtensions.RemotingSupported
      ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT
      : 0;
    layer.space = this->ReferenceSpace;
    layer.viewCount = (uint32_t)this->RenderResources->ProjectionLayerViews.size();
    layer.views = this->RenderResources->ProjectionLayerViews.data();

    // Add the layer to the submitted layers
    layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(&layer));
  }
  // Reset should render state
  this->ShouldRenderCurrentFrame = false;

  // Submit the composition layers for the predicted display time.
  // If the frame shouldn't be rendered, submit an empty vector
  XrFrameEndInfo frameEndInfo{ XR_TYPE_FRAME_END_INFO };
  frameEndInfo.displayTime = this->PredictedDisplayTime;
  frameEndInfo.environmentBlendMode = this->EnvironmentBlendMode;
  frameEndInfo.layerCount = (uint32_t)layers.size();
  frameEndInfo.layers = layers.data();
  xrEndFrame(this->Session, &frameEndInfo);

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::PollEvent(XrEventDataBuffer& eventData)
{
  eventData.type = XR_TYPE_EVENT_DATA_BUFFER;
  eventData.next = nullptr;
  return xrPollEvent(this->Instance, &eventData) == XR_SUCCESS;
}

//------------------------------------------------------------------------------
uint32_t vtkOpenXRManager::WaitAndAcquireSwapchainImage(const XrSwapchain& swapchainHandle)
{
  VTK_CHECK_NULL_XRHANDLE(
    swapchainHandle, "vtkOpenXRManager::WaitAndAcquireSwapchainImage, swapchain");

  uint32_t swapchainImageIndex;
  XrSwapchainImageAcquireInfo acquireInfo{ XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO };
  this->XrCheckWarn(xrAcquireSwapchainImage(swapchainHandle, &acquireInfo, &swapchainImageIndex),
    "Failed to acquire swapchain image !");

  XrSwapchainImageWaitInfo waitInfo{ XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO };
  waitInfo.timeout = XR_INFINITE_DURATION;
  this->XrCheckWarn(
    xrWaitSwapchainImage(swapchainHandle, &waitInfo), "Failed to wait swapchain image !");

  return swapchainImageIndex;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::XrCheckError(const XrResult& result, const std::string& message)
{
  if (XR_FAILED(result))
  {
    char xRResultString[XR_MAX_RESULT_STRING_SIZE];
    xrResultToString(this->Instance, result, xRResultString);
    vtkErrorWithObjectMacro(nullptr, << message << " [" << xRResultString << "].");
    return false;
  }
  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::XrCheckWarn(const XrResult& result, const std::string& message)
{
  if (XR_FAILED(result))
  {
    char xRResultString[XR_MAX_RESULT_STRING_SIZE];
    xrResultToString(this->Instance, result, xRResultString);
    vtkWarningWithObjectMacro(nullptr, << message << " [" << xRResultString << "].");
    return false;
  }
  return true;
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::PrintInstanceProperties()
{
  XrInstanceProperties instanceProperties = {
    XR_TYPE_INSTANCE_PROPERTIES, // .type
    nullptr,                     // .next
  };

  this->XrCheckWarn(
    xrGetInstanceProperties(this->Instance, &instanceProperties), "Failed to get instance info");

  std::cout << "Runtime Name: " << instanceProperties.runtimeName;
  std::cout << "Runtime Version: " << XR_VERSION_MAJOR(instanceProperties.runtimeVersion) << "."
            << XR_VERSION_MINOR(instanceProperties.runtimeVersion) << "."
            << XR_VERSION_PATCH(instanceProperties.runtimeVersion) << std::endl;
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::PrintSystemProperties(XrSystemProperties* systemProperties)
{
  std::cout << "System Properties for system id:" << systemProperties->systemId << ", with name \""
            << systemProperties->systemName << "\""
            << ", vendorID=" << systemProperties->vendorId << std::endl;

  std::cout << "\tMax Layers          : " << systemProperties->graphicsProperties.maxLayerCount
            << std::endl;
  std::cout << "\tMax Swapchain Height: "
            << systemProperties->graphicsProperties.maxSwapchainImageHeight << std::endl;
  std::cout << "\tMax Swapchain Width : "
            << systemProperties->graphicsProperties.maxSwapchainImageWidth << std::endl;
  std::cout << "\tOrientation Tracking: "
            << (systemProperties->trackingProperties.orientationTracking ? "True" : "False")
            << std::endl;
  std::cout << "\tPosition Tracking   : "
            << (systemProperties->trackingProperties.positionTracking ? "True" : "False")
            << std::endl;

  const XrBaseInStructure* next = static_cast<XrBaseInStructure*>(systemProperties->next);
  while (next)
  {
    if (next->type == XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT)
    {
      XrSystemHandTrackingPropertiesEXT* ht =
        static_cast<XrSystemHandTrackingPropertiesEXT*>(systemProperties->next);
      std::cout << "\tHand Tracking       : " << ht->supportsHandTracking << std::endl;
    }
    next = next->next;
  }
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::PrintSupportedViewConfigs()
{
  uint32_t viewConfigCount;
  this->XrCheckWarn(
    xrEnumerateViewConfigurations(this->Instance, this->SystemId, 0, &viewConfigCount, nullptr),
    "Failed to get view configuration count");

  std::cout << "Runtime supports " << viewConfigCount << " view configurations" << std::endl;

  std::vector<XrViewConfigurationType> viewConfigs(viewConfigCount);
  this->XrCheckWarn(xrEnumerateViewConfigurations(this->Instance, this->SystemId, viewConfigCount,
                      &viewConfigCount, viewConfigs.data()),
    "Failed to enumerate view configurations!");

  for (uint32_t i = 0; i < viewConfigCount; ++i)
  {
    XrViewConfigurationProperties props = { XR_TYPE_VIEW_CONFIGURATION_PROPERTIES };
    this->XrCheckWarn(
      xrGetViewConfigurationProperties(this->Instance, this->SystemId, viewConfigs[i], &props),
      "Failed to get view configuration info " + i);

    std::cout << "Type "
              << vtkOpenXRUtilities::GetViewConfigurationTypeAsString(props.viewConfigurationType)
              << ": FOV mutable: " << (props.fovMutable ? "True" : "False") << std::endl;
  }
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::PrintViewConfigViewInfo(
  const std::vector<XrViewConfigurationView>& viewconfigViews)
{
  for (size_t i = 0; i < viewconfigViews.size(); ++i)
  {
    const auto& vcfgv = viewconfigViews[i];
    std::cout << "View Configuration View " << i << std::endl;
    std::cout << "\tResolution       : Recommended: " << vcfgv.recommendedImageRectWidth << "x"
              << vcfgv.recommendedImageRectHeight << ", Max: " << vcfgv.maxImageRectWidth << "x"
              << vcfgv.maxImageRectHeight << std::endl;
    std::cout << "\tSwapchain Samples: Recommended: " << vcfgv.recommendedSwapchainSampleCount
              << ", Max: " << vcfgv.maxSwapchainSampleCount << std::endl;
  }
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::PrintReferenceSpaces()
{
  uint32_t refSpaceCount;
  this->XrCheckError(xrEnumerateReferenceSpaces(this->Session, 0, &refSpaceCount, nullptr),
    "Getting number of reference spaces failed!");

  std::vector<XrReferenceSpaceType> refSpaces(refSpaceCount);
  this->XrCheckError(
    xrEnumerateReferenceSpaces(this->Session, refSpaceCount, &refSpaceCount, refSpaces.data()),
    "Enumerating reference spaces failed!");

  std::cout << "Runtime supports " << refSpaceCount << " reference spaces:" << std::endl;
  for (uint32_t i = 0; i < refSpaceCount; i++)
  {
    if (refSpaces[i] == XR_REFERENCE_SPACE_TYPE_LOCAL)
    {
      std::cout << "\tXR_REFERENCE_SPACE_TYPE_LOCAL" << std::endl;
    }
    else if (refSpaces[i] == XR_REFERENCE_SPACE_TYPE_STAGE)
    {
      std::cout << "\tXR_REFERENCE_SPACE_TYPE_STAGE" << std::endl;
    }
    else if (refSpaces[i] == XR_REFERENCE_SPACE_TYPE_VIEW)
    {
      std::cout << "\tXR_REFERENCE_SPACE_TYPE_VIEW" << std::endl;
    }
    else
    {
      std::cout << "\tOther (extension?) refspace : " << refSpaces[i] << std::endl;
    }
  }

  return true;
}

//------------------------------------------------------------------------------
std::vector<const char*> vtkOpenXRManager::SelectExtensions()
{
  // Fetch the list of extensions supported by the runtime.
  uint32_t extensionCount;
  this->XrCheckError(xrEnumerateInstanceExtensionProperties(nullptr, 0, &extensionCount, nullptr),
    "Failed to enumerate number of extension properties");

  std::vector<XrExtensionProperties> extensionProperties(
    extensionCount, { XR_TYPE_EXTENSION_PROPERTIES });
  this->XrCheckError(xrEnumerateInstanceExtensionProperties(
                       nullptr, extensionCount, &extensionCount, extensionProperties.data()),
    "Failed to enumerate extension properties");

  std::vector<const char*> enabledExtensions;
  // Add a specific extension to the list of extensions to be enabled, if it is supported.
  auto EnableExtensionIfSupported = [&](const char* extensionName) {
    for (uint32_t i = 0; i < extensionCount; i++)
    {
      if (strcmp(extensionProperties[i].extensionName, extensionName) == 0)
      {
        enabledExtensions.push_back(extensionName);
        return true;
      }
    }
    return false;
  };

  // Don't forget here to use the name of the extension (uppercase with suffix EXTENSION_NAME)
  this->RenderingBackendExtensionSupported =
    EnableExtensionIfSupported(this->GraphicsStrategy->GetBackendExtensionName());

  this->OptionalExtensions.ControllerModelExtensionSupported =
    EnableExtensionIfSupported(XR_MSFT_CONTROLLER_MODEL_EXTENSION_NAME);

  EnableExtensionIfSupported(XR_EXT_HP_MIXED_REALITY_CONTROLLER_EXTENSION_NAME);

  this->OptionalExtensions.UnboundedRefSpaceSupported =
    EnableExtensionIfSupported(XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME);

  this->OptionalExtensions.SpatialAnchorSupported =
    EnableExtensionIfSupported(XR_MSFT_SPATIAL_ANCHOR_EXTENSION_NAME);

  this->OptionalExtensions.HandTrackingSupported =
    EnableExtensionIfSupported(XR_EXT_HAND_TRACKING_EXTENSION_NAME);

  this->OptionalExtensions.HandInteractionSupported =
    EnableExtensionIfSupported(XR_MSFT_HAND_INTERACTION_EXTENSION_NAME);

  this->OptionalExtensions.RemotingSupported =
    EnableExtensionIfSupported(this->ConnectionStrategy->GetExtensionName());

  this->PrintOptionalExtensions();

  return enabledExtensions;
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::PrintOptionalExtensions()
{
  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    std::cout << "Optional extensions DepthExtension is supported" << std::endl;
  }
  if (this->OptionalExtensions.ControllerModelExtensionSupported)
  {
    std::cout << "Optional extensions ControllerModelExtension is supported" << std::endl;
  }
  if (this->OptionalExtensions.UnboundedRefSpaceSupported)
  {
    std::cout << "Optional extensions UnboundedRefSpace is supported" << std::endl;
  }
  if (this->OptionalExtensions.SpatialAnchorSupported)
  {
    std::cout << "Optional extensions SpatialAnchor is supported" << std::endl;
  }
  if (this->OptionalExtensions.HandTrackingSupported)
  {
    std::cout << "Optional extensions HandTracking is supported" << std::endl;
  }
  if (this->OptionalExtensions.HandInteractionSupported)
  {
    std::cout << "Optional extensions HandInteraction is supported" << std::endl;
  }
  if (this->OptionalExtensions.RemotingSupported)
  {
    std::cout << "Optional extensions Remoting is supported" << std::endl;
  }
}

//------------------------------------------------------------------------------
// Instance and extensions
//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateInstance()
{
  // Start by selection available extensions
  const std::vector<const char*> enabledExtensions = this->SelectExtensions();

  // Check that the requested rendering backend is supported
  if (!this->RenderingBackendExtensionSupported)
  {
    vtkErrorWithObjectMacro(nullptr, << "Rendering backend extension is not supported. Aborting.");
    return false;
  }

  // Create the instance with enabled extensions.
  XrInstanceCreateInfo createInfo{ XR_TYPE_INSTANCE_CREATE_INFO };
  createInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size();
  createInfo.enabledExtensionNames = enabledExtensions.data();

  XrApplicationInfo applicationInfo = {
    "OpenXR with VTK",      // .applicationName
    1,                      // .applicationVersion
    "",                     // .engineName
    1,                      // .engineVersion
    XR_CURRENT_API_VERSION, // .apiVersion
  };

  createInfo.applicationInfo = applicationInfo;

  if (!this->XrCheckError(
        xrCreateInstance(&createInfo, &this->Instance), "Failed to create XR instance."))
  {
    return false;
  }

  this->PrintInstanceProperties();

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateSubactionPaths()
{
  if (!this->XrCheckError(xrStringToPath(this->Instance, "/user/hand/left",
                            &this->SubactionPaths[vtkOpenXRManager::ControllerIndex::Left]),
        "Failed to create left hand subaction path"))
  {
    return false;
  }
  if (!this->XrCheckError(xrStringToPath(this->Instance, "/user/hand/right",
                            &this->SubactionPaths[vtkOpenXRManager::ControllerIndex::Right]),
        "Failed to create right hand subaction path"))
  {
    return false;
  }

  return true;
}

//------------------------------------------------------------------------------
// System
//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateSystem()
{
  VTK_CHECK_NULL_XRHANDLE(this->Instance, "vtkOpenXRManager::CreateSystem, Instance");

  // --- Create XrSystem
  XrSystemGetInfo system_get_info = {
    XR_TYPE_SYSTEM_GET_INFO, // .type
    nullptr,                 // .next
    this->FormFactor,        // .formFactor
  };

  this->XrCheckError(xrGetSystem(this->Instance, &system_get_info, &this->SystemId),
    "Failed to get system for HMD form factor.");

  vtkDebugWithObjectMacro(
    nullptr, "Successfully got XrSystem with id " << this->SystemId << " for HMD form factor.");

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateSystemProperties()
{
  // checking system properties is generally optional, but we are interested in hand tracking
  // support
  {
    XrSystemProperties systemProperties = {
      XR_TYPE_SYSTEM_PROPERTIES, // .type
      nullptr,                   // .next
      XR_NULL_SYSTEM_ID,         // .systemId
      0,                         // .vendorId
      "",                        // .systemName
      { 0 },                     // .graphicsProperties,
      { 0 }                      // .trackingProperties,
    };

    XrSystemHandTrackingPropertiesEXT ht = {
      XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, // .type
      nullptr,                                     // .next
      false                                        // .supportsHandTracking
    };

    if (this->OptionalExtensions.HandTrackingSupported)
    {
      systemProperties.next = &ht;
    }

    this->XrCheckError(xrGetSystemProperties(this->Instance, this->SystemId, &systemProperties),
      "Failed to get System properties");

    this->OptionalExtensions.HandTrackingSupported =
      this->OptionalExtensions.HandTrackingSupported && ht.supportsHandTracking;

    this->PrintSystemProperties(&systemProperties);
  }

  // Choose an environment blend mode
  {
    // Query the list of supported environment blend modes for the current system
    uint32_t count;

    xrEnumerateEnvironmentBlendModes(
      this->Instance, this->SystemId, this->ViewType, 0, &count, nullptr);
    this->XrCheckError(xrEnumerateEnvironmentBlendModes(
                         this->Instance, this->SystemId, this->ViewType, 0, &count, nullptr),
      "Failed to get environment blend modes count");
    if (count == 0)
    {
      vtkErrorWithObjectMacro(
        nullptr, "A system must support at least one environment blend mode.");
    }

    std::vector<XrEnvironmentBlendMode> environmentBlendModes(count);
    xrEnumerateEnvironmentBlendModes(
      this->Instance, this->SystemId, this->ViewType, count, &count, environmentBlendModes.data());
    this->XrCheckError(xrEnumerateEnvironmentBlendModes(this->Instance, this->SystemId,
                         this->ViewType, count, &count, environmentBlendModes.data()),
      "Failed to enumerate environment blend modes");

    // Pick the system's preferred one
    this->EnvironmentBlendMode = environmentBlendModes[0];
  }

  this->PrintSupportedViewConfigs();

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateSession()
{
  VTK_CHECK_NULL_XRHANDLE(this->Instance, "vtkOpenXRManager::CreateSession, Instance");

  // --- Create session
  this->SessionState = XR_SESSION_STATE_UNKNOWN;

  XrSessionCreateInfo sessionCreateInfo = {
    XR_TYPE_SESSION_CREATE_INFO,                  // .type
    this->GraphicsStrategy->GetGraphicsBinding(), // .next
    0,                                            // .createFlags
    this->SystemId                                // .systemId
  };

  if (!this->XrCheckError(xrCreateSession(this->Instance, &sessionCreateInfo, &this->Session),
        "Failed to create session"))
  {
    return false;
  }

#ifdef XR_USE_GRAPHICS_API_OPENGL
  vtkDebugWithObjectMacro(nullptr, "Successfully created a session with OpenGL!");
#elif XR_USE_GRAPHICS_API_D3D11
  vtkDebugWithObjectMacro(nullptr, "Successfully created a session with DirectX!");
#endif

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateReferenceSpace()
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::CreateReferenceSpace, Session");

  // Many runtimes support at least STAGE and LOCAL but not all do.
  // Sophisticated apps might check if the chosen one is supported and try another one if not.
  // Here we will get an error from xrCreateReferenceSpace() and exit.
  if (!this->PrintReferenceSpaces())
  {
    return false;
  }

  // Choose an unbounded reference space to improve holographic remoting stability
  if (this->OptionalExtensions.RemotingSupported &&
    this->OptionalExtensions.UnboundedRefSpaceSupported)
  {
    this->ReferenceSpaceType = XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT;
  }

  XrReferenceSpaceCreateInfo refSpaceCreateInfo = {
    XR_TYPE_REFERENCE_SPACE_CREATE_INFO,  // .type
    nullptr,                              // .next
    this->ReferenceSpaceType,             // .referenceSpaceType
    vtkOpenXRUtilities::GetIdentityPose() // .poseInReferenceSpace
  };

  this->XrCheckError(
    xrCreateReferenceSpace(this->Session, &refSpaceCreateInfo, &this->ReferenceSpace),
    "Failed to create play space!");

  return true;
}

//------------------------------------------------------------------------------
std::tuple<int64_t, int64_t> vtkOpenXRManager::SelectSwapchainPixelFormats()
{
  // Query the runtime's preferred swapchain formats.
  uint32_t swapchainFormatsCount;
  this->XrCheckError(xrEnumerateSwapchainFormats(this->Session, 0, &swapchainFormatsCount, nullptr),
    "Failed to get number of supported swapchain formats");

  vtkDebugWithObjectMacro(
    nullptr, "Runtime supports " << swapchainFormatsCount << " swapchain formats");

  std::vector<int64_t> swapchainFormats(swapchainFormatsCount);
  this->XrCheckError(xrEnumerateSwapchainFormats(this->Session, swapchainFormatsCount,
                       &swapchainFormatsCount, swapchainFormats.data()),
    "Failed to enumerate swapchain formats");

  // Choose the first runtime-preferred format that this app supports.
  auto selectPixelFormat = [&](const std::vector<int64_t>& runtimePreferredFormats,
                             const std::vector<int64_t>& applicationSupportedFormats,
                             const std::string& formatName) {
    auto found =
      std::find_first_of(std::begin(runtimePreferredFormats), std::end(runtimePreferredFormats),
        std::begin(applicationSupportedFormats), std::end(applicationSupportedFormats));
    if (found == std::end(runtimePreferredFormats))
    {
      vtkErrorWithObjectMacro(
        nullptr, << "No runtime swapchain " << formatName << " format in the list is supported.");
      return (int64_t)-1;
    }
    return *found;
  };

  int64_t colorSwapchainFormat = selectPixelFormat(
    swapchainFormats, this->GraphicsStrategy->GetSupportedColorFormats(), "color");
  int64_t depthSwapchainFormat = -1;
  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    depthSwapchainFormat = selectPixelFormat(
      swapchainFormats, this->GraphicsStrategy->GetSupportedDepthFormats(), "depth");
    if (depthSwapchainFormat == -1)
    {
      vtkDebugWithObjectMacro(
        nullptr, "Disabling depth extension as no depth format are supported");
      this->OptionalExtensions.DepthExtensionSupported = false;
    }
  }

  return std::make_tuple(colorSwapchainFormat, depthSwapchainFormat);
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateSwapchains()
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::CreateSwapchains, Session");

  this->RenderResources = std::unique_ptr<RenderResources_t>(new RenderResources_t());

  // Select color and depth swapchain pixel formats.
  int64_t colorSwapchainFormat, depthSwapchainFormat;
  std::tie(colorSwapchainFormat, depthSwapchainFormat) = this->SelectSwapchainPixelFormats();

  // Query and cache view configuration views.
  this->CreateConfigViews();

  const XrViewConfigurationView& view = this->RenderResources->ConfigViews[0];

  // Use the system's recommended rendering parameters.
  const uint32_t imageRectWidth = view.recommendedImageRectWidth;
  const uint32_t imageRectHeight = view.recommendedImageRectHeight;
  const uint32_t swapchainSampleCount = view.recommendedSwapchainSampleCount;

  // Create swapchains with texture array for color and depth images.
  const uint32_t viewCount = (uint32_t)this->RenderResources->ConfigViews.size();

  // One swapchain per view to make it simple
  // We could also use a texture arraySize != 1 but the rendering
  // will be more complex
  this->RenderResources->ColorSwapchains.resize(viewCount);
  this->RenderResources->DepthSwapchains.resize(viewCount);

  this->GraphicsStrategy->SetNumberOfSwapchains(viewCount);

  for (uint32_t i = 0; i < viewCount; ++i)
  {
    this->RenderResources->ColorSwapchains[i] = this->CreateSwapchain(colorSwapchainFormat,
      imageRectWidth, imageRectHeight, swapchainSampleCount, 0 /*createFlags*/,
      XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT);
    this->GraphicsStrategy->EnumerateColorSwapchainImages(
      this->RenderResources->ColorSwapchains[i].Swapchain, i);

    if (this->OptionalExtensions.DepthExtensionSupported)
    {
      this->RenderResources->DepthSwapchains[i] = this->CreateSwapchain(depthSwapchainFormat,
        imageRectWidth, imageRectHeight, swapchainSampleCount, 0 /*createFlags*/,
        XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
      this->GraphicsStrategy->EnumerateDepthSwapchainImages(
        this->RenderResources->DepthSwapchains[i].Swapchain, i);
    }
  }

  // Preallocate view buffers for xrLocateViews later inside frame loop.
  this->RenderResources->Views.resize(viewCount, { XR_TYPE_VIEW });

  // Preallocate projection layer views and depth if needed
  this->RenderResources->ProjectionLayerViews.resize(viewCount);
  if (this->OptionalExtensions.DepthExtensionSupported)
  {
    this->RenderResources->DepthInfoViews.resize(viewCount);
  }

  return true;
}

//------------------------------------------------------------------------------
vtkOpenXRManager::Swapchain_t vtkOpenXRManager::CreateSwapchain(int64_t format, uint32_t width,
  uint32_t height, uint32_t sampleCount, XrSwapchainCreateFlags createFlags,
  XrSwapchainUsageFlags usageFlags)
{
  Swapchain_t swapchain;
  swapchain.Format = format;
  swapchain.Width = width;
  swapchain.Height = height;

  XrSwapchainCreateInfo swapchainCreateInfo{ XR_TYPE_SWAPCHAIN_CREATE_INFO };
  swapchainCreateInfo.arraySize = 1;
  swapchainCreateInfo.format = format;
  swapchainCreateInfo.width = width;
  swapchainCreateInfo.height = height;
  swapchainCreateInfo.mipCount = 1;
  swapchainCreateInfo.faceCount = 1;
  swapchainCreateInfo.sampleCount = sampleCount;
  swapchainCreateInfo.createFlags = createFlags;
  swapchainCreateInfo.usageFlags = usageFlags;

  this->XrCheckError(xrCreateSwapchain(this->Session, &swapchainCreateInfo, &swapchain.Swapchain),
    "Failed to create swapchain!");

  return swapchain;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateConfigViews()
{
  uint32_t viewCount;
  this->XrCheckError(xrEnumerateViewConfigurationViews(
                       this->Instance, this->SystemId, this->ViewType, 0, &viewCount, nullptr),
    "Failed to get view configuration view count!");
  if (viewCount != this->StereoViewCount)
  {
    vtkWarningWithObjectMacro(nullptr, << "StereoViewCount (" << this->StereoViewCount
                                       << ") is different than viewCount (" << viewCount << ")");
  }

  this->RenderResources->ConfigViews.resize(viewCount, { XR_TYPE_VIEW_CONFIGURATION_VIEW });

  if (!this->XrCheckError(
        xrEnumerateViewConfigurationViews(this->Instance, this->SystemId, this->ViewType, viewCount,
          &viewCount, this->RenderResources->ConfigViews.data()),
        "Failed to enumerate view configuration views!"))
  {
    return false;
  }

  this->PrintViewConfigViewInfo(this->RenderResources->ConfigViews);

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateActionSet(
  const std::string& actionSetName, const std::string& localizedActionSetName)
{
  vtkDebugWithObjectMacro(
    nullptr, "Create action set " << actionSetName << ": " << localizedActionSetName);

  XrActionSetCreateInfo actionSetInfo{ XR_TYPE_ACTION_SET_CREATE_INFO };

  strcpy(actionSetInfo.actionSetName, actionSetName.c_str());
  strcpy(actionSetInfo.localizedActionSetName, localizedActionSetName.c_str());

  XrActionSet actionSet;
  if (!this->XrCheckError(xrCreateActionSet(this->Instance, &actionSetInfo, &actionSet),
        "Failed to create default actionset"))
  {
    return false;
  }
  this->ActionSets.push_back(actionSet);

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::SelectActiveActionSet(unsigned int index)
{
  if (this->ActionSets.size() == 0)
  {
    vtkErrorWithObjectMacro(nullptr, << "An action set must be created prior to select one.");
    return false;
  }
  if (index >= this->ActionSets.size())
  {
    vtkWarningWithObjectMacro(nullptr,
      << "The selected action set at index : " << index << " does not exist. Pick the first one");
    index = 0;
  }

  this->ActiveActionSet = &this->ActionSets[index];

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::AttachSessionActionSets()
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::AttachSessionActionSets, Session");

  XrSessionActionSetsAttachInfo actionSetsAttachInfo = {
    XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // .type
    nullptr,                                 // .next
    (uint32_t)this->ActionSets.size(),       // .countActionSets
    this->ActionSets.data()                  // .actionSets
  };
  return this->XrCheckError(xrAttachSessionActionSets(this->Session, &actionSetsAttachInfo),
    "Failed to attach action sets");
}

//------------------------------------------------------------------------------
void vtkOpenXRManager::DestroyActionSets()
{
  for (XrActionSet actionSet : this->ActionSets)
  {
    xrDestroyActionSet(actionSet);
  }

  this->ActionSets.clear();

  // active action set pointed to one of those, so clear it now
  this->ActiveActionSet = nullptr;
}

//------------------------------------------------------------------------------
XrPath vtkOpenXRManager::GetXrPath(const std::string& path)
{
  VTK_CHECK_NULL_XRHANDLE(this->Instance, "vtkOpenXRManager::GetXrPath, Instance");

  XrPath xrPath;
  this->XrCheckWarn(
    xrStringToPath(this->Instance, path.c_str(), &xrPath), "Failed to get path " + path);
  return std::move(xrPath);
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateOneAction(
  Action_t& actionT, const std::string& name, const std::string& localizedName)
{
  if (this->ActiveActionSet == nullptr)
  {
    return false;
  }

  XrActionCreateInfo actionInfo = {
    XR_TYPE_ACTION_CREATE_INFO,            // .type
    nullptr,                               // .next
    "",                                    // .actionName
    actionT.ActionType,                    // .actionType
    (uint32_t)this->SubactionPaths.size(), // .countSubactionPaths
    this->SubactionPaths.data(),           // .subactionPaths
    ""                                     // .localizedActionName
  };
  strcpy(actionInfo.actionName, name.c_str());
  strcpy(actionInfo.localizedActionName, localizedName.c_str());

  if (!this->XrCheckError(xrCreateAction(*this->ActiveActionSet, &actionInfo, &actionT.Action),
        "Failed to create action " + std::string(name)))
  {
    return false;
  }

  // If this is a pose action, we need to create an action space
  // In order to use LocateSpace
  if (actionT.ActionType == XR_ACTION_TYPE_POSE_INPUT)
  {
    // One action space per pointer pose and store it in subaction space
    for (uint32_t hand :
      { vtkOpenXRManager::ControllerIndex::Left, vtkOpenXRManager::ControllerIndex::Right })
    {
      if (!this->CreateOneActionSpace(actionT.Action, this->SubactionPaths[hand],
            vtkOpenXRUtilities::GetIdentityPose(), actionT.PoseSpaces[hand]))
      {
        vtkErrorWithObjectMacro(nullptr,
          << "Failed to create pose action space for "
          << (hand == vtkOpenXRManager::ControllerIndex::Left ? "left" : "right") << " hand");
        return false;
      };
    }
  }

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::CreateOneActionSpace(const XrAction& action, const XrPath& subactionPath,
  const XrPosef& poseInActionSpace, XrSpace& space)
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::CreateOneActionSpace, Session");

  XrActionSpaceCreateInfo actionSpaceInfo = {
    XR_TYPE_ACTION_SPACE_CREATE_INFO, // .type
    nullptr,                          // .next
    action,                           // .action
    subactionPath,                    // .subactionPath
    poseInActionSpace                 // .poseInActionSpace
  };

  return this->XrCheckError(xrCreateActionSpace(this->Session, &actionSpaceInfo, &space), "");
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::SuggestActions(
  const std::string& profile, std::vector<XrActionSuggestedBinding>& actionSuggestedBindings)
{
  vtkDebugWithObjectMacro(nullptr, "SuggestActions for profile : " << profile);
  VTK_CHECK_NULL_XRHANDLE(this->Instance, "vtkOpenXRManager::SuggestActions, Instance");

  XrPath interactionProfilePath;
  this->XrCheckWarn(xrStringToPath(this->Instance, profile.c_str(), &interactionProfilePath),
    "Failed to get interaction profile path " + profile);

  const XrInteractionProfileSuggestedBinding suggestedBindings = {
    XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // .type
    nullptr,                                       // .next
    interactionProfilePath,                        // .interactionProfile
    (uint32_t)actionSuggestedBindings.size(),      // .countSuggestedBindings
    actionSuggestedBindings.data()                 // .suggestedBindings
  };

  this->XrCheckWarn(xrSuggestInteractionProfileBindings(this->Instance, &suggestedBindings),
    "Failed to suggest actions");

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::SyncActions()
{
  if (this->ActiveActionSet == nullptr)
  {
    return false;
  }
  const XrActionSet& actionSet = *this->ActiveActionSet;
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::SyncActions, Session");
  VTK_CHECK_NULL_XRHANDLE(actionSet, "vtkOpenXRManager::SyncActions, ActiveActionSet");

  // Only use the active action set, but we could add all action sets
  // in the following vector
  std::vector<XrActiveActionSet> activeActionSets = { { actionSet, XR_NULL_PATH } };
  XrActionsSyncInfo syncInfo{ XR_TYPE_ACTIONS_SYNC_INFO };
  syncInfo.countActiveActionSets = (uint32_t)activeActionSets.size();
  syncInfo.activeActionSets = activeActionSets.data();
  return this->XrCheckError(xrSyncActions(this->Session, &syncInfo), "Failed to sync actions");
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::UpdateActionData(Action_t& action_t, const int hand)
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::UpdateActionData, Session");
  VTK_CHECK_NULL_XRHANDLE(
    this->ReferenceSpace, "vtkOpenXRManager::UpdateActionData, ReferenceSpace");

  XrActionStateGetInfo info = {
    XR_TYPE_ACTION_STATE_GET_INFO, // .type
    nullptr,                       // .next
    action_t.Action,               // .action
    this->SubactionPaths[hand],    // .subactionPath
  };

  // we store the state of the action, depending on the selected hand
  switch (action_t.ActionType)
  {
    case XR_ACTION_TYPE_FLOAT_INPUT:
      action_t.States[hand]._float.type = XR_TYPE_ACTION_STATE_FLOAT;
      action_t.States[hand]._float.next = nullptr;
      if (!this->XrCheckError(xrGetActionStateFloat(Session, &info, &action_t.States[hand]._float),
            "Failed to get float value"))
      {
        return false;
      }
      break;
    case XR_ACTION_TYPE_BOOLEAN_INPUT:
      action_t.States[hand]._boolean.type = XR_TYPE_ACTION_STATE_BOOLEAN;
      action_t.States[hand]._boolean.next = nullptr;
      if (!this->XrCheckError(
            xrGetActionStateBoolean(this->Session, &info, &action_t.States[hand]._boolean),
            "Failed to get boolean value"))
      {
        return false;
      }
      break;
    case XR_ACTION_TYPE_VECTOR2F_INPUT:
      action_t.States[hand]._vec2f.type = XR_TYPE_ACTION_STATE_VECTOR2F;
      action_t.States[hand]._vec2f.next = nullptr;
      if (!this->XrCheckError(
            xrGetActionStateVector2f(this->Session, &info, &action_t.States[hand]._vec2f),
            "Failed to get vec2f"))
      {
        return false;
      }
      break;
    case XR_ACTION_TYPE_POSE_INPUT:
      action_t.States[hand]._pose.type = XR_TYPE_ACTION_STATE_POSE;
      action_t.States[hand]._pose.next = nullptr;
      if (!this->XrCheckError(
            xrGetActionStatePose(this->Session, &info, &action_t.States[hand]._pose),
            "Failed to get action state pose"))
      {
        return false;
      }

      if (action_t.States[hand]._pose.isActive)
      {
        action_t.PoseLocations[hand].type = XR_TYPE_SPACE_LOCATION;
        action_t.PoseLocations[hand].next = nullptr;

        if (this->StorePoseVelocities)
        {
          action_t.PoseVelocities[hand].type = XR_TYPE_SPACE_VELOCITY;
          action_t.PoseVelocities[hand].next = nullptr;
          action_t.PoseLocations[hand].next = &action_t.PoseVelocities[hand];
        }

        // Store the position of the hand
        if (!this->XrCheckError(xrLocateSpace(action_t.PoseSpaces[hand], this->ReferenceSpace,
                                  this->PredictedDisplayTime, &action_t.PoseLocations[hand]),
              "Failed to locate hand space"))
        {
          return false;
        }
      }

      break;
    default:
      break;
  }

  return true;
}

//------------------------------------------------------------------------------
bool vtkOpenXRManager::ApplyVibration(const Action_t& actionT, const int hand,
  const float amplitude, const float duration, const float frequency)
{
  VTK_CHECK_NULL_XRHANDLE(this->Session, "vtkOpenXRManager::ApplyVibration, Session");

  if (actionT.ActionType != XR_ACTION_TYPE_VIBRATION_OUTPUT)
  {
    vtkErrorWithObjectMacro(
      nullptr, << "vtkOpenXRManager::ApplyVibration must be called for an action of type "
                  "XR_ACTION_TYPE_VIBRATION_OUTPUT, not a "
               << vtkOpenXRUtilities::GetActionTypeAsString(actionT.ActionType));
    return false;
  }

  XrHapticActionInfo actionInfo{ XR_TYPE_HAPTIC_ACTION_INFO };
  actionInfo.action = actionT.Action;
  actionInfo.subactionPath = this->SubactionPaths[hand];

  XrHapticVibration vibration{ XR_TYPE_HAPTIC_VIBRATION };
  vibration.amplitude = amplitude;
  vibration.duration = duration;
  vibration.frequency = frequency;

  if (!this->XrCheckError(
        xrApplyHapticFeedback(this->Session, &actionInfo, (XrHapticBaseHeader*)&vibration),
        "Failed to apply haptic feedback"))
  {
    return false;
  }
  return true;
}
VTK_ABI_NAMESPACE_END