/
PointCloudViewerDX11.cs
1374 lines (1127 loc) · 43.1 KB
/
PointCloudViewerDX11.cs
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
// Point Cloud Binary Viewer DX11
// reads custom binary file and displays it with dx11 shader
// http://unitycoder.com
#if !UNITY_WEBPLAYER && !UNITY_SAMSUNGTV
using UnityEngine;
using System.IO;
using System.Threading;
using PointCloudHelpers;
using UnityEngine.Rendering;
using System.Runtime.InteropServices;
using System;
namespace unitycodercom_PointCloudBinaryViewer {
//[ExecuteInEditMode] // ** You can enable this, if you want to see DX11 cloud inside editor, without playmode NOTE: only works with V1 .bin and with threading disabled **
public class PointCloudViewerDX11 : MonoBehaviour {
[Header("Binary Source File")]
[Tooltip("Note: New v2 format uses .ucpc extension")]
public string fileName = "StreamingAssets/PointCloudViewerSampleData/sample.bin";
[Header("Settings")]
public bool loadAtStart = true;
public Material cloudMaterial;
[Tooltip("Create copy of the material. Must enable if viewing multiple clouds with same materials")]
public bool instantiateMaterial = false; // set True if using multiple viewers
[Tooltip("Load cloud at Start()")]
public bool useThreading = false;
public bool showDebug = false;
[Header("Visibility")]
public bool displayPoints = true;
[Tooltip("Enable this if you have multiple cameras and only want to draw in MainCamera")]
public bool renderOnlyMainCam = false;
[Header("Animated Point Clouds")]
public bool isAnimated = false; // Brekel binary cloud frames
public float playbackDelay = 0.025F;
// Brekel animated frames variables
private int[] numberOfPointsPerFrame;
private System.Int64[] frameBinaryPositionForEachFrame;
private Vector3[] animatedPointArray;
private Vector3[] animatedColorArray;
private int totalNumberOfPoints; // total from each frame
private int currentFrame = 0;
private int[] animatedOffset;
private float nextFrame = 0.0F;
private float[] byteArrayToFloats;
private Bounds cloudBounds;
private byte binaryVersion = 0;
private int numberOfFrames = 0;
[HideInInspector]
public bool containsRGB = false;
[HideInInspector]
public int totalPoints = 0;
[HideInInspector]
public int totalMaxPoints = 0; // new variable to keep total maximum point count
private ComputeBuffer bufferPoints;
//private ComputeBuffer bufferPointsDepth;
private ComputeBuffer bufferColors;
internal Vector3[] points; // actual point cloud points array
internal Vector3[] pointColors;
private Vector3 dataColor;
private float r, g, b;
private bool isLoading = false;
private bool haveError = false;
bool isLoadingNewData = false;
// Threading
bool abortReaderThread = false;
Thread importerThread;
// events
public delegate void OnLoadComplete(string filename);
public event OnLoadComplete OnLoadingComplete;
[Header("Experimental")]
[Tooltip("Shuffle points to use dynamic resolution adjuster *Cannot use if ReadCachedFile is enabled. **V2+ formats are usually already randomized")]
public bool randomizeArray = false;
[Tooltip("[v1 & v2 format only] Pack colors for GPU (Note: Use V4-packed material)")]
public bool packColors = false;
//[Tooltip("Pack colors for GPU (Note: Use V4-packed2 material) *Not working yet")]
//public bool packColors2 = false;
[Tooltip("[v2 format only] Read whole cloud (initialPointsToRead value is ignored)")]
public bool readWholeCloud = true;
[Tooltip("[v2 format only] Read only this many points initially")]
public int initialPointsToRead = 1000000;
[HideInInspector] public bool isNewFormat = false;
private Camera cam;
// Added by Scott Timmermans to accomodate a custom loading screen
private LoadingScreen loadingScreen;
[Header("Rendering")]
[Tooltip("Draw using CommandBuffer instead of OnRenderObject")]
public bool useCommandBuffer = false;
[Tooltip("Default value: AfterForwardOpaque")]
public CameraEvent camDrawPass = CameraEvent.AfterForwardOpaque;
internal CommandBuffer commandBuffer;
public bool forceDepthBufferPass = false;
Material depthMaterial;
[Tooltip("Changing CameraEvent takes effect only at Start(). Default value: AfterDepthTexture")]
public CameraEvent camDepthPass = CameraEvent.AfterDepthTexture;
#if UNITY_EDITOR
[Tooltip("Forces CommandBuffer to be rendered in Scene window also")]
public bool commandBufferToSceneCamera = false;
#endif
internal CommandBuffer commandBufferDepth;
Vector3 transformPos;
Matrix4x4 Matrix4x4identity = Matrix4x4.identity;
[Header("Caching")]
[Tooltip("Save .bin file again (to include randomizing or other changes to data during load *Not supported for new V2 format)")]
public bool reSaveBinFile = false;
string applicationStreamingAssetsPath;
struct PackedPoint {
public float x;
public float y;
public float z;
};
void Awake() {
applicationStreamingAssetsPath = Application.streamingAssetsPath;
}
// init
void Start() {
transformPos = transform.position;
cam = Camera.main;
loadingScreen = GameObject.Find("LoadingScreen").GetComponent<LoadingScreen>();
if (useCommandBuffer == true) {
commandBuffer = new CommandBuffer();
cam.AddCommandBuffer(camDrawPass, commandBuffer);
#if UNITY_EDITOR
if (commandBufferToSceneCamera == true)
UnityEditor.SceneView.GetAllSceneCameras()[0].AddCommandBuffer(camDrawPass, commandBuffer);
#endif
}
if (forceDepthBufferPass == true) {
depthMaterial = cloudMaterial;
commandBufferDepth = new CommandBuffer();
cam.AddCommandBuffer(camDepthPass, commandBufferDepth);
}
if (cam == null) { Debug.LogError("Camera main is missing..", gameObject); }
// create material clone, so can view multiple clouds
if (instantiateMaterial == true) {
cloudMaterial = new Material(cloudMaterial);
}
if (useThreading == true) {
// check if MainThread script exists in scene, its required only for threading
FixMainThreadHelper();
}
if (loadAtStart == true) {
if (useThreading == true) {
abortReaderThread = false;
CallReadPointCloudThreaded(fileName);
} else {
ReadPointCloud();
}
}
}
// ====================================== mainloop ======================================
void Update() {
if (isLoading == true || haveError == true)
return;
if (isAnimated == true) // animated point cloud frames (brekel, .bin)
{
if (Time.time > nextFrame) {
nextFrame = Time.time + playbackDelay;
System.Array.Copy(animatedPointArray, animatedOffset[currentFrame], points, 0, numberOfPointsPerFrame[currentFrame]);
bufferPoints.SetData(points);
if (bufferColors != null) {
System.Array.Copy(animatedColorArray, animatedOffset[currentFrame], pointColors, 0, numberOfPointsPerFrame[currentFrame]);
bufferColors.SetData(pointColors);
}
currentFrame = (++currentFrame) % numberOfFrames;
}
}
} // Update()
// binary point cloud reader *OLD, non-threaded
public void ReadPointCloud() {
Debug.LogWarning("This old non-threaded reader will be removed later.. public void ReadPointCloud()");
// if not full path, use streaming assets
if (Path.IsPathRooted(fileName) == false) {
fileName = Path.Combine(applicationStreamingAssetsPath, fileName);
}
if (PointCloudTools.CheckIfFileExists(fileName) == false) {
Debug.LogError("File not found:" + fileName);
haveError = true;
return;
}
Debug.Log("Reading pointcloud from: " + fileName);
if (isAnimated == true) {
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
ReadAnimatedPointCloud();
stopwatch.Stop();
Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
stopwatch.Reset();
return;
}
isLoading = true;
// new loader reads whole file at once
byte[] data;
try {
data = File.ReadAllBytes(fileName);
}
catch {
Debug.LogError(fileName + " cannot be opened with ReadAllBytes(), it might be too large >2gb");
return;
}
System.Int32 byteIndex = 0;
int binaryVersion = data[byteIndex];
byteIndex += sizeof(System.Byte);
if (binaryVersion > 1) {
Debug.LogError("File binaryVersion should have value (0) or (1). Loading cancelled... founded:" + binaryVersion + " (Is this animated cloud instead?)");
return;
}
totalPoints = System.BitConverter.ToInt32(data, byteIndex);
byteIndex += sizeof(System.Int32);
containsRGB = System.BitConverter.ToBoolean(data, byteIndex);
byteIndex += sizeof(System.Boolean);
points = new Vector3[totalPoints];
Debug.Log("Loading " + totalPoints + " points..");
float x, y, z;
float minX = Mathf.Infinity;
float minY = Mathf.Infinity;
float minZ = Mathf.Infinity;
float maxX = Mathf.NegativeInfinity;
float maxY = Mathf.NegativeInfinity;
float maxZ = Mathf.NegativeInfinity;
if (containsRGB == true)
pointColors = new Vector3[totalPoints];
var byteSize = sizeof(System.Single);
byteArrayToFloats = new float[(data.Length - byteIndex) / 4];
System.Buffer.BlockCopy(data, byteIndex, byteArrayToFloats, 0, data.Length - byteIndex);
int dataIndex = 0;
for (int i = 0; i < totalPoints; i++) {
x = byteArrayToFloats[dataIndex];
dataIndex++;
byteIndex += byteSize; // not used!
y = byteArrayToFloats[dataIndex];
dataIndex++;
byteIndex += byteSize;
z = byteArrayToFloats[dataIndex];
dataIndex++;
byteIndex += byteSize;
// need to move rgb after xyz
if (containsRGB == true) {
r = byteArrayToFloats[dataIndex];
dataIndex++;
g = byteArrayToFloats[dataIndex];
dataIndex++;
b = byteArrayToFloats[dataIndex];
dataIndex++;
pointColors[i].Set(r, g, b);
}
points[i].Set(x, y, z);
// get bounds
if (x < minX)
minX = x;
if (x > maxX)
maxX = x;
if (y < minY)
minY = y;
if (y > maxY)
maxY = y;
if (z < minZ)
minZ = z;
if (z > maxZ)
maxZ = z;
}
// for testing load timer
// stopwatch.Stop();
// Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
// stopwatch.Reset();
totalMaxPoints = totalPoints;
cloudBounds = new Bounds(new Vector3((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, (minZ + maxZ) * 0.5f), new Vector3((maxX - minX), (maxY - minY), (maxZ - minZ)));
if (randomizeArray == true) {
PointCloudTools.Shuffle(new System.Random(), ref points, ref pointColors);
Debug.Log("Randomizing array: Done");
}
InitDX11Buffers();
isLoading = false;
OnLoadingCompleteCallBack(fileName);
Debug.Log("Finished loading..");
}
public void CallReadPointCloudThreaded(string fullPath) {
if (Path.IsPathRooted(fullPath) == false) {
fullPath = Path.Combine(applicationStreamingAssetsPath, fullPath);
}
transformPos = transform.position;
// TEMP, needed later in loader, should pass instead
fileName = fullPath;
if (PointCloudTools.CheckIfFileExists(fullPath) == false) {
Debug.LogError("File not found:" + fullPath);
return;
}
if (Path.GetExtension(fullPath).ToLower() != ".bin" && Path.GetExtension(fullPath).ToLower() != ".ucpc") {
Debug.LogError("File is not v1 or v2 file (.bin or .ucpc extension is required) : " + Path.GetExtension(fullPath).ToLower());
return;
}
if (!isLoadingNewData) {
Debug.Log("(Viewer) Reading threaded pointcloud file: " + fullPath, gameObject);
loadingScreen.EnableLoadingScreen();
loadingScreen.SetStatusTextThread("Reading pointcloud file: " + fullPath);
loadingScreen.SetTargetProgressBarValue(.25f);
}
// pass in filename
//ThreadReaderInfo threadReaderData = new ThreadReaderInfo();
//threadReaderData.fileName = fullPath;
//ThreadPool.QueueUserWorkItem(new WaitCallback(ReadPointCloudThreaded), threadReaderData);
ParameterizedThreadStart start = new ParameterizedThreadStart(ReadPointCloudThreaded);
//Debug.Log(Path.GetExtension(fullPath).ToLower());
if (Path.GetExtension(fullPath).ToLower() == ".ucpc") {
if (isAnimated == true) {
Debug.LogError("Reading Animated Point Clouds in Separate thread is not supported");
return;
}
start = new ParameterizedThreadStart(ReadPointCloudThreadedNew);
isNewFormat = true;
} else {
start = new ParameterizedThreadStart(ReadPointCloudThreaded);
isNewFormat = false;
}
importerThread = new Thread(start);
importerThread.IsBackground = true;
importerThread.Start(fullPath);
// TODO need to close previous thread before loading new!
}
// v2 format
public void ReadPointCloudThreadedNew(System.Object a) {
if (showDebug) {
stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
}
isLoading = true;
byte[] headerdata = null;
byte[] dataPoints = null;
byte[] dataColors = null;
try {
// load header
// load x amount of points and colors
using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
using (BufferedStream bs = new BufferedStream(fs))
using (BinaryReader binaryReader = new BinaryReader(bs)) {
int headerSizeTemp = 34;
headerdata = new byte[headerSizeTemp];
headerdata = binaryReader.ReadBytes(headerSizeTemp);
int byteIndexTemp = 4 + 1 + 1;
/*
int binaryVersionTemp = headerdata[byteIndexTemp];
byteIndexTemp += sizeof(System.Byte);
Debug.Log("(header) binaryVersionTemp:" + binaryVersionTemp);
int rgbTemp = headerdata[byteIndexTemp];
byteIndexTemp += sizeof(System.Byte);
Debug.Log("(header) rgbTemp:" + rgbTemp);
*/
totalPoints = (int)System.BitConverter.ToInt32(headerdata, byteIndexTemp);
long totalMaxPointsTemp = totalPoints;
Debug.Log("(header) totalPoints:" + totalPoints);
byteIndexTemp += sizeof(System.Int32);
if (readWholeCloud == true) {
initialPointsToRead = totalPoints;
} else {
totalPoints = Mathf.Clamp(initialPointsToRead, 0, totalPoints);
}
//Debug.Log("initialPointsToRead="+ initialPointsToRead);
int pointsChunkSize = totalPoints * (4 + 4 + 4);
//Debug.Log("pointsChunkSize=" + pointsChunkSize);
//int colorsChunkSize = initialPointsToRead * (4 + 4 + 4);
//dataPoints = new byte[initialPointsToRead];
//dataPoints = new byte[2130702268];
dataPoints = binaryReader.ReadBytes(pointsChunkSize);
//Debug.Log("dataPoints=" + dataPoints.Length);
//Debug.Log(binaryReader.BaseStream.Position);
// jump to colors
binaryReader.BaseStream.Flush();
binaryReader.BaseStream.Position = (long)(totalMaxPointsTemp * (4 + 4 + 4) + headerdata.Length);
//Debug.Log(binaryReader.BaseStream.Position);
// dataColors = new byte[initialPointsToRead];
dataColors = binaryReader.ReadBytes(pointsChunkSize);
//Debug.Log("dataColors=" + dataColors.Length);
}
}
catch (Exception e) {
Debug.LogException(e);
Debug.LogError(fileName + " cannot be opened, its probably too large.. Test with [x] Load Limited amount (max 178m), or try splitting your data into smaller parts (using external point cloud editing tools)");
return;
}
System.Int32 byteIndex = 0;
// magic
var magic = new byte[] { headerdata[byteIndex++], headerdata[byteIndex++], headerdata[byteIndex++], headerdata[byteIndex++] };
if (showDebug)
Debug.Log("magic=" + System.Text.Encoding.ASCII.GetString(magic));
int binaryVersion = headerdata[byteIndex];
byteIndex += sizeof(System.Byte);
if (showDebug)
Debug.Log("binaryVersion=" + binaryVersion);
// check format
if (binaryVersion != 2) {
Debug.LogError("File binaryVersion should have value (2). Was " + binaryVersion + " - Loading cancelled.");
return;
}
containsRGB = System.BitConverter.ToBoolean(headerdata, byteIndex);
byteIndex += sizeof(System.Boolean);
if (containsRGB == false) {
if (isNewFormat == true) {
Debug.LogError("v2 format requires RGB data - loading cancelled");
return;
} else {
Debug.LogWarning("No RGB data in the file, cloud will be black..");
}
}
if (showDebug)
Debug.Log("containsRGB=" + containsRGB);
totalPoints = (int)System.BitConverter.ToInt32(headerdata, byteIndex);
totalMaxPoints = totalPoints;
byteIndex += sizeof(System.Int32);
//Debug.Log("totalPoints=" + totalPoints);
//if (showDebug) Debug.Log("totalPoints from file=" + totalPoints);
// TEST load initially less points
totalPoints = (int)Mathf.Clamp(initialPointsToRead, 0, totalPoints);
//if (showDebug) Debug.Log("totalPoints after clamp=" + totalPoints);
// bounds
float minX = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
float minY = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
float minZ = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
float maxX = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
float maxY = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
float maxZ = System.BitConverter.ToSingle(headerdata, byteIndex);
byteIndex += sizeof(System.Single);
cloudBounds = new Bounds(new Vector3((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, (minZ + maxZ) * 0.5f), new Vector3((maxX - minX), (maxY - minY), (maxZ - minZ)));
points = new Vector3[totalPoints];
if (showDebug)
Debug.Log("cloudBounds=" + cloudBounds);
if (showDebug && !isLoadingNewData)
Debug.Log("Loading new (V2) format: " + totalPoints + " points..");
GCHandle vectorPointer = GCHandle.Alloc(points, GCHandleType.Pinned);
IntPtr pV = vectorPointer.AddrOfPinnedObject();
Marshal.Copy(dataPoints, 0, pV, totalPoints * 4 * 3);
vectorPointer.Free();
if (containsRGB == true) {
pointColors = new Vector3[totalPoints];
var vectorPointer2 = GCHandle.Alloc(pointColors, GCHandleType.Pinned);
var pV2 = vectorPointer2.AddrOfPinnedObject();
Marshal.Copy(dataColors, 0, pV2, totalPoints * 4 * 3);
vectorPointer2.Free();
}
//memcpy(dstData.Scan0, srcData.Scan0, new UIntPtr((uint)height * (uint)srcData.Stride));
// 2018.x
// UnsafeUtility.MemCpyStride
// for testing load timer
// stopwatch.Stop();
// Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
// stopwatch.Reset();
//totalMaxPoints = totalPoints;
// if randomize enabled, and didnt read from cache, then randomize
if (randomizeArray == true) {
if (showDebug)
Debug.Log("Randomizing cloud..");
PointCloudTools.Shuffle(new System.Random(), ref points, ref pointColors);
}
// refresh buffers
UnityLibrary.MainThread.Call(InitDX11Buffers);
while (isInitializingBuffers == true && abortReaderThread == false) {
Thread.Sleep(1);
}
// NOTE: disabled this, was it needed?
//UnityLibrary.MainThread.Call(UpdatePointData);
//if (containsRGB == true) UnityLibrary.MainThread.Call(UpdateColorData);
// if caching, save as bin (except if already read from cache)
// TODO dont save if no changes to data
// TODO move to separate method, so can call save anytime, if modify or remove points manually
if (reSaveBinFile == true) {
if (isNewFormat == true) {
Debug.LogError("Cannot use reSaveBinFile with new V2 format");
} else {
var outputFile = fileName;
Debug.Log("saving " + fileName);
BinaryWriter writer = null;
try {
writer = new BinaryWriter(File.Open(outputFile, FileMode.Create));
}
catch (System.Exception e) {
Debug.LogException(e);
}
if (writer == null) {
Debug.LogError("Cannot output file: " + outputFile);
return;
}
writer.Write((byte)binaryVersion);
writer.Write((System.Int32)totalMaxPoints);
writer.Write(containsRGB);
for (int i = 0, length = points.Length; i < length; i++) {
writer.Write(points[i].x);
writer.Write(points[i].y);
writer.Write(points[i].z);
if (containsRGB == true) {
writer.Write(pointColors[i].x);
writer.Write(pointColors[i].y);
writer.Write(pointColors[i].z);
}
}
writer.Close();
Debug.Log("Finished saving cached file: " + outputFile);
} // cache
}
isLoading = false;
UnityLibrary.MainThread.Call(OnLoadingCompleteCallBack, fileName);
//data = null;
if (!isLoadingNewData)
Debug.Log("Finished Loading: " + initialPointsToRead + " / " + totalMaxPoints);
if (showDebug) {
stopwatch.Stop();
//Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
// 2243ms for 25m
// 3528ms for 50m > 2900ms (no .set)
// 380ms for 50m (new format)
stopwatch.Reset();
}
isLoadingNewData = false;
} // ReadPointCloudThreaded
System.Diagnostics.Stopwatch stopwatch;
// binary point cloud reader (using separate thread)
public void ReadPointCloudThreaded(System.Object a) {
if (isAnimated == true) {
Debug.LogError("Reading Animated Point Clouds in Separate thread is not supported");
haveError = true;
return;
}
// for testing loading times
if (showDebug) {
stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
}
isLoading = true;
byte[] data;
try {
data = File.ReadAllBytes(fileName);
}
catch {
Debug.LogError(fileName + " cannot be opened with ReadAllBytes(), it might be too large >2gb. Try splitting your data into smaller parts (using external point cloud editing tools)");
/*
// try reading in smaller parts
long fileSize = new System.IO.FileInfo(fileName).Length;
try
{
data = new byte[fileSize];
}
catch (System.Exception)
{
}
finally
{
Debug.LogError("File is too large, cannot create array: " + fileSize);
}
FileStream sourceFile = new FileStream(fileName, FileMode.Open);
BinaryReader reader = new BinaryReader(sourceFile);
reader.Close();
sourceFile.Close();
*/
return;
}
System.Int32 byteIndex = 0;
int binaryVersion = data[byteIndex];
byteIndex += sizeof(System.Byte);
// check format
if (binaryVersion > 1) {
Debug.LogError("File binaryVersion should have value (0-1). Was " + binaryVersion + " - Loading cancelled.");
return;
}
totalPoints = (int)System.BitConverter.ToInt32(data, byteIndex);
byteIndex += sizeof(System.Int32);
//Debug.Log(totalPoints);
containsRGB = System.BitConverter.ToBoolean(data, byteIndex);
byteIndex += sizeof(System.Boolean);
// TEST
//totalPoints = totalPoints * 2;
points = new Vector3[totalPoints];
Debug.Log("Loading old format: " + totalPoints + " points..");
loadingScreen.SetStatusTextThread("Loading Points: " + totalPoints.ToString() + " points...");
loadingScreen.SetTargetProgressBarValue(.5f);
float x, y, z;
float minX = Mathf.Infinity;
float minY = Mathf.Infinity;
float minZ = Mathf.Infinity;
float maxX = Mathf.NegativeInfinity;
float maxY = Mathf.NegativeInfinity;
float maxZ = Mathf.NegativeInfinity;
if (containsRGB == true)
pointColors = new Vector3[totalPoints];
byteArrayToFloats = new float[(data.Length - byteIndex) / 4];
System.Buffer.BlockCopy(data, byteIndex, byteArrayToFloats, 0, data.Length - byteIndex);
int dataIndex = 0;
for (int i = 0; i < totalPoints; i++) {
x = byteArrayToFloats[dataIndex] + transformPos.x;
dataIndex++;
y = byteArrayToFloats[dataIndex] + transformPos.y;
dataIndex++;
z = byteArrayToFloats[dataIndex] + transformPos.z;
dataIndex++;
points[i].x = x;
points[i].y = y;
points[i].z = z;
// get bounds
if (x < minX)
minX = x;
else if (x > maxX)
maxX = x;
//((x < minX) ? ref minX : ref maxX) = x; // c#7
if (y < minY)
minY = y;
else if (y > maxY)
maxY = y;
if (z < minZ)
minZ = z;
else if (z > maxZ)
maxZ = z;
if (containsRGB == true) {
r = byteArrayToFloats[dataIndex];
dataIndex++;
g = byteArrayToFloats[dataIndex];
dataIndex++;
b = byteArrayToFloats[dataIndex];
dataIndex++;
pointColors[i].x = r;
pointColors[i].y = g;
pointColors[i].z = b;
}
if (abortReaderThread == true) {
return;
}
} // for all points
// for testing load timer
// stopwatch.Stop();
// Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
// stopwatch.Reset();
cloudBounds = new Bounds(new Vector3((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, (minZ + maxZ) * 0.5f), new Vector3((maxX - minX), (maxY - minY), (maxZ - minZ)));
totalMaxPoints = totalPoints;
// if randomize enabled, and didnt read from cache, then randomize
if (randomizeArray == true) {
if (showDebug)
Debug.Log("Randomizing cloud..");
PointCloudTools.Shuffle(new System.Random(), ref points, ref pointColors);
}
// refresh buffers
UnityLibrary.MainThread.Call(InitDX11Buffers);
// NOTE: disabled this, was it needed?
//UnityLibrary.MainThread.Call(UpdatePointData);
//if (containsRGB == true) UnityLibrary.MainThread.Call(UpdateColorData);
// if caching, save as bin (except if already read from cache)
// TODO dont save if no changes to data
// TODO move to separate method, so can call save anytime, if modify or remove points manually
if (reSaveBinFile == true) {
if (isNewFormat == true) {
Debug.LogError("Cannot use reSaveBinFile with new V2 format");
} else {
var outputFile = fileName; // Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fileName) + "-cached.bin";
Debug.Log("saving cached file: " + fileName);
BinaryWriter writer = null;
try {
writer = new BinaryWriter(File.Open(outputFile, FileMode.Create));
}
catch (System.Exception e) {
Debug.LogException(e);
}
if (writer == null) {
Debug.LogError("Cannot output file: " + outputFile);
return;
}
writer.Write((byte)binaryVersion);
writer.Write((System.Int32)totalMaxPoints);
writer.Write(containsRGB);
for (int i = 0, length = points.Length; i < length; i++) {
writer.Write(points[i].x);
writer.Write(points[i].y);
writer.Write(points[i].z);
if (containsRGB == true) {
writer.Write(pointColors[i].x);
writer.Write(pointColors[i].y);
writer.Write(pointColors[i].z);
}
}
writer.Close();
Debug.Log("Finished saving cached file: " + outputFile);
}
} // cache
isLoading = false;
UnityLibrary.MainThread.Call(OnLoadingCompleteCallBack, fileName);
data = null;
Debug.Log("Finished Loading.");
loadingScreen.SetStatusTextThread("Finished Loading");
loadingScreen.SetTargetProgressBarValue(1f);
loadingScreen.DisableAfterSecondsThread(.5f);
if (showDebug) {
stopwatch.Stop();
Debug.Log("Timer: " + stopwatch.ElapsedMilliseconds + "ms");
// 2243ms for 25m
// 3528ms for 50m > 2900ms (no .set)
stopwatch.Reset();
}
} // ReadPointCloudThreaded
void ReadNewFormat() {
}
// For Brekel animated binary data only
void ReadAnimatedPointCloud() {
if (isAnimated == false) {
Debug.LogWarning("ReadAnimatedPointCloud() called, but isAnimated = false");
return;
}
isLoading = true;
int totalCounter = 0;
// check file size
long fileSize = new System.IO.FileInfo(fileName).Length;
//Debug.Log("fileSize=" + fileSize);
var tempPoint = Vector3.zero;
var tempColor = Vector3.zero;
byte[] data = null;
if (fileSize >= 2147483647) {
// large file
FileStream sourceFile = new FileStream(fileName, FileMode.Open);
BinaryReader reader = new BinaryReader(sourceFile);
// parse header data
System.Int32 byteIndex = 0;
binaryVersion = reader.ReadByte();
byteIndex += sizeof(System.Byte);
if (binaryVersion != 2) { Debug.LogError("For Animated point cloud, file binaryVersion should have value (2) or bigger. received=" + binaryVersion); isAnimated = false; return; }
numberOfFrames = reader.ReadInt32();
byteIndex += sizeof(System.Int32);
//int frameRate = (int)reader.ReadSingle();
byteIndex += sizeof(System.Single);
containsRGB = reader.ReadBoolean();
byteIndex += sizeof(System.Boolean);
numberOfPointsPerFrame = new int[numberOfFrames];
totalPoints = 0; // TODO: rename to pointsPerFrame
for (int i = 0; i < numberOfFrames; i++) {
numberOfPointsPerFrame[i] = reader.ReadInt32();
byteIndex += sizeof(System.Int32);
if (numberOfPointsPerFrame[i] > totalPoints)
totalPoints = numberOfPointsPerFrame[i]; // largest value will be used as a fixed size for point array
totalNumberOfPoints += numberOfPointsPerFrame[i];
}
frameBinaryPositionForEachFrame = new System.Int64[numberOfFrames];
for (int i = 0; i < numberOfFrames; i++) {
frameBinaryPositionForEachFrame[i] = reader.ReadInt64();
byteIndex += sizeof(System.Int64);
}
Debug.Log("totalNumberOfPoints: " + totalNumberOfPoints);
// init playback arrays
animatedPointArray = new Vector3[totalNumberOfPoints];
if (containsRGB == true)
animatedColorArray = new Vector3[totalNumberOfPoints];
//Debug.Log("binaryVersion:" + binaryVersion);
//Debug.Log("numberOfFrames:" + numberOfFrames);
//Debug.Log("frameRate:"+frameRate);
//Debug.Log("containsRGB:" + containsRGB);
//Debug.Log("numberOfPointsPerFrame[0]:" + numberOfPointsPerFrame[0]);
//Debug.Log("frameBinaryPositionForEachFrame[0]:" + frameBinaryPositionForEachFrame[0]);
points = new Vector3[totalPoints];
animatedOffset = new int[numberOfFrames];
if (containsRGB == true)
pointColors = new Vector3[totalPoints];
// main binary reader loop
var sizeOfSingle = sizeof(System.Single);
for (int frame = 0; frame < numberOfFrames; frame++) {
animatedOffset[frame] = totalCounter;
// read all points for frame
var bytesToRead = numberOfPointsPerFrame[frame] * 3 * sizeOfSingle;
if (containsRGB == true)
bytesToRead += numberOfPointsPerFrame[frame] * 3 * sizeOfSingle;
var bytes = reader.ReadBytes(bytesToRead);
byteIndex = 0;
for (int i = 0; i < numberOfPointsPerFrame[frame]; i++) {
tempPoint.x = System.BitConverter.ToSingle(bytes, byteIndex) + transformPos.x;
byteIndex += sizeOfSingle;
tempPoint.y = System.BitConverter.ToSingle(bytes, byteIndex) + transformPos.y;
byteIndex += sizeOfSingle;
tempPoint.z = System.BitConverter.ToSingle(bytes, byteIndex) + transformPos.z;
byteIndex += sizeOfSingle;
animatedPointArray[totalCounter] = tempPoint;
if (containsRGB == true) {
tempColor.x = System.BitConverter.ToSingle(bytes, byteIndex);
byteIndex += sizeOfSingle;
tempColor.y = System.BitConverter.ToSingle(bytes, byteIndex);
byteIndex += sizeOfSingle;
tempColor.z = System.BitConverter.ToSingle(bytes, byteIndex);
byteIndex += sizeOfSingle;
animatedColorArray[totalCounter] = tempColor;
}
totalCounter++;
}
}
sourceFile.Close(); //dispose streamer
reader.Close(); //dispose reader
} else // can read with allbytes
{
data = File.ReadAllBytes(fileName);
if (data.Length < 1) {
Debug.LogError("ReadAnimatedPointCloud() called, but isAnimated = false");
return;
}
// parse header data
System.Int32 byteIndex = 0;
binaryVersion = data[byteIndex];
if (binaryVersion != 2) { Debug.LogError("For Animated point cloud, file binaryVersion should have value (2) or bigger. received=" + binaryVersion); isAnimated = false; return; }
byteIndex += sizeof(System.Byte);
numberOfFrames = (int)System.BitConverter.ToInt32(data, byteIndex);
byteIndex += sizeof(System.Int32);
// frameRate = System.BitConverter.ToSingle(data,byteIndex); // not used
byteIndex += sizeof(System.Single);
containsRGB = System.BitConverter.ToBoolean(data, byteIndex);
byteIndex += sizeof(System.Boolean);
numberOfPointsPerFrame = new int[numberOfFrames];
totalPoints = 0;
for (int i = 0; i < numberOfFrames; i++) {
numberOfPointsPerFrame[i] = (int)System.BitConverter.ToInt32(data, byteIndex);
//Debug.Log(numberOfPointsPerFrame[i]);
byteIndex += sizeof(System.Int32);
if (numberOfPointsPerFrame[i] > totalPoints)