This repository has been archived by the owner on Feb 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QCARutils.mm
executable file
·1043 lines (850 loc) · 32.6 KB
/
QCARutils.mm
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 (c) 2010-2013 QUALCOMM Austria Research Center GmbH.
All Rights Reserved.
Qualcomm Confidential and Proprietary
==============================================================================*/
#import "QCARutils.h"
#import <QCAR/QCAR.h>
#import <QCAR/QCAR_iOS.h>
#import <QCAR/Renderer.h>
#import <QCAR/Tracker.h>
#import <QCAR/TrackerManager.h>
#import <QCAR/ImageTracker.h>
#import <QCAR/MarkerTracker.h>
#import <QCAR/VideoBackgroundConfig.h>
static NSString* const DatasetErrorTitle = @"Dataset Error";
@interface QCARutils()
- (void)updateApplicationStatus:(status)newStatus;
- (void)bumpAppStatus;
- (void)initQCAR;
- (int)initTracker;
- (void)loadTracker;
- (void)startCamera;
- (void)stopCamera;
- (void)configureVideoBackground;
- (void)cameraDidStart;
- (void)cameraDidStop;
@end
QCARutils *qUtils = nil; // singleton class
#pragma mark --- Class interface for DataSet list ---
@implementation DataSetItem
@synthesize name;
@synthesize path;
@synthesize dataSet;
- (id) initWithName:(NSString *)theName andPath:(NSString *)thePath
{
self = [super init];
if (self) {
name = [theName copy]; // copy retains
path = [thePath copy]; // copy retains
dataSet = nil;
}
return self;
}
- (void)dealloc
{
[name release];
[path release];
[super dealloc];
}
@end
#pragma mark --- Class implementation ---
@implementation QCARutils
@synthesize viewSize;
@synthesize delegate;
@synthesize contentScalingFactor;
@synthesize targetsList;
@synthesize QCARFlags;
@synthesize appStatus;
@synthesize errorCode;
@synthesize targetType;
@synthesize viewport;
@synthesize projectionMatrix;
@synthesize videoStreamStarted;
@synthesize noOfCameras, activeCamera, cameraTorchOn, cameraContinuousAFOn;
@synthesize isVisualSearchOn,vsAutoControlEnabled, orientationChanged;
@synthesize orientation;
// initialise QCARutils
- (id) init
{
if ((self = [super init]) != nil)
{
currentDataSet = nil;
contentScalingFactor = 1.0f; // non-Retina is default
appStatus = APPSTATUS_UNINITED;
viewSize = [[UIScreen mainScreen] bounds].size; // set as full screen
targetType = TYPE_IMAGETARGETS;
targetsList = [[NSMutableArray alloc] init];
// Initial camera settings
cameraTorchOn = NO;
cameraContinuousAFOn = YES;
videoStreamStarted = NO;
// Select the camera to open, set this to QCAR::CameraDevice::CAMERA_FRONT
// to activate the front camera instead.
activeCamera = QCAR::CameraDevice::CAMERA_BACK;
noOfCameras = 1;
}
return self;
}
// return QCARutils singleton, initing if necessary
+ (QCARutils *) getInstance
{
if (qUtils == nil)
{
qUtils = [[QCARutils alloc] init];
}
return qUtils;
}
// discard resources
- (void)dealloc {
targetsList = nil;
[super dealloc];
}
- (void) addTargetName:(NSString *)theName atPath:(NSString *)thePath
{
DataSetItem *dataSet = [[DataSetItem alloc] initWithName:theName andPath:thePath];
if (dataSet != nil)
[targetsList addObject:dataSet];
[dataSet release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (![[alertView title] isEqualToString:DatasetErrorTitle]) {
exit(0);
}
}
- (void)restoreCameraSettings
{
[self cameraSetTorchMode:cameraTorchOn];
[self cameraSetContinuousAFMode:cameraContinuousAFOn];
}
- (void)cameraSetTorchMode:(BOOL)switchOn
{
bool switchTorchOn = YES == switchOn ? true : false;
if (true == QCAR::CameraDevice::getInstance().setFlashTorchMode(switchTorchOn))
{
cameraTorchOn = switchOn;
}
}
- (void)cameraSetContinuousAFMode:(BOOL)switchOn
{
int focusMode = YES == switchOn ? QCAR::CameraDevice::FOCUS_MODE_CONTINUOUSAUTO : QCAR::CameraDevice::FOCUS_MODE_NORMAL;
if (true == QCAR::CameraDevice::getInstance().setFocusMode(focusMode))
{
cameraContinuousAFOn = switchOn;
}
}
- (void)cameraTriggerAF
{
[self performSelector:@selector(cameraPerformAF) withObject:nil afterDelay:.4];
}
- (void)cameraPerformAF
{
if (true == QCAR::CameraDevice::getInstance().setFocusMode(QCAR::CameraDevice::FOCUS_MODE_TRIGGERAUTO))
{
cameraContinuousAFOn = NO;
}
}
- (void)cameraCancelAF
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cameraPerformAF) object:nil];
}
#pragma mark --- external control of QCAR ---
////////////////////////////////////////////////////////////////////////////////
// create the Augmented Reality context
- (void)createARofSize:(CGSize)theSize forDelegate:(id)theDelegate
{
NSLog(@"QCARutils onCreate()");
if (appStatus != APPSTATUS_UNINITED)
return;
// to initialise QCAR we need the view size and a class for optional callbacks
viewSize = theSize;
delegate = theDelegate;
// start the initialisation sequence here...
[qUtils updateApplicationStatus:APPSTATUS_INIT_APP];
}
////////////////////////////////////////////////////////////////////////////////
// destroy the Augmented Reality context
- (void)destroyAR
{
NSLog(@"QCARutils onDestroy()");
// Deinitialise QCAR SDK
if (appStatus != APPSTATUS_UNINITED)
{
// deactivate the dataset and unload any pre-loaded datasets
[self deactivateDataSet:currentDataSet];
if (targetType != TYPE_FRAMEMARKERS)
{
// Unload all the requested datasets
for (DataSetItem *aDataSet in targetsList)
{
if (aDataSet.dataSet != nil)
{
[self unloadDataSet:aDataSet.dataSet];
aDataSet.dataSet = nil;
}
}
}
QCAR::deinit();
}
appStatus = APPSTATUS_UNINITED;
}
////////////////////////////////////////////////////////////////////////////////
// pause the camera view and the tracking of targets
- (void)pauseAR
{
NSLog(@"QCARutils onPause()");
// If the app status is APPSTATUS_CAMERA_RUNNING, QCAR must have been fully
// initialised
if (APPSTATUS_CAMERA_RUNNING == qUtils.appStatus) {
[qUtils updateApplicationStatus:APPSTATUS_CAMERA_STOPPED];
// QCAR-specific pause operation
QCAR::onPause();
}
}
////////////////////////////////////////////////////////////////////////////////
// resume the camera view and tracking of targets
- (void)resumeAR
{
NSLog(@"QCARutils onResume()");
// If the app status is APPSTATUS_CAMERA_STOPPED, QCAR must have been fully
// initialised
if (APPSTATUS_CAMERA_STOPPED == qUtils.appStatus) {
// QCAR-specific resume operation
QCAR::onResume();
[qUtils updateApplicationStatus:APPSTATUS_CAMERA_RUNNING];
}
}
#pragma mark --- QCAR initialisation ---
////////////////////////////////////////////////////////////////////////////////
- (void)updateApplicationStatus:(status)newStatus
{
if (newStatus != appStatus && APPSTATUS_ERROR != appStatus) {
appStatus = newStatus;
switch (appStatus) {
case APPSTATUS_INIT_APP:
NSLog(@"APPSTATUS_INIT_APP");
// Initialise the application
[self initApplication];
[self updateApplicationStatus:APPSTATUS_INIT_QCAR];
break;
case APPSTATUS_INIT_QCAR:
NSLog(@"APPSTATUS_INIT_QCAR");
// Initialise QCAR
[self performSelectorInBackground:@selector(initQCAR) withObject:nil];
break;
case APPSTATUS_INIT_TRACKER:
NSLog(@"APPSTATUS_INIT_TRACKER");
// Initialise the tracker
if ([self initTracker] > 0) {
[self updateApplicationStatus: APPSTATUS_INIT_APP_AR];
}
break;
case APPSTATUS_INIT_APP_AR:
NSLog(@"APPSTATUS_INIT_APP_AR");
// AR-specific initialisation
[self initApplicationAR];
// skip the loading of a DataSet for markers
if (targetType != TYPE_FRAMEMARKERS)
[self updateApplicationStatus:APPSTATUS_LOAD_TRACKER];
else
[self updateApplicationStatus:APPSTATUS_INITED];
break;
case APPSTATUS_LOAD_TRACKER:
NSLog(@"APPSTATUS_LOAD_TRACKER");
// Load tracker data
[self performSelectorInBackground:@selector(loadTracker) withObject:nil];
break;
case APPSTATUS_INITED:
NSLog(@"APPSTATUS_INITED");
// Tasks for after QCAR inited but before camera starts running
QCAR::onResume(); // ensure it's called first time in
[self postInitQCAR];
[self updateApplicationStatus:APPSTATUS_CAMERA_RUNNING];
break;
case APPSTATUS_CAMERA_RUNNING:
NSLog(@"APPSTATUS_CAMERA_RUNNING");
// Start the camera and tracking
[self startCamera];
videoStreamStarted = YES;
[self cameraDidStart];
break;
case APPSTATUS_CAMERA_STOPPED:
NSLog(@"APPSTATUS_CAMERA_STOPPED");
// Stop the camera and tracking
[self stopCamera];
[self cameraDidStop];
break;
default:
NSLog(@"updateApplicationStatus: invalid app status");
break;
}
}
if (APPSTATUS_ERROR == appStatus) {
// Application initialisation failed, display an alert view
UIAlertView* alert;
const char *msgDevice = "Failed to initialize QCAR because this device is not supported.";
const char *msgDefault = "Application initialisation failed.";
const char* msgNoNetwork = "Failed to initialize Visual Search because the device has no network connection.";
const char* msgNoService = "Failed to initialize Visual Search because the service is not available.";
const char *msg = msgDefault;
switch (errorCode) {
case QCAR_ERRCODE_NO_NETWORK_CONNECTION:
msg = msgNoNetwork;
break;
case QCAR_ERRCODE_NO_SERVICE_AVAILABLE:
msg = msgNoService;
break;
case QCAR::INIT_DEVICE_NOT_SUPPORTED:
msg = msgDevice;
break;
case QCAR::INIT_ERROR:
case QCAR_ERRCODE_INIT_TRACKER:
case QCAR_ERRCODE_CREATE_DATASET:
case QCAR_ERRCODE_LOAD_DATASET:
case QCAR_ERRCODE_ACTIVATE_DATASET:
case QCAR_ERRCODE_DEACTIVATE_DATASET:
default:
break;
}
alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithUTF8String:msg] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
////////////////////////////////////////////////////////////////////////////////
// Bump the application status on one step
- (void)bumpAppStatus
{
[self updateApplicationStatus:(status)(appStatus + 1)];
}
////////////////////////////////////////////////////////////////////////////////
// Initialise the application
- (void)initApplication
{
// Inform QCAR that the drawing surface has been created
QCAR::onSurfaceCreated();
// Invoke optional application initialisation in the delegate class
if ((delegate != nil) && [delegate respondsToSelector:@selector(initApplication)])
[delegate performSelectorOnMainThread:@selector(initApplication) withObject:nil waitUntilDone:YES];
}
////////////////////////////////////////////////////////////////////////////////
// Initialise QCAR [performed on a background thread]
- (void)initQCAR
{
// Background thread must have its own autorelease pool
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
QCAR::setInitParameters(QCARFlags);
// QCAR::init() will return positive numbers up to 100 as it progresses towards success
// and negative numbers for error indicators
NSInteger initSuccess = 0;
do {
initSuccess = QCAR::init();
} while (0 <= initSuccess && 100 > initSuccess);
if (initSuccess != 100) {
appStatus = APPSTATUS_ERROR;
errorCode = initSuccess;
}
// Continue execution on the main thread
[self performSelectorOnMainThread:@selector(bumpAppStatus) withObject:nil waitUntilDone:NO];
[pool release];
}
////////////////////////////////////////////////////////////////////////////////
// Initialise the AR parts of the application
- (void)initApplicationAR
{
// Invoke optional AR initialisation in the delegate class
if ((delegate != nil) && [delegate respondsToSelector:@selector(initApplicationAR)])
[delegate performSelectorOnMainThread:@selector(initApplicationAR) withObject:nil waitUntilDone:YES];
}
//////////////////////////////////////////////////////////////////////////////////
// Initialise the tracker [performed on a background thread]
- (int)initTracker
{
int res = 0;
// Initialize the image or marker tracker
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
if (targetType != TYPE_FRAMEMARKERS)
{
// Image Tracker...
QCAR::Tracker* trackerBase = trackerManager.initTracker(QCAR::Tracker::IMAGE_TRACKER);
if (trackerBase == NULL)
{
NSLog(@"Failed to initialize ImageTracker.");
}
else
{
NSLog(@"Successfully initialized ImageTracker.");
res = 1;
}
}
else
{
// Marker Tracker...
QCAR::Tracker* trackerBase = trackerManager.initTracker(QCAR::Tracker::MARKER_TRACKER);
if (trackerBase == NULL)
{
NSLog(@"Failed to initialize MarkerTracker.");
}
else
{
NSLog(@"Successfully initialized MarkerTracker.");
// Create the markers required
QCAR::MarkerTracker* markerTracker = static_cast<QCAR::MarkerTracker*>(trackerBase);
if (markerTracker == NULL)
{
NSLog(@"Failed to get MarkerTracker.");
}
else
{
NSLog(@"Successfully got MarkerTracker.");
// Create frame markers:
if (!markerTracker->createFrameMarker(0, "MarkerQ", QCAR::Vec2F(50,50)) ||
!markerTracker->createFrameMarker(1, "MarkerC", QCAR::Vec2F(50,50)) ||
!markerTracker->createFrameMarker(2, "MarkerA", QCAR::Vec2F(50,50)) ||
!markerTracker->createFrameMarker(3, "MarkerR", QCAR::Vec2F(50,50)))
{
NSLog(@"Failed to create frame markers.");
}
else
{
NSLog(@"Successfully created frame markers.");
res = 1;
}
}
}
}
if (res == 0)
{
appStatus = APPSTATUS_ERROR;
errorCode = QCAR_ERRCODE_INIT_TRACKER;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
// Load the tracker data [performed on a background thread]
- (void)loadTracker
{
// Background thread must have its own autorelease pool
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
BOOL haveLoadedOneDataSet = NO;
if (targetType != TYPE_FRAMEMARKERS)
{
// Load all the requested datasets
for (DataSetItem *aDataSet in targetsList)
{
if (aDataSet.path != nil)
{
aDataSet.dataSet = [self loadDataSet:aDataSet.path];
if (haveLoadedOneDataSet == NO)
{
if (aDataSet.dataSet != nil)
{
// activate the first one in the list
[self activateDataSet:aDataSet.dataSet];
haveLoadedOneDataSet = YES;
}
}
}
}
// Check that we've loaded at least one target
if (!haveLoadedOneDataSet)
{
NSLog(@"QCARutils: Failed to load any target");
appStatus = APPSTATUS_ERROR;
errorCode = QCAR_ERRCODE_LOAD_TARGET;
}
}
// Continue execution on the main thread
if (appStatus != APPSTATUS_ERROR)
[self performSelectorOnMainThread:@selector(bumpAppStatus) withObject:nil waitUntilDone:NO];
[pool release];
}
////////////////////////////////////////////////////////////////////////////////
// Start capturing images from the camera
- (void)startCamera
{
// Initialise the camera
if (QCAR::CameraDevice::getInstance().init(activeCamera)) {
// Configure video background
[self configureVideoBackground];
//// Select the default mode - given as example of how and where to set the Camera mode
//if (QCAR::CameraDevice::getInstance().selectVideoMode(QCAR::CameraDevice::MODE_DEFAULT)) {
// Start camera capturing
if (QCAR::CameraDevice::getInstance().start()) {
// Start the tracker
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::Tracker* tracker = trackerManager.getTracker(targetType == TYPE_FRAMEMARKERS ?
QCAR::Tracker::MARKER_TRACKER :
QCAR::Tracker::IMAGE_TRACKER);
if(tracker != 0)
tracker->start();
// Cache the projection matrix:
const QCAR::CameraCalibration& cameraCalibration = QCAR::CameraDevice::getInstance().getCameraCalibration();
projectionMatrix = QCAR::Tool::getProjectionGL(cameraCalibration, 2.0f, 2500.0f);
}
// Restore camera settings
[self restoreCameraSettings];
}
}
////////////////////////////////////////////////////////////////////////////////
// Stop capturing images from the camera
- (void)stopCamera
{
// Stop the tracker:
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::Tracker* tracker = trackerManager.getTracker(targetType == TYPE_FRAMEMARKERS ?
QCAR::Tracker::MARKER_TRACKER :
QCAR::Tracker::IMAGE_TRACKER);
if(tracker != 0)
tracker->stop();
QCAR::CameraDevice::getInstance().stop();
QCAR::CameraDevice::getInstance().deinit();
}
////////////////////////////////////////////////////////////////////////////////
// Do the things that need doing after initialisation
- (void)postInitQCAR
{
// Get the device screen dimensions, allowing for hi-res mode
viewSize.width *= contentScalingFactor; // set by the view initialisation before QCAR initialisation
viewSize.height *= contentScalingFactor;
// Inform QCAR that the drawing surface size has changed
QCAR::onSurfaceChanged(viewSize.height, viewSize.width);
// let the delegate handle this if wanted
if ((delegate != nil) && [delegate respondsToSelector:@selector(postInitQCAR)])
[delegate performSelectorOnMainThread:@selector(postInitQCAR) withObject:nil waitUntilDone:YES];
}
////////////////////////////////////////////////////////////////////////////////
// Perform actions following the camera starting
- (void)cameraDidStart
{
// Inform the delegate
if ((delegate != nil) && [delegate respondsToSelector:@selector(cameraDidStart)]) {
[delegate performSelectorOnMainThread:@selector(cameraDidStart) withObject:nil waitUntilDone:YES];
}
}
////////////////////////////////////////////////////////////////////////////////
// Perform actions following the camera stopping
- (void)cameraDidStop
{
// Inform the delegate
if ((delegate != nil) && [delegate respondsToSelector:@selector(cameraDidStop)]) {
[delegate performSelectorOnMainThread:@selector(cameraDidStop) withObject:nil waitUntilDone:YES];
}
}
////////////////////////////////////////////////////////////////////////////////
// Configure the video background
- (void)configureVideoBackground
{
// Get the default video mode
QCAR::CameraDevice& cameraDevice = QCAR::CameraDevice::getInstance();
QCAR::VideoMode videoMode = cameraDevice.getVideoMode(QCAR::CameraDevice::MODE_DEFAULT);
// Configure the video background
QCAR::VideoBackgroundConfig config;
config.mEnabled = true;
config.mSynchronous = true;
config.mPosition.data[0] = 0.0f;
config.mPosition.data[1] = 0.0f;
// Compare aspect ratios of video and screen. If they are different
// we use the full screen size while maintaining the video's aspect
// ratio, which naturally entails some cropping of the video.
// Note - screenRect is portrait but videoMode is always landscape,
// which is why "width" and "height" appear to be reversed.
float arVideo = (float)videoMode.mWidth / (float)videoMode.mHeight;
float arScreen = viewSize.height / viewSize.width;
int width;
int height;
if (arVideo > arScreen)
{
// Video mode is wider than the screen. We'll crop the left and right edges of the video
config.mSize.data[0] = (int)viewSize.width * arVideo;
config.mSize.data[1] = (int)viewSize.width;
width = (int)viewSize.width;
height = (int)viewSize.height;
}
else
{
// Video mode is taller than the screen. We'll crop the top and bottom edges of the video.
// Also used when aspect ratios match (no cropping).
config.mSize.data[0] = (int)viewSize.height;
config.mSize.data[1] = (int)viewSize.height / arVideo;
width = (int)viewSize.height;
height = (int)viewSize.width;
}
// Calculate the viewport for the app to use when rendering. This may or
// may not be used, depending on the desired functionality of the app
viewport.posX = ((width - config.mSize.data[0]) / 2) + config.mPosition.data[0];
viewport.posY = (((int)(height - config.mSize.data[1])) / (int) 2) + config.mPosition.data[1];
viewport.sizeX = config.mSize.data[0];
viewport.sizeY = config.mSize.data[1];
// Set the config
QCAR::Renderer::getInstance().setVideoBackgroundConfig(config);
}
#pragma mark --- configuration methods ---
////////////////////////////////////////////////////////////////////////////////
// Load and Unload Data Set
- (BOOL)unloadDataSet:(QCAR::DataSet *)theDataSet
{
BOOL success = NO;
// Get the image tracker:
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>(trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));
if (imageTracker == NULL)
{
NSLog(@"Failed to unload tracking data set because the ImageTracker has not been initialized.");
errorCode = QCAR_ERRCODE_INIT_TRACKER;
}
else
{
// If activated deactivate the data set:
if ((theDataSet == currentDataSet) && ![self deactivateDataSet:theDataSet])
{
NSLog(@"Failed to deactivate data set.");
errorCode = QCAR_ERRCODE_DEACTIVATE_DATASET;
}
else
{
if (!imageTracker->destroyDataSet(theDataSet))
{
NSLog(@"Failed to destroy data set.");
errorCode = QCAR_ERRCODE_DESTROY_DATASET;
}
else
{
NSLog(@"Successfully unloaded data set.");
success = YES;
}
}
}
currentDataSet = nil;
return success;
}
- (QCAR::DataSet *)loadDataSet:(NSString *)dataSetPath
{
QCAR::DataSet *theDataSet = nil;
const char* msg;
const char* msgNotInit = "Failed to load tracking data set because the ImageTracker has not been initialized.";
const char* msgFailedToCreate = "Failed to create a new tracking data.";
const char* msgFailedToLoad = "Failed to load data set.";
// Get the image tracker:
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>(trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));
if (imageTracker == NULL)
{
msg = msgNotInit;
errorCode = QCAR_ERRCODE_INIT_TRACKER;
}
else
{
// Create the data sets:
theDataSet = imageTracker->createDataSet();
if (theDataSet == nil)
{
msg = msgFailedToCreate;
errorCode = QCAR_ERRCODE_CREATE_DATASET;
}
else
{
// Load the data set from the App Bundle
// If the DataSet were in the Documents folder we'd use STORAGE_ABSOLUTE and the full path
if (!theDataSet->load([dataSetPath cStringUsingEncoding:NSASCIIStringEncoding], QCAR::DataSet::STORAGE_APPRESOURCE))
{
msg = msgFailedToLoad;
errorCode = QCAR_ERRCODE_LOAD_DATASET;
imageTracker->destroyDataSet(theDataSet);
theDataSet = nil;
}
else
{
NSLog(@"Successfully loaded data set.");
}
}
}
if (theDataSet == nil)
{
NSString* nsMsg = [NSString stringWithUTF8String:msg];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:DatasetErrorTitle message:nsMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
NSLog(@"%@", nsMsg);
[alert show];
[alert release];
}
return theDataSet;
}
- (BOOL)deactivateDataSet:(QCAR::DataSet *)theDataSet
{
if ((currentDataSet == nil) || (theDataSet != currentDataSet))
{
NSLog(@"Invalid request to deactivate data set.");
errorCode = QCAR_ERRCODE_DEACTIVATE_DATASET;
return NO;
}
BOOL success = NO;
// Get the image tracker:
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>(trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));
if (imageTracker == NULL)
{
NSLog(@"Failed to unload tracking data set because the ImageTracker has not been initialized.");
errorCode = QCAR_ERRCODE_INIT_TRACKER;
}
else
{
// Activate the data set:
if (!imageTracker->deactivateDataSet(theDataSet))
{
NSLog(@"Failed to deactivate data set.");
errorCode = QCAR_ERRCODE_DEACTIVATE_DATASET;
}
else
{
success = YES;
}
}
currentDataSet = nil;
return success;
}
- (BOOL)activateDataSet:(QCAR::DataSet *)theDataSet
{
// if we've previously recorded an activation, deactivate it
if (currentDataSet != nil)
{
[self deactivateDataSet:currentDataSet];
}
BOOL success = NO;
// Get the image tracker:
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>(trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));
if (imageTracker == NULL) {
NSLog(@"Failed to load tracking data set because the ImageTracker has not been initialized.");
errorCode = QCAR_ERRCODE_INIT_TRACKER;
}
else
{
// Activate the data set:
if (!imageTracker->activateDataSet(theDataSet))
{
NSLog(@"Failed to activate data set.");
errorCode = QCAR_ERRCODE_ACTIVATE_DATASET;
}
else
{
NSLog(@"Successfully activated data set.");
currentDataSet = theDataSet;
success = YES;
}
}
return success;
}
- (void) allowDataSetModification
{
QCAR::ImageTracker* it = reinterpret_cast<QCAR::ImageTracker*>(QCAR::TrackerManager::getInstance().getTracker(QCAR::Tracker::IMAGE_TRACKER));
// Deactivate the data set prior to reconfiguration:
it->deactivateDataSet(currentDataSet);
}
- (void) saveDataSetModifications
{
QCAR::ImageTracker* it = reinterpret_cast<QCAR::ImageTracker*>(QCAR::TrackerManager::getInstance().getTracker(QCAR::Tracker::IMAGE_TRACKER));
// Deactivate the data set prior to reconfiguration:
it->activateDataSet(currentDataSet);
}
#pragma mark --- Data management ---
////////////////////////////////////////////////////////////////////////////////
-(NSMutableArray*) loadTextures:(NSArray*) textureList
{
int nErr = noErr;
int nTextures = [textureList count];
NSMutableArray* textures = [[NSMutableArray array] retain];
@try {
for (int i = 0; i < nTextures; ++i) {
Texture* tex = [[[Texture alloc] init] autorelease];
NSString* file = [textureList objectAtIndex:i];
nErr = [tex loadImage:file] == YES ? noErr : 1;
[textures addObject:tex];
if (noErr != nErr) {
break;
}
}
}
@catch (NSException* e) {
NSLog(@"NSMutableArray addObject exception");
}
assert([textures count] == nTextures);
if ([textures count] != nTextures) {
NSLog(@"All the required textures are not loaded");
}
return textures;
}
- (Texture *) createTexture:(NSString*)fileName
{
Texture* tex = [[[Texture alloc] init] autorelease];
[tex loadImage:fileName];
return tex;
}
#pragma mark --- target utilities ---
////////////////////////////////////////////////////////////////////////////////
// Target Utility methods
// In the current loaded data set, find the named target
- (QCAR::ImageTarget *) findImageTarget:(const char *) name
{
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = (QCAR::ImageTracker*)
trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER);
if (imageTracker != nil || currentDataSet == nil)
{
for(int i=0; i<currentDataSet->getNumTrackables(); i++)
{
if(currentDataSet->getTrackable(i)->getType()==QCAR::Trackable::IMAGE_TARGET)
{
if(!strcmp(currentDataSet->getTrackable(i)->getName(),name))
return reinterpret_cast<QCAR::ImageTarget*>(currentDataSet->getTrackable(i));
}
}
}
return NULL;
}
// See if there's a multi-target in the current data set
- (QCAR::MultiTarget *) findMultiTarget
{
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = (QCAR::ImageTracker*)
trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER);
QCAR::MultiTarget *mit = NULL;
if (imageTracker == nil || currentDataSet == nil)
return NULL;
// Go through all Trackables to find the MultiTarget instance
//
for(int i=0; i<currentDataSet->getNumTrackables(); i++)
{