-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathG3DCamera.cs
More file actions
1608 lines (1408 loc) · 54.3 KB
/
G3DCamera.cs
File metadata and controls
1608 lines (1408 loc) · 54.3 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
#if UNITY_EDITOR
#endif
#if G3D_HDRP
using UnityEngine.Rendering.HighDefinition;
#endif
#if G3D_URP
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;
#endif
/// <summary>
/// IMPORTANT: This script must not be attached to a camera already using a G3D camera script.
/// </summary>
[RequireComponent(typeof(Camera))]
[DisallowMultipleComponent]
public class G3DCamera
: MonoBehaviour,
ITNewHeadPositionCallback,
ITNewShaderParametersCallback,
ITNewErrorMessageCallback
{
[Tooltip("Drop the calibration file for the display you want to use here.")]
public TextAsset calibrationFile;
[Tooltip(
"This path has to be set to the directory where the folder containing the calibration files for your monitor are located. The folder has to have the same name as your camera model."
)]
public string calibrationPathOverwrite = "";
#region 3D Effect settings
public G3DCameraMode mode = G3DCameraMode.DIORAMA;
public static string CAMERA_NAME_PREFIX = "g3dcam_";
[Tooltip(
"This value can be used to scale the real world values used to calibrate the extension. For example if your scene is 10 times larger than the real world, you can set this value to 10. Do NOT change this while the game is already running!"
)]
[Min(0.000001f)]
public float sceneScaleFactor = 1.0f;
[Tooltip(
"If set to true, the views will be flipped horizontally. This is necessary for holoboxes."
)]
public bool mirrorViews = false;
[Tooltip(
"Set a percentage value to render only that percentage of the width and height per view. E.g. a reduction of 50% will reduce the rendered size by a factor of 4. Adapt Render Resolution To Views takes precedence."
)]
[Range(1, 100)]
public int renderResolutionScale = 100;
[Tooltip(
"Set the dolly zoom effekt. 1 correponds to no dolly zoom. 0 is all the way zoomed in to the focus plane. 3 is all the way zoomed out."
)]
[Range(0.001f, 3)]
public float dollyZoom = 1;
[Tooltip(
"Scale the view offset up or down. 1.0f is no scaling, 0.5f is half the distance, 2.0f is double the distance. This can be used to adjust the view offset down for very large scenes."
)]
[Range(0.0f, 5.0f)]
public float viewOffsetScale = 1.0f; // scale the view offset to the focus distance. 1.0f is no scaling, 0.5f is half the distance, 2.0f is double the distance.
/// <summary>
/// Shifts the individual views to the left or right by the specified number of views.
/// </summary>
[Tooltip("Shifts the individual views to the left or right by the specified number of views.")]
public int viewOffset = 0;
[Tooltip(
"Scales the strength of the head tracking effect. 1.0f is no scaling, 0.5f is half the distance, 2.0f is double the distance."
)]
[Min(0.0f)]
public float headTrackingScale = 1.0f; // scale the head tracking effect
#endregion
#region Advanced settings
[Tooltip(
"Smoothes the head position (Size of the filter kernel). Not filtering is applied, if set to all zeros. DO NOT CHANGE THIS WHILE GAME IS ALREADY RUNNING!"
)]
public Vector3Int headPositionFilter = new Vector3Int(5, 5, 5);
public LatencyCorrectionMode latencyCorrectionMode = LatencyCorrectionMode.LCM_SIMPLE;
[Tooltip("If set to true, the head tracking library will print debug messages to the console.")]
public bool debugMessages = false;
[Tooltip(
"If set to true, the gizmos for the focus distance (green) and eye separation (blue) will be shown."
)]
public bool showGizmos = true;
[Tooltip("Scales the gizmos. Affectd by scene scale factor.")]
[Range(0.005f, 1.0f)]
public float gizmoSize = 0.2f;
public bool invertViewsInDiorama = false;
[Tooltip(
"Where the views start to yoyo in the index map. Index map contains the order of views."
)]
[Range(0.0f, 1.0f)]
public float indexMapYoyoStart = 0.0f;
[Tooltip("Inverts the entire index map. Index map contains the order of views.")]
public bool invertIndexMap = false;
[Tooltip("Inverts the indices in the index map. Index map contains the order of views.")]
public bool invertIndexMapIndices = false;
#endregion
#region Private variables
private PreviousValues previousValues;
private IndexMap indexMap = IndexMap.Instance;
private LibInterface libInterface;
private string calibrationPath;
// distance between the two cameras for diorama mode (in meters). DO NOT USE FOR MULTIVIEW MODE!
private float viewSeparation = 0.065f;
/// <summary>
/// The distance between the camera and the focus plane in meters. Default is 70 cm.
/// Is read from calibration file at startup
/// </summary>
private float focusDistance = 0.7f;
private const int MAX_CAMERAS = 16; //shaders dont have dynamic arrays and this is the max supported. change it here? change it in the shaders as well ...
private int internalCameraCount = 2;
private int oldRenderResolutionScale = 100;
/// <summary>
/// This struct is used to store the current head position.
/// It is updated in a different thread, so always use getHeadPosition() to get the current head position.
/// NEVER use headPosition directly.
/// </summary>
private HeadPosition headPosition;
private HeadPosition filteredHeadPosition;
private static object headPosLock = new object();
private static object shaderLock = new object();
private Camera mainCamera;
private List<Camera> cameras = null;
private GameObject focusPlaneObject = null;
private GameObject cameraParent = null;
private Material material;
#if G3D_HDRP
private G3DHDRPCustomPass customPass;
private HDAdditionalCameraData.AntialiasingMode antialiasingMode = HDAdditionalCameraData
.AntialiasingMode
.None;
#endif
#if G3D_URP
private G3DUrpScriptableRenderPass customPass;
private AntialiasingMode antialiasingMode = AntialiasingMode.None;
#endif
private ShaderHandles shaderHandles;
private G3DShaderParameters shaderParameters;
private Vector2Int cachedWindowPosition;
private Vector2Int cachedWindowSize;
// half of the width of field of view at start at focus distance
private float halfCameraWidthAtStart = 1.0f;
private Queue<string> headPositionLog;
private HeadtrackingHandler headtrackingHandler;
/// <summary>
/// This value is calculated based on the calibration file
/// </summary>
private float baseFieldOfView = 16.0f;
private bool showTestFrame = false;
/// <summary>
/// Focus distance scaled by scene scale factor.
/// </summary>
public float scaledFocusDistance
{
get { return focusDistance * sceneScaleFactor; }
}
public float scaledFocusDistanceAndDolly
{
get
{
float dollyZoomFactor = scaledFocusDistance - scaledFocusDistance * dollyZoom;
float focusDistanceWithDollyZoom = scaledFocusDistance - dollyZoomFactor;
return focusDistanceWithDollyZoom;
}
}
private float scaledViewSeparation
{
get { return viewSeparation * sceneScaleFactor * viewOffsetScale; }
}
private float scaledHalfCameraWidthAtStart
{
get { return halfCameraWidthAtStart * sceneScaleFactor; }
}
#endregion
// TODO Handle viewport resizing/ moving
#region Initialization
void Start()
{
previousValues.init();
calibrationPath = System.Environment.GetFolderPath(
Environment.SpecialFolder.CommonDocuments
);
calibrationPath = Path.Combine(calibrationPath, "3D Global", "calibrations");
if (!string.IsNullOrEmpty(calibrationPathOverwrite))
{
calibrationPath = calibrationPathOverwrite;
}
mainCamera = GetComponent<Camera>();
oldRenderResolutionScale = renderResolutionScale;
setupCameras();
// create a focus plane object at focus distance from camera.
// then parent the camera parent to that object
// this way we can place the camera parent relative to the focus plane
// disable rendering on main camera after other cameras have been created and settings have been copied over
// otherwise the secondary cameras are initialized wrong
mainCamera.cullingMask = 0; //disable rendering of the main camera
mainCamera.clearFlags = CameraClearFlags.Color;
shaderHandles = new ShaderHandles()
{
leftViewportPosition = Shader.PropertyToID("v_pos_x"),
bottomViewportPosition = Shader.PropertyToID("v_pos_y"),
screenWidth = Shader.PropertyToID("s_width"),
screenHeight = Shader.PropertyToID("s_height"),
nativeViewCount = Shader.PropertyToID("nativeViewCount"),
angleRatioNumerator = Shader.PropertyToID("zwinkel"),
angleRatioDenominator = Shader.PropertyToID("nwinkel"),
leftLensOrientation = Shader.PropertyToID("isleft"),
BGRPixelLayout = Shader.PropertyToID("isBGR"),
mstart = Shader.PropertyToID("mstart"),
showTestFrame = Shader.PropertyToID("test"),
showTestStripe = Shader.PropertyToID("stest"),
testGapWidth = Shader.PropertyToID("testgap"),
track = Shader.PropertyToID("track"),
hqViewCount = Shader.PropertyToID("hqview"),
hviews1 = Shader.PropertyToID("hviews1"),
hviews2 = Shader.PropertyToID("hviews2"),
blur = Shader.PropertyToID("blur"),
blackBorder = Shader.PropertyToID("bborder"),
blackSpace = Shader.PropertyToID("bspace"),
bls = Shader.PropertyToID("bls"),
ble = Shader.PropertyToID("ble"),
brs = Shader.PropertyToID("brs"),
bre = Shader.PropertyToID("bre"),
zCorrectionValue = Shader.PropertyToID("tvx"),
zCompensationValue = Shader.PropertyToID("zkom"),
};
if (mode == G3DCameraMode.DIORAMA)
{
initLibrary();
}
reinitializeShader();
updateScreenViewportProperties();
loadShaderParametersFromCalibrationFile();
updateShaderParameters();
if (mode == G3DCameraMode.DIORAMA)
{
try
{
libInterface.startHeadTracking();
}
catch (Exception e)
{
Debug.LogError("Failed to start head tracking: " + e.Message);
}
}
#if G3D_HDRP
// init fullscreen postprocessing for hd render pipeline
var customPassVolume = gameObject.AddComponent<CustomPassVolume>();
customPassVolume.injectionPoint = CustomPassInjectionPoint.AfterPostProcess;
customPassVolume.isGlobal = true;
// Make the volume invisible in the inspector
customPassVolume.hideFlags = HideFlags.HideInInspector | HideFlags.DontSave;
customPass = customPassVolume.AddPassOfType(typeof(G3DHDRPCustomPass)) as G3DHDRPCustomPass;
customPass.fullscreenPassMaterial = material;
customPass.materialPassName = "G3DFullScreen3D";
antialiasingMode = mainCamera.GetComponent<HDAdditionalCameraData>().antialiasing;
#endif
#if G3D_URP
customPass = new G3DUrpScriptableRenderPass(material);
antialiasingMode = mainCamera.GetUniversalAdditionalCameraData().antialiasing;
mainCamera.GetUniversalAdditionalCameraData().antialiasing = AntialiasingMode.None;
#endif
headtrackingHandler = new HeadtrackingHandler(focusDistance);
updateCameras();
updateShaderRenderTextures();
// This has to be done after the cameras are updated
cachedWindowPosition = new Vector2Int(
Screen.mainWindowPosition.x,
Screen.mainWindowPosition.y
);
cachedWindowSize = new Vector2Int(Screen.width, Screen.height);
headPositionLog = new Queue<string>(10000);
indexMap.UpdateIndexMap(
getCameraCountFromCalibrationFile(),
internalCameraCount,
indexMapYoyoStart,
invertIndexMap,
invertIndexMapIndices
);
}
void OnApplicationQuit()
{
deinitLibrary();
}
/// <summary>
/// this variable is onle here to track changes made to the public calibration file from the editor.
/// </summary>
/// <summary>
/// OnValidate gets called every time the script is changed in the editor.
/// This is used to react to changes made to the parameters.
/// </summary>
void OnValidate()
{
if (enabled == false)
{
// do not run this code if the script is not enabled
return;
}
if (
calibrationFile != previousValues.calibrationFile
|| previousValues.sceneScaleFactor != sceneScaleFactor
)
{
previousValues.calibrationFile = calibrationFile;
setupCameras(true);
}
if (previousValues.mode != mode)
{
previousValues.mode = mode;
if (mode == G3DCameraMode.MULTIVIEW)
{
CalibrationProvider calibration = CalibrationProvider.getFromString(
calibrationFile.text
);
loadMultiviewViewSeparationFromCalibration(calibration);
}
else
{
viewSeparation = 0.065f;
}
updateCameraCountBasedOnMode();
}
if (
previousValues.indexMapYoyoStart != indexMapYoyoStart
|| previousValues.invertIndexMap != invertIndexMap
|| previousValues.invertIndexMapIndices != invertIndexMapIndices
)
{
previousValues.indexMapYoyoStart = indexMapYoyoStart;
previousValues.invertIndexMap = invertIndexMap;
previousValues.invertIndexMapIndices = invertIndexMapIndices;
indexMap.UpdateIndexMap(
getCameraCountFromCalibrationFile(),
internalCameraCount,
indexMapYoyoStart,
invertIndexMap,
invertIndexMapIndices
);
}
}
/// <summary>
/// Us this to run OnValidate after parameters changed from a script.
/// </summary>
public void Validate()
{
OnValidate();
}
public void loadShaderParametersFromCalibrationFile()
{
if (calibrationFile == null)
{
Debug.LogError(
"No calibration file set. Please set a calibration file. Using default values."
);
return;
}
lock (shaderLock)
{
CalibrationProvider calibrationProvider = CalibrationProvider.getFromString(
calibrationFile.text
);
shaderParameters = calibrationProvider.getShaderParameters();
}
}
private void loadMultiviewViewSeparationFromCalibration(CalibrationProvider calibration)
{
if (mode != G3DCameraMode.MULTIVIEW)
{
return;
}
int BasicWorkingDistanceMM = calibration.getInt("BasicWorkingDistanceMM");
int NativeViewcount = calibration.getInt("NativeViewcount");
float ApertureAngle = 14.0f;
try
{
ApertureAngle = calibration.getFloat("ApertureAngle");
}
catch (Exception e)
{
Debug.LogWarning(e.Message);
}
float BasicWorkingDistanceMeter = BasicWorkingDistanceMM / 1000.0f;
float halfZoneOpeningAngleRad = ApertureAngle * Mathf.Deg2Rad / 2.0f;
float halfWidthZoneAtbasicDistance =
Mathf.Tan(halfZoneOpeningAngleRad) * BasicWorkingDistanceMeter;
// calculate eye separation/ view separation
if (mode == G3DCameraMode.MULTIVIEW)
{
viewSeparation = halfWidthZoneAtbasicDistance * 2 / NativeViewcount;
}
}
/// <summary>
/// Updates all camera parameters based on the calibration file (i.e. focus distance, fov, etc.).
/// Includes shader parameters (i.e. lense shear angle, camera count, etc.).
///
/// Updates calibration file as well.
/// </summary>
public void setupCameras(TextAsset calibrationFile, bool calledFromValidate = false)
{
this.calibrationFile = calibrationFile;
setupCameras(calledFromValidate);
}
/// <summary>
/// Sets up all camera parameters based on the calibration file (i.e. focus distance, fov, etc.).
/// Includes shader parameters (i.e. lense shear angle, camera count, etc.).
///
/// Does not update calibration file.
/// </summary>
public void setupCameras(bool calledFromValidate = false)
{
if (mainCamera == null)
{
mainCamera = GetComponent<Camera>();
}
if (Application.isPlaying && !calledFromValidate)
{
// only run this code if not in editor mode (this function (setupCameras()) is called from OnValidate as well -> from editor ui)
initCamerasAndParents();
}
if (calibrationFile == null)
{
Debug.LogError(
"No calibration file set. Please set a calibration file. Using default values."
);
mainCamera.fieldOfView = 16.0f;
focusDistance = 0.7f;
viewSeparation = 0.065f;
if (mode == G3DCameraMode.MULTIVIEW)
{
viewSeparation = 0.031f;
}
if (focusPlaneObject != null)
{
focusPlaneObject.transform.localPosition = new Vector3(0, 0, scaledFocusDistance);
}
return;
}
// load values from calibration file
CalibrationProvider calibration = CalibrationProvider.getFromString(calibrationFile.text);
int BasicWorkingDistanceMM = calibration.getInt("BasicWorkingDistanceMM");
float PhysicalSizeInch = calibration.getFloat("PhysicalSizeInch");
int NativeViewcount = calibration.getInt("NativeViewcount");
int HorizontalResolution = calibration.getInt("HorizontalResolution");
int VerticalResolution = calibration.getInt("VerticalResolution");
// calculate intermediate values
float BasicWorkingDistanceMeter = BasicWorkingDistanceMM / 1000.0f;
float physicalSizeInMeter = PhysicalSizeInch * 0.0254f;
float aspectRatio = (float)HorizontalResolution / (float)VerticalResolution;
float FOV =
2 * Mathf.Atan(physicalSizeInMeter / 2.0f / BasicWorkingDistanceMeter) * Mathf.Rad2Deg;
// set focus distance
focusDistance = (float)BasicWorkingDistanceMeter;
// set camera fov
baseFieldOfView = Camera.HorizontalToVerticalFieldOfView(FOV, aspectRatio);
mainCamera.fieldOfView = baseFieldOfView;
// calculate eye separation/ view separation
if (mode == G3DCameraMode.MULTIVIEW)
{
loadMultiviewViewSeparationFromCalibration(calibration);
}
else
{
viewSeparation = 0.065f;
}
updateCameraCountBasedOnMode();
// only run this code if not in editor mode (this function (setupCameras()) is called from OnValidate as well -> from editor ui)
if (Application.isPlaying)
{
// update focus plane distance
if (focusPlaneObject != null)
{
focusPlaneObject.transform.localPosition = new Vector3(0, 0, scaledFocusDistance);
}
if (cameraParent != null)
{
cameraParent.transform.localPosition = new Vector3(0, 0, -scaledFocusDistance);
}
}
halfCameraWidthAtStart =
Mathf.Tan(mainCamera.fieldOfView * Mathf.Deg2Rad / 2) * focusDistance;
loadShaderParametersFromCalibrationFile();
}
/// <summary>
/// Initializes the cameras and their parents.
/// if cameras are already initialized, this function only returns the focus plane.
/// </summary>
/// <returns>
/// The focus plane game object.
/// </returns>
private void initCamerasAndParents()
{
if (focusPlaneObject == null)
{
focusPlaneObject = new GameObject("focus plane center");
focusPlaneObject.transform.parent = transform;
focusPlaneObject.transform.localPosition = new Vector3(0, 0, scaledFocusDistance);
focusPlaneObject.transform.localRotation = Quaternion.identity;
}
//initialize cameras
if (cameraParent == null)
{
cameraParent = new GameObject("g3dcams");
cameraParent.transform.parent = focusPlaneObject.transform;
cameraParent.transform.localPosition = new Vector3(0, 0, -scaledFocusDistance);
cameraParent.transform.localRotation = Quaternion.identity;
}
if (cameras == null)
{
cameras = new List<Camera>();
for (int i = 0; i < MAX_CAMERAS; i++)
{
cameras.Add(new GameObject(CAMERA_NAME_PREFIX + i).AddComponent<Camera>());
cameras[i].transform.SetParent(cameraParent.transform, true);
cameras[i].gameObject.SetActive(false);
cameras[i].transform.localRotation = Quaternion.identity;
cameras[i].clearFlags = mainCamera.clearFlags;
cameras[i].backgroundColor = mainCamera.backgroundColor;
cameras[i].targetDisplay = mainCamera.targetDisplay;
cameras[i].depth = mainCamera.depth - 1; // make sure the main camera renders on top of the secondary cameras
#if G3D_HDRP
cameras[i].gameObject.AddComponent<HDAdditionalCameraData>();
#endif
}
}
}
private int getCameraCountFromCalibrationFile()
{
if (calibrationFile == null)
{
Debug.LogError(
"No calibration file set. Please set a calibration file. Using default values."
);
return 2;
}
// TODO do not recreate the calibration provider every time
// This gets called every frame in UpdateCameraCountBasedOnMode
CalibrationProvider calibration = CalibrationProvider.getFromString(calibrationFile.text);
return getCameraCountFromCalibrationFile(calibration);
}
private int getCameraCountFromCalibrationFile(CalibrationProvider calibration)
{
int NativeViewcount = calibration.getInt("NativeViewcount");
return NativeViewcount;
}
private Vector2Int getDisplayResolutionFromCalibrationFile()
{
if (calibrationFile == null)
{
Debug.LogError(
"No calibration file set. Please set a calibration file. Using default values."
);
return new Vector2Int(1920, 1080);
}
CalibrationProvider calibration = CalibrationProvider.getFromString(calibrationFile.text);
int HorizontalResolution = calibration.getInt("HorizontalResolution");
int VerticalResolution = calibration.getInt("VerticalResolution");
return new Vector2Int(HorizontalResolution, VerticalResolution);
}
private void initLibrary()
{
string applicationName = Application.productName;
if (string.IsNullOrEmpty(applicationName))
{
applicationName = "Unity";
}
var invalids = System.IO.Path.GetInvalidFileNameChars();
applicationName = String
.Join("_", applicationName.Split(invalids, StringSplitOptions.RemoveEmptyEntries))
.TrimEnd('.');
applicationName = applicationName + "_G3D_Config.ini";
try
{
bool useHimaxD2XXDevices = true;
bool useHimaxRP2040Devices = true;
bool usePmdFlexxDevices = true;
libInterface = LibInterface.Instance;
libInterface.init(
calibrationPath,
Application.persistentDataPath,
applicationName,
this,
this,
this,
debugMessages,
useHimaxD2XXDevices,
useHimaxRP2040Devices,
usePmdFlexxDevices
);
}
catch (Exception e)
{
Debug.LogError("Failed to initialize library: " + e.Message);
return;
}
// set initial values
// intialize head position at focus distance from focus plane
headPosition = new HeadPosition
{
headDetected = false,
imagePosIsValid = false,
imagePosX = 0,
imagePosY = 0,
worldPosX = 0.0,
worldPosY = 0.0,
worldPosZ = -focusDistance
};
filteredHeadPosition = new HeadPosition
{
headDetected = false,
imagePosIsValid = false,
imagePosX = 0,
imagePosY = 0,
worldPosX = 0.0,
worldPosY = 0.0,
worldPosZ = -focusDistance
};
if (usePositionFiltering())
{
try
{
libInterface.initializePositionFilter(
headPositionFilter.x,
headPositionFilter.y,
headPositionFilter.z
);
}
catch (Exception e)
{
Debug.LogError("Failed to initialize position filter: " + e.Message);
}
}
}
private void deinitLibrary()
{
if (libInterface == null || !libInterface.isInitialized())
{
return;
}
try
{
libInterface.stopHeadTracking();
libInterface.unregisterHeadPositionChangedCallback(this);
libInterface.unregisterShaderParametersChangedCallback(this);
libInterface.unregisterMessageCallback(this);
libInterface.deinit();
}
catch (Exception e)
{
Debug.Log(e);
}
}
private void reinitializeShader()
{
if (mode == G3DCameraMode.MULTIVIEW)
{
material = new Material(Shader.Find("G3D/AutostereoMultiview"));
}
else
{
material = new Material(Shader.Find("G3D/Autostereo"));
}
}
#if G3D_URP
private void OnEnable()
{
RenderPipelineManager.beginCameraRendering += OnBeginCamera;
}
private void OnDisable()
{
RenderPipelineManager.beginCameraRendering -= OnBeginCamera;
}
private void OnBeginCamera(ScriptableRenderContext context, Camera cam)
{
// Use the EnqueuePass method to inject a custom render pass
cam.GetUniversalAdditionalCameraData().scriptableRenderer.EnqueuePass(customPass);
if (mainCamera.GetUniversalAdditionalCameraData().renderPostProcessing)
{
for (int i = 0; i < MAX_CAMERAS; i++)
{
cameras[i].GetUniversalAdditionalCameraData().renderPostProcessing = true;
}
}
}
#endif
#endregion
#region Updates
void Update()
{
// update the shader parameters (only in diorama mode)
if (mode == G3DCameraMode.DIORAMA)
{
libInterface.calculateShaderParameters(latencyCorrectionMode);
lock (shaderLock)
{
shaderParameters = libInterface.getCurrentShaderParameters();
}
}
bool cameraCountChanged = updateCameraCountBasedOnMode();
updateCameras();
updateShaderParameters();
bool screenSizeChanged = false;
if (windowResized() || windowMoved())
{
updateScreenViewportProperties();
screenSizeChanged = true;
}
if (
screenSizeChanged
|| cameraCountChanged
|| oldRenderResolutionScale != renderResolutionScale
)
{
oldRenderResolutionScale = renderResolutionScale;
updateShaderRenderTextures();
}
}
private void updateScreenViewportProperties()
{
Vector2Int displayResolution = getDisplayResolutionFromCalibrationFile();
if (mode == G3DCameraMode.MULTIVIEW)
{
shaderParameters.screenWidth = displayResolution.x;
shaderParameters.screenHeight = displayResolution.y;
shaderParameters.leftViewportPosition = Screen.mainWindowPosition.x;
shaderParameters.bottomViewportPosition = Screen.mainWindowPosition.y + Screen.height;
}
else
{
try
{
// This is the size of the entire monitor screen
libInterface.setScreenSize(displayResolution.x, displayResolution.y);
// this refers to the window in which the 3D effect is rendered (including eg windows top window menu)
libInterface.setWindowSize(Screen.width, Screen.height);
libInterface.setWindowPosition(
Screen.mainWindowPosition.x,
Screen.mainWindowPosition.y
);
// This refers to the actual viewport in which the 3D effect is rendered
libInterface.setViewportSize(Screen.width, Screen.height);
libInterface.setViewportOffset(0, 0);
}
catch (Exception e)
{
Debug.LogError("Failed to update screen viewport properties: " + e.Message);
}
}
// this parameter is used in the shader to invert the y axis
material?.SetInt(Shader.PropertyToID("viewportHeight"), Screen.height);
}
private void updateShaderParameters()
{
lock (shaderLock)
{
material?.SetInt(
shaderHandles.leftViewportPosition,
shaderParameters.leftViewportPosition
);
material?.SetInt(
shaderHandles.bottomViewportPosition,
shaderParameters.bottomViewportPosition
);
material?.SetInt(shaderHandles.screenWidth, shaderParameters.screenWidth);
material?.SetInt(shaderHandles.screenHeight, shaderParameters.screenHeight);
material?.SetInt(shaderHandles.nativeViewCount, shaderParameters.nativeViewCount);
material?.SetInt(
shaderHandles.angleRatioNumerator,
shaderParameters.angleRatioNumerator
);
material?.SetInt(
shaderHandles.angleRatioDenominator,
shaderParameters.angleRatioDenominator
);
material?.SetInt(
shaderHandles.leftLensOrientation,
shaderParameters.leftLensOrientation
);
material?.SetInt(shaderHandles.mstart, shaderParameters.mstart);
// test frame and stripe
material?.SetInt(shaderHandles.showTestFrame, showTestFrame ? 1 : 0);
material?.SetInt(shaderHandles.showTestStripe, shaderParameters.showTestStripe);
material?.SetInt(shaderHandles.testGapWidth, shaderParameters.testGapWidth);
material?.SetInt(shaderHandles.track, shaderParameters.track);
material?.SetInt(shaderHandles.hqViewCount, shaderParameters.hqViewCount);
material?.SetInt(shaderHandles.hviews1, shaderParameters.hviews1);
material?.SetInt(shaderHandles.hviews2, shaderParameters.hviews2);
material?.SetInt(shaderHandles.blur, shaderParameters.blur);
material?.SetInt(shaderHandles.blackBorder, shaderParameters.blackBorder);
material?.SetInt(shaderHandles.blackSpace, shaderParameters.blackSpace);
material?.SetInt(shaderHandles.bls, shaderParameters.bls);
material?.SetInt(shaderHandles.ble, shaderParameters.ble);
material?.SetInt(shaderHandles.brs, shaderParameters.brs);
material?.SetInt(shaderHandles.bre, shaderParameters.bre);
material?.SetInt(shaderHandles.zCorrectionValue, shaderParameters.zCorrectionValue);
material?.SetInt(shaderHandles.zCompensationValue, shaderParameters.zCompensationValue);
material?.SetInt(shaderHandles.BGRPixelLayout, shaderParameters.BGRPixelLayout);
material?.SetInt(Shader.PropertyToID("cameraCount"), internalCameraCount);
material?.SetInt(Shader.PropertyToID("mirror"), mirrorViews ? 1 : 0);
if (mode == G3DCameraMode.MULTIVIEW)
{
material.SetInt(Shader.PropertyToID("indexMapLength"), indexMap.currentMap.Length);
material.SetFloatArray(
Shader.PropertyToID("index_map"),
indexMap.getPaddedIndexMapArray()
);
material?.SetInt(Shader.PropertyToID("viewOffset"), viewOffset);
}
else
{
if (invertViewsInDiorama)
{
material.SetInt(Shader.PropertyToID("invertViews"), 1);
}
else
{
material.SetInt(Shader.PropertyToID("invertViews"), 0);
}
}
}
}
void updateCameras()
{
Vector3 targetPosition = new Vector3(0, 0, -scaledFocusDistance);
; // position for the camera center (base position from which all other cameras are offset)
float targetViewSeparation = 0.0f;
// calculate the camera center position and eye separation if head tracking and the diorama effect are enabled
if (mode == G3DCameraMode.DIORAMA)
{
HeadPosition headPosition;
if (usePositionFiltering())
{
headPosition = getFilteredHeadPosition();
}
else
{
headPosition = getHeadPosition();
}
headtrackingHandler.handleHeadTrackingState(
ref headPosition,
ref targetPosition,
ref targetViewSeparation,
scaledViewSeparation,
scaledFocusDistance,
cameraParent.transform.localPosition
);
}
else if (mode == G3DCameraMode.MULTIVIEW)
{
targetViewSeparation = scaledViewSeparation;
}
cameraParent.transform.localPosition = targetPosition;
float horizontalOffset = targetPosition.x;
float verticalOffset = targetPosition.y;
float currentFocusDistance = -cameraParent.transform.localPosition.z;
float dollyZoomOffset = currentFocusDistance - currentFocusDistance * dollyZoom;
float focusDistanceWithDollyZoom = currentFocusDistance - dollyZoomOffset;
mainCamera.fieldOfView =
2
* Mathf.Atan(scaledHalfCameraWidthAtStart / focusDistanceWithDollyZoom)
* Mathf.Rad2Deg;
// set the camera parent position to the focus distance
cameraParent.transform.localPosition = new Vector3(
horizontalOffset,
verticalOffset,
-currentFocusDistance
);
//calculate camera positions and matrices
for (int i = 0; i < internalCameraCount; i++)