-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleGL.cpp
More file actions
1180 lines (966 loc) · 32.9 KB
/
simpleGL.cpp
File metadata and controls
1180 lines (966 loc) · 32.9 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
////////////////////////////////////////////////////////////////////////////
//
// Copyright 1993-2012 NVIDIA Corporation. All rights reserved.
//
// Please refer to the NVIDIA end user license agreement (EULA) associated
// with this source code for terms and conditions that govern your use of
// this software. Any use, reproduction, disclosure, or distribution of
// this software and related documentation outside the terms of the EULA
// is strictly prohibited.
//
////////////////////////////////////////////////////////////////////////////
/*
This example demonstrates how to use the Cuda OpenGL bindings to
dynamically modify a vertex buffer using a Cuda kernel.
The steps are:
1. Create an empty vertex buffer object (VBO)
2. Register the VBO with Cuda
3. Map the VBO for writing from Cuda
4. Run Cuda kernel to modify the vertex positions
5. Unmap the VBO
6. Render the results using OpenGL
Host code
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
// OpenGL Graphics includes
#include <GL/glew.h>
#if defined (__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/freeglut.h>
#endif
// includes, cuda
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
// CUDA utilities and system includes
#include <rendercheck_gl.h>
#include <helper_functions.h>
//#include <helper_cuda.h> // includes for cuda initialization and error checking
#include <shrQATest.h> // standard utility and system includes
#include <vector_types.h>
#include <limits.h>
#define MAX_EPSILON_ERROR 10.0f
#define THRESHOLD 0.30f
#define REFRESH_DELAY 10 //ms
typedef unsigned char Pixel;
////////////////////////////////////////////////////////////////////////////////
// constants
const unsigned int window_width = 512;
const unsigned int window_height = 512;
unsigned int mesh_width = 1024;
unsigned int mesh_height = 1024;
// vbo variables
GLuint vbo;
struct cudaGraphicsResource *cuda_vbo_resource;
void *d_vbo_buffer = NULL;
float g_fAnim = 0.0;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;
float rotate_x = 0.0, rotate_y = 0.0;
float translate_z = -3.0;
StopWatchInterface *timer = NULL;
// Auto-Verification Code
const int frameCheckNumber = 4;
int fpsCount = 0; // FPS count for averaging
int fpsLimit = 1; // FPS limit for sampling
int g_Index = 0;
unsigned int frameCount = 0;
unsigned int g_TotalErrors = 0;
bool g_Verify = false;
bool g_bQAReadback = false;
bool g_bGLVerify = false;
int *pArgc = NULL;
char **pArgv = NULL;
/*
* ------ GLOBALS FROM SobelFilter
*/
unsigned int g_Bpp;
// Display Data
static GLuint pbo_buffer = 0; // Front and back CA buffers
struct cudaGraphicsResource *cuda_pbo_resource; // CUDA Graphics Resource (to transfer PBO)
static GLuint texid = 0; // Texture for display
float imageScale = 1.f; // Image exposure
// Create containers for the original image, the histogram, and the HistEq image
unsigned int gHistogram[UCHAR_MAX-1];
unsigned char *pixels = NULL; // Image pixel data on the host
unsigned char *hEqImage = NULL;
/*
*
*
*/
// CheckFBO/BackBuffer class objects
CheckRender *g_CheckRender = NULL;
#define MAX(a,b) ((a > b) ? a : b)
////////////////////////////////////////////////////////////////////////////////
// kernels
//#include <simpleGL_kernel.cu>
extern "C" void launch_kernel(float4 *pos, unsigned int mesh_width, unsigned int mesh_height, float time);
extern "C" void sobelFilter(Pixel *odata, int iw, int ih, float fScale);
extern "C" void setupTexture(int iw, int ih, Pixel *data, int Bpp);
extern "C" void deleteTexture(void);
////////////////////////////////////////////////////////////////////////////////
// declaration, forward
bool runTest(int argc, char **argv);
void loadDefaultImage(char *loc_exec);
void initializeData(char *file);
void histogramCreate_CPU(const unsigned char *pixels);
void cleanup();
// GL functionality
bool initGL(int *argc, char **argv);
void createVBO(GLuint *vbo, struct cudaGraphicsResource **vbo_res,
unsigned int vbo_res_flags);
void deleteVBO(GLuint *vbo, struct cudaGraphicsResource *vbo_res);
// rendering callbacks
void display();
void keyboard(unsigned char key, int x, int y);
void mouse(int button, int state, int x, int y);
void motion(int x, int y);
void timerEvent(int value);
// Cuda functionality
void runCuda(struct cudaGraphicsResource **vbo_resource);
void runAutoTest();
void checkResultCuda(int argc, char **argv, const GLuint &vbo);
const char *SDK_name = "simpleGL (VBO)";
char* g_cCurrentDeviceName;
////////////////////////////////////////////////////////////////////////////////
// These are CUDA Helper functions
// This will output the proper CUDA error strings in the event that a CUDA host call returns an error
#define checkCudaErrors(err) __checkCudaErrors (err, __FILE__, __LINE__)
inline void __checkCudaErrors(cudaError err, const char *file, const int line)
{
if (cudaSuccess != err)
{
fprintf(stderr, "%s(%i) : CUDA Runtime API error %d: %s.\n",
file, line, (int)err, cudaGetErrorString(err));
exit(-1);
}
}
// This will output the proper error string when calling cudaGetLastError
#define getLastCudaError(msg) __getLastCudaError (msg, __FILE__, __LINE__)
inline void __getLastCudaError(const char *errorMessage, const char *file, const int line)
{
cudaError_t err = cudaGetLastError();
if (cudaSuccess != err)
{
fprintf(stderr, "%s(%i) : getLastCudaError() CUDA error : %s : (%d) %s.\n",
file, line, errorMessage, (int)err, cudaGetErrorString(err));
exit(-1);
}
}
// General GPU Device CUDA Initialization
int gpuDeviceInit(int devID)
{
int deviceCount;
checkCudaErrors(cudaGetDeviceCount(&deviceCount));
if (deviceCount == 0)
{
fprintf(stderr, "gpuDeviceInit() CUDA error: no devices supporting CUDA.\n");
exit(-1);
}
if (devID < 0)
{
devID = 0;
}
if (devID > deviceCount-1)
{
fprintf(stderr, "\n");
fprintf(stderr, ">> %d CUDA capable GPU device(s) detected. <<\n", deviceCount);
fprintf(stderr, ">> gpuDeviceInit (-device=%d) is not a valid GPU device. <<\n", devID);
fprintf(stderr, "\n");
exit(-1);
}
cudaDeviceProp deviceProp;
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, devID));
if (deviceProp.major < 1)
{
fprintf(stderr, "gpuDeviceInit(): GPU device does not support CUDA.\n");
exit(-1);
}
checkCudaErrors(cudaSetDevice(devID));
printf("gpuDeviceInit() CUDA Device [%d]: \"%s\n", devID, deviceProp.name);
return devID;
}
#ifndef MAX
#define MAX(a,b) (a > b ? a : b)
#endif
// Beginning of GPU Architecture definitions
inline int _ConvertSMVer2Cores(int major, int minor)
{
// Defines for GPU Architecture types (using the SM version to determine the # of cores per SM
typedef struct
{
int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
int Cores;
} sSMtoCores;
sSMtoCores nGpuArchCoresPerSM[] =
{
{ 0x10, 8 }, // Tesla Generation (SM 1.0) G80 class
{ 0x11, 8 }, // Tesla Generation (SM 1.1) G8x class
{ 0x12, 8 }, // Tesla Generation (SM 1.2) G9x class
{ 0x13, 8 }, // Tesla Generation (SM 1.3) GT200 class
{ 0x20, 32 }, // Fermi Generation (SM 2.0) GF100 class
{ 0x21, 48 }, // Fermi Generation (SM 2.1) GF10x class
{ 0x30, 192}, // Fermi Generation (SM 3.0) GK10x class
{ -1, -1 }
};
int index = 0;
while (nGpuArchCoresPerSM[index].SM != -1)
{
if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor))
{
return nGpuArchCoresPerSM[index].Cores;
}
index++;
}
printf("MapSMtoCores undefined SM %d.%d is undefined (please update to the latest SDK)!\n", major, minor);
return -1;
}
// end of GPU Architecture definitions
// This function returns the best GPU (with maximum GFLOPS)
int gpuGetMaxGflopsDeviceId()
{
int current_device = 0, sm_per_multiproc = 0;
int max_compute_perf = 0, max_perf_device = 0;
int device_count = 0, best_SM_arch = 0;
int best_SM_minor = 0;
cudaDeviceProp deviceProp;
cudaGetDeviceCount(&device_count);
// Find the best major SM Architecture GPU device
while (current_device < device_count)
{
cudaGetDeviceProperties(&deviceProp, current_device);
printf("Device name: %s - DeviceProp.major = %d\n", deviceProp.name, deviceProp.major);
if (deviceProp.major > 0 && deviceProp.major < 9999)
{
best_SM_arch = MAX(best_SM_arch, deviceProp.major);
best_SM_minor = MAX(best_SM_minor, deviceProp.minor);
}
current_device++;
}
// Find the best CUDA capable GPU device
current_device = 0;
while (current_device < device_count)
{
cudaGetDeviceProperties(&deviceProp, current_device);
printf("Device found: %s\n", deviceProp.name);
if (deviceProp.major == 9999 && deviceProp.minor == 9999)
{
sm_per_multiproc = 1;
}
else
{
sm_per_multiproc = _ConvertSMVer2Cores(deviceProp.major, deviceProp.minor);
}
int compute_perf = deviceProp.multiProcessorCount * sm_per_multiproc * deviceProp.clockRate;
printf("Current device compute performance: %d\n", compute_perf);
if (compute_perf > max_compute_perf)
{
max_compute_perf = compute_perf;
max_perf_device = current_device;
printf("Current device has best perf\n");
}
++current_device;
}
// Get the name of the best performing device
cudaGetDeviceProperties(&deviceProp, max_perf_device);
g_cCurrentDeviceName = (char*)malloc(strlen(deviceProp.name));
strcpy(g_cCurrentDeviceName, deviceProp.name);
printf("Max performance device: %d - %s\n", max_perf_device, g_cCurrentDeviceName);
return max_perf_device;
}
// Initialization code to find the best CUDA Device
int findCudaDevice(int argc, const char **argv)
{
cudaDeviceProp deviceProp;
int devID = 0;
// If the command-line has a device number specified, use it
if (checkCmdLineFlag(argc, argv, "device"))
{
devID = getCmdLineArgumentInt(argc, argv, "device=");
if (devID < 0)
{
printf("Invalid command line parameter\n ");
exit(-1);
}
else
{
devID = gpuDeviceInit(devID);
if (devID < 0)
{
printf("exiting...\n");
shrQAFinishExit(argc, (const char **)argv, QA_FAILED);
exit(-1);
}
}
}
else
{
// Otherwise pick the device with highest Gflops/s
devID = gpuGetMaxGflopsDeviceId();
checkCudaErrors(cudaSetDevice(devID));
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, devID));
printf("GPU Device %d: \"%s\" with compute capability %d.%d\n\n", devID, deviceProp.name, deviceProp.major, deviceProp.minor);
}
return devID;
}
inline int gpuGLDeviceInit(int ARGC, char **ARGV)
{
int deviceCount;
checkCudaErrors(cudaGetDeviceCount(&deviceCount));
if (deviceCount == 0)
{
fprintf(stderr, "CUDA error: no devices supporting CUDA.\n");
exit(-1);
}
int dev = 0;
dev = getCmdLineArgumentInt(ARGC, (const char **) ARGV, "device=");
if (dev < 0)
{
dev = 0;
}
if (dev > deviceCount-1)
{
fprintf(stderr, "\n");
fprintf(stderr, ">> %d CUDA capable GPU device(s) detected. <<\n", deviceCount);
fprintf(stderr, ">> gpuGLDeviceInit (-device=%d) is not a valid GPU device. <<\n", dev);
fprintf(stderr, "\n");
return -dev;
}
cudaDeviceProp deviceProp;
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev));
if (deviceProp.major < 1)
{
fprintf(stderr, "Error: device does not support CUDA.\n");
exit(-1);
\
}
if (checkCmdLineFlag(ARGC, (const char **) ARGV, "quiet") == false)
{
fprintf(stderr, "Using device %d: %s\n", dev, deviceProp.name);
}
checkCudaErrors(cudaGLSetGLDevice(dev));
return dev;
}
// This function will pick the best CUDA device available with OpenGL interop
inline int findCudaGLDevice(int argc, char **argv)
{
int devID = 0;
// If the command-line has a device number specified, use it
if (checkCmdLineFlag(argc, (const char **)argv, "device"))
{
devID = gpuGLDeviceInit(argc, argv);
if (devID < 0)
{
printf("exiting...\n");
cudaDeviceReset();
exit(0);
}
}
else
{
// Otherwise pick the device with highest Gflops/s
devID = gpuGetMaxGflopsDeviceId();
cudaGLSetGLDevice(devID);
}
return devID;
}
////////////////////////////////////////////////////////////////////////////
//! Check for OpenGL error
//! @return true if no GL error has been encountered, otherwise 0
//! @param file __FILE__ macro
//! @param line __LINE__ macro
//! @note The GL error is listed on stderr
//! @note This function should be used via the CHECK_ERROR_GL() macro
////////////////////////////////////////////////////////////////////////////
inline bool
sdkCheckErrorGL(const char *file, const int line)
{
bool ret_val = true;
// check for error
GLenum gl_error = glGetError();
if (gl_error != GL_NO_ERROR)
{
#ifdef _WIN32
char tmpStr[512];
// NOTE: "%s(%i) : " allows Visual Studio to directly jump to the file at the right line
// when the user double clicks on the error line in the Output pane. Like any compile error.
sprintf_s(tmpStr, 255, "\n%s(%i) : GL Error : %s\n\n", file, line, gluErrorString(gl_error));
OutputDebugString(tmpStr);
#endif
fprintf(stderr, "GL Error in file '%s' in line %d :\n", file, line);
fprintf(stderr, "%s\n", gluErrorString(gl_error));
ret_val = false;
}
return ret_val;
}
#define SDK_CHECK_ERROR_GL() \
if( false == sdkCheckErrorGL( __FILE__, __LINE__)) { \
exit(EXIT_FAILURE); \
}
// end of CUDA Helper Functions
bool checkHW(char *name, char *gpuType, int dev)
{
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, dev);
strcpy(name, deviceProp.name);
if (!STRNCASECMP(deviceProp.name, gpuType, strlen(gpuType)))
{
return true;
}
else
{
return false;
}
}
int findGraphicsGPU(char *name)
{
int nGraphicsGPU = 0;
int deviceCount = 0;
bool bFoundGraphics = false;
char firstGraphicsName[256], temp[256];
cudaError_t error_id = cudaGetDeviceCount(&deviceCount);
if (error_id != cudaSuccess)
{
printf("cudaGetDeviceCount returned %d\n-> %s\n", (int)error_id, cudaGetErrorString(error_id));
shrQAFinishExit(*pArgc, (const char **)pArgv, QA_FAILED);
}
// This function call returns 0 if there are no CUDA capable devices.
if (deviceCount == 0)
{
printf("> There are no device(s) supporting CUDA\n");
return false;
}
else
{
printf("> Found %d CUDA Capable Device(s)\n", deviceCount);
}
for (int dev = 0; dev < deviceCount; ++dev)
{
bool bGraphics = !checkHW(temp, "Tesla", dev);
printf("> %s\t\tGPU %d: %s\n", (bGraphics ? "Graphics" : "Compute"), dev, temp);
if (bGraphics)
{
if (!bFoundGraphics)
{
strcpy(firstGraphicsName, temp);
}
nGraphicsGPU++;
}
}
if (nGraphicsGPU)
{
strcpy(name, firstGraphicsName);
}
else
{
strcpy(name, "this hardware");
}
return nGraphicsGPU;
}
void equalizeImage(const unsigned char* pixels){
// Create output image
hEqImage = (unsigned char*)malloc( sizeof(unsigned char) * mesh_width * mesh_height);
unsigned int cdf[UCHAR_MAX];
unsigned int runningSum = 0;
for(int i = 0; i < UCHAR_MAX-1; i++){
runningSum += gHistogram[i];
cdf[i] = runningSum;
}
// Calculate equalized image
unsigned int totalElements = (unsigned int)mesh_width * (unsigned int)mesh_height;
unsigned int currentValue = 0;
unsigned int currentResult = 0;
for(int i = 0; i < mesh_width * mesh_height; i++){
currentValue = cdf[ pixels[i] ];
currentResult = (currentValue * (UCHAR_MAX-1)) / totalElements;
hEqImage[i] = (unsigned char)currentResult;
}
printf("Finished equalizing\n");
//FILE *fp;
//fopen(fp, "lena_eq.pgm", "wb");
char *saveFile = "./data/lena_eq.pgm";
sdkSavePGM(saveFile, hEqImage, mesh_width, mesh_height);
}
void histogramCreate_CPU(const unsigned char *pixels)
{
// Clear out the histogram counts
memset(gHistogram, 0x0, sizeof(Pixel) * UCHAR_MAX);
// Create histogram
for(int i = 0; i < mesh_width * mesh_height; i++){
gHistogram[ pixels[i] ]++;
}
// Print the histogram in the console
/*int count = 0;
for(int i = 0; i < UCHAR_MAX; i++){
count = gHistogram[i];
// print a '|' character for each 10 counts for a value
if(count > 10){
printf("[%d]: |", i);
for(int i = 0; i < count; i++){
if(count % 10 == 0)
printf("|");
}
printf("\n");
}
}*/
}
void initializeData(char *file)
{
GLint bsize;
unsigned int w, h;
size_t file_length= strlen(file);
// Load one frame of image
if (!strcmp(&file[file_length-3], "pgm"))
{
printf("Filename: %s \n", file);
if (sdkLoadPGM<unsigned char>(file, &pixels, &w, &h) != true)
{
printf("Failed to load PGM image file: %s\n", file);
exit(-1);
}
printf("Loaded image successfully.\n");
g_Bpp = 1;
}
// Create a texture and load the image onto it
mesh_width = (int)w;
mesh_height = (int)h;
setupTexture(mesh_width, mesh_height, pixels, g_Bpp);
printf("Texture setup completed. Size: %d x %d\n", mesh_width, mesh_height);
// Create histogram
histogramCreate_CPU(pixels);
equalizeImage(pixels);
//memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * mesh_width * mesh_height);
if (!g_bQAReadback)
{
printf("Starting PBO setup.\n");
// This code creates a PBO for the output image
// But in our application it is NOT necessary
/*glGenBuffers(1, &pbo_buffer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
glBufferData(GL_PIXEL_UNPACK_BUFFER,
g_Bpp * sizeof(Pixel) * mesh_width * mesh_height,
pixels, GL_STREAM_DRAW);
glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize);
if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * mesh_width * mesh_height))
{
printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);
cudaDeviceReset();
exit(-1);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
// register this buffer object with CUDA
checkCudaErrors(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo_buffer, cudaGraphicsMapFlagsWriteDiscard));
*/
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA),
mesh_width, mesh_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
}
}
void loadDefaultImage(char *loc_exec)
{
printf("Reading image: lena.pgm\n");
const char *image_filename = "lena.pgm";
char *image_path = sdkFindFilePath(image_filename, loc_exec);
if (image_path == NULL)
{
printf("Failed to read image file: <%s>\n", image_filename);
shrQAFinishExit2(false, *pArgc, (const char **)pArgv, QA_FAILED);
}
initializeData(image_path);
free(image_path);
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
pArgc = &argc;
pArgv = argv;
shrQAStart(argc, argv);
if (argc > 1)
{
if (checkCmdLineFlag(argc, (const char **)argv, "qatest") ||
checkCmdLineFlag(argc, (const char **)argv, "noprompt"))
{
printf("- (automated test no-OpenGL)\n");
g_bQAReadback = true;
// g_bGLVerify = true;
fpsLimit = frameCheckNumber;
}
else if (checkCmdLineFlag(argc, (const char **)argv, "glverify"))
{
printf("- (automated test OpenGL rendering)\n");
g_bGLVerify = true;
fpsLimit = frameCheckNumber;
}
}
printf("\n");
runTest(argc, argv);
cudaDeviceReset();
shrQAFinishExit(argc, (const char **)argv, (g_TotalErrors == 0) ? QA_PASSED : QA_FAILED);
}
void AutoQATest()
{
if (g_CheckRender && g_CheckRender->IsQAReadback())
{
char temp[256];
sprintf(temp, "AutoTest: Cuda GL Interop (VBO)");
glutSetWindowTitle(temp);
shrQAFinishExit2(true, *pArgc, (const char **)pArgv, QA_PASSED);
}
}
void computeFPS()
{
frameCount++;
fpsCount++;
if (fpsCount == fpsLimit-1)
{
g_Verify = true;
}
if (fpsCount == fpsLimit)
{
char fps[256];
float ifps = 1.f / (sdkGetAverageTimerValue(&timer) / 1000.f);
if(frameCount % 10 == 0){
sprintf(fps, "%sSimpleGL_Image: %3.1f fps on device [%s]",
((g_CheckRender && g_CheckRender->IsQAReadback()) ? "AutoTest: " : ""), ifps, g_cCurrentDeviceName);
glutSetWindowTitle(fps);
}
fpsCount = 0;
if (g_CheckRender && !g_CheckRender->IsQAReadback())
{
fpsLimit = (int)MAX(ifps, 1.f);
}
sdkResetTimer(&timer);
AutoQATest();
}
}
////////////////////////////////////////////////////////////////////////////////
//! Initialize GL
////////////////////////////////////////////////////////////////////////////////
bool initGL(int *argc, char **argv)
{
glutInit(argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(window_width, window_height);
glutCreateWindow("Cuda GL Interop (VBO)");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMotionFunc(motion);
glutTimerFunc(REFRESH_DELAY, timerEvent,0);
// initialize necessary OpenGL extensions
glewInit();
if (! glewIsSupported("GL_VERSION_2_0 "))
{
fprintf(stderr, "ERROR: Support for necessary OpenGL extensions missing.");
fflush(stderr);
return false;
}
// default initialization
glClearColor(0.0, 0.0, 0.0, 1.0);
glDisable(GL_DEPTH_TEST);
// viewport
glViewport(0, 0, window_width, window_height);
// projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)window_width / (GLfloat) window_height, 0.1, 10.0);
SDK_CHECK_ERROR_GL();
return true;
}
////////////////////////////////////////////////////////////////////////////////
//! Run a simple test for CUDA
////////////////////////////////////////////////////////////////////////////////
bool runTest(int argc, char **argv)
{
// Create the CUTIL timer
sdkCreateTimer(&timer);
printf("Finished loading image\n");
// command line mode only
if (g_bQAReadback)
{
// This will pick the best possible CUDA capable device
int devID = findCudaDevice((const int)argc, (const char **)argv);
// create VBO
createVBO(NULL, NULL, 0);
}
else
{
// First initialize OpenGL context, so we can properly set the GL for CUDA.
// This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
if (false == initGL(&argc, argv))
{
return false;
}
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
if (checkCmdLineFlag(argc, (const char **)argv, "device"))
{
gpuGLDeviceInit(argc, argv);
}
else
{
cudaGLSetGLDevice(gpuGetMaxGflopsDeviceId());
}
// Load input image into a texture
loadDefaultImage(argv[0]);
// register callbacks
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMotionFunc(motion);
// create VBO
createVBO(&vbo, &cuda_vbo_resource, cudaGraphicsMapFlagsWriteDiscard);
}
if (g_bQAReadback)
{
g_CheckRender = new CheckBackBuffer(window_width, window_height, 4, false);
g_CheckRender->setPixelFormat(GL_RGBA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
runAutoTest();
}
else
{
if (g_bGLVerify)
{
g_CheckRender = new CheckBackBuffer(window_width, window_height, 4);
g_CheckRender->setPixelFormat(GL_RGBA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
}
// run the cuda part
runCuda(&cuda_vbo_resource);
}
// check result of Cuda step
checkResultCuda(argc, argv, vbo);
if (!g_bQAReadback)
{
atexit(cleanup);
// start rendering mainloop
glutMainLoop();
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
//! Run the Cuda part of the computation
////////////////////////////////////////////////////////////////////////////////
void runCuda(struct cudaGraphicsResource **vbo_resource)
{
// map OpenGL buffer object for writing from CUDA
float4 *dptr;
// DEPRECATED: checkCudaErrors(cudaGLMapBufferObject((void**)&dptr, vbo));
checkCudaErrors(cudaGraphicsMapResources(1, vbo_resource, 0));
size_t num_bytes;
checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&dptr, &num_bytes,
*vbo_resource));
//printf("CUDA mapped VBO: May access %ld bytes\n", num_bytes);
// execute the kernel
// dim3 block(8, 8, 1);
// dim3 grid(mesh_width / block.x, mesh_height / block.y, 1);
// kernel<<< grid, block>>>(dptr, mesh_width, mesh_height, g_fAnim);
launch_kernel(dptr, mesh_width, mesh_height, g_fAnim);
// unmap buffer object
// DEPRECATED: checkCudaErrors(cudaGLUnmapBufferObject(vbo));
checkCudaErrors(cudaGraphicsUnmapResources(1, vbo_resource, 0));
}
////////////////////////////////////////////////////////////////////////////////
//! Run the Cuda part of the computation
////////////////////////////////////////////////////////////////////////////////
void runAutoTest()
{
// execute the kernel
launch_kernel((float4 *)d_vbo_buffer, mesh_width, mesh_height, g_fAnim);
cudaDeviceSynchronize();
getLastCudaError("launch_kernel failed");
checkCudaErrors(cudaMemcpy(g_CheckRender->imageData(), d_vbo_buffer, mesh_width*mesh_height*sizeof(float), cudaMemcpyDeviceToHost));
g_CheckRender->dumpBin((void *)g_CheckRender->imageData(), mesh_width*mesh_height*sizeof(float), "simpleGL.bin");
if (!g_CheckRender->compareBin2BinFloat("simpleGL.bin", "ref_simpleGL.bin", mesh_width*mesh_height*sizeof(float), MAX_EPSILON_ERROR, THRESHOLD))
{
g_TotalErrors++;
}
}
////////////////////////////////////////////////////////////////////////////////
//! Create VBO
////////////////////////////////////////////////////////////////////////////////
void createVBO(GLuint *vbo, struct cudaGraphicsResource **vbo_res,
unsigned int vbo_res_flags)
{
if (vbo)
{
// create buffer object
glGenBuffers(1, vbo);
glBindBuffer(GL_ARRAY_BUFFER, *vbo);
// initialize buffer object
unsigned int size = mesh_width * mesh_height * 4 * sizeof(float);
glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// register this buffer object with CUDA
// DEPRECATED: checkCudaErrors(cudaGLRegisterBufferObject(*vbo));
printf("Registering VBO with CUDA\n");
checkCudaErrors(cudaGraphicsGLRegisterBuffer(vbo_res, *vbo, vbo_res_flags));
SDK_CHECK_ERROR_GL();