-
Notifications
You must be signed in to change notification settings - Fork 2
/
ConsoleApp.hpp
3833 lines (3305 loc) · 119 KB
/
ConsoleApp.hpp
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
#pragma once
// LIPScan3D ConsoleApp.cpp : 此檔案包含 'main' 函式。程式會於該處開始執行及結束執行。
//
#include <string>
#include <iostream>
#include <filesystem>
#include <windows.h>
#include <stdio.h>
#include <direct.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#pragma region//LIPScan3D SDK console application, eason-20210813//
#include "configParser.h"
#include "lips_camera.h"
#include "lips_camera_set.h"
#include "lips_scanner.h"
#include "lips_scanner_set.h"
#include "lips_object3d.h"
#include "lips_model_edit.h"
#include "algorithm.h"
#ifdef LIPS_CLOUDCOMPARE
#include "lips_cloud_compare.h"
#endif
using namespace std;
using namespace lips;
#define LIPSCAN3D_PROCESS
#define DEPTH_TO_POINT
#define DepthEvaluation
#define ICP_3D
#define FINISH_3DSCAN
#define VIEWER_CAMERA
#define VIEWER_3DSCAN
#define MESHCOMPARISON_COLORGAUGE
#define DEFECTS_2D_DETECTION
#pragma region Process const char array
typedef std::uint64_t hash_t;
constexpr hash_t prime = 0x100000001B3ull;
constexpr hash_t basis = 0xCBF29CE484222325ull;
hash_t hash_(char const* str)
{
hash_t ret{ basis };
while (*str) {
ret ^= *str;
ret *= prime;
str++;
}
return ret;
}
constexpr hash_t hash_compile_time(char const* str, hash_t last_value = basis)
{
return *str ? hash_compile_time(str + 1, (*str ^ last_value) * prime) : last_value;
}
#pragma endregion
// Configurations of Realsense Camera
bool FirstRun = true;
char RootDirectory[512];
typedef vector<string> RealsenseCfgVector;
typedef map<lips::RangeParam_lib, RealsenseCfgVector> Scan3dCfgMap;
typedef struct SIZE_MODE_CONFIG
{
string scanner;
string realsense;
};
typedef std::map<string, SIZE_MODE_CONFIG> SIZE_MODE_CONFIG_MAP;
SIZE_MODE_CONFIG_MAP camera_cfg_map;
SIZE_MODE_CONFIG_MAP Init3DscanConfig(const char* rootdir, const char* devicename, const char* resolution);
// Object for Implement stereo 3D reconstruction
bool connect_camera;
int camera_slot;
string camera_resolution = "1280x720"; //Default
char* camera_devicename = new char[100];
int frame_width;
int frame_height;
string gScan_mode = "medium"; //Default
lips::RangeParam_lib gScan_range = lips::RangeParam_lib::RangeParam_lib_MEDIUM; //default scan mode: 25~40 cm
lips::Camera* gCamera = NULL; //high-level API class of AE400
lips::DepthmapProcess* gDepthpostproc = NULL; // depth image post-rocessing API class
lips::ScannerProcess gReconstructor; //point cloud registraion & triangulation API class
lips::Rect frame_roi;
cv::Rect cv_frame_roi;
//--- Initialize & Release LIPScan 3D SDK ---
bool InitLIPScan3D(char*, int&, int&); //Initialize API object
void ReleaseLIPScan3D(void); //Release API object
//--- Export Camera Frame ---
int FrameCount = 0;
bool dirExists(const std::string& path);
void SaveCameraScannerFrames(void);
//--- 3D Scan off-line Process---
unsigned int ColorTable[256];
void InitDepthToColorTable(void);
void DepthToColor(unsigned short*, unsigned char*, int, int);
void ImportCameraRawData(char*, char*, char*, unsigned char*, unsigned short*, float*, int, int);
HandleTriMeshModel Scan3D_Offline_Process(char*, int, int, int);
//--- Automatically cycling 3D scan process ---
UINT trigger_count;
BOOL trigger_scan_3D;
BOOL finish_scan_3D;
char localtime_str[512];
double scan_3D_duration;
HANDLE auto_cycling_scan3D_thread_handle = NULL;
DWORD auto_cycling_scan3D_ExitCode;
DWORD __stdcall auto_cycling_scan3D_ThreadProc(void);
//--- Variables for 3D reconstruction ---
float* points_data; // Depth data in real world coordinate
//--- Variables for Display Camera Frame ---
IplImage* color_img;
IplImage* depth_output;
IplImage* depth_img; // RGB scale of depth image
unsigned char* color_map = NULL; // RGB image buffer
unsigned short* depth_data = NULL; // Depth image buffer
unsigned char* depth_map = NULL; // Pixel buffer for RGB scale of depth image
//--- Rotate Camera Images ---
void RotateDisplayImage(unsigned char*, int, int, int);
//--- Variables for Display Scanning Model Image -------
unsigned char* copy_color_map = NULL; //avoid bug of display image
IplImage* scan_img; // 3D Model image
unsigned char* scan_map = NULL; // 3D model image pixel data
//----- Variables for Access 3D mesh object ---------
bool bScanFinish = false;
lips::HandleTriMeshModel gHandle_obj3d = NULL; //handle for current 3D reconstruction
//----- OpenGL render mesh model -----
struct PrmLight
{
float Ambient[4];
float Diffuse[4];
float Specular[4];
float Position[4];
float SpotDirection[3];
float SpotExponent;
float SpotCutoff;
float ConstantAttenuation;
float LinearAttenuation;
float QuadraticAttenuation;
};
struct ORTHO_PROJECTION_POSITION
{
GLdouble left;
GLdouble right;
GLdouble bottom;
GLdouble top;
GLdouble znear;
GLdouble zfar;
};
PrmLight *m_pLight = new PrmLight;
ORTHO_PROJECTION_POSITION* orth_position = new ORTHO_PROJECTION_POSITION;
float pointMinHeightVertex[3];
float CameraTrans[3];
float CameraPos[3];
double CameraRotate[9];
double ScaleObj;
UINT RenderMode = 0; // 0:Color, 1:Mesh, 2:WireFrame
void InitGLCamera();
void InitLight(PrmLight *);
void SetLights(PrmLight *);
void ResetObjPosition(lips::HandleTriMeshModel*, int);
void ResetCameraView(float*, float*, double*, float);
void PrepareTransformation(lips::HandleTriMeshModel*, int);
void DrawGLScene(); //3D transformation API provided from liblipscan3d.lib
void ChangeCursor(HINSTANCE hinstance, LPCSTR cursor_name); //Display default cursor
void ChangeCursor_HourGlass(void); //Display hourglass cursor
//--- Mesh Data Buffer for OpenGL rendering ----
struct MeshRenderBuffer
{
MeshRenderBuffer()
{
TriBuf = NULL;
P3dBuf = NULL;
NrmBuf = NULL;
ColorBuf = NULL;
SelBuf = NULL;
}
int TriNum;
int* TriBuf;
float* P3dBuf;
float* NrmBuf;
unsigned char* ColorBuf;
bool* SelBuf;
};
MeshRenderBuffer MeshBuf[10];
void PrepareRenderBuf(lips::HandleTriMeshModel, MeshRenderBuffer&);
void ReleaseRenderBuf(MeshRenderBuffer&);
void RenderMeshList(MeshRenderBuffer*, ORTHO_PROJECTION_POSITION*, int, size_t, bool, bool*);
#pragma region CLOUDCOMPARE_MENU
#ifdef LIPS_CLOUDCOMPARE
//--- define event for mesh comparison pop-up menu ---
#define SWM_ICP WM_APP + 3 // Fine registration (ICP)
#define SWM_DISTANCE WM_APP + 4 // Compute mesh distances
#define SWM_LOAD_COMPMESH WM_APP + 6 // Load Ref and Comp mesh file
#define SWM_LOAD_REFMESH WM_APP + 7 // Matching Point Pair Align
#define SWM_PICK_COMPMESH_POINTS WM_APP + 8
#define SWM_PICK_REFMESH_POINTS WM_APP + 9
#define SWM_MATCHING_POINT_PAIRS WM_APP + 10
#define SWM_EXPORT_MESHDISTANCE_HISTOGRAM WM_APP + 11
#define SWM_EXPORT_DISTANCERGB_MESH WM_APP + 12
#define SWM_CLEAR_COMPMESH_POINTS WM_APP + 13
#define SWM_CLEAR_REFMESH_POINTS WM_APP + 14
#define SWM_RESET_MESHCOMPARISON WM_APP + 15
#define SWM_POSE_COMPMESH WM_APP + 16
#define SWM_POSE_REFMESH WM_APP + 17
#define SWM_COMPMESH_VISIBILITY WM_APP + 18
#define SWM_REFMESH_VISIBILITY WM_APP + 19
#define SWM_RESET WM_APP + 20
#define SWM_COLORSCALE WM_APP + 21
#define SWM_SET_SCAN_COMPMESH WM_APP + 22 // Set Scan Data to Comp Mesh
//----------------------------------------------------
enum MeshComparisonState {
NONE,
LOAD,
POSE,
PICK,
ALIGN,
ICP,
COMPUTE,
EXPORT
};
unsigned int process_mode = 0; //0: 3D Scan, 1:Mesh Comparison
void PopUpMenu_MeshComparison(HWND, MeshComparisonState&, MeshComparison&); //Pop-up mesh for mesh comparison
lips::MeshComparison compare_mesh_tool; //mesh comparison
MeshComparisonState meshcomparer_status = MeshComparisonState::NONE; //status recorder
int ICP_criteria = -5;
int ICP_sampling_num = 50000;
bool bVisibleObj[10] = {0,0,0,0,0,0,0,0,0,0};
bool bTransformObj[10] = { 0,0,0,0,0,0,0,0,0,0 };
string opensavefilename(const char*, HWND, bool);
void load_comp_mesh(MeshComparison&);
void load_ref_mesh(MeshComparison&);
void clear_comp_mesh(MeshComparison&);
void clear_ref_mesh(MeshComparison&);
vector<string> colorscale_names;
unsigned int colorscale_index = 0;
int octree_projection = 0;
bool SelectTriangleAll(int, int, HandleTriMeshModel*, bool*, int, int *, int *, int *);
void ResetObjPositionAll();
void TranslateMeshCompareObj(float m_x, float m_y, float m_z);
void RotateMeshCompareObj(float m_x, float m_y, float m_z);
bool ResizeMeshObj(HandleTriMeshModel, float);
//--- Texture mapping of MeshComparison ---
#define GL_CLAMP_TO_EDGE 0x812F
typedef struct GL_POINT2D
{
int x;
int y;
};
typedef struct RENDER_IMAGE_LOCATION
{
GL_POINT2D p1;
GL_POINT2D p2;
};
ORTHO_PROJECTION_POSITION* orth_image_position = new ORTHO_PROJECTION_POSITION;
void RenderImageTexture(GLuint, ORTHO_PROJECTION_POSITION*, RENDER_IMAGE_LOCATION, int, int);
void ByteArrayToTexture(unsigned char*, GLuint*, int, int);
ColorScaleBar mesh_comparison_gauge;
GLuint lipscan_color_bar_texture;
GLuint* lipscan_color_bar_word_texture = NULL;
RENDER_IMAGE_LOCATION colorbar_word_render_location;
RENDER_IMAGE_LOCATION colorbar_render_location;
const char* csv_filter;
string csv_extension;
string csv_filename;
#endif
#pragma endregion
//--- Win32 window with OpenGL setting ---
LPCSTR main_window_title = NULL;
RECT WindowRect;
WNDCLASS wc;
DWORD dwExStyle;
DWORD dwStyle;
HWND hWnd = NULL;
HINSTANCE hInstance;
HICON main_icon = NULL;
HCURSOR stand_hcur = NULL;
HGLRC hGLRC = NULL;
HDC hDC = NULL;
GLuint PixelFormat;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
bool CreateWin32glWindow(LPCSTR);
int InitGL(GLvoid);
GLvoid ReSizeGLScene(GLsizei, GLsizei);
GLvoid KillGLWindow(GLvoid);
//--- Win32 openGL window interaction ---
bool mouseDownEvent = false;
POINT mouseDown;
POINT mouseUp;
float mouse_x, mouse_y, mouse_dx, mouse_dy;
bool MoveObj = false;
bool MouseMoveMode = false;
void PushMouse(float, float, float); //使用滑鼠平移
void RotateMouse(float, float); //使用滑鼠旋轉
//--- Export Mesh File ---
char Typename[256];
char main_name[256];
char open_model_filename[512];
//--- Information of Camera Stream ---
double fps;
double FPS();
//--- Information of 3D scan proceesing's FPS ---
UINT scan_count;
double scan_fps;
fstream cost_file;
//--- Window name for camera & scanner ---
string camera_color_wnd_name;
string camera_depth_wnd_name;
string scanner_wnd_name;
LPCSTR gl_wnd_name;
LPCSTR gl_wnd_name_cmpmesh;
//--- Win32 basic process ---
char* initalCurrentWorkDirectory(char * directory);
void terminateCurrentProcess();
HANDLE threadStart(HANDLE threadHandle, LPTHREAD_START_ROUTINE thread_function);
int ConsoleAppScript(int argc, char** argv)
{
#pragma region Check Device Connection
if (FirstRun) {
initalCurrentWorkDirectory(RootDirectory);
FirstRun = false;
}
bScanFinish = false;
gCamera = new lips::Camera(camera_slot, camera_devicename);
if (camera_slot == -1)
{
wstring title;
wstring text;
title = L"Error";
text = L"can't found camera";
MessageBoxW(NULL, text.c_str(), title.c_str(), MB_OK);
terminateCurrentProcess();
}
delete gCamera;
gCamera = NULL;
#pragma endregion
#pragma region Print Device Information
std::cout << "-------LIPScan 3D SDK console application--------" << endl;
std::cout << "Device Name : " << camera_devicename << endl;
#pragma endregion
#pragma region GUI for Camera and Scanner
#ifdef VIEWER_CAMERA
camera_color_wnd_name = "Camera Color Frame";
camera_depth_wnd_name = "Camera Depth Frame";
//cvNamedWindow(camera_color_wnd_name.c_str(), CV_WINDOW_AUTOSIZE);
//cvNamedWindow(camera_depth_wnd_name.c_str(), CV_WINDOW_AUTOSIZE);
#endif
#ifdef VIEWER_3DSCAN
scanner_wnd_name = "3D Reconstruction";
gl_wnd_name = "LIPScan3D 3D viewer";
//cvNamedWindow(scanner_wnd_name.c_str(), CV_WINDOW_AUTOSIZE);
#endif
#pragma endregion
#pragma region Choose Operation Mode
do {
std::cout << "Choose program mode by key-in corresponding number and press 'Enter'." << endl;
std::cout << "0 : 3D Scan" << endl;
std::cout << "1 : Mesh Comparison" << endl;
std::cout << "3 : Offline 3D Reconstruction" << endl;
//std::cout << "2 : Automatic cycling 3D Scan" << endl;
std::cin >> process_mode;
} while ( (process_mode!=0) && (process_mode!=1) && (process_mode!=3));
#pragma endregion
#pragma region 3D Scan Opearation
if (process_mode == 0 || process_mode == 2)
{
std::cout << "--- Start 3D Scan Operation ---" << endl;
#pragma region Read Realsense Configuration List
int scanner_resolution_idx = 0; // 1282x720 = 0, 640x480 = 1
switch (process_mode)
{
case 0:
#pragma region Manual Set Camera Resolution
//--- Choose Camera Resolution
do {
std::cout << "Chooose Camera resolution mode, Key in and press Enter : 1280x720 = 0, 640x480 = 1" << endl;
std::cin >> scanner_resolution_idx;
if (scanner_resolution_idx == 0)
{
camera_resolution = "1280x720";
//Message Hint for HD resolution 3D scan
std::string title = "HD resolution 3D scan";
std::string msg = "Please slow down scannig speed in HD resolution. Recommanded 40 seconds per revolution.";
MessageBox(NULL, msg.c_str(), title.c_str(), MB_OK);
}
else if (scanner_resolution_idx == 1)
camera_resolution = "640x480";
else
std::cout << "Out of range, please choose 0,1!" << endl;
} while (scanner_resolution_idx < 0 || scanner_resolution_idx > 1);
#pragma endregion
break;
case 2:
//--- Choose Camera Resolution for Automatically cycling scan 3D ---
do {
std::cout << "Chooose Camera resolution mode, Key in and press Enter : 1280x720 = 0, 640x480 = 1" << endl;
std::cin >> scanner_resolution_idx;
if (scanner_resolution_idx == 0)
camera_resolution = "1280x720";
else if (scanner_resolution_idx == 1)
camera_resolution = "640x480";
else
std::cout << "Out of range, please choose 0,1!" << endl;
} while (scanner_resolution_idx < 0 || scanner_resolution_idx > 1);
//camera_resolution = "640x480"; //HD resolution
std::cout << "Automatically 3D scan resolution = " << camera_resolution << endl;
break;
default:
std::cout << "Unexpected situation of camera resolution selection." << endl;
terminateCurrentProcess();
break;
}
camera_cfg_map = Init3DscanConfig(RootDirectory, camera_devicename, camera_resolution.c_str());
#pragma endregion
#pragma region Initialize LIPScan3D SDK
//--- Choose Scan 3D Range
int scanner_rgn_idx = 1; //default 'Medium' mode
switch (process_mode)
{
case 0: //
#pragma region Manually Choose 3D Scan Distance
if (strcmp(camera_devicename, "L210")) //Not L210
{
do {
std::cout << "Chooose Scan 3D range mode, Key in and press Enter : Small = 0, Medium = 1, Large = 2" << endl;
std::cin >> scanner_rgn_idx;
if (scanner_rgn_idx < 0 || scanner_rgn_idx > 2)
std::cout << "Out of range, please choose 0,1,2!" << endl;
} while (scanner_rgn_idx < 0 || scanner_rgn_idx > 2);
}
else //L210
{
do {
std::cout << "Chooose Scan 3D range mode, Key in and press Enter : Medium = 1, Large = 2" << endl;
std::cin >> scanner_rgn_idx;
if (scanner_rgn_idx < 1 || scanner_rgn_idx > 2)
std::cout << "Out of range, please choose 0,1,2!" << endl;
} while (scanner_rgn_idx < 1 || scanner_rgn_idx > 2);
}
#pragma endregion
break;
case 2:
//--- Choose Scan 3D Range for automatically cycling scan3D ---
if (strcmp(camera_devicename, "L210")) //Not L210
{
do {
std::cout << "Chooose Scan 3D range mode, Key in and press Enter : Small = 0, Medium = 1, Large = 2" << endl;
std::cin >> scanner_rgn_idx;
if (scanner_rgn_idx < 0 || scanner_rgn_idx > 2)
std::cout << "Out of range, please choose 0,1,2!" << endl;
} while (scanner_rgn_idx < 0 || scanner_rgn_idx > 2);
}
else //L210
{
do {
std::cout << "Chooose Scan 3D range mode, Key in and press Enter : Medium = 1, Large = 2" << endl;
std::cin >> scanner_rgn_idx;
if (scanner_rgn_idx < 1 || scanner_rgn_idx > 2)
std::cout << "Out of range, please choose 0,1,2!" << endl;
} while (scanner_rgn_idx < 1 || scanner_rgn_idx > 2);
}
std::cout << "Automatically 3D scan distance mode = " << scanner_rgn_idx << endl;
break;
default:
std::cout << "Unexpected situation of 3D scan distance mode selection." << endl;
terminateCurrentProcess();
break;
}
gScan_range = lips::RangeParam_lib(scanner_rgn_idx);
//--- Initialize LIPScan3D SDK
//string scan_mode;
char cfg_filename[512];
switch (gScan_range)
{
case 0:
gScan_mode = "small";
break;
case 1:
gScan_mode = "medium";
break;
case 2:
gScan_mode = "large";
break;
default:
gScan_mode = "";
break;
}
if (InitLIPScan3D((char*)camera_cfg_map[gScan_mode].realsense.c_str(), frame_width, frame_height))
std::cout << "Initialize LIPScan 3D SDK successfully." << endl;
else
{
std::cout << "Initialize LIPScan 3D SDK failed." << endl;
terminateCurrentProcess();
}
#pragma endregion
#pragma region Set3DScanQuality
if ((frame_width == 1280 && frame_height == 720) || (frame_width == 1280 && frame_height == 800))
{
double volume_pitch = sqrt(0.5);
lips::SetScannerConfigFloatMember(gReconstructor.handle_context, lips::ScannerConfigParam_FloatMember::VolumePitch, volume_pitch);
//std::cout << "Set 3D reconstruction volume pitch = " << volume_pitch << std::endl;
int avg_times = 3;
lips::SetScannerConfigIntMember(gReconstructor.handle_context, lips::ScannerConfigParam_IntMember::AverageTimes, avg_times);
//std::cout << "Set 3D reconstruction smooth mesh times = " << avg_times << std::endl;
}
#pragma endregion
#pragma region Setting 3D Scan Time Duration
double scan_duration;
switch (process_mode)
{
case 0:
std::cout << "Key-in 3D scan duration(seconds) and press enter : ";
std::cin >> scan_duration;
break;
case 2:
scan_duration = 60.0;
std::cout << "Automatically 3D scan duraion : " << scan_duration << "seconds." << endl;
break;
default:
std::cout << "Unexpected situation of specify 3D scan duration." << endl;
terminateCurrentProcess();
break;
}
#pragma endregion
#pragma region LIPScan 3D SDK process
double time_duration = 0; //Count real 3D scan duration(seconds)
BOOL done = FALSE; //Flag of terminate 3D scan reconstruction
switch (process_mode)
{
case 0: //Manually 3D scan mode
#ifdef LIPSCAN3D_PROCESS
double proc_head, proc_end;
double cycle_head, cycle_end;
MeshNum = 0; // no mesh object before finish 3D scan process
scan_count = 0;// count scan frames for compute average FPS
while (!done) // Loop That Runs Until done=TRUE
{
cycle_head = clock();
if (!gCamera->GetFrame(color_map, depth_data))
terminateCurrentProcess();
memcpy(copy_color_map, color_map, frame_width*frame_height * 3);
#ifdef DEPTH_TO_POINT
lips::convertDepthTo3DWorld(points_data, gCamera, frame_roi);
bool bDepthProc = gDepthpostproc->Process(depth_data, points_data, depth_map);
#endif
#pragma region Display Camera Frame
RotateDisplayImage((unsigned char*)color_img->imageData, frame_height, frame_width, 2);
RotateDisplayImage((unsigned char*)depth_img->imageData, frame_height, frame_width, 2);
cvShowImage(camera_color_wnd_name.c_str(), color_img);
cvShowImage(camera_depth_wnd_name.c_str(), depth_img);
cvWaitKey(1);
#pragma endregion
#ifdef DepthEvaluation
RECT depth_roi;
int DepthPeak;
depth_roi.left = depth_roi.bottom = 0;
depth_roi.right = frame_width;
depth_roi.top = frame_height;
if (strcmp(camera_devicename, "L210") == 0) // depth unit is 100um
DepthPeak = gDepthpostproc->DepthRangeEvaluation(depth_data, 30, 24, 16, depth_roi, 10, 10.0);
else //depth unit is 1mm
DepthPeak = gDepthpostproc->DepthRangeEvaluation(depth_data, 30, 24, 16, depth_roi, 10, 1.0);
#endif
#ifdef ICP_3D
bool bScan3D = gReconstructor.ScanData(copy_color_map, points_data, frame_width, frame_height, scan_map);
#pragma region Display 3D Reconstruction Frame
RotateDisplayImage((unsigned char*)scan_img->imageData, frame_height, frame_width, 2);
cvShowImage(scanner_wnd_name.c_str(), scan_img);
cvWaitKey(1);
#pragma endregion
#endif
scan_count++; //count 3D Scan cycle numbers
cycle_end = clock();
time_duration += ((cycle_end - cycle_head) / CLOCKS_PER_SEC);
// Export 3D Scan Mesh data to file
if (time_duration > scan_duration)
{
#ifdef FINISH_3DSCAN
gHandle_obj3d = gReconstructor.FinishScan();
if (gHandle_obj3d)
{
#pragma region Prepare Rendering Data for 3D Viewer
bScanFinish = true;
MeshNum = 1;
pObj[0] = gHandle_obj3d; //assign mesh address to container in API
bVisibleObj[0] = true;
PrepareTransformation(pObj, 0);
PrepareRenderBuf(pObj[0], MeshBuf[0]); //copy triangle mesh data to buffer for opengl rendering
#pragma endregion
#pragma region Export 3D Scan Mesh File
strcpy(Typename, "ply");
strcpy(main_name, "LIPScan_SDK_example_scan");
sprintf(open_model_filename, "%s\\%s.%s", RootDirectory, main_name, Typename);
bool bExport = lips::ExportFile(open_model_filename, gHandle_obj3d, 4);
if (bExport)
std::cout << "Finish export mesh file!" << endl;
else
std::cout << "License error, unsupported function." << endl;
#pragma endregion
}
else {
bScanFinish = false; //FinishScan() costruct mesh object failure
std::cout << "Reconstrcut 3D mesh object failure, please check the camera and object setting and repeat operation again." << endl;
}
#endif
done = true;
std::cout << "3D Scan times up : " << time_duration << " Seconds " << endl;
scan_fps = scan_count / time_duration;
std::cout << "Average FPS = " << scan_fps << endl;
}
}
#endif
break;
case 2: //Automatically 3D scan mode
std::cout << "Automatically cycling 3D scan process will trigger when 3D viewer alive." << endl;
break;
default:
std::cout << "Unexpected situation when execute 3D scan process." << endl;
terminateCurrentProcess();
break;
}
#pragma endregion
std::cout << "--- End 3D Scan Operation ---" << endl;
}
#pragma endregion
#pragma region Mesh Comparison Operation
else if(process_mode == 1)
{
std::cout << "--- Start Mesh Comparison Operation ---" << endl;
//Initialize LIPScan3D SDK with default settiing
camera_resolution = "640x480"; //set camera resolution as VGA
camera_cfg_map = Init3DscanConfig(RootDirectory, camera_devicename, camera_resolution.c_str());
gScan_range = lips::RangeParam_lib(1); //set scan range as medium
if (InitLIPScan3D((char*)camera_cfg_map["medium"].realsense.c_str(), frame_width, frame_height))
std::cout << "Initialize LIPScan 3D SDK successfully." << endl;
else
{
std::cout << "Initialize LIPScan 3D SDK failed." << endl;
terminateCurrentProcess();
}
compare_mesh_tool.Init(gCamera->GetSerialNumber());
MeshNum = 10; // no mesh object before mesh comparison process
std::cout << "--- End Mesh Comparison Operation ---" << endl;
}
#pragma endregion
#pragma region Offline 3D Reconstruction
else if (process_mode == 3)
{
//--- 3D reconstruction from camera binary frame files ---
char cfg_path[512];
sprintf_s(cfg_path, 512, "%s\\offline3dscan.json", RootDirectory);
string cfg_str(cfg_path);
fstream tmp_file;
tmp_file.open(cfg_path);
if (!tmp_file.is_open()) {
std::cout << "Open file failure! Please check file path!" << endl;
}
lips::JsonParser* jsonParser = new lips::JsonParser();
jsonParser->jsontree = jsonParser->Read(cfg_str);
string path = jsonParser->jsontree.get<string>("dir");
int src_w = jsonParser->jsontree.get<int>("width");
int src_h = jsonParser->jsontree.get<int>("height");
int src_count = jsonParser->jsontree.get<int>("frame");
char src_path[512];
char dst_mesh_path[512];
sprintf_s(src_path, 512, "%s\\%s", RootDirectory, path.c_str());
sprintf_s(dst_mesh_path, 512, "%s\\Offline_3DReconstruction.ply", src_path);
if (gHandle_obj3d) {
ReleaseTriMeshModel(gHandle_obj3d);
gHandle_obj3d = NULL;
}
gHandle_obj3d = Scan3D_Offline_Process(src_path, src_w, src_h, src_count);
if (gHandle_obj3d)
{
#pragma region Prepare Rendering Data for 3D Viewer
bScanFinish = true;
MeshNum = 1;
pObj[0] = gHandle_obj3d; //assign mesh address to container in API
bVisibleObj[0] = true;
PrepareTransformation(pObj, 0);
PrepareRenderBuf(pObj[0], MeshBuf[0]); //copy triangle mesh data to buffer for opengl rendering
#pragma endregion
#pragma region Export 3D Scan Mesh File
bool bExport = lips::ExportFile(dst_mesh_path, gHandle_obj3d, 4);
if (bExport) {
std::cout << "Finish export mesh file! filename:" << endl;
std::cout << dst_mesh_path << endl;
}
else
std::cout << "License error, unsupported function." << endl;
#pragma endregion
frame_width = src_w;
frame_height = src_h;
}
else {
bScanFinish = false; //FinishScan() costruct mesh object failure
std::cout << "Reconstrcut 3D mesh object failure, please check the configurations in 'offline3dscan.json' file and source file(.bin)." << endl;
}
//------------------------------------
}
#pragma endregion
#pragma region Failure Of Operation Selection
else
{
std::cout << "--- Failure Of Operation Selection ---" << endl;
}
#pragma endregion
#pragma region Launch 3D Viewer
#ifdef VIEWER_3DSCAN
std::cout << "Launch 3D Viewer window." << endl;
std::cout << "If user want to repeat 3D Scan process, press 'Esc' button on 3D Viewer window." << endl;
CreateWin32glWindow(gl_wnd_name);
MSG msg;
BOOL done_viewer = FALSE;
while (!done_viewer)
{
#pragma region Start Thread Of Automatically Cycling Scan3D
if ( (process_mode) == 2 && (auto_cycling_scan3D_thread_handle == NULL) )
auto_cycling_scan3D_thread_handle = threadStart(auto_cycling_scan3D_thread_handle, (LPTHREAD_START_ROUTINE)auto_cycling_scan3D_ThreadProc);
#pragma endregion
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE)
{
#pragma region Terminate Thread Of Automatically Cycling Scan3D
if ((process_mode == 2) && (auto_cycling_scan3D_thread_handle != NULL))
{
TerminateThread(auto_cycling_scan3D_thread_handle, 0); // Dangerous source of errors!
CloseHandle(auto_cycling_scan3D_thread_handle);
auto_cycling_scan3D_thread_handle = NULL;
}
#pragma endregion
done_viewer = TRUE;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
SendMessage(hWnd, WM_PAINT, 0, 0);
}
DrawGLScene();
SwapBuffers(hDC);
#ifdef VIEWER_FPS
double fps = FPS();
std::cout << "3D Render FPS = " << fps << endl;
#endif
}
#pragma endregion
#pragma region Release Rendering Data Of Mesh Object
switch (process_mode)
{
case 0: //Manually 3D Scan
cvDestroyWindow(camera_color_wnd_name.c_str());
cvDestroyWindow(camera_depth_wnd_name.c_str());
cvDestroyWindow(scanner_wnd_name.c_str());
KillGLWindow();
ReleaseRenderBuf(MeshBuf[0]);
ReleaseLIPScan3D();
MeshNum = 0;
std::cout << "Release resources of manually 3D scan process." << endl;
break;
case 1: //Mesh Comparison
KillGLWindow();
meshcomparer_status = MeshComparisonState::NONE;
compare_mesh_tool.Reset();
if (MeshBuf[0].TriNum > 0) ReleaseRenderBuf(MeshBuf[0]); //clear render buffer of compared mesh
if (MeshBuf[1].TriNum > 0) ReleaseRenderBuf(MeshBuf[1]); //clear render buffer of referenced mesh
ReleaseLIPScan3D();
pObj[0] = NULL; //memeries released by lips::MeshComparison::Reset()
pObj[1] = NULL; //memeries released by lips::MeshComparison::Reset()
RenderMode = 0; //
std::cout << "Release resources of mesh comparison." << endl;
break;
case 2: //Automatically 3D scan mode
cvDestroyWindow(camera_color_wnd_name.c_str());
cvDestroyWindow(camera_depth_wnd_name.c_str());
cvDestroyWindow(scanner_wnd_name.c_str());
KillGLWindow();
Sleep(100);
ReleaseRenderBuf(MeshBuf[0]);
MeshNum = 0;
std::cout << "Release resources of automatically cycling 3D scan process." << endl;
break;
case 3: //Offline 3D reconstruction
KillGLWindow();
Sleep(100);
ReleaseRenderBuf(MeshBuf[0]);
MeshNum = 0;
std::cout << "Release resources of offline 3D reconstruction process." << endl;
break;
default:
std::cout << "Exit unknown process mode." << endl;
break;
}
std::cout << "Destroy all window." << endl;
#pragma endregion
#endif
#define REPEAT_SCAN3D
#ifdef REPEAT_SCAN3D
char ch;
//std::cout << "Repeat 3D scan agian? (Y/y)" << endl;
std::cout << "Repeat LIPScan3D SDK example operation again? (Y/y)" << endl;
std::cin >> ch;
if (ch == 'Y' || ch == 'y')
return ConsoleAppScript(argc, argv);
#endif
}
char* initalCurrentWorkDirectory(char * directory)
{
GetModuleFileName(NULL, directory, 512);
PathRemoveFileSpec(directory);
if (strstr(directory, "WindowsApps") != NULL)
{
SetCurrentDirectory(directory);
GetCurrentDirectory(512, directory);
}
else
{
GetCurrentDirectory(512, directory);
}
std::cout << "dirname: " << directory << std::endl;
return directory;
}
void terminateCurrentProcess()
{
DWORD pid = GetCurrentProcessId();
HANDLE handle;
handle = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, pid);
TerminateProcess(handle, 0);
}
HANDLE threadStart(HANDLE threadHandle, LPTHREAD_START_ROUTINE thread_function)
{
threadHandle = CreateThread(NULL, NULL, thread_function, NULL, NULL, NULL);
return threadHandle;
}
SIZE_MODE_CONFIG_MAP Init3DscanConfig(const char* rootdir, const char* devicename, const char* resolution)
{
SIZE_MODE_CONFIG_MAP config_map;
string scan3dconfig_dir = rootdir;
scan3dconfig_dir += "\\Config_files\\";
scan3dconfig_dir += devicename;
scan3dconfig_dir += "\\";
scan3dconfig_dir += resolution;
string scan3d_config_list_filename = scan3dconfig_dir + "\\scan3d_config.txt";
string config_json_filename;
fstream scan3d_config_list;
scan3d_config_list.open(scan3d_config_list_filename.c_str());
if (scan3d_config_list.is_open())
{
string config_mode;
SIZE_MODE_CONFIG config_info;
while (!scan3d_config_list.eof())
{
scan3d_config_list >> config_mode;
scan3d_config_list >> config_info.realsense;
config_json_filename = scan3dconfig_dir + "\\";
config_json_filename += config_info.realsense;
config_info.realsense = config_json_filename;
config_map.insert(std::pair<string, SIZE_MODE_CONFIG>(config_mode, config_info));
}
}