-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshrUtils.cpp
1926 lines (1731 loc) · 70.6 KB
/
shrUtils.cpp
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-2010 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.
*
*/
// *********************************************************************
// Generic Utilities for NVIDIA GPU Computing SDK
// *********************************************************************
// includes
#include "StdAfx.h"
#include <shrUtils.h>
#include <cmd_arg_reader.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdio.h>
using namespace std;
// size of PGM file header
const unsigned int PGMHeaderSize = 0x40;
#define MIN_EPSILON_ERROR 1e-3f
// Deallocate memory allocated within shrUtils
// *********************************************************************
void shrFree(void* ptr)
{
if( NULL != ptr) free( ptr);
}
// Helper function to init data arrays
// *********************************************************************
void shrFillArray(float* pfData, int iSize)
{
int i;
const float fScale = 1.0f / (float)RAND_MAX;
for (i = 0; i < iSize; ++i)
{
pfData[i] = fScale * rand();
}
}
// Helper function to print data arrays
// *********************************************************************
void shrPrintArray(float* pfData, int iSize)
{
int i;
for (i = 0; i < iSize; ++i)
{
shrLog("%d: %.3f\n", i, pfData[i]);
}
}
// Helper function to return precision delta time for 3 counters since last call based upon host high performance counter
// *********************************************************************
double shrDeltaT(int iCounterID = 0)
{
// local var for computation of microseconds since last call
double DeltaT;
#ifdef _WIN32 // Windows version of precision host timer
// Variables that need to retain state between calls
static LARGE_INTEGER liOldCount[3] = { {0, 0}, {0, 0}, {0, 0} };
// locals for new count, new freq and new time delta
LARGE_INTEGER liNewCount, liFreq;
if (QueryPerformanceFrequency(&liFreq))
{
// Get new counter reading
QueryPerformanceCounter(&liNewCount);
if (iCounterID >= 0 && iCounterID <= 2)
{
// Calculate time difference for timer 0. (zero when called the first time)
DeltaT = liOldCount[iCounterID].LowPart ? (((double)liNewCount.QuadPart - (double)liOldCount[iCounterID].QuadPart) / (double)liFreq.QuadPart) : 0.0;
// Reset old count to new
liOldCount[iCounterID] = liNewCount;
}
else
{
// Requested counter ID out of range
DeltaT = -9999.0;
}
// Returns time difference in seconds sunce the last call
return DeltaT;
}
else
{
// No high resolution performance counter
return -9999.0;
}
#elif defined(UNIX) // Linux version of precision host timer. See http://www.informit.com/articles/article.aspx?p=23618&seqNum=8
static struct timeval _NewTime; // new wall clock time (struct representation in seconds and microseconds)
static struct timeval _OldTime[3]; // old wall clock timers 0, 1, 2 (struct representation in seconds and microseconds)
// Get new counter reading
gettimeofday(&_NewTime, NULL);
if (iCounterID >= 0 && iCounterID <= 2)
{
// Calculate time difference for timer (iCounterID). (zero when called the first time)
DeltaT = ((double)_NewTime.tv_sec + 1.0e-6 * (double)_NewTime.tv_usec) - ((double)_OldTime[iCounterID].tv_sec + 1.0e-6 * (double)_OldTime[iCounterID].tv_usec);
// Reset old timer (iCounterID) to new timer
_OldTime[iCounterID].tv_sec = _NewTime.tv_sec;
_OldTime[iCounterID].tv_usec = _NewTime.tv_usec;
}
else
{
// Requested counterID is out of rangewith respect to available counters
DeltaT = -9999.0;
}
// Returns time difference in seconds sunce the last call
return DeltaT;
#elif defined (__APPLE__) || defined (MACOSX)
static time_t _NewTime;
static time_t _OldTime[3];
_NewTime = clock();
if (iCounterID >= 0 && iCounterID <= 2)
{
// Calculate time difference for timer (iCounterID). (zero when called the first time)
DeltaT = double(_NewTime-_OldTime[iCounterID])/CLOCKS_PER_SEC;
// Reset old time (iCounterID) to the new one
_OldTime[iCounterID].tv_sec = _NewTime.tv_sec;
_OldTime[iCounterID].tv_usec = _NewTime.tv_usec;
}
else
{
// Requested counter ID out of range
DeltaT = -9999.0;
}
return DeltaT;
#else
printf("shrDeltaT returning early\n");
#endif
}
// Optional LogFileName Override function
// *********************************************************************
char* cLogFilePathAndName = NULL;
void shrSetLogFileName (const char* cOverRideName)
{
if( cLogFilePathAndName != NULL ) {
free(cLogFilePathAndName);
}
cLogFilePathAndName = (char*) malloc(strlen(cOverRideName) + 1);
#ifdef WIN32
strcpy_s(cLogFilePathAndName, strlen(cOverRideName) + 1, cOverRideName);
#else
strcpy(cLogFilePathAndName, cOverRideName);
#endif
return;
}
// Function to log standardized information to console, file or both
// *********************************************************************
static int shrLogV(int iLogMode, int iErrNum, const char* cFormatString, va_list vaArgList)
{
static FILE* pFileStream0 = NULL;
static FILE* pFileStream1 = NULL;
size_t szNumWritten = 0;
char cFileMode [3];
// if the sample log file is closed and the call includes a "write-to-file", open file for writing
if ((pFileStream0 == NULL) && (iLogMode & LOGFILE))
{
// if the default filename has not been overriden, set to default
if (cLogFilePathAndName == NULL)
{
shrSetLogFileName(DEFAULTLOGFILE);
}
#ifdef _WIN32 // Windows version
// set the file mode
if (iLogMode & APPENDMODE) // append to prexisting file contents
{
sprintf_s (cFileMode, 3, "a+");
}
else // replace prexisting file contents
{
sprintf_s (cFileMode, 3, "w");
}
// open the individual sample log file in the requested mode
errno_t err = fopen_s(&pFileStream0, cLogFilePathAndName, cFileMode);
// if error on attempt to open, be sure the file is null or close it, then return negative error code
if (err != 0)
{
if (pFileStream0)
{
fclose (pFileStream0);
}
iLogMode = LOGCONSOLE; // if we can't open a file, we will still output to the console window
}
#else // Linux & Mac version
// set the file mode
if (iLogMode & APPENDMODE) // append to prexisting file contents
{
sprintf (cFileMode, "a+");
}
else // replace prexisting file contents
{
sprintf (cFileMode, "w");
}
// open the file in the requested mode
if ((pFileStream0 = fopen(cLogFilePathAndName, cFileMode)) == 0)
{
// if error on attempt to open, be sure the file is null or close it, then return negative error code
if (pFileStream0)
{
fclose (pFileStream0);
}
iLogMode = LOGCONSOLE; // if we can't open a file, we will still output to the console window
}
#endif
}
// if the master log file is closed and the call incudes a "write-to-file" and MASTER, open master logfile file for writing
if ((pFileStream1 == NULL) && (iLogMode & LOGFILE) && (iLogMode & MASTER))
{
#ifdef _WIN32 // Windows version
// open the master log file in append mode
errno_t err = fopen_s(&pFileStream1, MASTERLOGFILE, "a+");
// if error on attempt to open, be sure the file is null or close it, then return negative error code
if (err != 0)
{
if (pFileStream1)
{
fclose (pFileStream1);
pFileStream1 = NULL;
}
iLogMode = LOGCONSOLE; // Force to LOGCONSOLE only since the file stream is invalid
// return -err;
}
#else // Linux & Mac version
// open the file in the requested mode
if ((pFileStream1 = fopen(MASTERLOGFILE, "a+")) == 0)
{
// if error on attempt to open, be sure the file is null or close it, then return negative error code
if (pFileStream1)
{
fclose (pFileStream1);
pFileStream1 = NULL;
}
iLogMode = LOGCONSOLE; // Force to LOGCONSOLE only since the file stream is invalid
// return -1;
}
#endif
// If master log file length has become excessive, empty/reopen
if (iLogMode != LOGCONSOLE)
{
fseek(pFileStream1, 0L, SEEK_END);
if (ftell(pFileStream1) > 50000L)
{
fclose (pFileStream1);
#ifdef _WIN32 // Windows version
fopen_s(&pFileStream1, MASTERLOGFILE, "w");
#else
pFileStream1 = fopen(MASTERLOGFILE, "w");
#endif
}
}
}
// Handle special Error Message code
if (iLogMode & ERRORMSG)
{
// print string to console if flagged
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf ("\n !!! Error # %i at ", iErrNum); // console
}
// print string to file if flagged
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, "\n !!! Error # %i at ", iErrNum); // sample log file
}
}
// Vars used for variable argument processing
const char* pStr;
const char* cArg;
int iArg;
double dArg;
unsigned int uiArg;
std::string sFormatSpec;
const std::string sFormatChars = " -+#0123456789.dioufnpcsXxEeGgAa";
const std::string sTypeChars = "dioufnpcsXxEeGgAa";
char cType = 'c';
// Start at the head of the string and scan to the null at the end
for (pStr = cFormatString; *pStr; ++pStr)
{
// Check if the current character is not a formatting specifier ('%')
if (*pStr != '%')
{
// character is not '%', so print it verbatim to console and/or files as flagged
if (iLogMode & LOGCONSOLE)
{
szNumWritten = putc(*pStr, stdout); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = putc(*pStr, pFileStream0); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = putc(*pStr, pFileStream1); // master log file
}
}
}
else
{
// character is '%', so skip over it and read the full format specifier for the argument
++pStr;
sFormatSpec = '%';
// special handling for string of %%%%
bool bRepeater = (*pStr == '%');
if (bRepeater)
{
cType = '%';
}
// chars after the '%' are part of format if on list of constants... scan until that isn't true or NULL is found
while (pStr && ((sFormatChars.find(*pStr) != string::npos) || bRepeater))
{
sFormatSpec += *pStr;
// If the char is a type specifier, trap it and stop scanning
// (a type specifier char is always the last in the format except for string of %%%)
if (sTypeChars.find(*pStr) != string::npos)
{
cType = *pStr;
break;
}
// Special handling for string of %%%
// If a string of %%% was started and then it ends, break (There won't be a typical type specifier)
if (bRepeater && (*pStr != '%'))
{
break;
}
pStr++;
}
// Now handle the arg according to type
switch (cType)
{
case '%': // special handling for string of %%%%
{
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf(sFormatSpec.c_str()); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str()); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str()); // master log file
}
}
continue;
}
case 'c': // single byte char
case 's': // string of single byte chars
{
// Set cArg as the next value in list and print to console and/or files if flagged
cArg = va_arg(vaArgList, char*);
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf(sFormatSpec.c_str(), cArg); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), cArg); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), cArg); // master log file
}
}
continue;
}
case 'd': // signed decimal integer
case 'i': // signed decimal integer
{
// set iArg as the next value in list and print to console and/or files if flagged
iArg = va_arg(vaArgList, int);
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf(sFormatSpec.c_str(), iArg); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), iArg); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), iArg); // master log file
}
}
continue;
}
case 'u': // unsigned decimal integer
case 'o': // unsigned octal integer
case 'x': // unsigned hexadecimal integer using "abcdef"
case 'X': // unsigned hexadecimal integer using "ABCDEF"
{
// set uiArg as the next value in list and print to console and/or files if flagged
uiArg = va_arg(vaArgList, unsigned int);
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf(sFormatSpec.c_str(), uiArg); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), uiArg); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), uiArg); // master log file
}
}
continue;
}
case 'f': // float/double
case 'e': // scientific double/float
case 'E': // scientific double/float
case 'g': // scientific double/float
case 'G': // scientific double/float
case 'a': // signed hexadecimal double precision float
case 'A': // signed hexadecimal double precision float
{
// set dArg as the next value in list and print to console and/or files if flagged
dArg = va_arg(vaArgList, double);
if (iLogMode & LOGCONSOLE)
{
szNumWritten = printf(sFormatSpec.c_str(), dArg); // console
}
if (iLogMode & LOGFILE)
{
szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), dArg); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), dArg); // master log file
}
}
continue;
}
default:
{
// print arg of unknown/unsupported type to console and/or file if flagged
if (iLogMode & LOGCONSOLE) // console
{
szNumWritten = putc(*pStr, stdout);
}
if (iLogMode & LOGFILE)
{
szNumWritten = putc(*pStr, pFileStream0); // sample log file
if (iLogMode & MASTER)
{
szNumWritten = putc(*pStr, pFileStream1); // master log file
}
}
}
}
}
}
// end the sample log with a horizontal line if closing
if (iLogMode & CLOSELOG)
{
if (iLogMode & LOGCONSOLE)
{
printf(HDASHLINE);
}
if (iLogMode & LOGFILE)
{
fprintf(pFileStream0, HDASHLINE);
}
}
// flush console and/or file buffers if updated
if (iLogMode & LOGCONSOLE)
{
fflush(stdout);
}
if (iLogMode & LOGFILE)
{
fflush (pFileStream0);
// if the master log file has been updated, flush it too
if (iLogMode & MASTER)
{
fflush (pFileStream1);
}
}
// If the log file is open and the caller requests "close file", then close and NULL file handle
if ((pFileStream0) && (iLogMode & CLOSELOG))
{
fclose (pFileStream0);
pFileStream0 = NULL;
}
if ((pFileStream1) && (iLogMode & CLOSELOG))
{
fclose (pFileStream1);
pFileStream1 = NULL;
}
// return error code or OK
if (iLogMode & ERRORMSG)
{
return iErrNum;
}
else
{
return 0;
}
}
// Function to log standardized information to console, file or both
// *********************************************************************
int shrLogEx(int iLogMode = LOGCONSOLE, int iErrNum = 0, const char* cFormatString = "", ...)
{
va_list vaArgList;
// Prepare variable agument list
va_start(vaArgList, cFormatString);
int ret = shrLogV(iLogMode, iErrNum, cFormatString, vaArgList);
// end variable argument handler
va_end(vaArgList);
return ret;
}
// Function to log standardized information to console, file or both
// *********************************************************************
int shrLog(const char* cFormatString = "", ...)
{
va_list vaArgList;
// Prepare variable agument list
va_start(vaArgList, cFormatString);
int ret = shrLogV(LOGBOTH, 0, cFormatString, vaArgList);
// end variable argument handler
va_end(vaArgList);
return ret;
}
//////////////////////////////////////////////////////////////////////////////
//! Find the path for a file assuming that
//! files are found in the searchPath.
//!
//! @return the path if succeeded, otherwise 0
//! @param filename name of the file
//! @param executable_path optional absolute path of the executable
//////////////////////////////////////////////////////////////////////////////
char* shrFindFilePath(const char* filename, const char* executable_path)
{
// <executable_name> defines a variable that is replaced with the name of the executable
// Typical relative search paths to locate needed companion files (e.g. sample input data, or JIT source files)
// The origin for the relative search may be the .exe file, a .bat file launching an .exe, a browser .exe launching the .exe or .bat, etc
const char* searchPath[] =
{
"./", // same dir
"./data/", // "/data/" subdir
"./src/", // "/src/" subdir
"./src/<executable_name>/data/", // "/src/<executable_name>/data/" subdir
"./inc/", // "/inc/" subdir
"../", // up 1 in tree
"../data/", // up 1 in tree, "/data/" subdir
"../src/", // up 1 in tree, "/src/" subdir
"../inc/", // up 1 in tree, "/inc/" subdir
"../OpenCL/src/<executable_name>/", // up 1 in tree, "/OpenCL/src/<executable_name>/" subdir
"../OpenCL/src/<executable_name>/data/", // up 1 in tree, "/OpenCL/src/<executable_name>/data/" subdir
"../OpenCL/src/<executable_name>/src/", // up 1 in tree, "/OpenCL/src/<executable_name>/src/" subdir
"../OpenCL/src/<executable_name>/inc/", // up 1 in tree, "/OpenCL/src/<executable_name>/inc/" subdir
"../C/src/<executable_name>/", // up 1 in tree, "/C/src/<executable_name>/" subdir
"../C/src/<executable_name>/data/", // up 1 in tree, "/C/src/<executable_name>/data/" subdir
"../C/src/<executable_name>/src/", // up 1 in tree, "/C/src/<executable_name>/src/" subdir
"../C/src/<executable_name>/inc/", // up 1 in tree, "/C/src/<executable_name>/inc/" subdir
"../DirectCompute/src/<executable_name>/", // up 1 in tree, "/DirectCompute/src/<executable_name>/" subdir
"../DirectCompute/src/<executable_name>/data/", // up 1 in tree, "/DirectCompute/src/<executable_name>/data/" subdir
"../DirectCompute/src/<executable_name>/src/", // up 1 in tree, "/DirectCompute/src/<executable_name>/src/" subdir
"../DirectCompute/src/<executable_name>/inc/", // up 1 in tree, "/DirectCompute/src/<executable_name>/inc/" subdir
"../../", // up 2 in tree
"../../data/", // up 2 in tree, "/data/" subdir
"../../src/", // up 2 in tree, "/src/" subdir
"../../inc/", // up 2 in tree, "/inc/" subdir
"../../../", // up 3 in tree
"../../../src/<executable_name>/", // up 3 in tree, "/src/<executable_name>/" subdir
"../../../src/<executable_name>/data/", // up 3 in tree, "/src/<executable_name>/data/" subdir
"../../../src/<executable_name>/src/", // up 3 in tree, "/src/<executable_name>/src/" subdir
"../../../src/<executable_name>/inc/", // up 3 in tree, "/src/<executable_name>/inc/" subdir
"../../../sandbox/<executable_name>/", // up 3 in tree, "/sandbox/<executable_name>/" subdir
"../../../sandbox/<executable_name>/data/", // up 3 in tree, "/sandbox/<executable_name>/data/" subdir
"../../../sandbox/<executable_name>/src/", // up 3 in tree, "/sandbox/<executable_name>/src/" subdir
"../../../sandbox/<executable_name>/inc/" // up 3 in tree, "/sandbox/<executable_name>/inc/" subdir
};
// Extract the executable name
std::string executable_name;
if (executable_path != 0)
{
executable_name = std::string(executable_path);
#ifdef _WIN32
// Windows path delimiter
size_t delimiter_pos = executable_name.find_last_of('\\');
executable_name.erase(0, delimiter_pos + 1);
if (executable_name.rfind(".exe") != string::npos)
{
// we strip .exe, only if the .exe is found
executable_name.resize(executable_name.size() - 4);
}
#else
// Linux & OSX path delimiter
size_t delimiter_pos = executable_name.find_last_of('/');
executable_name.erase(0,delimiter_pos+1);
#endif
}
// Loop over all search paths and return the first hit
for( unsigned int i = 0; i < sizeof(searchPath)/sizeof(char*); ++i )
{
std::string path(searchPath[i]);
size_t executable_name_pos = path.find("<executable_name>");
// If there is executable_name variable in the searchPath
// replace it with the value
if(executable_name_pos != std::string::npos)
{
if(executable_path != 0)
{
path.replace(executable_name_pos, strlen("<executable_name>"), executable_name);
}
else
{
// Skip this path entry if no executable argument is given
continue;
}
}
// Test if the file exists
path.append(filename);
std::fstream fh(path.c_str(), std::fstream::in);
if (fh.good())
{
// File found
// returning an allocated array here for backwards compatibility reasons
char* file_path = (char*) malloc(path.length() + 1);
#ifdef _WIN32
strcpy_s(file_path, path.length() + 1, path.c_str());
#else
strcpy(file_path, path.c_str());
#endif
return file_path;
}
}
// File not found
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//! Read file \filename and return the data
//! @return shrTRUE if reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
//////////////////////////////////////////////////////////////////////////////
template<class T>
shrBOOL
shrReadFile( const char* filename, T** data, unsigned int* len, bool verbose)
{
// check input arguments
ARGCHECK(NULL != filename);
ARGCHECK(NULL != len);
// intermediate storage for the data read
std::vector<T> data_read;
// open file for reading
std::fstream fh( filename, std::fstream::in);
// check if filestream is valid
if(!fh.good())
{
if (verbose)
std::cerr << "shrReadFile() : Opening file failed." << std::endl;
return shrFALSE;
}
// read all data elements
T token;
while( fh.good())
{
fh >> token;
data_read.push_back( token);
}
// the last element is read twice
data_read.pop_back();
// check if reading result is consistent
if( ! fh.eof())
{
if (verbose)
std::cerr << "WARNING : readData() : reading file might have failed."
<< std::endl;
}
fh.close();
// check if the given handle is already initialized
if( NULL != *data)
{
if( *len != data_read.size())
{
std::cerr << "shrReadFile() : Initialized memory given but "
<< "size mismatch with signal read "
<< "(data read / data init = " << (unsigned int)data_read.size()
<< " / " << *len << ")" << std::endl;
return shrFALSE;
}
}
else
{
// allocate storage for the data read
*data = (T*) malloc( sizeof(T) * data_read.size());
// store signal size
*len = static_cast<unsigned int>( data_read.size());
}
// copy data
memcpy( *data, &data_read.front(), sizeof(T) * data_read.size());
return shrTRUE;
}
//////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename
//! @return shrTRUE if writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
//////////////////////////////////////////////////////////////////////////////
template<class T>
shrBOOL
shrWriteFile( const char* filename, const T* data, unsigned int len,
const T epsilon, bool verbose)
{
ARGCHECK(NULL != filename);
ARGCHECK(NULL != data);
// open file for writing
std::fstream fh( filename, std::fstream::out);
// check if filestream is valid
if(!fh.good())
{
if (verbose)
std::cerr << "shrWriteFile() : Opening file failed." << std::endl;
return shrFALSE;
}
// first write epsilon
fh << "# " << epsilon << "\n";
// write data
for( unsigned int i = 0; (i < len) && (fh.good()); ++i)
{
fh << data[i] << ' ';
}
// Check if writing succeeded
if( ! fh.good())
{
if (verbose)
std::cerr << "shrWriteFile() : Writing file failed." << std::endl;
return shrFALSE;
}
// file ends with nl
fh << std::endl;
return shrTRUE;
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg single precision floating point data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFilef( const char* filename, float** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg double precision floating point data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFiled( const char* filename, double** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg integer data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFilei( const char* filename, int** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg unsigned integer data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFileui( const char* filename, unsigned int** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg char / byte data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFileb( const char* filename, char** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Read file \filename containg unsigned char / byte data
//! @return shrTRUEif reading the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data uninitialized pointer, returned initialized and pointing to
//! the data read
//! @param len number of data elements in data, -1 on error
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrReadFileub( const char* filename, unsigned char** data, unsigned int* len, bool verbose)
{
return shrReadFile( filename, data, len, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for single precision floating point data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFilef( const char* filename, const float* data, unsigned int len,
const float epsilon, bool verbose)
{
return shrWriteFile( filename, data, len, epsilon, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for double precision floating point data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFiled( const char* filename, const double* data, unsigned int len,
const double epsilon, bool verbose)
{
return shrWriteFile( filename, data, len, epsilon, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for integer data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFilei( const char* filename, const int* data, unsigned int len, bool verbose)
{
return shrWriteFile( filename, data, len, 0, verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for unsigned integer data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFileui( const char* filename,const unsigned int* data,unsigned int len, bool verbose)
{
return shrWriteFile( filename, data, len, static_cast<unsigned int>(0), verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for byte / char data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFileb( const char* filename, const char* data, unsigned int len, bool verbose)
{
return shrWriteFile( filename, data, len, static_cast<char>(0), verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for byte / char data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFileub( const char* filename, const unsigned char* data,
unsigned int len, bool verbose)
{
return shrWriteFile( filename, data, len, static_cast<unsigned char>(0), verbose);
}
////////////////////////////////////////////////////////////////////////////////
//! Write a data file \filename for unsigned byte / char data
//! @return shrTRUEif writing the file succeeded, otherwise shrFALSE
//! @param filename name of the source file
//! @param data data to write
//! @param len number of data elements in data, -1 on error
//! @param epsilon epsilon for comparison
////////////////////////////////////////////////////////////////////////////////
shrBOOL shrWriteFileb( const char* filename,const unsigned char* data,unsigned int len, bool verbose)
{
return shrWriteFile( filename, data, len, static_cast<unsigned char>(0), verbose);
}
//////////////////////////////////////////////////////////////////////////////
//! Load PGM or PPM file
//! @note if data == NULL then the necessary memory is allocated in the
//! function and w and h are initialized to the size of the image
//! @return shrTRUE if the file loading succeeded, otherwise shrFALSE
//! @param file name of the file to load
//! @param data handle to the memory for the image file data
//! @param w width of the image
//! @param h height of the image