-
Notifications
You must be signed in to change notification settings - Fork 2
/
v002_Model_ImporterPlugIn.mm
1519 lines (1235 loc) · 58.3 KB
/
v002_Model_ImporterPlugIn.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
//
// v002_Model_ImporterPlugIn.m
// v002 Model Importer
//
// Created by vade on 9/14/10.
// Copyright (c) 2010 __MyCompanyName__. All rights reserved.
//
#import <OpenGL/CGLMacro.h>
#import <OPenGL/glu.h>
#import "v002_Model_ImporterPlugIn.h"
#import "config.h"
#import "cimport.h"
#define kQCPlugIn_Name @"v002 Model Importer"
#define kQCPlugIn_Description @"v002 Model Importer supports a variety of plugin formats:\n\r Collada (.dae), 3ds Max 3DS (.3ds), 3ds Max ASE (.ase), Wavefront Object (.obj), Stanford Polygon Library (.ply), AutoCAD DXF (.dxf), LightWave (.lwo), Modo (.lxo), Stereolithography (.stl), AC3D (.ac), Milkshape 3D (.ms3d), TrueSpace (.cob, .scn), Valve Model (.smd,.vta), Quake I (.mdl), Quake II (.md2), Quake III (.md3), Return to Castle Wolfenstein (.mdc), Doom 3 (.md5), Biovision BVH (.bvh), CharacterStudio Motion (.csm), DirectX X (.x)., BlitzBasic 3D (.b3d)., Quick3D (.q3d,.q3s)., Ogre XML (.mesh, .xml)., Irrlicht Mesh (.irrmesh)., Irrlicht Scene (.irr)., Neutral File Format (.nff), Sense8 WorldToolKit (.nff), Object File Format (.off), PovRAY Raw (.raw), Terragen Terrain (.ter), 3D GameStudio (.mdl) and 3D GameStudio Terrain (.hmp)"
#define kv002DescriptionAddOnText @"\n\rv002 Plugins : http://v002.info\n\nCopyright:\nvade - Anton Marini.\nbangnoise - Tom Butterworth\n\n2008-2012 - Creative Commons Non Commercial Share Alike Attribution 3.0"
#define aisgl_min(x,y) (x<y?x:y)
#define aisgl_max(x,y) (y>x?y:x)
// TODO: look at
// http://github.com/mgottschlag/CoreRender/blob/master/CoreRender/src/render/ModelRenderable.cpp
// http://github.com/mgottschlag/CoreRender/blob/master/Tools/ModelConverter/src/main.cpp
// http://sourceforge.net/mailarchive/forum.php?thread_name=414314.62490.qm%40web55207.mail.re4.yahoo.com&forum_name=assimp-discussions
// http://sourceforge.net/mailarchive/forum.php?thread_name=4AD880BD.2070704%40sio.midco.net&forum_name=assimp-discussions
// Eventual optimization: http://lists.apple.com/archives/mac-opengl/2004/Jan/msg00180.html
//TODO:
//Fix image paths so it can go up one level and find relative paths.
static void color4_to_float4(const aiColor4D *c, float f[4])
{
f[0] = c->r;
f[1] = c->g;
f[2] = c->b;
f[3] = c->a;
}
static void set_float4(float f[4], float a, float b, float c, float d)
{
f[0] = a;
f[1] = b;
f[2] = c;
f[3] = d;
}
// Can't send color down as a pointer to aiColor4D because AI colors are ABGR.
static void Color4f(CGLContextObj cgl_ctx, const aiColor4D *color)
{
glColor4f(color->r, color->g, color->b, color->a);
}
@implementation v002_Model_ImporterPlugIn
@dynamic inputModelPath;
@dynamic inputImage;
@dynamic inputColor;
//@dynamic inputOverrideColor;
@dynamic inputAnimation;
@dynamic inputRenderingMode;
@dynamic inputUVGenMode;
@dynamic inputTranslationX;
@dynamic inputTranslationY;
@dynamic inputTranslationZ;
@dynamic inputRotationX;
@dynamic inputRotationY;
@dynamic inputRotationZ;
@dynamic inputScaleX;
@dynamic inputScaleY;
@dynamic inputScaleZ;
@dynamic inputBlendMode;
@dynamic inputDepthMode;
@dynamic inputCullMode;
@dynamic inputNormalizeScale;
@dynamic inputAutoCenter;
//@dynamic inputSilhouette;
//@dynamic inputSilhouetteWidth;
//@dynamic inputSilhouetteOffset;
//@dynamic inputSilhouetteColor;
@dynamic inputLoadTextures;
@dynamic inputPointSpriteImage;
@dynamic inputPointSize;
@dynamic inputAttenuatePoints;
@dynamic inputConstantAttenuation;
@dynamic inputLinearAttenuation;
@dynamic inputQuadraticAttenuation;
+ (NSDictionary*) attributes
{
return [NSDictionary dictionaryWithObjectsAndKeys:kQCPlugIn_Name, QCPlugInAttributeNameKey,
[kQCPlugIn_Description stringByAppendingString:kv002DescriptionAddOnText], QCPlugInAttributeDescriptionKey,
kQCPlugIn_Category, @"categories", nil];
}
+ (NSDictionary*) attributesForPropertyPortWithKey:(NSString*)key
{
if([key isEqualToString:@"inputModelPath"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Model Path", QCPortAttributeNameKey, nil];
/* if([key isEqualToString:@"inputModelLoadingQuality"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Model Quality", QCPortAttributeNameKey,
[NSArray arrayWithObjects:@"Realtime Fast", @"Realtime Quality", @"Max Quality", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithUnsignedInt:2], QCPortAttributeMaximumValueKey,
[NSNumber numberWithUnsignedInt:2], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
*/
if([key isEqualToString:@"inputImage"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Image", QCPortAttributeNameKey, nil];
if([key isEqualToString:@"inputColor"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Tint Color", QCPortAttributeNameKey, nil];
//
// if([key isEqualToString:@"inputOverrideColor"])
// return [NSDictionary dictionaryWithObjectsAndKeys:@"Use Tint Color", QCPortAttributeNameKey, [NSNumber numberWithBool:FALSE], QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputAnimation"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Animation ID", QCPortAttributeNameKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
if([key isEqualToString:@"inputRenderingMode"])
return @{QCPortAttributeNameKey: @"Rendering Mode" ,
QCPortAttributeMenuItemsKey : @[@"Model", @"Wireframe", @"Point"],
QCPortAttributeDefaultValueKey : [NSNumber numberWithUnsignedInt:0],
QCPortAttributeMinimumValueKey : [NSNumber numberWithUnsignedInt:0],
QCPortAttributeMaximumValueKey : [NSNumber numberWithUnsignedInt:2],
};
if([key isEqualToString:@"inputUVGenMode"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Texture Coordinates", QCPortAttributeNameKey,
[NSArray arrayWithObjects:@"Model", @"Object Linear", @"Eye Linear", @"Sphere Map", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithUnsignedInt:3], QCPortAttributeMaximumValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
if([key isEqualToString:@"inputRotationX"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Rotation X", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputRotationY"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Rotation Y", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputRotationZ"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Rotation Z", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputTranslationX"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Translation X", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputTranslationY"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Translation Y", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputTranslationZ"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Translation Z", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputScaleX"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Scale X", QCPortAttributeNameKey, [NSNumber numberWithDouble:1.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputScaleY"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Scale Y", QCPortAttributeNameKey, [NSNumber numberWithDouble:1.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputScaleZ"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Scale Z", QCPortAttributeNameKey, [NSNumber numberWithDouble:1.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputBlendMode"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Blending", QCPortAttributeNameKey,
[NSArray arrayWithObjects:@"Replace", @"Over", @"Add", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithUnsignedInt:2], QCPortAttributeMaximumValueKey,
[NSNumber numberWithUnsignedInt:1], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
if([key isEqualToString:@"inputDepthMode"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Depth Testing", QCPortAttributeNameKey,
[NSArray arrayWithObjects:@"None", @"Read/Write", @"Read-Only", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithUnsignedInt:2], QCPortAttributeMaximumValueKey,
[NSNumber numberWithUnsignedInt:1], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
if([key isEqualToString:@"inputCullMode"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Face Culling", QCPortAttributeNameKey,
[NSArray arrayWithObjects:@"Model", @"Front", @"Back", @"None", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithUnsignedInt:3], QCPortAttributeMaximumValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithUnsignedInt:0], QCPortAttributeMinimumValueKey, nil];
if([key isEqualToString:@"inputNormalizeScale"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Auto Scale", QCPortAttributeNameKey, [NSNumber numberWithBool:YES],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputAutoCenter"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Auto Center", QCPortAttributeNameKey, [NSNumber numberWithBool:YES],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputLoadTextures"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Load Textures", QCPortAttributeNameKey, [NSNumber numberWithBool:YES],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputPointSpriteImage"])
return [NSDictionary dictionaryWithObject:@"Point Sprite Image" forKey:QCPortAttributeNameKey];
if([key isEqualToString:@"inputPointSize"])
return @{QCPortAttributeNameKey : @"Point Size",
QCPortAttributeDefaultValueKey : @1.0,
QCPortAttributeMinimumValueKey : @0.1,
QCPortAttributeMaximumValueKey : @64.0
};
if([key isEqualToString:@"inputAttenuatePoints"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Point Attenuation",QCPortAttributeNameKey, nil];
if([key isEqualToString:@"inputConstantAttenuation"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Point Constant Attenuation", QCPortAttributeNameKey, [NSNumber numberWithDouble:1.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputLinearAttenuation"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Point Linear Attenuation", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
if([key isEqualToString:@"inputQuadraticAttenuation"])
return [NSDictionary dictionaryWithObjectsAndKeys:@"Point Quadratic Attenuation", QCPortAttributeNameKey, [NSNumber numberWithDouble:0.0],QCPortAttributeDefaultValueKey, nil];
return nil;
}
+ (NSArray*) sortedPropertyPortKeys
{
return [NSArray arrayWithObjects:@"inputModelPath",
/*@"inputModelLoadingQuality", */
@"inputImage",
@"inputAnimation",
@"inputRenderingMode",
@"inputGenerateUVs",
@"inputUVGenMode",
@"inputRotationX",
@"inputRotationY",
@"inputRotationZ",
@"inputTranslationX",
@"inputTranslationY",
@"inputTranslationZ",
@"inputScaleX",
@"inputScaleY",
@"inputScaleZ",
@"inputBlendMode",
@"inputDepthMode",
@"inputCullMode",
@"inputNormalizeScale",
@"inputAutoCenter"
@"inputPointSpriteImage",
@"inputPointSize",
@"inputAttenuatePoints",
@"inputConstantAttenuation",
@"inputLinearAttenuation",
@"inputQuadraticAttenuation"
, nil];
}
+ (QCPlugInExecutionMode) executionMode
{
return kQCPlugInExecutionModeConsumer;
}
+ (QCPlugInTimeMode) timeMode
{
return kQCPlugInTimeModeTimeBase;
}
- (id) init
{
if(self = [super init])
{
// // generate UUID
// CFUUIDRef uuidObj = CFUUIDCreate(nil);
// CFStringRef uuid = CFUUIDCreateString(nil, uuidObj);
// CFRelease(uuidObj);
// NSString *result = [[NSString alloc] initWithFormat:@"%@", uuid];
// CFRelease(uuid);
//
// _queue = dispatch_queue_create([result cStringUsingEncoding:NSUTF8StringEncoding], NULL);
//
// [result release];
//animationIndex = 0;
animationTime = 0;
usingExternalTexture = FALSE;
}
return self;
}
- (void) finalize
{
//dispatch_release(_queue);
[super finalize];
}
- (void) dealloc
{
//dispatch_release(_queue);
[super dealloc];
}
@end
@implementation v002_Model_ImporterPlugIn (Execution)
- (BOOL) startExecution:(id<QCPlugInContext>)context
{
CGLContextObj cgl_ctx = [context CGLContextObj];
// create our 1 x 1 GL_TEXTURE_2D color texture, and set its color to our
if(!colorTextureID)
{
glPushAttrib(GL_TEXTURE_BIT);
glGenTextures(1, &colorTextureID);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, colorTextureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, 1, 1, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPopAttrib();
}
return YES;
}
- (void) stopExecution:(id<QCPlugInContext>)context
{
CGLContextObj cgl_ctx = [context CGLContextObj];
// delete our color texture
if(colorTextureID)
{
glDeleteTextures(1, &colorTextureID);
colorTextureID = 0;
}
}
- (void) enableExecution:(id<QCPlugInContext>)context
{
}
- (BOOL) execute:(id<QCPlugInContext>)context atTime:(NSTimeInterval)time withArguments:(NSDictionary*)arguments
{
CGLContextObj cgl_ctx = [context CGLContextObj];
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
if([self didValueForInputKeyChange:@"inputColor"])
{
// update our texture
const CGFloat *mcolor;
mcolor = CGColorGetComponents(self.inputColor);
if(mcolor)
{
const GLfloat fColor[4] = {(GLfloat)mcolor[0],
(GLfloat)mcolor[1],
(GLfloat)mcolor[2],
(GLfloat)mcolor[3]};
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, colorTextureID);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 1, 1, GL_RGBA, GL_FLOAT, fColor);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
}
if([self didValueForInputKeyChange:@"inputCullMode"])
{
cullMode = self.inputCullMode;
}
if([self didValueForInputKeyChange:@"inputModelPath"]) // || ![self.inputModelPath isEqualToString:[[[self class] attributesForPropertyPortWithKey:@"inputModelPath"] valueForKey:QCPortAttributeDefaultValueKey]] )
{
// delete the existing scene - allows us to 'unload'
if(v002Scene)
{
aiReleaseImport(v002Scene);
v002Scene = NULL;
glDeleteTextures([textureDictionary count], textureIds);
[textureDictionary release];
textureDictionary = nil;
free(textureIds);
textureIds = NULL;
[self deleteGLResourcesInContext:cgl_ctx];
}
NSString * path = [self.inputModelPath stringByStandardizingPath];
// relative to composition ?
if(![path hasPrefix:@"/"])
path = [NSString pathWithComponents:[NSArray arrayWithObjects:[[[context compositionURL] path]stringByDeletingLastPathComponent], path, nil]];
path = [path stringByStandardizingPath];
if([[NSFileManager defaultManager] fileExistsAtPath:path])
{
// Load our new path.
// only ever give us triangles.
aiPropertyStore* store = aiCreatePropertyStore();
aiSetImportPropertyInteger(store, AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT );
NSUInteger aiPostProccesFlags =
aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible
aiProcess_GenSmoothNormals | // generate normals if they are not specified.
aiProcess_JoinIdenticalVertices | // join identical vertices/ optimize indexing
aiProcess_ValidateDataStructure | // perform a full validation of the loader's output
aiProcess_ImproveCacheLocality | // improve the cache locality of the output vertices
aiProcess_RemoveRedundantMaterials | // remove redundant materials
aiProcess_FindDegenerates | // remove degenerated polygons from the import
aiProcess_FindInvalidData | // detect invalid model data, such as invalid normal vectors
aiProcess_GenUVCoords | // convert spherical, cylindrical, box and planar mapping to proper UVs
aiProcess_TransformUVCoords | // preprocess UV transformations (scaling, translation ...)
aiProcess_FindInstances | // search for instanced meshes and remove them by references to one master
aiProcess_LimitBoneWeights | // limit bone weights to 4 per vertex
aiProcess_OptimizeMeshes | // join small meshes, if possible;
aiProcess_OptimizeGraph | // reduce drawcalls
aiProcess_SplitLargeMeshes | // reduce number of triangles batched in a single mesh/drawcall
aiProcess_SortByPType | // splits meshes with more than one primitive type in homogeneous submeshes.
aiProcess_Triangulate | // triangulate quads/polymeshes so we render one primitive type only
aiProcess_FlipUVs | // for whatever reason, this is required for us.
aiProcess_FixInfacingNormals | // fix unintentional back facing faces.
0;
v002Scene = (aiScene*) aiImportFile([path cStringUsingEncoding:[NSString defaultCStringEncoding]], aiPostProccesFlags );
if(v002Scene)
{
textureDictionary = [[NSMutableDictionary alloc] initWithCapacity:5];
if(self.inputLoadTextures)
[self loadTexturesInContext:context withModelPath:[self.inputModelPath stringByStandardizingPath]];
[self getBoundingBoxWithMinVector:&scene_min maxVectr:&scene_max];
scene_center.x = (scene_min.x + scene_max.x) / 2.0f;
scene_center.y = (scene_min.y + scene_max.y) / 2.0f;
scene_center.z = (scene_min.z + scene_max.z) / 2.0f;
// optional normalized scaling
normalizedScale = scene_max.x-scene_min.x;
normalizedScale = aisgl_max(scene_max.y - scene_min.y,normalizedScale);
normalizedScale = aisgl_max(scene_max.z - scene_min.z,normalizedScale);
normalizedScale = 1.f / normalizedScale;
if(v002Scene->HasAnimations())
NSLog(@"scene has %i animations", v002Scene->mNumAnimations);
// create new mesh helpers for each mesh, will populate their data later.
modelMeshes = [[NSMutableArray alloc] initWithCapacity:v002Scene->mNumMeshes];
[self createGLResourcesInContext:cgl_ctx node:v002Scene->mRootNode];
}
else
{
[context logMessage:@"Could not load file %@", path];
}
aiReleasePropertyStore(store);
}
}
if(v002Scene)
{
glEnable(GL_NORMALIZE);
glPushMatrix();
if(self.inputBlendMode == 0)
glDisable(GL_BLEND);
else if(self.inputBlendMode == 1)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
if(self.inputDepthMode == 0)
glDisable(GL_DEPTH_TEST);
else if(self.inputDepthMode == 1)
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
}
else
{
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
}
glTranslated(self.inputTranslationX, self.inputTranslationY, self.inputTranslationZ);
// Normalize Scale
if(self.inputNormalizeScale)
glScaled(normalizedScale , normalizedScale, normalizedScale);
glScaled(self.inputScaleX, self.inputScaleY, self.inputScaleZ);
// rotate model.
glRotated(self.inputRotationX, 1.0, 0.0, 0.0);
glRotated(self.inputRotationY, 0.0, 1.0, 0.0);
glRotated(self.inputRotationZ, 0.0, 0.0, 1.0);
// center the model
if(self.inputAutoCenter)
glTranslated( -scene_center.x, -scene_center.y, -scene_center.z);
id<QCPlugInInputImageSource> image = self.inputImage;
if(image)
{
if([image lockTextureRepresentationWithColorSpace:[context colorSpace] forBounds:[image imageBounds]])
{
usingExternalTexture = TRUE;
glActiveTexture(GL_TEXTURE0);
[image bindTextureRepresentationToCGLContext:cgl_ctx textureUnit:GL_TEXTURE0 normalizeCoordinates:YES];
if(GL_TEXTURE_2D == [image textureTarget])
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
else
{
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
if(self.inputUVGenMode)
{
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
GLenum uvGenMode;
switch (self.inputUVGenMode)
{
case 1:
uvGenMode = GL_OBJECT_LINEAR;
break;
case 2:
uvGenMode = GL_EYE_LINEAR;
break;
case 3:
uvGenMode = GL_SPHERE_MAP;
break;
default:
uvGenMode = GL_OBJECT_LINEAR;
break;
}
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, uvGenMode);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, uvGenMode);
// need to manually handle flipping
if([image textureFlipped])
{
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glScalef(1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
}
else
{
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
}
}
}
else
{
usingExternalTexture = FALSE;
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
}
if(v002Scene->HasAnimations())
{
NSUInteger animation = MIN(self.inputAnimation, v002Scene->mNumAnimations - 1);
[self updateAnimation:animation atTime:time];
[self updateGLResources:cgl_ctx];
}
// bind our color
if(colorTextureID)
{
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, colorTextureID);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glActiveTexture(GL_TEXTURE0);
}
switch (self.inputRenderingMode)
{
case 0:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
[self drawMeshesInContext:cgl_ctx enableMaterials:YES];
break;
case 1:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
[self drawMeshesInContext:cgl_ctx enableMaterials:YES];
break;
case 2:
{
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glPointSize((GLfloat)self.inputPointSize);
id<QCPlugInInputImageSource> sprite = self.inputPointSpriteImage;
float coefficients[3];
if(self.inputAttenuatePoints)
{
coefficients[0] = self.inputConstantAttenuation;
coefficients[1] = self.inputLinearAttenuation;
coefficients[2] = self.inputQuadraticAttenuation;
}
else
{
coefficients[0] = 1;
coefficients[1] = 0;
coefficients[2] = 0;
}
glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, coefficients);
if(sprite && [sprite lockTextureRepresentationWithColorSpace:[context colorSpace] forBounds:[sprite imageBounds]])
{
glActiveTexture(GL_TEXTURE2);
glEnable(GL_POINT_SPRITE);
[sprite bindTextureRepresentationToCGLContext:cgl_ctx textureUnit:GL_TEXTURE2 normalizeCoordinates:YES];
if([sprite textureTarget] == GL_TEXTURE_2D)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// //Sample RGB, multiply by previous texunit result
// glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); //Modulate RGB with RGB
// glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS);
// glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE);
// glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
// glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
// //Sample ALPHA, multiply by previous texunit result
// glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE); //Modulate ALPHA with ALPHA
// glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PREVIOUS);
// glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_TEXTURE);
// glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
// glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
}
// draw
[self drawMeshesInContext:cgl_ctx enableMaterials:YES];
if(sprite)
{
glDisable(GL_POINT_SPRITE);
glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_FALSE);
[sprite unbindTextureRepresentationFromCGLContext:cgl_ctx textureUnit:GL_TEXTURE2];
[sprite unlockTextureRepresentation];
}
}
break;
}
// unbind our color texture id
if(colorTextureID)
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glActiveTexture(GL_TEXTURE0);
}
// if(self.inputSilhouette)
// {
// // Draw Filled Polygons
// glEnable(GL_CULL_FACE);
// glPolygonMode(GL_FRONT,GL_FILL);
// // dont draw shared edges
// glDepthFunc(GL_LESS);
// // draw front facing polys only
// glCullFace(GL_BACK);
// // draw model
//
//
// [self drawMeshesInContext:cgl_ctx enableMaterials:YES];
//
// // Draw Lines
// glPolygonMode(GL_BACK,GL_LINE);
// // Draw shared edges
// glDepthFunc(GL_LEQUAL);
// // Draw back facing edges only
// glCullFace(GL_FRONT);
//
// glLineWidth(self.inputSilhouetteWidth);
//
// //glDisable(GL_BLEND);
// glEnable(GL_LINE_SMOOTH);
//
//
// glEnable(GL_POLYGON_OFFSET_LINE);
// glPolygonOffset(self.inputSilhouetteOffset, 1.0);
//
// glDisable(GL_LIGHTING);
//
// if(image)
// glBindTexture([image textureTarget], 0);
// else
// glBindTexture(GL_TEXTURE_2D, 0);
//
// const CGFloat *color;
//
// color = CGColorGetComponents(self.inputSilhouetteColor);
//
// glColor4f(color[0], color[1], color[2], color[3]);
//
// // Draw Model
// [self drawMeshesInContext:cgl_ctx enableMaterials:self.inputOverrideColor];
// }
//
// else
if(image)
{
if(self.inputUVGenMode)
{
// need to manually handle flipping
if([image textureFlipped])
{
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
}
[image unbindTextureRepresentationFromCGLContext:cgl_ctx textureUnit:GL_TEXTURE0];
[image unlockTextureRepresentation];
}
else
{
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
glPopMatrix();
}
glPopClientAttrib();
glPopAttrib();
return YES;
}
- (void) disableExecution:(id<QCPlugInContext>)context
{
}
#pragma mark -
#pragma mark Texture Loading
- (void) loadTexturesInContext:(id <QCPlugInContext>)context withModelPath:(NSString*) modelPath
{
CGLContextObj cgl_ctx = [context CGLContextObj];
if (v002Scene->HasTextures())
{
NSLog(@"Support for meshes with embedded textures is not implemented");
return;
}
/* getTexture Filenames and Numb of Textures */
for (unsigned int m = 0; m < v002Scene->mNumMaterials; m++)
{
int texIndex = 0;
aiReturn texFound = AI_SUCCESS;
aiString path; // filename
// TODO: handle other aiTextureTypes
while (texFound == AI_SUCCESS)
{
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_SPECULAR, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_EMISSIVE, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_HEIGHT, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_NORMALS, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_SHININESS, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_OPACITY, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_DISPLACEMENT, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_LIGHTMAP, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_REFLECTION, texIndex, &path);
if(texFound != AI_SUCCESS)
texFound = v002Scene->mMaterials[m]->GetTexture(aiTextureType_UNKNOWN, texIndex, &path);
if(texFound == AI_SUCCESS)
{
NSString* texturePath = [NSString stringWithCString:path.data encoding:[NSString defaultCStringEncoding]];
// add our path to the texture and the index to our texture dictionary.
[textureDictionary setValue:[NSNumber numberWithUnsignedInt:texIndex] forKey:texturePath];
texIndex++;
}
}
}
textureIds = (GLuint*) malloc(sizeof(GLuint) * [textureDictionary count]); //new GLuint[ [textureDictionary count] ];
glGenTextures([textureDictionary count], textureIds);
NSLog(@"textureDictionary: %@", textureDictionary);
// create our textures, populate them, and alter our textureID value for the specific textureID we create.
// so we can modify while we enumerate...
NSDictionary *textureCopy = [textureDictionary copy];
// GCD attempt.
//dispatch_sync(_queue, ^{
int i = 0;
for(NSString* texturePath in textureCopy)
{
NSString* fullTexturePath = [[[modelPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[texturePath stringByStandardizingPath]] stringByStandardizingPath];
// relative to composition ?
if(![fullTexturePath hasPrefix:@"/"])
fullTexturePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[[[context compositionURL] path]stringByDeletingLastPathComponent], fullTexturePath, nil]];
fullTexturePath = [fullTexturePath stringByStandardizingPath];
NSLog(@"texturePath: %@", fullTexturePath);
NSImage* textureImage = [[NSImage alloc] initWithContentsOfFile:fullTexturePath];
if(textureImage)
{
//NSLog(@"Have Texture Image");
[textureImage lockFocus];
NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, textureImage.size.width, textureImage.size.height)];
[textureImage unlockFocus];
glPushAttrib(GL_ALL_ATTRIB_BITS);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureIds[i]);
//glPixelStorei(GL_UNPACK_ROW_LENGTH, [bitmap pixelsWide]);
//glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// generate mip maps
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// draw into our bitmap
int samplesPerPixel = [bitmap samplesPerPixel];
if(![bitmap isPlanar] && (samplesPerPixel == 3 || samplesPerPixel == 4))
{
glTexImage2D(GL_TEXTURE_2D,
0,
//samplesPerPixel == 4 ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8,
[bitmap pixelsWide],
[bitmap pixelsHigh],
0,
samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE,
[bitmap bitmapData]);
}
glPopAttrib();
// update our dictionary to contain the proper textureID value (from out array of generated IDs)
[textureDictionary setValue:[NSNumber numberWithUnsignedInt:textureIds[i]] forKey:texturePath];
[bitmap release];
}
else
{
[textureDictionary removeObjectForKey:texturePath];
NSLog(@"Could not Load Texture: %@, removing reference to it.", fullTexturePath);
}
[textureImage release];
i++;
}
//});
glBindTexture(GL_TEXTURE_2D, 0);
[textureCopy release];
}
- (void) getBoundingBoxWithMinVector:(aiVector3D*) min maxVectr:(aiVector3D*) max
{
aiMatrix4x4 trafo;
aiIdentityMatrix4(&trafo);
min->x = min->y = min->z = 1e10f;
max->x = max->y = max->z = -1e10f;
[self getBoundingBoxForNode:v002Scene->mRootNode minVector:min maxVector:max matrix:&trafo];
}
- (void) getBoundingBoxForNode:(const aiNode*)nd minVector:(aiVector3D*) min maxVector:(aiVector3D*) max matrix:(aiMatrix4x4*) trafo
{
aiMatrix4x4 prev;
unsigned int n = 0, t;
prev = *trafo;
aiMultiplyMatrix4(trafo,&nd->mTransformation);
for (; n < nd->mNumMeshes; ++n)
{
const struct aiMesh* mesh = v002Scene->mMeshes[nd->mMeshes[n]];
for (t = 0; t < mesh->mNumVertices; ++t)
{
aiVector3D tmp = mesh->mVertices[t];
aiTransformVecByMatrix4(&tmp,trafo);
min->x = aisgl_min(min->x,tmp.x);
min->y = aisgl_min(min->y,tmp.y);
min->z = aisgl_min(min->z,tmp.z);
max->x = aisgl_max(max->x,tmp.x);
max->y = aisgl_max(max->y,tmp.y);
max->z = aisgl_max(max->z,tmp.z);
}
}
for (n = 0; n < nd->mNumChildren; ++n)
{
[self getBoundingBoxForNode:nd->mChildren[n] minVector:min maxVector:max matrix:trafo];
}
*trafo = prev;
}
#pragma mark -
#pragma mark Rendering
- (void) createGLResourcesInContext:(CGLContextObj)cgl_ctx node:(aiNode*)node
{
// create OpenGL buffers and populate them based on each meshes pertinant info.