-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsvafstream.cpp
More file actions
3648 lines (3108 loc) · 160 KB
/
svafstream.cpp
File metadata and controls
3648 lines (3108 loc) · 160 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
#include "stdafx.h"
#include "ArenaApi.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <chrono>
#include <cmath>
#include <set>
#include <cnpy.h>
#include <iomanip>
#include <sstream>
#include <CL/cl.h>
#include <CL/cl_gl.h>
#include <map>
#include "warpPerspective.h" // Add include for WarpPerspective class
#include "dpflow.h"
#include "slic.h"
#include "turbo_colormap_lut.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
// Maximum packet size
#define TAB1 " "
#define MAX_PACKET_SIZE true
// SLM parameters
const int cameraWidth = 1224;
const int cameraTopMargin = 45;
const int cameraBottomMargin = 55;
const int cameraHeight = 1024;
const int cameraChannels = 3;
const int SLM_WIDTH = 4000;
const int SLM_HEIGHT = 2464;
const double LEFT_FREQ = 1.0/4.0; // Left 2/3 of image
const double RIGHT_FREQ = -1.0/5.0; // Right 1/3 of image
const size_t globalCameraSize[2] = {static_cast<size_t>(cameraWidth), static_cast<size_t>(cameraHeight)};
const size_t globalSLMSize[2] = {static_cast<size_t>(SLM_WIDTH), static_cast<size_t>(SLM_HEIGHT)};
// DPflow and SLIC parameters
float flow_scalar_learning_rate = 0.1f; // optical flow learning rate
int window_size = 202;
bool enableSuperpixels = false;
int numSuperpixels = 500;
float compactness = 13.0f;
float lambda_reg = 1e-6f;
bool green = false;
int devignet = 0;
int iterations = 1;
// Display mode flag: true = corner depth display, false = side-by-side display
bool cornerDepthDisplay = true;
// SVAF status: 1 = OFF (red), 2/3 = ON (green)
int svafStatus = 1;
// Pre-rendered text overlays
cv::Mat svafOffOverlay = cv::Mat::zeros(static_cast<int>(cameraHeight), static_cast<int>(cameraWidth), CV_8UC4); // BGRA format
cv::Mat svafOnCenterOverlay = cv::Mat::zeros(static_cast<int>(cameraHeight), static_cast<int>(cameraWidth), CV_8UC4);
cv::Mat svafOnOverlay = cv::Mat::zeros(static_cast<int>(cameraHeight), static_cast<int>(cameraWidth), CV_8UC4);
// OpenCL buffers for text overlays (three separate buffers)
cl_mem g_clTextOverlayOff = nullptr;
cl_mem g_clTextOverlayOnCenter = nullptr;
cl_mem g_clTextOverlayOn = nullptr;
// Function to create text overlays at initialization
void CreateTextOverlays() {
std::cout << "Creating SVAF status text overlays...\n";
// Text properties
int fontFace = cv::FONT_HERSHEY_PLAIN;
double fontScale = 2;
int thickness = 3;
int baseline = 0;
// Position text in bottom-left corner
cv::Point textPosition(20, static_cast<int>(cameraHeight) - 66);
// Create "SVAF OFF" overlay (red text)
cv::Size textSize = cv::getTextSize("SVAF OFF", fontFace, fontScale, thickness, &baseline);
cv::putText(svafOffOverlay, "SVAF OFF", textPosition, fontFace, fontScale,
cv::Scalar(255, 0, 0, 255), thickness); // Red text
// Create "SVAF ON (CENTER ONLY)" overlay (green text)
textSize = cv::getTextSize("SVAF ON (CENTER ONLY)", fontFace, fontScale, thickness, &baseline);
cv::putText(svafOnCenterOverlay, "SVAF ON (CENTER ONLY)", textPosition, fontFace, fontScale, cv::Scalar(0, 255, 0, 255), thickness); // Green text
// Create "SVAF ON" overlay (green text)
textSize = cv::getTextSize("SVAF ON", fontFace, fontScale, thickness, &baseline);
cv::putText(svafOnOverlay, "SVAF ON", textPosition, fontFace, fontScale,
cv::Scalar(0, 255, 0, 255), thickness); // Green text
// Flip all overlays horizontally and vertically to match display coordinate system
cv::flip(svafOffOverlay, svafOffOverlay, -1); // -1 flips both horizontally and vertically
cv::flip(svafOnCenterOverlay, svafOnCenterOverlay, -1);
cv::flip(svafOnOverlay, svafOnOverlay, -1);
std::cout << "Text overlays created and flipped successfully\n";
}
// OpenCL variables
cl_context g_clContext = nullptr; // Single context
cl_command_queue g_clQueue = nullptr; // Single queue
cl_device_id g_clDevice = nullptr;
cl_program g_clProgram = nullptr;
cl_program g_clConvertToFloatProgram = nullptr;
cl_kernel g_clKernel = nullptr;
cl_kernel g_clPeriodMapKernel = nullptr;
cl_kernel g_clConvertLeftImageToFloatKernel = nullptr;
cl_kernel g_clConvertRightImageToFloatKernel = nullptr;
cl_kernel g_clConvertTopImageToFloatKernel = nullptr;
cl_kernel g_clConvertBottomImageToFloatKernel = nullptr;
cl_program g_clPeriodMapProgram = nullptr;
cl_mem g_clTempLeftBuffer = nullptr;
cl_mem g_clTempRightBuffer = nullptr;
cl_mem g_clTempTopBuffer = nullptr;
cl_mem g_clTempBottomBuffer = nullptr;
cl_mem g_clLeftImage = nullptr;
cl_mem g_clRightImage = nullptr;
cl_mem g_clTopImage = nullptr;
cl_mem g_clBottomImage = nullptr;
cl_mem g_clMask = nullptr;
cl_mem g_clFlow = nullptr;
cl_mem g_clLeftDevignetMap = nullptr;
cl_mem g_clRightDevignetMap = nullptr;
cl_mem g_clTopDevignetMap = nullptr;
cl_mem g_clBottomDevignetMap = nullptr;
cl_mem g_clSpatialFreqMap = nullptr;
cl_mem g_clLabels = nullptr;
cl_mem g_clSpatialFreqMapSuperpixels = nullptr;
cl_mem g_clWarpedFreqMap = nullptr;
cl_mem g_clHomography = nullptr;
cl_mem g_clPeriodTempMap = nullptr;
cl_mem g_clPeriodMap = nullptr;
cl_mem g_clYGrid = nullptr;
cl_mem g_clSharedTexture = nullptr;
void* hostPtr = nullptr;
// Add new OpenCL variables for flow multiplication
cl_kernel g_clUpdateFlowKernel = nullptr;
cl_program g_clUpdateFlowProgram = nullptr;
// Add WarpPerspective object as global variable
WarpPerspective* g_warp = nullptr;
// OpenGL variables
HWND g_SLMWnd = nullptr;
HWND g_capturedWnd = nullptr;
HDC g_sharedDC = nullptr;
HGLRC g_sharedRC = nullptr;
GLuint g_SLMTextureID = 0;
GLuint g_capturedTextureID = 0;
GLuint g_SLMPBOID = 0;
GLuint g_capturedPBOID = 0;
// Add new OpenCL variables for captured display
cl_kernel g_clCombineImagesKernel = nullptr;
cl_program g_clCombineImagesProgram = nullptr;
cl_mem g_clCombinedDisplay = nullptr;
cl_mem g_clTurboLUT = nullptr;
cl_mem g_clResizedDepthMap = nullptr;
cl_kernel g_clResizeDepthMapKernel = nullptr;
cl_program g_clResizeDepthMapProgram = nullptr;
// Text overlay blending
cl_kernel g_clBlendTextOverlayKernel = nullptr;
cl_program g_clBlendTextOverlayProgram = nullptr;
std::string g_devignet_folder = "C:/Users/matth/Desktop/SVAF/images/measurements/devignet_maps";
// Define OpenGL function pointer types
typedef void (APIENTRY *PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRY *PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void* data, GLenum usage);
typedef void (APIENTRY *PFNGLGENBUFFERSPROC) (GLsizei n, GLuint* buffers);
typedef void (APIENTRY *PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint* buffers);
// Create Y grid for SLM (constant)
cv::Mat CreateYGrid() {
cv::Mat Y_grid(SLM_HEIGHT, SLM_WIDTH, CV_32F); // Changed to float (CV_32F)
for (int y = 0; y < SLM_HEIGHT; y++) {
for (int x = 0; x < SLM_WIDTH; x++) {
Y_grid.at<float>(y, x) = static_cast<float>(y + 1.0f); // Cast to float
}
}
return Y_grid;
}
const cv::Mat Y_GRID = CreateYGrid();
// Add newOpenCL kernel for converting uchar to float and applying devignet map
const char* convertToFloatKernel = R"(
__kernel void convertToFloat(
__global const uchar* input,
__global float* output,
__global const float* devignetMap,
const int devignet,
const int width,
const int height,
const int channels)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
int idx = (y * width + x) * channels;
int devignetIdx = y * width + x;
for (int c = 0; c < channels; c++) {
if (devignet) {
output[idx + c] = (float)input[idx + c] / 255.0f * devignetMap[devignetIdx];
} else {
output[idx + c] = (float)input[idx + c] / 255.0f;
}
}
}
)";
// Add new OpenCL kernel for computing SLM pattern
const char* kernelSource = R"(
__kernel void computeSLMPattern(
__global const float* periodMap,
__global const float* yGrid,
__global uchar* output, // Explicitly unsigned char
const int width,
const int height,
const int flag,
const float depth)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
int idx = y * width + x;
float period = periodMap[idx]; //round(periodMap[idx]);
if (flag == 1) {
period = 0.3*sin(2*depth*3.14159);
}
if (flag == 2) {
if (x >= width/2 - 400 && x < width/2 + 400 && y >= height/2 - 400 && y < height/2 + 400) {
period = 0.3*sin(2*depth*3.14159) + 0.3;
} else {
period = 0;
}
}
/*if (period == 0.0f) {
output[idx] = 0;
return;
}
float phase = (period > 0.0f ? yGrid[idx] : -yGrid[idx]);
float absPeriod = fabs(period);
float modResult = fmod(phase, absPeriod);
if (fmod(absPeriod, 2.0f) == 0.0f) {
modResult = fmod(modResult + absPeriod, absPeriod);
} else if (modResult < 0.0f) {
modResult += absPeriod;
}*/
uchar tmp = (uchar) fmod(fabs(yGrid[idx] * 255.0f * period), 255.0f);
//int iperiod = ceil(1 / fabs(period));
//uchar tmp = (uchar) 255.0f * fabs(period) * (yGrid[idx] - iperiod * floor(yGrid[idx] / iperiod));
output[idx] = (period >= 0 ? tmp : 255-tmp); //(uchar)((modResult / (absPeriod - 1.0f)) * 255.0f); // 0 MATT's EDIT
}
)";
// Add new OpenCL kernel for computing spatial period map
const char* spatialPeriodMapKernel = R"(
__kernel void computeSpatialPeriodMap(
__global const float* spatialFreqMap,
__global float* periodMap,
const int width,
const int height)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
int idx = y * width + x;
float freq = spatialFreqMap[idx];
if (freq != 0.0) {
periodMap[idx] = freq; //1.0 / freq; //round(1.0 / freq);
} else {
periodMap[idx] = 0.0;
}
}
)";
// Add new OpenCL kernel for multiplying flow with scalar
const char* updateFlowKernel = R"(
__kernel void updateFlowWithScalar(
__global const float* flow,
__global float* spatialFreqMap, // Changed to float to match flow type
const float scalar, // Changed to float
const int width,
const int height)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
int idx = y * width + x;
float freq = spatialFreqMap[idx] + flow[idx] * 0.015;
// Clip freq between -1/4 and 1/4
if (freq < -0.4f) {
freq = -0.4f;
} else if (freq > 0.4f) {
freq = 0.4f;
}
// Compute period map as round of 1/spatialFreqMap[idx]
/*float period = 0.0f;
if (freq != 0.0f) {
period = round(1.0f / freq);
spatialFreqMap[idx] = 1.0f / period;
} else {
spatialFreqMap[idx] = 0.0f;
}*/
spatialFreqMap[idx] = freq;
}
)";
// Add new OpenCL kernel for resizing depth map
const char* resizeDepthMapKernel = R"(
__kernel void resizeDepthMap(
__global const float* inputDepthMap,
__global float* outputDepthMap,
const int inputWidth,
const int inputHeight,
const int outputWidth,
const int outputHeight)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= outputWidth || y >= outputHeight) return;
// Calculate scaling factors
float scaleX = (float)inputWidth / (float)outputWidth;
float scaleY = (float)inputHeight / (float)outputHeight;
// Map output coordinates to input coordinates
int inputX = (int)(x * scaleX);
int inputY = (int)(y * scaleY);
// Clamp to valid range
inputX = max(0, min(inputWidth - 1, inputX));
inputY = max(0, min(inputHeight - 1, inputY));
// Copy depth value
int inputIdx = inputY * inputWidth + inputX;
int outputIdx = y * outputWidth + x;
outputDepthMap[outputIdx] = inputDepthMap[inputIdx];
}
)";
// Add new OpenCL kernel for combining images and applying turbo colormap
const char* combineImagesKernel = R"(
__kernel void combineImagesWithColormap(
__global const float* topImage,
__global const float* bottomImage,
__global const float* leftImage,
__global const float* rightImage,
__global const float* spatialFreqMap,
__global const float* resizedDepthMap,
__global uchar* combinedDisplay,
__constant float* turbo,
const int cameraTopMargin,
const int cameraBottomMargin,
const int width,
const int height,
const int mode,
const int cornerDisplay)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
if (y < cameraTopMargin || y >= height - cameraBottomMargin) return;
int idx = y * width + x;
int combinedIdx, rightIdx;
// Calculate indices based on display mode
if (cornerDisplay) {
// Corner display mode: RGB fills entire image, depth in top-right corner
combinedIdx = y * width + x;
rightIdx = combinedIdx; // Same position for RGB
} else {
// Side-by-side mode: RGB on right, depth on left
combinedIdx = y * (width * 2) + x;
rightIdx = combinedIdx + width;
}
float r, g, b;
// Get RGB values from total image
if (mode == 0) {
r = 2*(topImage[idx * 3 + 0] + bottomImage[idx * 3 + 2] + leftImage[idx * 3 + 0] + rightImage[idx * 3 + 0])/4;
g = 2*(topImage[idx * 3 + 1] + bottomImage[idx * 3 + 2] + leftImage[idx * 3 + 1] + rightImage[idx * 3 + 1])/4;
b = 2*(topImage[idx * 3 + 2] + bottomImage[idx * 3 + 2] + leftImage[idx * 3 + 2] + rightImage[idx * 3 + 2])/4;
} else if (mode == 1) {
float tmp = leftImage[idx * 3 + 1] - rightImage[idx * 3 + 1];
float tmp2 = leftImage[idx * 3 + 1] + rightImage[idx * 3 + 1];
tmp = 0.5*tmp/tmp2 + 0.5;
r = tmp;
g = tmp;
b = tmp;
}
// Ensure values are in valid range
r = max(0.0f, min(1000.0f, r));
g = max(0.0f, min(1000.0f, g));
b = max(0.0f, min(1000.0f, b));
// Apply contrast enhancement (stretch the dynamic range)
float contrast_factor = 1.5f; // Increase contrast
r = (r - 0.5f) * contrast_factor + 0.5f;
g = (g - 0.5f) * contrast_factor + 0.5f;
b = (b - 0.5f) * contrast_factor + 0.5f;
// Apply gamma correction for better visual appearance
r = 0.45f * pow(r, 1/1.11f); // Increased from 0.4f and 1/1.3f
g = 0.45f * pow(g, 1/1.11f);
b = 0.45f * pow(b, 1/1.11f);
// Apply saturation enhancement
float luminance = 0.299f * r + 0.587f * g + 0.114f * b; // Standard luminance weights
float saturation_factor = 1.08f; // Increase saturation
r = luminance + (r - luminance) * saturation_factor;
g = luminance + (g - luminance) * saturation_factor;
b = luminance + (b - luminance) * saturation_factor;
// Apply vibrance enhancement (selective saturation boost)
float vibrance_factor = 1.2f;
float max_channel = fmax(fmax(r, g), b);
float min_channel = fmin(fmin(r, g), b);
float saturation = max_channel - min_channel;
if (saturation > 0.1f) { // Only enhance if there's significant color
float vibrance_boost = (1.0f - saturation) * vibrance_factor;
r = r + (r - luminance) * vibrance_boost;
g = g + (g - luminance) * vibrance_boost;
b = b + (b - luminance) * vibrance_boost;
}
// Clamp values to valid range
r = max(0.0f, min(1.0f, r));
g = max(0.0f, min(1.0f, g));
b = max(0.0f, min(1.0f, b));
// Get spatial frequency value
float freq = spatialFreqMap[idx];
// Normalize to [-0.5, 0.5] range (assuming typical flow values)
float min_freq = -0.4f;
float max_freq = 0.4f;
float normalized = max(min_freq, min(max_freq, freq));
normalized = (normalized - min_freq) / (max_freq - min_freq); // Map to [0, 1]
// Apply turbo colormap
int turbo_idx = (int)(max(0.0f, min(1.0f, normalized)) * 255.0f);
float r_depth = turbo[3 * turbo_idx + 0];
float g_depth = turbo[3 * turbo_idx + 1];
float b_depth = turbo[3 * turbo_idx + 2];
if (cornerDisplay) {
// Corner display mode: RGB fills entire image, depth in top-right corner
// Note: Image is flipped both vertically and horizontally during rendering
// So we position corner in bottom-left of kernel coordinates to appear top-right after flip
int cornerWidth = width / 5;
int cornerHeight = height / 5;
int cornerStartX = 0; // Left side in kernel (appears right after flip)
int cornerStartY = height - cornerHeight - cameraBottomMargin; // Bottom side in kernel (appears top after flip)
// Check if current pixel is in the corner region
if (x >= cornerStartX && x < cornerWidth && y >= cornerStartY && y < cornerStartY + cornerHeight) {
// In corner region - display resized depth map
int cornerX = x - cornerStartX;
int cornerY = y - cornerStartY;
int resizedIdx = cornerY * cornerWidth + cornerX;
float resized_freq = resizedDepthMap[resizedIdx];
// Normalize to [-0.5, 0.5] range (assuming typical flow values)
float min_freq = -0.4f;
float max_freq = 0.4f;
float normalized = max(min_freq, min(max_freq, resized_freq));
normalized = (normalized - min_freq) / (max_freq - min_freq); // Map to [0, 1]
// Apply turbo colormap to resized depth
int turbo_idx = (int)(max(0.0f, min(1.0f, normalized)) * 255.0f);
float r_resized_depth = turbo[3 * turbo_idx + 0];
float g_resized_depth = turbo[3 * turbo_idx + 1];
float b_resized_depth = turbo[3 * turbo_idx + 2];
combinedDisplay[combinedIdx * 3] = (uchar)(r_resized_depth * 255.0f); // R
combinedDisplay[combinedIdx * 3 + 1] = (uchar)(g_resized_depth * 255.0f); // G
combinedDisplay[combinedIdx * 3 + 2] = (uchar)(b_resized_depth * 255.0f); // B
} else {
// Outside corner region - display RGB
combinedDisplay[combinedIdx * 3] = (uchar)(r * 255.0f); // R
combinedDisplay[combinedIdx * 3 + 1] = (uchar)(g * 255.0f); // G
combinedDisplay[combinedIdx * 3 + 2] = (uchar)(b * 255.0f); // B
}
} else {
// Side-by-side mode: RGB on right, depth on left
// Copy RGB to right half
combinedDisplay[rightIdx * 3] = (uchar)(r * 255.0f); // R
combinedDisplay[rightIdx * 3 + 1] = (uchar)(g * 255.0f); // G
combinedDisplay[rightIdx * 3 + 2] = (uchar)(b * 255.0f); // B
// Write depth to left half
combinedDisplay[combinedIdx * 3] = (uchar)(r_depth * 255.0f); // R
combinedDisplay[combinedIdx * 3 + 1] = (uchar)(g_depth * 255.0f); // G
combinedDisplay[combinedIdx * 3 + 2] = (uchar)(b_depth * 255.0f); // B
}
}
)";
// OpenCL kernel for blending text overlay
const char* blendTextOverlayKernel = R"(
__kernel void blendTextOverlay(
__global uchar* combinedDisplay,
__global const uchar* textOverlay,
const int width,
const int height)
{
int x = get_global_id(0);
int y = get_global_id(1);
if (x >= width || y >= height) return;
int idx = y * width + x;
int overlayIdx = idx * 4; // BGRA format
int displayIdx = idx * 3; // BGR format
// Get overlay pixel (BGRA)
uchar overlayB = textOverlay[overlayIdx];
uchar overlayG = textOverlay[overlayIdx + 1];
uchar overlayR = textOverlay[overlayIdx + 2];
uchar overlayA = textOverlay[overlayIdx + 3];
// Only blend if overlay has alpha > 0
if (overlayA > 0) {
float alpha = overlayA / 255.0f;
// Get current display pixel (BGR)
uchar displayB = combinedDisplay[displayIdx];
uchar displayG = combinedDisplay[displayIdx + 1];
uchar displayR = combinedDisplay[displayIdx + 2];
// Blend: result = background * (1 - alpha) + foreground * alpha
combinedDisplay[displayIdx] = (uchar)(displayB * (1.0f - alpha) + overlayB * alpha);
combinedDisplay[displayIdx + 1] = (uchar)(displayG * (1.0f - alpha) + overlayG * alpha);
combinedDisplay[displayIdx + 2] = (uchar)(displayR * (1.0f - alpha) + overlayR * alpha);
}
}
)";
// Configure for high frame rates
// (1) maximizes packet size
// (2) sets large number of buffers
void SetUpForRapidAcquisition(Arena::IDevice* pDevice)
{
int64_t deviceStreamChannelPacketSizeInitial;
if (MAX_PACKET_SIZE)
{
deviceStreamChannelPacketSizeInitial = Arena::GetNodeValue<int64_t>(pDevice->GetNodeMap(), "DeviceStreamChannelPacketSize");
}
// Set maximum stream channel packet size
// Maximizing packet size increases frame rate by reducing the amount of
// overhead required between images. This includes both extra
// header/trailer data per packet as well as extra time from intra-packet
// spacing (the time between packets). In order to grab images at the
// maximum packet size, the Ethernet adapter must be configured
// appropriately: 'Jumbo packet' must be set to its maximum, 'UDP checksum
// offload' must be set to 'Rx & Tx Enabled', and 'Received Buffers' must
// be set to its maximum.
if (MAX_PACKET_SIZE)
{
std::cout << TAB1 << "Set maximum device stream channel packet size";
GenApi::CIntegerPtr pDeviceStreamChannelPacketSize = pDevice->GetNodeMap()->GetNode("DeviceStreamChannelPacketSize");
if (!pDeviceStreamChannelPacketSize || !GenApi::IsReadable(pDeviceStreamChannelPacketSize) || !GenApi::IsWritable(pDeviceStreamChannelPacketSize))
{
throw GenICam::GenericException("DeviceStreamChannelPacketSize node not found/readable/writable", __FILE__, __LINE__);
}
std::cout << " (" << pDeviceStreamChannelPacketSize->GetMax() << " " << pDeviceStreamChannelPacketSize->GetUnit() << ")\n";
pDeviceStreamChannelPacketSize->SetValue(pDeviceStreamChannelPacketSize->GetMax());
}
if (!MAX_PACKET_SIZE)
{
// enable stream auto negotiate packet size
Arena::SetNodeValue<bool>(pDevice->GetTLStreamNodeMap(), "StreamAutoNegotiatePacketSize", true);
}
// enable stream packet resend
Arena::SetNodeValue<bool>(pDevice->GetTLStreamNodeMap(), "StreamPacketResendEnable", true);
if (MAX_PACKET_SIZE)
{
Arena::SetNodeValue<int64_t>(pDevice->GetNodeMap(), "DeviceStreamChannelPacketSize", deviceStreamChannelPacketSizeInitial);
}
}
// Function to read and load image files
void LoadDevignetMaps() {
// Read the image files
cv::Mat imgl1 = cv::imread(g_devignet_folder + "/imgl_0d_devignetmap.tiff", cv::IMREAD_UNCHANGED);
cv::Mat imgr1 = cv::imread(g_devignet_folder + "/imgr_90d_devignetmap.tiff", cv::IMREAD_UNCHANGED);
cv::Mat imgtop = cv::imread(g_devignet_folder + "/imgtotal_135d_devignetmap.tiff", cv::IMREAD_UNCHANGED);
cv::Mat imgbottom = cv::imread(g_devignet_folder + "/imgtotal_45d_devignetmap.tiff", cv::IMREAD_UNCHANGED);
if (imgl1.empty() || imgr1.empty() || imgtop.empty() || imgbottom.empty()) {
throw std::runtime_error("Failed to load image files");
}
// Create OpenCL buffers for the images
cl_int err;
g_clLeftDevignetMap = clCreateBuffer(g_clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
imgl1.total() * imgl1.elemSize(), imgl1.data, &err);
if (err != CL_SUCCESS) {
throw std::runtime_error("Failed to create left image buffer");
}
g_clRightDevignetMap = clCreateBuffer(g_clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
imgr1.total() * imgr1.elemSize(), imgr1.data, &err);
if (err != CL_SUCCESS) {
throw std::runtime_error("Failed to create right image buffer");
}
g_clTopDevignetMap = clCreateBuffer(g_clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
imgtop.total() * imgtop.elemSize(), imgtop.data, &err);
if (err != CL_SUCCESS) {
throw std::runtime_error("Failed to create top image buffer");
}
g_clBottomDevignetMap = clCreateBuffer(g_clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
imgbottom.total() * imgbottom.elemSize(), imgbottom.data, &err);
if (err != CL_SUCCESS) {
throw std::runtime_error("Failed to create bottom image buffer");
}
}
// Function to initialize OpenCL
bool InitOpenCL() {
try {
std::cout << "Starting OpenCL initialization...\n";
// Verify both OpenGL contexts are properly initialized
if (!g_sharedDC || !g_sharedRC) {
std::cout << "OpenGL context not properly initialized\n";
return false;
}
// Get platform
cl_platform_id platform;
cl_uint numPlatforms;
cl_int err = clGetPlatformIDs(0, nullptr, &numPlatforms);
if (err != CL_SUCCESS) {
std::cout << "Failed to get number of platforms: " << err << std::endl;
return false;
}
if (numPlatforms == 0) {
std::cout << "No OpenCL platforms found\n";
return false;
}
err = clGetPlatformIDs(1, &platform, nullptr);
if (err != CL_SUCCESS) {
std::cout << "Failed to get platform: " << err << std::endl;
return false;
}
// Get platform info
char platformName[1024];
err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platformName), platformName, nullptr);
if (err == CL_SUCCESS) {
std::cout << "OpenCL Platform: " << platformName << "\n";
}
// Get device
cl_uint numDevices;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, nullptr, &numDevices);
if (err != CL_SUCCESS) {
std::cout << "Failed to get number of devices: " << err << std::endl;
return false;
}
if (numDevices == 0) {
std::cout << "No GPU devices found\n";
return false;
}
std::cout << "Found " << numDevices << " GPU devices\n";
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &g_clDevice, nullptr);
if (err != CL_SUCCESS) {
std::cout << "Failed to get device: " << err << std::endl;
return false;
}
// Get device info
char deviceName[1024];
err = clGetDeviceInfo(g_clDevice, CL_DEVICE_NAME, sizeof(deviceName), deviceName, nullptr);
if (err == CL_SUCCESS) {
std::cout << "OpenCL Device: " << deviceName << "\n";
}
// Get device extensions
size_t extensionsSize;
err = clGetDeviceInfo(g_clDevice, CL_DEVICE_EXTENSIONS, 0, nullptr, &extensionsSize);
if (err != CL_SUCCESS) {
std::cout << "Failed to get device extensions size: " << err << std::endl;
return false;
}
std::vector<char> extensions(extensionsSize);
err = clGetDeviceInfo(g_clDevice, CL_DEVICE_EXTENSIONS, extensionsSize, extensions.data(), nullptr);
if (err != CL_SUCCESS) {
std::cout << "Failed to get device extensions: " << err << std::endl;
return false;
}
std::string extensionsStr(extensions.data());
std::cout << "Device Extensions: " << extensionsStr << "\n";
// Check for OpenGL sharing support
bool hasGLSharing = extensionsStr.find("cl_khr_gl_sharing") != std::string::npos;
if (!hasGLSharing) {
std::cout << "Device does not support OpenGL sharing\n";
return false;
}
// Create single context properties for SLM sharing
cl_context_properties properties[] = {
CL_GL_CONTEXT_KHR, (cl_context_properties)g_sharedRC, // OpenGL context
CL_WGL_HDC_KHR, (cl_context_properties)g_sharedDC, // OpenGL DC
CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
0
};
// Create single context
g_clContext = clCreateContext(properties, 1, &g_clDevice, nullptr, nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create OpenCL context: " << err << std::endl;
return false;
}
// Create single command queue
g_clQueue = clCreateCommandQueue(g_clContext, g_clDevice, 0, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create command queue: " << err << std::endl;
return false;
}
// Make OpenGL context current
if (!wglMakeCurrent(g_sharedDC, g_sharedRC)) {
std::cout << "Failed to make SLM context current for PBO sharing\n";
return false;
}
// Create shared buffers in the single context
g_clSharedTexture = clCreateFromGLBuffer(g_clContext, CL_MEM_WRITE_ONLY, g_SLMPBOID, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create shared texture buffer: " << err << std::endl;
return false;
}
g_clCombinedDisplay = clCreateFromGLBuffer(g_clContext, CL_MEM_WRITE_ONLY, g_capturedPBOID, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create combined display buffer: " << err << std::endl;
return false;
}
int displayWidth = cornerDepthDisplay ? cameraWidth : cameraWidth * 2;
std::cout << "Combined display buffer created successfully (size: " << displayWidth << "x" << cameraHeight << ")\n";
// Create program and kernel for spatial period map computation
g_clPeriodMapProgram = clCreateProgramWithSource(g_clContext, 1, &spatialPeriodMapKernel, nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create period map program: " << err << std::endl;
return false;
}
err = clBuildProgram(g_clPeriodMapProgram, 1, &g_clDevice, nullptr, nullptr, nullptr);
if (err != CL_SUCCESS) {
std::cout << "Failed to build period map program: " << err << std::endl;
return false;
}
g_clPeriodMapKernel = clCreateKernel(g_clPeriodMapProgram, "computeSpatialPeriodMap", &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create period map kernel: " << err << std::endl;
return false;
}
// Create program for SLM context
g_clProgram = clCreateProgramWithSource(g_clContext, 1, &kernelSource, nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create program: " << err << std::endl;
return false;
}
// Build program
err = clBuildProgram(g_clProgram, 1, &g_clDevice, nullptr, nullptr, nullptr);
if (err != CL_SUCCESS) {
char buildLog[4096];
clGetProgramBuildInfo(g_clProgram, g_clDevice, CL_PROGRAM_BUILD_LOG, sizeof(buildLog), buildLog, nullptr);
std::cout << "OpenCL build error:\n" << buildLog << std::endl;
return false;
}
// Create kernel for SLM context
g_clKernel = clCreateKernel(g_clProgram, "computeSLMPattern", &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create kernel: " << err << std::endl;
return false;
}
// Create program and kernel for flow multiplication
g_clUpdateFlowProgram = clCreateProgramWithSource(g_clContext, 1, &updateFlowKernel, nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create flow multiply program: " << err << std::endl;
return false;
}
// Build program with detailed error checking
err = clBuildProgram(g_clUpdateFlowProgram, 1, &g_clDevice, nullptr, nullptr, nullptr);
if (err != CL_SUCCESS) {
std::cout << "Failed to build flow multiply program. Error code: " << err << std::endl;
return false;
}
g_clUpdateFlowKernel = clCreateKernel(g_clUpdateFlowProgram, "updateFlowWithScalar", &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create flow multiply kernel: " << err << std::endl;
return false;
}
// Load devignet maps
if (0) {//devignet) {
LoadDevignetMaps();
}
// Create buffers in captured display context
size_t leftImageSize = cameraWidth * cameraHeight * cameraChannels * sizeof(float);
std::cout << "Creating left image buffer of size: " << leftImageSize << " bytes\n";
// Create a zero-initialized host buffer
std::vector<float> leftImageData(leftImageSize, 0);
g_clLeftImage = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, leftImageSize, leftImageData.data(), &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create left image buffer. Error code: " << err << std::endl;
return false;
}
std::cout << "Left image buffer created successfully\n";
size_t rightImageSize = cameraWidth * cameraHeight * cameraChannels * sizeof(float);
std::cout << "Creating right image buffer of size: " << rightImageSize << " bytes\n";
// Create a zero-initialized host buffer
std::vector<float> rightImageData(rightImageSize, 0);
g_clRightImage = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, rightImageSize, rightImageData.data(), &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create right image buffer: " << err << std::endl;
return false;
}
std::cout << "Right image buffer created successfully\n";
size_t topImageSize = cameraWidth * cameraHeight * cameraChannels * sizeof(float);
std::cout << "Creating top image buffer of size: " << topImageSize << " bytes\n";
// Create a zero-initialized host buffer
std::vector<float> topImageData(topImageSize, 0);
g_clTopImage = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, topImageSize, topImageData.data(), &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create top image buffer: " << err << std::endl;
return false;
}
std::cout << "Top image buffer created successfully\n";
size_t bottomImageSize = cameraWidth * cameraHeight * cameraChannels * sizeof(float);
std::cout << "Creating bottom image buffer of size: " << bottomImageSize << " bytes\n";
// Create a zero-initialized host buffer
std::vector<float> bottomImageData(bottomImageSize, 0);
g_clBottomImage = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, bottomImageSize, bottomImageData.data(), &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create bottom image buffer: " << err << std::endl;
return false;
}
std::cout << "Bottom image buffer created successfully\n";
cv::Mat mask = cv::Mat::ones(cameraHeight, cameraWidth, CV_32F);
// Set top and bottom margins to 0
for (int y = 0; y < cameraTopMargin; y++) {
for (int x = 0; x < cameraWidth; x++) {
mask.at<float>(y, x) = 0.0f;
}
}
for (int y = cameraHeight - cameraBottomMargin; y < cameraHeight; y++) {
for (int x = 0; x < cameraWidth; x++) {
mask.at<float>(y, x) = 0.0f;
}
}
g_clMask = clCreateBuffer(g_clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, cameraWidth * cameraHeight * sizeof(float), mask.data, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create mask buffer: " << err << std::endl;
return false;
}
g_clFlow = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE, cameraWidth * cameraHeight * sizeof(float), nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create flow buffer: " << err << std::endl;
return false;
}
// Create a zero-initialized host buffer for spatial frequency map
std::vector<float> zeroImage(cameraWidth * cameraHeight, 0.0f);
// Create the spatial frequency map buffer with proper flags and host pointer
g_clSpatialFreqMap = clCreateBuffer(g_clContext,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
cameraWidth * cameraHeight * sizeof(float),
zeroImage.data(),
&err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create spatial frequency map buffer. Error code: " << err << std::endl;
return false;
}
g_clSpatialFreqMapSuperpixels = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
cameraWidth * cameraHeight * sizeof(float),
zeroImage.data(), &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create spatial frequency map superpixels buffer: " << err << std::endl;
return false;
}
std::cout << "Spatial frequency map superpixels buffer created successfully\n";
g_clLabels = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE,
cameraWidth * cameraHeight * sizeof(int),
nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create labels buffer: " << err << std::endl;
return false;
}
g_clWarpedFreqMap = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE,
SLM_WIDTH * SLM_HEIGHT * sizeof(float),
nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create warped frequency map buffer: " << err << std::endl;
return false;
}
g_clHomography = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE,
9 * sizeof(float), nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create homography buffer: " << err << std::endl;
return false;
}
// Create temporary buffer in captured context for period map computation
g_clPeriodTempMap = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE,
SLM_WIDTH * SLM_HEIGHT * sizeof(float), nullptr, &err);
if (err != CL_SUCCESS) throw std::runtime_error("Failed to create temporary period map buffer");
// Create period map buffer in SLM context instead of captured context
g_clPeriodMap = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE, SLM_WIDTH * SLM_HEIGHT * sizeof(float), nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create period map buffer: " << err << std::endl;
return false;
}
g_clYGrid = clCreateBuffer(g_clContext, CL_MEM_READ_WRITE, SLM_WIDTH * SLM_HEIGHT * sizeof(float), nullptr, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to create Y grid buffer: " << err << std::endl;