-
Notifications
You must be signed in to change notification settings - Fork 179
/
CC3DemoMashUpScene.m
executable file
·3916 lines (3384 loc) · 193 KB
/
CC3DemoMashUpScene.m
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
/*
* CC3DemoMashUpScene.m
*
* Cocos3D 2.0.2
* Author: Bill Hollings
* Copyright (c) 2010-2014 The Brenwill Workshop Ltd. All rights reserved.
* http://www.brenwill.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://en.wikipedia.org/wiki/MIT_License
*
* The Cocos3D mascot model was created by Alexandru Barbulescu, and used here
* by permission. Further rights may be claimed for that model.
*
* See header file CC3DemoMashUpScene.h for full API documentation.
*/
#import "CC3DemoMashUpScene.h"
#import "CC3OSExtensions.h"
#import "CC3Billboard.h"
#import "CC3Actions.h"
#import "CC3ModelSampleFactory.h"
#import "CCLabelTTF.h"
#import "CGPointExtension.h"
#import "CC3PODNode.h"
#import "CC3PODResourceNode.h"
#import "CC3BoundingVolumes.h"
#import "CC3PointParticleSamples.h"
#import "CC3MeshParticleSamples.h"
#import "CC3MeshParticles.h"
#import "CC3DemoMashUpLayer.h"
#import "CC3VertexSkinning.h"
#import "CC3ShadowVolumes.h"
#import <objc/runtime.h>
#import "CC3LinearMatrix.h"
#import "CC3AffineMatrix.h"
#import "CC3ProjectionMatrix.h"
#import "CC3PFXResource.h"
#import "CC3BitmapLabelNode.h"
#import "CC3EnvironmentNodes.h"
#import "CCTextureCache.h"
// File names
#define kRobotPODFile @"IntroducingPOD_float.pod"
#define kBeachBallPODFile @"BeachBall.pod"
#define kGlobeTextureFile @"earthmap1k.jpg"
#define kMascotPODFile @"cocos3dMascot.pod"
#define kDieCubePODFile @"DieCube.pod"
#define kGroundTextureFile @"Grass.jpg"
#define kSignTextureFile @"Crate.png"
#define kSignStampTextureFile @"Stamp.png"
#define kSignStampNormalsTextureFile @"Stamp-nm.png"
#define kHeadPODFile @"Head.pod"
#define kHeadTextureFile @"Head_diffuse.png"
#define kHeadBumpFile @"Head_clonespace.png"
#define kCubeTextureFile @"BoxTexture.png"
#define kBrickTextureFile @"Bricks-Red.jpg"
#define kRunningManPODFile @"man.pod"
#define kMalletPODFile @"mallet.pod"
#define kPointParticleTextureFile @"fire.ppng"
#define kMeshParticleTextureFile @"BallBoxTexture.png"
#define kReflectiveMaskPODFile @"ReflectiveMask.pod"
#define kEtchedMaskPODFile @"EtchedMask.pod"
#define kReflectivePFXFile @"ReflectiveEffects.pfx"
#define kEtchedPFXFile @"EtchedEffects.pfx"
#define kEtchedMaskPFXEffect @"EtchedEffect"
#define kTVPODFile @"samsung_tv-med.pod"
#define kTVTestCardFile @"TVTestCard.jpg"
#define kPostProcPFXFile @"PostProc.pfx"
// Model names
#define kLandingCraftName @"LandingCraft"
#define kPODRobotRezNodeName @"RobotPODRez"
#define kPODLightName @"FDirect01"
#define kPODCameraName @"Camera01"
#define kRobotTopArm @"TopArm"
#define kRobotBottomArm @"BottomArm"
#define kRobotCylinder @"Cylinder01"
#define kRobotBase @"GeoSphere01"
#define kRobotCameraName @"Camera01"
#define kBeachBallRezNodeName @"BeachBallPODRez"
#define kBeachBallName @"BeachBall"
#define kBeachBallWhiteSegment @"BeachBall-submesh0"
#define kGlobeName @"Globe"
#define kDieCubeName @"DieCube"
#define kDieCubePODName @"Cube"
#define kTexturedTeapotName @"Teapot"
#define kRainbowTeapotName @"RainbowTeapot"
#define kTeapotHolderName @"TeapotHolder"
#define kTeapotRedName @"TeapotRed"
#define kTeapotGreenName @"TeapotGreen"
#define kTeapotBlueName @"TeapotBlue"
#define kTeapotWhiteName @"TeapotWhite"
#define kTeapotOrangeName @"TeapotOrange"
#define kBillboardName @"DizzyLabel"
#define kBitmapLabelName @"BitmapLabel"
#define kSunName @"Sun"
#define kSpotlightName @"Spotlight"
#define kBeachName @"Beach"
#define kGroundName @"Ground"
#define kFloaterName @"Floater"
#define kMascotName @"cocos2d_3dmodel_unsubdivided"
#define kDistractedMascotName @"DistractedMascot"
#define kSignName @"MultiTextureSign"
#define kSignLabelName @"SignLabel"
#define kPODHeadRezNodeName @"HeadPODRez"
#define kFloatingHeadName @"head03low01"
#define kBumpMapLightTrackerName @"BumpMapLightTracker"
#define kExplosionName @"Explosion"
#define kPointHoseEmitterName @"PointHose"
#define kMeshHoseEmitterName @"MeshHose"
#define kTexturedCubeName @"TexturedCube"
#define kBrickWallName @"BrickWall"
#define kMalletName @"Ellipse01"
#define kRunningTrackName @"RunningTrack"
#define kRunnerName @"Runner"
#define kRunnerCameraName @"Camera01"
#define kRunnerLampName @"Spot01"
#define kLittleBrotherName @"LittleBrother"
#define kTVName @"Television"
#define kTVScreenName @"TVScreen"
#define kMultiTextureCombinerLabel @"Multi-texture combiner function: %@"
#define kCameraMoveDuration 3.0
#define kTeapotRotationActionTag 1
#define kSkyColor ccc4f(0.4, 0.5, 0.9, 1.0)
#define kFadeInDuration 1.0f
#define kNoFadeIn 0.0f
#define kFlappingActionTag 77
#define kGlidingActionTag 78
// Size of the television
#define kTVScale 40
static CC3IntSize kTVTexSize = { (16 * kTVScale), (9 * kTVScale) };
// Locations for the brick wall in open and closed position
static CC3Vector kBrickWallOpenLocation = { -190, 150, -840 };
static CC3Vector kBrickWallClosedLocation = { -115, 150, -765 };
@interface CCAction (PrivateMethods)
// This method doesn't actually exist on CCAction, but it does on all subclasses we use in this project.
-(CCAction*) reverse;
@end
@interface CC3Node (TemplateMethods)
@property(nonatomic, readonly) CCColorRef initialDescriptorColor;
@end
@implementation CC3DemoMashUpScene
@synthesize primaryCC3DemoMashUpLayer=_primaryCC3DemoMashUpLayer;
@synthesize playerDirectionControl=_playerDirectionControl;
@synthesize playerLocationControl=_playerLocationControl;
@synthesize isManagingShadows=_isManagingShadows;
/**
* Add the initial content to the scene.
*
* Once the scene is displayed and running, additional content is added asynchronously in
* the addSceneContentAsynchronously method, which is invoked on a background thread by the
* CC3Backgrounder singleton.
*/
-(void) initializeScene {
[self initCustomState]; // Set up any initial state tracked by this subclass
[self preloadAssets]; // Loads, compiles, links, and pre-warms all shader programs
// used by this scene, and certain textures.
[self addBackdrop]; // Add a static solid sky-blue backdrop, or optional textured backdrop.
[self addGround]; // Add a ground plane to provide some perspective to the user
// [self addSkyBox]; // Add a skybox around the scene. This is the skybox that is reflected
// in the reflective runner added in the addSkinnedRunners method
[self addRobot]; // Add an animated robot arm, a light, and a camera. This POD file
// contains the primary camera of this scene.
[self addProjectedLabel]; // Attach a text label to the hand of the animated robot.
// [self addPointParticles]; // Uncomment to add a platform of multi-colored, light-interactive,
// point particles hanging in the scene.
// [self addMeshParticles]; // Uncomment to add a platform of multi-colored, mesh particles
// hanging in the scene.
[self addPointHose]; // Attach a point particle hose to the hand of the animated robot.
// The hose is turned on and off when the robot arm is touched.
[self addMeshHose]; // Attach a point particle hose to the hand of the animated robot.
// The hose is turned on and off when the robot arm is touched.
[self addSun]; // Add a Cocos2D particle emitter as the sun in the sky.
[self addSpotlight]; // Add a spotlight to the camera.
// This spotlight will be turned on when the sun is turned off.
[self addLightProbes]; // Adds light probes to the scene, as an alternate to using lights.
// Using the light probes can be turned on and off.
[self configureLighting]; // Set up the lighting
[self configureCamera]; // Check out some interesting camera options.
// Configure all content added so far in a standard manner. This illustrates how CC3Node
// properties and methods can be applied to large assemblies of nodes, and even the entire
// scene itself, allowing us to perform this only once, for all current scene content.
// For content that is added dynamically after this initial content, this method will also
// be invoked on each new content component.
[self configureForScene: self andMaterializeWithDuration: kNoFadeIn];
// The existing node structure of the scene is logged using the following line.
LogInfo(@"The structure of this scene is: %@", [self structureDescription]);
}
/**
* Adds additional scene content dynamically and asynchronously.
*
* This method is invoked from a code block that is run on a background thread by the
* CC3Backgrounder singleton. It adds content dynamically and asynchronously after
* rendering has begun on the rendering thread.
*
* To emphasize that the loading is happening on a background thread while the existing scene
* is running, this method takes a small pause before loading each model. This pause is purely
* for dramatic effect for the purposes of this demo app. Pauses are NOT required before normal
* background model loading.
*
* Certain assets, notably shader programs, will cause short, but unavoidable, delays in the
* rendering of the scene, because certain finalization steps from shader compilation occur on
* the main thread. Shaders and certain other critical assets are pre-loaded in the preloadAssets
* method, which is invoked prior to the opening of this scene.
*/
-(void) addSceneContentAsynchronously {
[self pauseDramatically];
[self addAxisMarkers]; // Add colored teapots to mark each coordinate axis
[self pauseDramatically];
[self addLightMarker]; // Add a small white teapot to show the direction toward the light
[self pauseDramatically];
[self addBitmapLabel]; // Add a bitmapped string label
[self pauseDramatically];
[self addSkinnedMallet]; // Adds a flexible mallet to the scene, showing bone skinning.
[self pauseDramatically];
[self addSkinnedRunners]; // Adds two running figures to the scene, showing bone skinning.
[self pauseDramatically];
[self addDieCube]; // Add a game die whose rotation is controlled by touch-swipe user action
[self pauseDramatically];
[self addTexturedCube]; // Add another cube, this one textured, below the die cube.
[self pauseDramatically];
[self addGlobe]; // Add a rotating globe from a parametric sphere covered by a texture
[self pauseDramatically];
[self addFloatingRing]; // Add a large yellow band floating above the ground, using a texture
// containing transparency. The band as a whole fades in and out
// periodically. This demonstrates managing opacity and translucency
// at both the texture and material level.
[self pauseDramatically];
[self addBeachBall]; // Add a transparent bouncing beach ball...exported from Blender
[self pauseDramatically];
[self addTelevision]; // Add a television showing the view from the runner camera
// This demonstrates dynamic rendering-to-texture capabilities.
// Must be added after the skinned runners.
[self pauseDramatically];
[self addTeapotAndSatellite]; // Add a large textured teapot with a smaller satellite teapot
[self pauseDramatically];
[self addBrickWall]; // Add a brick wall that can block the path of the satellite teapot
// This must happen after camera is loaded (in addRobot).
[self pauseDramatically];
[self addWoodenSign]; // Add the multi-texture wooden sign.
// This must happen after camera is loaded (in addRobot).
[self pauseDramatically];
[self addFloatingHead]; // Add the bump-mapped floating head.
// This must happen after camera is loaded (in addRobot).
[self pauseDramatically];
[self addReflectiveMask]; // Adds a floating mask that uses GLSL shaders loaded via a PowerVR
// PFX file. Under OpenGL ES 1.1, mask appears with a default texture.
[self pauseDramatically];
[self addEtchedMask]; // Adds a floating mask that uses GLSL shaders loaded via a PowerVR
// PFX file. Under OpenGL ES 1.1, mask appears with a default texture.
[self pauseDramatically];
[self addMascots]; // Add the Cocos3D mascot.
[self pauseDramatically];
[self addDragon]; // Add a flying dragon that demos blending between animation tracks
// Log a list of the shader programs that are being used by the scene. During development,
// we can use this list as a starting point for populating the preloadAssets method.
LogRez(@"The following list contains the shader programs currently in use in this scene."
@" You can copy and paste much of this list into the preloadAssets method"
@" in order to pre-load the shader programs during scene initialization. %@",
[CC3ShaderProgram loadedProgramsDescription]);
// Log a list of the PFX resources that are being used by the scene. During development, we can
// use this list as a starting point for adding PFX files to the preloadAssets method.
// When initially building this list, set the CC3Resource.isPreloading to YES and leave it there.
LogRez(@"The following list contains the resource files currently in use in this scene."
@" You can copy the PFX resources from this list and paste them into the"
@" preloadAssets method, in order to pre-load additional shader programs"
@" that originate in PFX files, during scene initialization. %@",
[CC3PFXResource cachedResourcesDescription]);
// Remove the pre-loaded PFX resources, now that we no longer need them.
// Other weakly-cached PFX resources will have been automatically removed already.
[CC3PFXResource removeAllResources];
LogRez(@"Finished loading on background thread!");
}
/**
* When loading in the background, periodically pause the loading to phase the scene in over time.
* We put an explicit test here, because if the CC3Backgrounder shouldRunTasksOnRequestingThread
* property is set to YES, the addSceneContentAsynchronously method will be run in the foreground,
* and we don't want to add any unncessary delays in that case.
*/
-(void) pauseDramatically {
if (!CC3OpenGL.sharedGL.isRenderingContext) {
NSTimeInterval pauseDuration = 0.25f;
LogRez(@"Pausing for %i milliseconds before loading next resource", (int)(pauseDuration * 1000));
[NSThread sleepForTimeInterval: pauseDuration];
}
}
/**
* Invoked by the customized initializeScene to set up any initial state for
* this customized scene. This is broken into a separate method so that the
* initializeScene method can focus on loading the artifacts of the 3D scene.
*/
-(void) initCustomState {
_isManagingShadows = NO;
_playerDirectionControl = CGPointZero;
_playerLocationControl = CGPointZero;
// The order in which meshes are drawn to the GL engine can be tailored to your needs.
// The default is to draw opaque objects first, then alpha-blended objects in reverse Z-order.
// ([CC3BTreeNodeSequencer sequencerLocalContentOpaqueFirst]).
//
// To experiment with an alternate drawing order, set a different node sequence sorter
// by uncommenting one of the lines here and commenting out the others. The last option
// does not use a drawing sequencer, and draws the objects hierarchically instead.
// With this, notice that the transparent beach ball now appears opaque, because it
// was added first, and is traversed ahead of other objects in the hierarchical assembly,
// resulting it in being drawn first, and so it cannot blend with the background objects.
//
// You can of course write your own node sequencers to customize to your specific
// app needs. Best to change the node sequencer before any model objects are added.
// self.drawingSequencer = [CC3BTreeNodeSequencer sequencerLocalContentOpaqueFirstGroupMeshes];
// self.drawingSequencer = [CC3BTreeNodeSequencer sequencerLocalContentOpaqueFirstGroupTextures];
// self.drawingSequencer = nil;
}
/**
* Pre-loads certain assets, such as shader programs, and certain textures, prior to the
* scene being displayed.
*
* Much of the scene is loaded on a background thread, while the scene is visible. However,
* the handling of some assets on the background thread can interrupt the main rendering thread.
*
* The GL drivers often leave the final stages of shader compilation and configuration until
* the first time the shader program is used to render an object. This can often introduce a
* short, unwanted pause if the shader program is loaded while the scene is running.
*
* Unfortunately, although resources such as models, textures, and shader programs can be loaded
* on a background thread, the final stages of shader programs compilation must be performed on
* the primary rendering thread. Because of this, the only way to avoid an unwanted pause while
* a shader program compilation is finalized is to therefore perform all shader program loading
* prior to the scene being displayed, including shader programs that may not be required until
* additional content is loaded later in the scene on a background thread.
*
* In order to ensure that the shader programs will be available when the models are loaded
* at a later point in the scene (usually via background loading), the cache must be configured
* to retain the loaded shader programs even though they will not immediately be used to display
* any models. This is done by turning on the value of the class-side isPreloading property.
*
* In addition, the automatic creation of mipmaps on larger textures, particularly cube-map
* textures (which require a set of six mipmaps), can cause excessive work for the GPU in
* the background, which can spill over into a delay on the primary rendering thread.
*
* As a result, a large cube-map texture is loaded here and cached, for later access once
* the model that uses it is loaded in the background.
*/
-(void) preloadAssets {
#if CC3_GLSL
// Strongly cache the shader programs loaded here, so they'll be availble
// when models are loaded on the background loading thread.
CC3ShaderProgram.isPreloading = YES;
[CC3ShaderProgram programFromVertexShaderFile: @"CC3ClipSpaceTexturable.vsh"
andFragmentShaderFile: @"CC3ClipSpaceNoTexture.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3ClipSpaceTexturable.vsh"
andFragmentShaderFile: @"CC3Fog.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3PointSprites.vsh"
andFragmentShaderFile: @"CC3PointSprites.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3BumpMapObjectSpace.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3BumpMapTangentSpace.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3NoTexture.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3SingleTexture.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3SingleTextureAlphaTest.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3Texturable.vsh"
andFragmentShaderFile: @"CC3SingleTextureReflect.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3TexturableBones.vsh"
andFragmentShaderFile: @"CC3SingleTexture.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3TexturableBones.vsh"
andFragmentShaderFile: @"CC3SingleTextureReflect.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3TexturableRigidBones.vsh"
andFragmentShaderFile: @"CC3BumpMapTangentSpace.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3TexturableRigidBones.vsh"
andFragmentShaderFile: @"CC3NoTexture.fsh"];
[CC3ShaderProgram programFromVertexShaderFile: @"CC3TexturableRigidBones.vsh"
andFragmentShaderFile: @"CC3SingleTexture.fsh"];
// Now pre-load shader programs that originate in PFX resources.
// Leave the shader program preloading on too...since effects will also load shaders.
CC3Resource.isPreloading = YES;
[CC3PFXResource resourceFromFile: kPostProcPFXFile];
[CC3PFXResource resourceFromFile: kReflectivePFXFile];
// All done with shader pre-loading...let me know in the logs if any further shader programs
// are loaded during the scene operation.
CC3Resource.isPreloading = NO;
CC3ShaderProgram.isPreloading = NO;
#endif // CC3_GLSL
// The automatic generation of mipmap in the environment map texture on the background
// thread causes a short delay in rendering on the main thread. The text glyph texture
// also requires substantial time for mipmap generation. For such textures, by loading
// the texture, creating the mipmap, and caching the texture here, we can avoid the delay.
// All other textures are loaded on the background thread.
CC3Texture.isPreloading = YES;
[CC3Texture textureFromFile: @"Arial32BMGlyph.png"];
#if !CC3_OGLES_1
[CC3Texture textureCubeFromFilePattern: @"EnvMap%@.jpg"];
#endif // !CC3_OGLES_1
CC3Texture.isPreloading = NO;
}
/** Various options for configuring interesting camera behaviours. */
-(void) configureCamera {
CC3Camera* cam = self.activeCamera;
// Camera starts out embedded in the scene.
_cameraZoomType = kCameraZoomNone;
// The camera comes from the POD file and is actually animated.
// Stop the camera from being animated so the user can control it via the user interface.
[cam disableAnimation];
// Keep track of which object the camera is pointing at
_origCamTarget = cam.target;
_camTarget = _origCamTarget;
// Set the field of view orientation to diagonal, to give a good overall average view of
// the scene, regardless of the shape of the viewing screen. As loaded from the POD file,
// the FOV is measured horizontally.
cam.fieldOfViewOrientation = CC3FieldOfViewOrientationDiagonal;
// For cameras, the scale property determines camera zooming, and the effective field of view.
// You can adjust this value to play with camera zooming. Conversely, if you find that objects
// in the periphery of your view appear elongated, you can adjust the fieldOfView and/or
// uniformScale properties to reduce this "fish-eye" effect. See the notes of the CC3Camera
// fieldOfView property for more on this.
cam.uniformScale = 0.5;
// You can configure the camera to use orthographic projection instead of the default
// perspective projection by setting the isUsingParallelProjection property to YES.
// You will also need to adjust the scale to match the different projection.
// cam.isUsingParallelProjection = YES;
// cam.uniformScale = 0.015;
// To see the effect of mounting a camera on a moving object, uncomment the following
// lines to mount the camera on a virtual boom attached to the beach ball.
// Since the beach ball rotates as it bounces, you might also want to comment out the
// CC3ActionRotateForever action that is run on the beach ball in the addBeachBall method!
// [_beachBall addChild: cam]; // Mount the camera on the beach ball
// cam.location = cc3v(2.0, 1.0, 0.0); // Relative to the parent beach ball
// cam.rotation = cc3v(0.0, 90.0, 0.0); // Point camera out over the beach ball
// To see the effect of mounting a camera on a moving object AND having the camera track a
// location or object, even as the moving object bounces and rotates, uncomment the following
// lines to mount the camera on a virtual boom attached to the beach ball, but stay pointed at
// the moving rainbow teapot, even as the beach ball that the camera is mounted on bounces and
// rotates. In this case, you do not need to comment out the CC3ActionRotateForever action that
// is run on the beach ball in the addBeachBall method
// [_beachBall addChild: cam]; // Mount the camera on the beach ball
// cam.location = cc3v(2.0, 1.0, 0.0); // Relative to the parent beach ball
// cam.target = teapotSatellite; // Look toward the rainbow teapot...
// cam.shouldTrackTarget = YES; // ...and track it as it moves
}
/** Configure the lighting. */
-(void) configureLighting {
// Start out with a sunny day
_lightingType = kLightingSun;
// Set the ambient scene lighting.
self.ambientLight = ccc4f(0.3, 0.3, 0.3, 1.0);
// Adjust the relative ambient and diffuse lighting of the main light to
// improve realisim, particularly on shadow effects.
_robotLamp.diffuseColor = ccc4f(0.8, 0.8, 0.8, 1.0);
// Another mechansim for adjusting shadow intensities is shadowIntensityFactor.
// For better effect, set here to a value less than one to lighten the shadows
// cast by the main light.
_robotLamp.shadowIntensityFactor = 0.75f;
// The light from the robot POD file is animated to move back and forth, changing
// the lighting of the scene as it moves. To turn this animation off, comment out
// the following line. This can be useful when reviewing shadowing.
// [_robotLamp disableAnimation];
}
/**
* Configures the specified node and all its descendants for use in the scene, and then fades
* them in over the specified duration, in seconds. Specifying zero for the duration will
* instantly materialize the node without employing any fading.
*
* This scene is highly complex, and it helps to configure the nodes within it in a standardized
* manner, including whether we use VBO's to manage the vertices, whether the vertices need to
* also be retained in main memory, whether bounding volumes are required, and to force early
* selection of shaders for use with the nodes.
*
* The specified node can be the root of an arbitrarily complex node tree, and the behaviour
* applied in this method is propagated to all descendant nodes of the specified node, and the
* materialization fading will be applied to the entire node tree. The specified node can even
* be the entire scene itself.
*/
-(void) configureForScene: (CC3Node*) aNode andMaterializeWithDuration: (CCTime) duration {
// This scene is quite complex, containing many objects. As the user moves the camera
// around the scene, objects move in and out of the camera's field of view. At any time,
// there may be a number of objects that are out of view of the camera. With such a scene
// layout, we can save significant GPU processing by not drawing those objects. To make
// that happen, we assign a bounding volume to each mesh node. Once that is done, only
// those objects whose bounding volumes intersect the camera frustum will be drawn.
// Bounding volumes can also be used for collision detection between nodes. You can see
// the effect of not using bounding volumes on drawing perfomance by commenting out the
// following line and taking note of the drop in performance for this scene. However,
// testing bounding volumes against the camera's frustum does take some CPU processing,
// and in scenes where all or most of the objects are in front of the camera at all times,
// using bounding volumes may actually result in slightly lower performance. By including
// or not including the line below, you can test both scenarios and decide which approach
// is best for your particular scene. Bounding volumes are not automatically created for
// skinned meshes, such as the runners and mallet. See the addSkinnedRunners and
// addSkinnedMallet methods to see how those bounding volumes are added manually.
[aNode createBoundingVolumes];
// Create OpenGL buffers for the vertex arrays to keep things fast and efficient, and
// to save memory, release the vertex data in main memory because it is now redundant.
// However, because we can add shadow volumes dynamically to any node, we need to keep the
// vertex location, index and skinning data of all meshes around to build shadow volumes.
// If we had added the shadow volumes before here, we wouldn't have to retain this data.
[aNode retainVertexLocations];
[aNode retainVertexIndices];
[aNode retainVertexBoneWeights];
[aNode retainVertexBoneIndices];
[aNode createGLBuffers];
[aNode releaseRedundantContent];
// The following line displays the bounding volumes of each node. The bounding volume of
// all mesh nodes, except the globe, contains both a spherical and bounding-box bounding
// volume, to optimize testing. For something extra cool, touch the robot arm to see the
// bounding volume of the particle emitter grow and shrink dynamically. Use the joystick
// controls or gestures to back the camera away to get the full effect. You can also turn
// on this property on individual nodes or node structures. See the notes for this property
// and the shouldDrawBoundingVolume property in the CC3Node class notes.
// aNode.shouldDrawAllBoundingVolumes = YES;
// Select the appropriate shaders for each mesh node descendent now. If this step is omitted,
// shaders will be selected for each mesh node the first time that mesh node is drawn.
// Doing it now adds some additional time up front, but avoids potential pauses as the
// shaders are loaded, compiled, and linked, the first time it is needed during drawing.
// Shader selection is driven by the characteristics of each mesh node and its material,
// including the number of textures, whether alpha testing is used, etc. To have the
// correct shaders selected, it is important that you finish configuring the mesh nodes
// prior to invoking this method. If you change any of these characteristics that affect
// the shader selection, you can invoke the removeShaders method to cause different shaders
// to be selected, based on the new mesh node and material characteristics.
[aNode selectShaders];
// For an interesting effect, to draw text descriptors and/or bounding boxes on every node
// during debugging, uncomment one or more of the following lines. The first line displays
// short descriptive text for each node (including class, node name & tag). The second line
// displays bounding boxes of only those nodes with local content (eg- meshes). The third
// line shows the bounding boxes of all nodes, including those with local content AND
// structural nodes. You can also turn on any of these properties at a more granular level
// by using these and similar methods on individual nodes or node structures. See the CC3Node
// class notes. This family of properties can be particularly useful during development to
// track down display issues.
// aNode.shouldDrawAllDescriptors = YES;
// aNode.shouldDrawAllLocalContentWireframeBoxes = YES;
// aNode.shouldDrawAllWireframeBoxes = YES;
// Use a standard CCActionFadeIn to fade the node in over the specified duration
if (duration > 0.0f) {
aNode.opacity = 0; // Needed for Cocos2D 1.x, which doesn't start fade-in from zero opacity
[aNode runAction: [CCActionFadeIn actionWithDuration: duration]];
}
}
/**
* Creates a clear-blue-sky backdrop. Or install a textured backdrop by uncommenting the
* 2nd & 3rd lines of this method. See the notes for the backdrop property for more info.
*/
-(void) addBackdrop {
self.backdrop = [CC3Backdrop nodeWithName: @"Backdrop" withColor: kSkyColor];
// self.backdrop = [CC3Backdrop nodeWithName: @"Backdrop"
// withTexture: [CC3Texture textureFromFile: kBrickTextureFile]];
}
/**
* Add a large circular grass-covered ground to give everything perspective.
* The ground is tessellated into many smaller faces to improve realism of spotlight.
*/
-(void) addGround {
_ground = [CC3PlaneNode nodeWithName: kGroundName];
[_ground populateAsDiskWithRadius: 1500 andTessellation: CC3TessellationMake(8, 32)];
// To demonstrate that a Cocos3D CC3Texture can be created from an existing Cocos2D CCTexture,
// we first load a CCTexture, and create the CC3Texture from it. We then assign the CC3Texture
// a unique name and add it to the texture cache it so it will be available for later use.
CCTexture* tex2D = [CCTextureCache.sharedTextureCache addImage: kGroundTextureFile];
CC3Texture* tex3D = [CC3Texture textureWithCCTexture: tex2D];
tex3D.name = kGroundTextureFile;
[CC3Texture addTexture: tex3D];
_ground.texture = tex3D;
// To simply load a Cocos3D texture directly, without first loading a Cocos2D texture,
// comment out the lines above, and uncomment the following line.
// _ground.texture = [CC3Texture textureFromFile: kGroundTextureFile];
// The ground uses a repeating texture
[_ground repeatTexture: (ccTex2F){10, 10}]; // Grass
// [_ground repeatTexture: (ccTex2F){3, 3}]; // MountainGrass
_ground.location = cc3v(0.0, -100.0, 0.0);
_ground.rotation = cc3v(-90.0, 180.0, 0.0);
_ground.shouldCullBackFaces = NO; // Show the ground from below as well.
_ground.touchEnabled = YES; // Allow the ground to be selected by touch events.
[_ground retainVertexLocations]; // Retain location data in main memory, even when it
// is buffered to a GL VBO via releaseRedundantContent,
// so that it may be accessed for further calculations
// when dropping objects on the ground.
[self addChild: _ground];
}
/**
* Adds a large rectangular orange ring floating above the ground. This ring is created from a plane
* using a texture that combines transparency and opacity. It demonstrates the use of transparency in
* textures. You can see through the transparent areas to the scene behind the texture. The texture
* as a whole fades in and out periodically, and rotates around the vertical (Y) axis.
*
* The type of blending function used to blend the transparent/translucent areas of the texture
* with the object behind is set automatically, and is influenced by the opacity of the object,
* whether the texture contains an alpha channel, and whether the color channels of the texture
* have been pre-multiplied by the alpha channel in the texture. Here we provide the option to
* demonstrate textures with either pre-multiplied content or non-pre-multiplied content, and
* the resulting blending function is logged to help you understand the difference.
*
* The non-premultiplied alpha texture is a PNG file with the special file-extension PPNG.
* This is a normal PNG file, but the renamed extension will stop Xcode from modifying the file
* to pre-multiply the alpha during app building. The PPNG file is loaded with a custom image
* loader, again, to avoid iOS pre-multiplying the texture content during image loading.
* This allows the texture to appear exactly as it was created. This is an important feature
* when loading textures that contain custom content, such as normal-maps, light-maps, shininess,
* weightings, etc. See the notes for the CC3STBImage useForFileExtensions property to learn
* more about these special file extensions.
*
* As the ring rotates, both sides are visible. This is because the shouldCullBackFaces property is
* set to NO, so that both sides of each face are rendered.
*
* A border is drawn around the bounding box of the mesh to highlight the extent of the
* transparency in the texture.
*/
-(void) addFloatingRing {
CC3MeshNode* floater = [CC3PlaneNode nodeWithName: kFloaterName];
[floater populateAsCenteredRectangleWithSize: CGSizeMake(120.0, 120.0)];
// The OrangeRing.ppng texture will be loaded without pre-multiplied alpha.
// The OrangeRing.png texture will be loaded without pre-multiplied alpha.
// Comment out one or other of the following lines to see the difference. The effect
// on the material blending that is automatically assigned is output in the logs.
floater.texture = [CC3Texture textureFromFile: @"OrangeRing.ppng"];
// floater.texture = [CC3Texture textureFromFile: @"OrangeRing.png"];
floater.isOpaque = NO; // Not strictly needed, because will be set automatically
// during fading action, but set here to allow the blending
// function to be logged on the next line.
LogInfo(@"%@ with %@ blending (%@/%@) and %@ %@ pre-multiplied alpha.",
floater, floater.material,
NSStringFromGLEnum(floater.material.sourceBlend),
NSStringFromGLEnum(floater.material.destinationBlend),
floater.texture, (floater.texture.hasPremultipliedAlpha ? @"with" : @"without"));
// This is a simple plane node. To make this object visible from behind, we need
// to show the back sides of the faces as well.
floater.shouldCullBackFaces = NO; // Show from behind as well.
// This object has some unexpected behaviour when using fog using GLSL. Since fog is dependent
// on the depth buffer, the fog intensity will be that of this object, even though the farther
// objects can be see through the transparent parts of this ring. To help with this, we
// can cause the transparent fragments to be discarded, which helps because the transparent
// fragments will not be written to the depth buffer. This works well except for the fact
// that we also fade the entire object in and out, which causes issues as the opqaue areas
// of the ring approach full transparency under fading. In general, opaque areas that have
// been faded almost away will not play well with GLSL fog.
floater.shouldDrawLowAlpha = NO;
floater.material.alphaTestReference = 0.05;
floater.location = cc3v(400.0, 150.0, -250.0);
floater.touchEnabled = YES;
floater.shouldDrawLocalContentWireframeBox = YES; // Draw an box around texture
// Ring is added on on background thread. Configure it for the scene, and fade it in slowly.
[self configureForScene: floater andMaterializeWithDuration: kFadeInDuration];
[self addChild: floater];
// Fade the floating ring in and out
CCActionInterval* fadeOut = [CCActionFadeOut actionWithDuration: 5.0];
CCActionInterval* fadeIn = [CCActionFadeIn actionWithDuration: 5.0];
[floater runAction: [[CCActionSequence actionOne: fadeOut two: fadeIn] repeatForever]];
// Rotate the floating ring to see the effect on the orientation of the plane normals
[floater runAction: [CC3ActionRotateForever actionWithRotationRate: cc3v(0.0, 30.0, 0.0)]];
}
/** Utility method to copy a file from the resources directory to the Documents directory */
-(BOOL) copyResourceToDocuments: (NSString*) fileName {
NSString* srcDir = [[NSBundle mainBundle] resourcePath];
NSString* srcPath = [srcDir stringByAppendingPathComponent: fileName];
NSString* dstDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
NSString* dstPath = [dstDir stringByAppendingPathComponent: fileName];
NSError* err = nil;
NSFileManager* fileMgr = [NSFileManager defaultManager];
[fileMgr removeItemAtPath: dstPath error: &err];
if ( [fileMgr copyItemAtPath: srcPath toPath: dstPath error: &err] ) {
LogRez(@"Copied %@ to %@", srcPath, dstPath);
return YES;
} else {
LogError(@"Could not copy %@ to %@ because (%li) in %@: %@",
srcPath, dstPath, (long)err.code, err.domain, err.userInfo);
return NO;
}
}
/**
* Loads a POD file containing a semi-transparent beach ball
* sporting multiple materials, exported from Blender.
*/
-(void) addBeachBall {
// To show it is possible to load model files from other directories,
// we copy the POD file to the application Document directory.
[self copyResourceToDocuments: kBeachBallPODFile];
NSString* docDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
NSString* podPath = [docDir stringByAppendingPathComponent: kBeachBallPODFile];
// Load the POD file from the application Documents directory. It will also
// load any needed textures from that directory as well.
CC3ResourceNode* bbRez = [CC3PODResourceNode nodeWithName: kBeachBallRezNodeName fromFile: podPath];
// Configure the bouncing beach ball
_beachBall = [bbRez getNodeNamed: kBeachBallName];
_beachBall.location = cc3v(200.0, 200.0, -400.0);
_beachBall.uniformScale = 50.0;
// Allow this beach ball node to be selected by touch events.
// The beach ball is actually a structural assembly containing four child nodes,
// one for each separately colored mesh. By marking the node assembly as touch-enabled,
// and NOT marking each component mesh node as touch-enabled, when any of the component
// nodes is touched, the entire beach ball structural node will be selected.
_beachBall.touchEnabled = YES;
// Bounce the beach ball...simply...we're not trying for realistic physics here,
// but we can still do some fun and interesting stuff with Ease-actions.
GLfloat hangTime = 3.0f;
CC3Vector dropLocation = _beachBall.location;
CC3Vector landingLocation = dropLocation;
landingLocation.y = _ground.location.y + 30.0f;
CCActionInterval* dropAction = [CC3ActionMoveTo actionWithDuration: hangTime moveTo: landingLocation];
dropAction = [CCActionEaseOut actionWithAction: [CCActionEaseIn actionWithAction: dropAction rate: 4.0f] rate: 1.6f];
CCActionInterval* riseAction = [CC3ActionMoveTo actionWithDuration: hangTime moveTo: dropLocation];
riseAction = [CCActionEaseIn actionWithAction: [CCActionEaseOut actionWithAction: riseAction rate: 4.0f] rate: 1.6f];
[_beachBall runAction: [[CCActionSequence actionOne: dropAction two: riseAction] repeatForever]];
// For extra realism, also rotate the beach ball as it bounces.
[_beachBall runAction: [CC3ActionRotateForever actionWithRotationRate: cc3v(30.0, 0.0, 45.0)]];
// Beach ball is added on on background thread. Configure it for the scene, and fade it in slowly.
[self configureForScene: _beachBall andMaterializeWithDuration: kFadeInDuration];
[self addChild: _beachBall];
}
/**
* Adds a rotating globe that is created programatically from a prametric sphere,
* and is covered with a rectangular texture containing a cylindrical projection
* (typical of earth maps taken from space).
*/
-(void) addGlobe {
// To show it is possible to load texture files from other directories,
// we copy the texture file to the application Document directory.
[self copyResourceToDocuments: kGlobeTextureFile];
NSString* docDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
NSString* texPath = [docDir stringByAppendingPathComponent: kGlobeTextureFile];
// Configure the rotating globe
_globe = [CC3SphereNode nodeWithName: kGlobeName]; // weak reference
[_globe populateAsSphereWithRadius: 1.0f andTessellation: CC3TessellationMake(32, 32)];
_globe.texture = [CC3Texture textureFromFile: texPath];
_globe.location = cc3v(150.0, 200.0, -150.0);
_globe.uniformScale = 50.0;
_globe.ambientColor = kCCC4FLightGray; // Increase the ambient reflection
_globe.touchEnabled = YES; // allow this node to be selected by touch events
// Rotate the globe
[_globe runAction: [CC3ActionRotateForever actionWithRotationRate: cc3v(0.0, 30.0, 0.0)]];
// Cube is added on on background thread. Configure it for the scene, and fade it in slowly.
[self configureForScene: _globe andMaterializeWithDuration: kFadeInDuration];
[self addChild: _globe];
// For something interesting, uncomment the following lines to make the
// globe invisible, but still touchable, and still able to cast a shadow.
// _globe.visible = NO;
// _globe.shouldAllowTouchableWhenInvisible = YES;
// _globe.shouldCastShadowsWhenInvisible = YES;
}
/**
* Adds a die cube that can be rotated by the user touching it and then swiping in any
* direction. The die cube rotates in the direction of the swipe, at a speed proportional
* to the speed and length of the swipe, and then steadily slows down over time.
*
* While the user is touching the cube and moving the finger, the die cube is rotated
* under direct finger motion. Once the finger is lifted, the die cube spins in a
* freewheel fashion, and slows down over time due to friction.
*
* This die cube does not use a CCAction to rotate. Instead, a custom SpinningNode class
* replaces the node loaded from the POD file. This custom class spins by adjusting its
* rotational state on each update pass. It contains a spinSpeed property to indicate how
* fast it is currently spinning, and a friction property to adjust the spinSpeed on each
* update.
*
* To handle the behaviour of the node while it is freewheeling, we create it as a
* specialized subclass. Since this node is loaded from a POD file, one way to do this
* is to load the POD class and then copy it to the subclass we want. That is done here.
*
* To rotate a node using changes in rotation using the rotateBy... family of methods,
* as is done to this node, does NOT requre a specialized class. This specialized class
* is required to handle the freewheeling and friction nature of the behaviour after the
* rotation has begun.
*
* The die cube POD file was created from a Blender model available from the Blender
* "Two dice" modeling tutorial available online at:
* http://wiki.blender.org/index.php/Doc:Tutorials/Modeling/Two_dice
*/
-(void) addDieCube {
// Fetch the die cube model from the POD file.
CC3ResourceNode* podRezNode = [CC3PODResourceNode nodeFromFile: kDieCubePODFile];
CC3Node* podDieCube = [podRezNode getNodeNamed: kDieCubePODName];
// We want this node to be a SpinningNode class instead of the CC3PODNode class that
// is loaded from the POD file. We can swap it out by creating a copy of the loaded
// POD node, using a different node class as the base.
_dieCube = [podDieCube copyWithName: kDieCubeName asClass: [SpinningNode class]];
// Now set some properties, including the friction, and add the die cube to the scene
_dieCube.uniformScale = 30.0;
_dieCube.location = cc3v(-200.0, 200.0, 0.0);
_dieCube.touchEnabled = YES;
_dieCube.friction = 1.0;
// Cube is added on on background thread. Configure it for the scene, and fade it in slowly.
[self configureForScene: _dieCube andMaterializeWithDuration: kFadeInDuration];
[self addChild: _dieCube];
}
/**
* Adds a parametric textured cube that rotates by swiping, similar to the die cube.
*
* This is a single box mesh (not constructed from six separate plane meshes), and is
* wrapped by a single texture, that wraps around all six sides of the cube. The texture
* must be constructed to do this. Have a look at the BoxTexture.png texture file to
* understand how the texture is wrapped to the different sides.
*/
-(void) addTexturedCube {
NSString* itemName;
// Create a parametric textured cube, centered on the local origin.
CC3BoxNode* texCube = [CC3BoxNode nodeWithName: kTexturedCubeName];
[texCube populateAsSolidBox: CC3BoxMake(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f)];
texCube.uniformScale = 30.0;
// Add a texture to the textured cube. This creates a material automatically.
// For kicks, we use a texture that contains two distinct images, one for a box and
// one for a ball, and set a texture rectangle on the node so it will use only one
// part of the texture to cover the box.
texCube.texture = [CC3Texture textureFromFile: kMeshParticleTextureFile];
texCube.textureRectangle = CGRectMake(0, 0, 1, 0.75);
// texCube.texture = [CC3Texture textureFromFile: kCubeTextureFile]; // Alternately, use a full texture
texCube.ambientColor = ccc4f(0.6, 0.6, 0.6, 1.0); // Increase the ambient reflection
// Add direction markers to demonstrate how the sides are oriented. In the local coordinate
// system of the cube node, the red marker point in the direction of the positive-X axis,
// the green marker in the direction of the positive-Y axis, and the blue marker in the
// direction of the positive-Z axis. As these demonstrate, the front faces the positive-Z
// direction, and the top faces the positive-Y direction.
[texCube addAxesDirectionMarkers];
// Wrap the cube in a spinner node to allow it to be rotated by touch swipes.
// Give the spinner some friction so that it slows down over time one released.
itemName = [NSString stringWithFormat: @"%@-Spinner", texCube.name];
_texCubeSpinner = [SpinningNode nodeWithName: itemName];
_texCubeSpinner.friction = 1.0;
_texCubeSpinner.location = cc3v(-200.0, 75.0, 0.0);
_texCubeSpinner.touchEnabled = YES;
// Add the cube to the spinner and the spinner to the scene.
[_texCubeSpinner addChild: texCube];
// Cube is added on on background thread. Configure it for the scene, and fade it in slowly.
[self configureForScene: _texCubeSpinner andMaterializeWithDuration: kFadeInDuration];
[self addChild: _texCubeSpinner];
}
/**
* Adds a large textured teapot and a small multicolored teapot orbiting it.
*
* When running with GLSL shaders under OpenGL ES 2.0 on iOS, or OpenGL on OSX, the textured
* teapot reflects the surrounding environment dynamically. This is performed by adding a
* environmental cube-map texture to the teapot. A cube-map texture actually consists of six
* textures, each representing a view of the scene from one of the six scene axes. The reflection
* texture is updated each frame (see the generateTeapotEnvironmentMapWithVisitor method), so
* the teapot reflects the dynamic scene. As objects move around the scene, they are reflected
* in the teapot.
*
* The default program matcher assigns the GLSL shaders CC3Texturable.vsh and
* CC3SingleTextureReflect.fsh shaders to the reflective teapot.
*
* The textured teapot actually has two textures. The first is the reflective cube-map, and the
* second can provide an optional surface material effect (in this case brushed metal), that
* blends with the reflection, to more realistically mimic a non-silvered reflective material.
* The reflectivity property of the material covering the teapot adjusts the blend between the
* reflective and material textures, and can be used to control how reflective the surface is.
* For demonstative effect, the reflectivity property is set to the maximum value of 1.0, making
* the material fully reflective (like a mirror or chrome), and none of the brushed metal texture