Oolite
Loading...
Searching...
No Matches
OOMesh.m
Go to the documentation of this file.
1/*
2
3OOMesh.m
4
5A note on memory management:
6The dynamically-sized buffers used by OOMesh (_vertex etc) are the byte arrays
7of NSDatas, which are tracked using the _retainedObjects dictionary. This
8simplifies the implementation of -dealloc, but more importantly, it means
9bytes are refcounted. This means bytes read from the cache don't need to be
10copied, we just need to retain the relevant NSData object (by sticking it in
11_retainedObjects).
12
13Since _retainedObjects is a dictionary its members can be replaced,
14potentially allowing mutable meshes, although we have no use for this at
15present.
16
17
18Oolite
19Copyright (C) 2004-2013 Giles C Williams and contributors
20
21This program is free software; you can redistribute it and/or
22modify it under the terms of the GNU General Public License
23as published by the Free Software Foundation; either version 2
24of the License, or (at your option) any later version.
25
26This program is distributed in the hope that it will be useful,
27but WITHOUT ANY WARRANTY; without even the implied warranty of
28MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29GNU General Public License for more details.
30
31You should have received a copy of the GNU General Public License
32along with this program; if not, write to the Free Software
33Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
34MA 02110-1301, USA.
35
36*/
37
38#import "OOMesh.h"
39#import "Entity.h" // for NO_DRAW_DISTANCE_FACTOR.
41#import "OOBasicMaterial.h"
43#import "OODebugFlags.h"
44#import "OODebugGLDrawing.h"
46#import "OOMacroOpenGL.h"
51#import "OOShaderMaterial.h"
52#import "Octree.h"
53#import "ResourceManager.h"
54#import "Universe.h"
55
56#import "OODebugStandards.h"
57#import "OOJavaScriptEngine.h"
58
59// If set, collision octree depth varies depending on the size of the mesh.
60#define ADAPTIVE_OCTREE_DEPTH 1
61
62// If set, cachable memory is scribbled with FEEDFACE to identify junk in cache.
63#define SCRIBBLE 0
64
65enum {
66 kBaseOctreeDepth = 5, // 32x32x32
67 // kMaxOctreeDepth declared in Octree.h.
68 kSmallOctreeDepth = 4, // 16x16x16
69 kOctreeSizeThreshold = 900, // Size at which we start increasing octree depth
71};
72
78
79static NSString* const kOOLogMeshDataNotFound = @"mesh.load.failed.fileNotFound";
80static NSString* const kOOLogMeshTooManyMaterials = @"mesh.load.failed.tooManyMaterials";
81
82#if OOMESH_PROFILE
83#define PROFILE(tag) \
84 do { \
85 _stopwatchLastTime = Profile(tag, _stopwatch, _stopwatchLastTime); \
86 } while (0)
87static OOTimeDelta Profile(NSString* tag, OOProfilingStopwatch* stopwatch, OOTimeDelta lastTime)
88{
89 OOTimeDelta now = [stopwatch currentTime];
90 OOLog(@"mesh.profile", @"Mesh profile: stage %@, %g seconds (delta %g)", tag, now, now - lastTime);
91 return now;
92}
93#else
94#define PROFILE(tag) \
95 do { \
96 } while (0)
97#endif
98
99/* VertexFaceRef
100 List of indices of faces used by a given vertex.
101 Always access using the provided functions.
102
103 NOTE: VFRAddFace may use autoreleased memory. All accesses to a given VFR
104 must be inside the same autorelease pool.
105*/
106enum {
107#if OOLITE_64_BIT
108 kVertexFaceDefInternalCount = 11 // sizeof (VertexFaceRef) = 32
109#else
110 kVertexFaceDefInternalCount = 5 // sizeof (VertexFaceRef) = 16
111#endif
112};
113
114typedef struct VertexFaceRef {
115 uint16_t internCount;
116 uint16_t internFaces[kVertexFaceDefInternalCount];
117 NSMutableArray* extra;
119
120static void VFRAddFace(VertexFaceRef* vfr, NSUInteger index);
121static NSUInteger VFRGetCount(VertexFaceRef* vfr);
122static NSUInteger VFRGetFaceAtIndex(VertexFaceRef* vfr, NSUInteger index);
123
124@interface OOMesh (Private) <NSMutableCopying, OOGraphicsResetClient>
125
126- (id)initWithName:(NSString*)name
127 cacheKey:(NSString*)cacheKey
128 materialDictionary:(NSDictionary*)materialDict
129 shadersDictionary:(NSDictionary*)shadersDict
130 smooth:(BOOL)smooth
131 shaderMacros:(NSDictionary*)macros
132 shaderBindingTarget:(id<OOWeakReferenceSupport>)object
133 scaleFactor:(float)scale
134 cacheWriteable:(BOOL)cacheWriteable;
135
136- (BOOL)loadData:(NSString*)filename scaleFactor:(float)scale;
139- (void)calculateVertexNormalsAndTangentsWithFaceRefs:(VertexFaceRef*)faceRefs;
140- (void)calculateVertexTangentsWithFaceRefs:(VertexFaceRef*)faceRefs;
141
142- (void)deleteDisplayLists;
143
144- (NSDictionary*)modelData;
145- (BOOL)setModelFromModelData:(NSDictionary*)dict name:(NSString*)fileName;
146
147- (void)getNormal:(Vector*)outNormal andTangent:(Vector*)outTangent forVertex:(OOMeshVertexCount)v_index inSmoothGroup:(OOMeshSmoothGroup)smoothGroup;
148
149- (BOOL)setUpVertexArrays;
150
152
153- (void)rescaleByFactor:(GLfloat)factor;
154
155#ifdef OO_DEBUG_MONITOR_ENABLED
156- (void)debugDrawNormals;
157#endif
158
159// Manage set of objects we need to hang on to, particularly NSDatas owning buffers.
160- (void)setRetainedObject:(id)object forKey:(NSString*)key;
161- (void*)allocateBytesWithSize:(size_t)size count:(NSUInteger)count key:(NSString*)key;
162
163// Allocate all per-vertex/per-face buffers.
164- (BOOL)allocateVertexBuffersWithCount:(NSUInteger)count;
165- (BOOL)allocateNormalBuffersWithCount:(NSUInteger)count;
166- (BOOL)allocateFaceBuffersWithCount:(NSUInteger)count;
167- (BOOL)allocateVertexArrayBuffersWithCount:(NSUInteger)count;
168
169- (void)renameTexturesFrom:(NSString*)from to:(NSString*)to;
170
171@end
172
173@interface OOCacheManager (OOMesh)
174
175+ (NSDictionary*)meshDataForName:(NSString*)inShipName;
176+ (void)setMeshData:(NSDictionary*)inData forName:(NSString*)inShipName;
177
178@end
179
181{
182 /* True for modes that predate the "normal mode" concept, i.e. per-face
183 and smooth. These modes require automatic winding correction.
184 */
185 switch (mode) {
188 return YES;
189
191 return NO;
192 }
193
194#ifndef NDEBUG
195 [NSException raise:NSInvalidArgumentException
196 format:@"Unexpected normal mode in %s", __PRETTY_FUNCTION__];
197#endif
198 return NO;
199}
200
202{
203 /* True for modes that have per-vertex normals, i.e. not per-face mode.
204 */
205 switch (mode) {
207 return NO;
208
211 return YES;
212 }
213
214#ifndef NDEBUG
215 [NSException raise:NSInvalidArgumentException
216 format:@"Unexpected normal mode in %s", __PRETTY_FUNCTION__];
217#endif
218 return NO;
219}
220
221@implementation OOMesh
222
223+ (instancetype)meshWithName:(NSString*)name
224 cacheKey:(NSString*)cacheKey
225 materialDictionary:(NSDictionary*)materialDict
226 shadersDictionary:(NSDictionary*)shadersDict
227 smooth:(BOOL)smooth
228 shaderMacros:(NSDictionary*)macros
229 shaderBindingTarget:(id<OOWeakReferenceSupport>)object
230{
231 return [[[self alloc] initWithName:name
232 cacheKey:cacheKey
233 materialDictionary:materialDict
234 shadersDictionary:shadersDict
235 smooth:smooth
236 shaderMacros:macros
237 shaderBindingTarget:object
238 scaleFactor:1.0f
239 cacheWriteable:YES] autorelease];
240}
241
242+ (instancetype)meshWithName:(NSString*)name
243 cacheKey:(NSString*)cacheKey
244 materialDictionary:(NSDictionary*)materialDict
245 shadersDictionary:(NSDictionary*)shadersDict
246 smooth:(BOOL)smooth
247 shaderMacros:(NSDictionary*)macros
248 shaderBindingTarget:(id<OOWeakReferenceSupport>)object
249 scaleFactor:(float)scale
250 cacheWriteable:(BOOL)cacheWriteable
251{
252 return [[[self alloc] initWithName:name
253 cacheKey:cacheKey
254 materialDictionary:materialDict
255 shadersDictionary:shadersDict
256 smooth:smooth
257 shaderMacros:macros
258 shaderBindingTarget:object
259 scaleFactor:scale
260 cacheWriteable:cacheWriteable] autorelease];
261}
262
264{
266
267 if (placeholderMaterial == nil) {
268 placeholderMaterial = [[OOBasicMaterial alloc] initWithName:@"/placeholder/" configuration:[[ResourceManager materialDefaults] oo_dictionaryForKey:@"no-textures-material"]];
269 }
270
271 return placeholderMaterial;
272}
273
274- (id)init
275{
276 self = [super init];
277 if (self == nil)
278 return nil;
279
280 baseFile = @"No Model";
281 baseFileOctreeCacheRef = @"No Model-0.000";
282 _cacheWriteable = YES;
283#if OO_MULTITEXTURE
284 _textureUnitCount = NSNotFound;
285#endif
286
288 _lastRotMatrix = kZeroMatrix; // not identity
290
291 return self;
292}
293
294- (void)dealloc
295{
296 unsigned i;
297
301
302 [self deleteDisplayLists];
303
304 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
305 DESTROY(materials[i]);
307 }
308
310
312
318
319#if OOMESH_PROFILE
320 DESTROY(_stopwatch);
321#endif
322
323 [super dealloc];
324}
325
327{
328 switch (mode) {
330 return @"per-face";
332 return @"smooth";
334 return @"explicit";
335 }
336
337 return @"unknown";
338}
339
341{
342 return [NSString stringWithFormat:@"\"%@\", %zu vertices, %zu faces, radius: %g m normals: %@", [self modelName], [self vertexCount], [self faceCount], [self collisionRadius], NormalModeDescription(_normalMode)];
343}
344
345- (id)copyWithZone:(NSZone*)zone
346{
347 if (zone == [self zone])
348 return [self retain]; // OK because we're immutable seen from the outside
349 else
350 return [self mutableCopyWithZone:zone];
351}
352
353- (NSString*)modelName
354{
355 return baseFile;
356}
357
358- (size_t)vertexCount
359{
360 return vertexCount;
361}
362
363- (size_t)faceCount
364{
365 return faceCount;
366}
367
369{
371
372 BOOL meshBelongsToVisualEffect = [_shaderBindingTarget isVisualEffect];
373
375
376 OOGL(glVertexPointer(3, GL_FLOAT, 0, _displayLists.vertexArray));
377 OOGL(glNormalPointer(GL_FLOAT, 0, _displayLists.normalArray));
378
379 // for visual effects enable blending. This will allow use of alpha
380 // channel in shaders - note, this is a bit of cheating the system,
381 // which expects blending to be disabled at this point
382 if (meshBelongsToVisualEffect) {
383 OOGL(glEnable(GL_BLEND));
384 OOGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
385 }
386
387#if OO_SHADERS
388 if ([[OOOpenGLExtensionManager sharedManager] shadersSupported]) {
389 OOGL(glEnableVertexAttribArrayARB(kTangentAttributeIndex));
390 OOGL(glVertexAttribPointerARB(kTangentAttributeIndex, 3, GL_FLOAT, GL_FALSE, 0, _displayLists.tangentArray));
391 }
392#endif
393
394 BOOL usingNormalsAsTexCoords = NO;
396
397 /* FIXME: really, really horrible hack to set up texture coordinates for
398 each texture unit. Very messy and still fails to handle some possibly-
399 basic stuff, like switching usingNormalsAsTexCoords per texture unit.
400 The right way to do this is probably to move attribute setup into the
401 material model.
402 -- Ahruman 2010-04-12
403 */
404#if OO_MULTITEXTURE
405 if (_textureUnitCount == NSNotFound) {
406 _textureUnitCount = 0;
407 for (ti = 0; ti < materialCount; ti++) {
408 NSUInteger count = [materials[ti] countOfTextureUnitsWithBaseCoordinates];
409 if (_textureUnitCount < count)
410 _textureUnitCount = count;
411 }
412 }
413
414 NSUInteger unit;
415 if (_textureUnitCount <= 1) {
416 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
417 } else {
418 /* It should not be possible to have multiple texture units if
419 texture combiners are not available.
420 */
421 NSAssert2([[OOOpenGLExtensionManager sharedManager] textureCombinersSupported], @"Mesh %@ uses %zu texture units, but multitexturing is not available.", [self shortDescription], _textureUnitCount);
422
423 for (unit = 0; unit < _textureUnitCount; unit++) {
424 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
425 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
426 }
427 }
428#else
429 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
430#endif
431
432 @try {
433 if (!listsReady) {
434 OOGL(displayList0 = glGenLists(materialCount));
435
436 // Ensure all textures are loaded
437 for (ti = 0; ti < materialCount; ti++) {
439 }
440 }
441
442 for (ti = 0; ti < materialCount; ti++) {
443 BOOL wantsNormalsAsTextureCoordinates = [materials[ti] wantsNormalsAsTextureCoordinates];
444 if (ti == 0 || wantsNormalsAsTextureCoordinates != usingNormalsAsTexCoords) {
445 // FIXME: enabling/disabling texturing should be handled by the material.
446#if OO_MULTITEXTURE
447 for (unit = 0; unit < _textureUnitCount; unit++) {
448 if (_textureUnitCount > 1) {
449 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
450 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB + unit));
451 }
452#endif
453 if (!wantsNormalsAsTextureCoordinates) {
454 OOGL(glDisable(GL_TEXTURE_CUBE_MAP));
455 OOGL(glTexCoordPointer(2, GL_FLOAT, 0, _displayLists.textureUVArray));
456 /* FIXME: Not including the line below breaks multitexturing in no-shaders mode.
457 However, the OpenGL state manager should probably be handling this;
458 TEXTURE_2D is part of OPENGL_STATE_OPAQUE, which has already been set.
459 - Nikos 20130103
460 */
461 OOGL(glEnable(GL_TEXTURE_2D));
462 } else {
463 OOGL(glDisable(GL_TEXTURE_2D));
464 OOGL(glTexCoordPointer(3, GL_FLOAT, 0, _displayLists.vertexArray));
465 OOGL(glEnable(GL_TEXTURE_CUBE_MAP));
466 }
467#if OO_MULTITEXTURE
468 }
469#endif
470 usingNormalsAsTexCoords = wantsNormalsAsTextureCoordinates;
471 }
472
473 [materials[ti] apply];
474 OOGL(glDrawArrays(GL_TRIANGLES, triangle_range[ti].location, triangle_range[ti].length));
475 }
476
477 listsReady = YES;
478 brokenInRender = NO;
479 }
480 @catch (NSException* exception) {
481 if (!brokenInRender) {
482 OOLog(kOOLogException, @"***** %s for %@ encountered exception: %@ : %@ *****", __PRETTY_FUNCTION__, self, [exception name], [exception reason]);
483 brokenInRender = YES;
484 }
485 if ([[exception name] hasPrefix:@"Oolite"])
486 [UNIVERSE handleOoliteException:exception]; // handle these ourself
487 else
488 @throw exception; // pass these on
489 }
490
491#if OO_SHADERS
492 if ([[OOOpenGLExtensionManager sharedManager] shadersSupported]) {
493 OOGL(glDisableVertexAttribArrayARB(kTangentAttributeIndex));
494 }
495#endif
496
498 OOCheckOpenGLErrors(@"OOMesh after drawing %@", self);
499
500#if OO_MULTITEXTURE
501 if (_textureUnitCount <= 1) {
502 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
503 } else {
504 for (unit = 0; unit < _textureUnitCount; unit++) {
505 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
506 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
507 }
508
509 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB));
510 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB));
511 }
512#else
513 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
514#endif
515
516#ifdef OO_DEBUG_MONITOR_ENABLED
518 [self debugDrawNormals];
520 [[self octree] drawOctree];
521#endif
522
523 // visual effect - disable previously enabled blending
524 if (meshBelongsToVisualEffect)
525 OOGL(glDisable(GL_BLEND));
526
528}
529
531{
533 OOMaterial* material = nil;
534
535 if (materialCount != 0) {
536 for (i = 0; i != materialCount; ++i) {
537 OOMaterial* oldMaterial = materials[i];
538
539 if (![materialKeys[i] isEqualToString:@"_oo_placeholder_material"]) {
540 material = [OOMaterial materialWithName:materialKeys[i]
541 cacheKey:_cacheKey
542 materialDictionary:_materialDict
543 shadersDictionary:_shadersDict
544 macros:_shaderMacros
545 bindingTarget:[_shaderBindingTarget weakRefUnderlyingObject] // Windows DEP fix.
546 forSmoothedMesh:IsPerVertexNormalMode(_normalMode)];
547 } else {
548 material = nil;
549 }
550
551 if (material != nil) {
552 materials[i] = [material retain];
553 } else {
555 }
556
557 /* Release is deferred to here to ensure we don't end up releasing
558 a texture that's not in the recent-cache and then reloading it.
559 */
560 [oldMaterial release];
561 }
562 }
563}
564
565- (NSDictionary*)materials
566{
567 return _materialDict;
568}
569
570- (NSDictionary*)shaders
571{
572 return _shadersDict;
573}
574
576{
577 return YES;
578}
579
581{
582 return collisionRadius;
583}
584
586{
587 return maxDrawDistance;
588}
589
590#if ADAPTIVE_OCTREE_DEPTH
591- (unsigned)octreeDepth
592{
593 float threshold = kOctreeSizeThreshold;
594 unsigned result = kBaseOctreeDepth;
595 GLfloat xs, ys, zs, t, size;
596
598 // Shuffle dimensions around so zs is smallest
599 if (xs < zs) {
600 t = zs;
601 zs = xs;
602 xs = t;
603 }
604 if (ys < zs) {
605 t = zs;
606 zs = ys;
607 ys = t;
608 }
609 size = (xs + ys) / 2.0f; // Use average of two largest
610
612 result = kSmallOctreeDepth;
613 else
614 while (result < kMaxOctreeDepth) {
615 if (size < threshold)
616 break;
617 threshold *= 2.0f;
618 result++;
619 }
620
621 OOLog(@"mesh.load.octree.size", @"Selected octree depth %u for size %g for %@", result, size, baseFile);
622 return result;
623}
624#else
625- (unsigned)octreeDepth
626{
627 return kBaseOctreeDepth;
628}
629#endif
630
632{
633 if (octree == nil) {
634 octree = [[OOCacheManager octreeForModel:baseFileOctreeCacheRef] retain];
635 if (octree == nil) {
636 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
637
640 for (i = 0; i < faceCount; i++) {
641 // Somewhat surprisingly, this method doesn't even show up in profiles. -- Ahruman 2012-09-22
642 Triangle tri;
643 tri.v[0] = _vertices[_faces[i].vertex[0]];
644 tri.v[1] = _vertices[_faces[i].vertex[1]];
645 tri.v[2] = _vertices[_faces[i].vertex[2]];
647 }
648
650 [octree retain];
651 if (EXPECT(_cacheWriteable)) {
652 [OOCacheManager setOctree:octree forModel:baseFileOctreeCacheRef];
653 }
654
655 [pool release];
656 } else {
657 OOLog(@"mesh.load.octreeCached", @"Retrieved octree \"%@\" from cache.", baseFileOctreeCacheRef);
658 }
659 }
660
661 return octree;
662}
663
664- (BoundingBox)findBoundingBoxRelativeToPosition:(Vector)opv
665 ri:(Vector)ri
666 rj:(Vector)rj
667 rk:(Vector)rk
668 selfPosition:(Vector)position
669 si:(Vector)si
670 sj:(Vector)sj
671 sk:(Vector)sk
672{
673 BoundingBox result;
674 Vector pv, rv;
675
676 // FIXME: rewrite with matrices
677 Vector rpos = vector_subtract(position, opv); // model origin relative to opv
678
679 rv.x = dot_product(ri, rpos);
680 rv.y = dot_product(rj, rpos);
681 rv.z = dot_product(rk, rpos); // model origin rel to opv in ijk
682
683 if (EXPECT_NOT(vertexCount < 1)) {
684 bounding_box_reset_to_vector(&result, rv);
685 } else {
686 pv.x = rpos.x + si.x * _vertices[0].x + sj.x * _vertices[0].y + sk.x * _vertices[0].z;
687 pv.y = rpos.y + si.y * _vertices[0].x + sj.y * _vertices[0].y + sk.y * _vertices[0].z;
688 pv.z = rpos.z + si.z * _vertices[0].x + sj.z * _vertices[0].y + sk.z * _vertices[0].z; // _vertices[0] position rel to opv
689 rv.x = dot_product(ri, pv);
690 rv.y = dot_product(rj, pv);
691 rv.z = dot_product(rk, pv); // _vertices[0] position rel to opv in ijk
692 bounding_box_reset_to_vector(&result, rv);
693 }
694
696 for (i = 1; i < vertexCount; i++) {
697 pv.x = rpos.x + si.x * _vertices[i].x + sj.x * _vertices[i].y + sk.x * _vertices[i].z;
698 pv.y = rpos.y + si.y * _vertices[i].x + sj.y * _vertices[i].y + sk.y * _vertices[i].z;
699 pv.z = rpos.z + si.z * _vertices[i].x + sj.z * _vertices[i].y + sk.z * _vertices[i].z;
700 rv.x = dot_product(ri, pv);
701 rv.y = dot_product(rj, pv);
702 rv.z = dot_product(rk, pv);
703 bounding_box_add_vector(&result, rv);
704 }
705
706 return result;
707}
708
709- (BoundingBox)findSubentityBoundingBoxWithPosition:(Vector)position rotMatrix:(OOMatrix)rotMatrix
710{
711 // HACK! Should work out what the various bounding box things do and make it neat and consistent.
712 // FIXME: this is a bottleneck.
713 // Try to fix bottleneck by caching for common case where subentity
714 // pos+rot is constant from frame to frame. - CIM
715
716 if (vector_equal(position, _lastPosition) && OOMatrixEqual(rotMatrix, _lastRotMatrix)) {
717 return _lastBoundingBox;
718 }
719
720 BoundingBox result;
721 Vector v;
722
723 v = vector_add(position, OOVectorMultiplyMatrix(_vertices[0], rotMatrix));
725
727 for (i = 1; i < vertexCount; i++) {
728 v = vector_add(position, OOVectorMultiplyMatrix(_vertices[i], rotMatrix));
729 bounding_box_add_vector(&result, v);
730 }
731
732 _lastBoundingBox = result;
733 _lastPosition = position;
734 _lastRotMatrix = rotMatrix;
735
736 return result;
737}
738
739- (OOMesh*)meshRescaledBy:(GLfloat)scaleFactor
740{
741 OOMesh* result = [self mutableCopy];
742 [result rescaleByFactor:scaleFactor];
743 return [result autorelease];
744}
745
746- (void)setBindingTarget:(id<OOWeakReferenceSupport>)target
747{
748 unsigned i;
749
750 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
751 [materials[i] setBindingTarget:target];
752 }
753}
754
755#ifdef OO_DEBUG_MONITOR_ENABLED
756- (void)dumpSelfState
757{
758 [super dumpSelfState];
759
760 if (baseFile != nil)
761 OOLog(@"dumpState.mesh", @"Model file: %@", baseFile);
762 OOLog(@"dumpState.mesh", @"Vertex count: %u, face count: %u", vertexCount, faceCount);
763 OOLog(@"dumpState.mesh", @"Normals: %@", NormalModeDescription(_normalMode));
764}
765#endif
766
767#ifdef OO_DEBUG_MONITOR_ENABLED
768- (NSSet*)allTextures
769{
770 NSMutableSet* result = [NSMutableSet set];
772 for (i = 0; i != materialCount; i++) {
773 [result unionSet:[materials[i] allTextures]];
774 }
775
776 return result;
777}
778
779- (size_t)totalSize
780{
781 size_t result = [super totalSize];
782 if (_vertices != NULL)
783 result += sizeof *_vertices * vertexCount;
784 if (_normals != NULL)
785 result += sizeof *_normals * vertexCount;
786 if (_tangents != NULL)
787 result += sizeof *_tangents * vertexCount;
788 if (_faces != NULL)
789 result += sizeof *_faces * faceCount;
790
791 result += _displayLists.count * (sizeof(GLint) + sizeof(GLfloat) + sizeof(Vector) * 3);
792
794 for (i = 0; i != materialCount; i++) {
795 result += [materials[i] oo_objectSize];
796 }
797
798 result += [octree totalSize];
799 return result;
800}
801#endif
802
803/* This method exists purely to suppress Clang static analyzer warnings that
804 these ivars are unused (but may be used by categories, which they are).
805 FIXME: there must be a feature macro we can use to avoid actually building
806 this into the app, but I can't find it in docs.
807*/
809{
810 return _normals && _tangents && _faces && boundingBox.min.x;
811}
812
813@end
814
815@implementation OOMesh (Private)
816
817- (id)initWithName:(NSString*)name
818 cacheKey:(NSString*)cacheKey
819 materialDictionary:(NSDictionary*)materialDict
820 shadersDictionary:(NSDictionary*)shadersDict
821 smooth:(BOOL)smooth
822 shaderMacros:(NSDictionary*)macros
823 shaderBindingTarget:(id<OOWeakReferenceSupport>)target
824 scaleFactor:(float)scale
825 cacheWriteable:(BOOL)cacheWriteable
826{
828
829 self = [super init];
830 if (self == nil)
831 return nil;
832
833 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
834 _normalMode = smooth ? kNormalModeSmooth : kNormalModePerFace;
835 _cacheWriteable = cacheWriteable;
836
837#if OOMESH_PROFILE
838 _stopwatch = [[OOProfilingStopwatch alloc] init];
839#endif
840
841 if ([self loadData:name scaleFactor:scale]) {
843 PROFILE(@"finished calculateBoundingVolumes (again\?\?)");
844
845 baseFile = [name copy];
846 baseFileOctreeCacheRef = [[NSString stringWithFormat:@"%@-%.3f", baseFile, scale] copy];
847
848 /* New in r3033: save the material-defining parameters here so we
849 can rebind the materials at any time.
850 -- Ahruman 2010-02-17
851 */
852 _materialDict = [materialDict copy];
853 _shadersDict = [shadersDict copy];
854 _cacheKey = [cacheKey copy];
855 _shaderMacros = [macros copy];
856 _shaderBindingTarget = [target weakRetain];
857
858 [self rebindMaterials];
859 PROFILE(@"finished material setup");
860
862 } else {
863 [self release];
864 self = nil;
865 }
866#if OOMESH_PROFILE
867 DESTROY(_stopwatch);
868#endif
869#if OO_MULTITEXTURE
870 if (EXPECT(self != nil)) {
871 _textureUnitCount = NSNotFound;
872 }
873#endif
874
875 [pool release];
876 return self;
877
879}
880
881- (id)mutableCopyWithZone:(NSZone*)zone
882{
883 OOMesh* result = nil;
885
886 result = (OOMesh*)NSCopyObject(self, 0, zone);
887
888 if (result != nil) {
889 [result->baseFile retain];
890 [result->baseFileOctreeCacheRef retain];
891 [result->octree retain];
892 [result->_retainedObjects retain];
893 [result->_materialDict retain];
894 [result->_shadersDict retain];
895 [result->_cacheKey retain];
896 [result->_shaderMacros retain];
897 [result->_shaderBindingTarget retain];
898
899 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
900 [result->materialKeys[i] retain];
901 [result->materials[i] retain];
902 }
903
904 // Reset unsharable GL state
905 result->listsReady = NO;
906
908 }
909
910 return result;
911}
912
914{
915 if (listsReady) {
917
918 OOGL(glDeleteLists(displayList0, materialCount));
919 listsReady = NO;
920 }
921}
922
924{
925 [self deleteDisplayLists];
926 [self rebindMaterials];
927 _textureUnitCount = NSNotFound;
928}
929
930- (NSDictionary*)modelData
931{
933
934 NSNumber *vertCnt = nil,
935 *faceCnt = nil;
936 NSData *vertData = nil,
937 *normData = nil,
938 *tanData = nil,
939 *faceData = nil;
940 NSArray* mtlKeys = nil;
941 NSNumber* normMode = nil;
942
943 BOOL includeNormals = IsPerVertexNormalMode(_normalMode);
944
945 // Prepare cache data elements.
946 vertCnt = [NSNumber numberWithUnsignedInt:vertexCount];
947 faceCnt = [NSNumber numberWithUnsignedInt:faceCount];
948
949 vertData = [_retainedObjects objectForKey:@"vertices"];
950 faceData = [_retainedObjects objectForKey:@"faces"];
951 if (includeNormals) {
952 normData = [_retainedObjects objectForKey:@"normals"];
953 tanData = [_retainedObjects objectForKey:@"tangents"];
954 }
955
956 if (materialCount != 0) {
957 mtlKeys = [NSArray arrayWithObjects:materialKeys count:materialCount];
958 } else {
959 mtlKeys = [NSArray array];
960 }
961 normMode = [NSNumber numberWithUnsignedChar:_normalMode];
962
963 // Ensure we have all the required data elements.
964 if (vertCnt == nil || faceCnt == nil || vertData == nil || faceData == nil || mtlKeys == nil || normMode == nil) {
965 return nil;
966 }
967
968 if (includeNormals) {
969 if (normData == nil || tanData == nil)
970 return nil;
971 }
972
973 // All OK; stick 'em in a dictionary.
974 return [NSDictionary dictionaryWithObjectsAndKeys:
975 vertCnt, @"vertex count",
976 vertData, @"vertex data",
977 faceCnt, @"face count",
978 faceData, @"face data",
979 mtlKeys, @"material keys",
980 normMode, @"normal mode",
981 /* NOTE: order matters. Since normData and tanData
982 are last, if they're nil the dictionary will be
983 built without them, which is desired behaviour.
984 */
985 normData, @"normal data",
986 tanData, @"tangent data",
987 nil];
988
990}
991
992- (BOOL)setModelFromModelData:(NSDictionary*)dict name:(NSString*)fileName
993{
995
996 NSData *vertData = nil,
997 *normData = nil,
998 *tanData = nil,
999 *faceData = nil;
1000 NSArray* mtlKeys = nil;
1001 NSString* key = nil;
1002 unsigned i;
1003
1004 if (dict == nil || ![dict isKindOfClass:[NSDictionary class]])
1005 return NO;
1006
1007 vertexCount = [dict oo_unsignedIntForKey:@"vertex count"];
1008 faceCount = [dict oo_unsignedIntForKey:@"face count"];
1009
1010 if (vertexCount == 0 || faceCount == 0)
1011 return NO;
1012
1013 // Read data elements from dictionary.
1014 vertData = [dict oo_dataForKey:@"vertex data"];
1015 faceData = [dict oo_dataForKey:@"face data"];
1016
1017 mtlKeys = [dict oo_arrayForKey:@"material keys"];
1018 _normalMode = [dict oo_unsignedCharForKey:@"normal mode"];
1019 BOOL includeNormals = IsPerVertexNormalMode(_normalMode);
1020
1021 // Ensure we have all the required data elements.
1022 if (vertData == nil || faceData == nil || mtlKeys == nil) {
1023 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad cache data for mesh \"%@\".", fileName);
1024 return NO;
1025 }
1026
1027 if (includeNormals) {
1028 normData = [dict oo_dataForKey:@"normal data"];
1029 tanData = [dict oo_dataForKey:@"tangent data"];
1030 if (normData == nil || tanData == nil) {
1031 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad normal/tangent cache data for mesh \"%@\".", fileName);
1032 return NO;
1033 }
1034 }
1035
1036 // Ensure data objects are of correct size.
1037 if ([vertData length] != sizeof *_vertices * vertexCount)
1038 return NO;
1039 if ([faceData length] != sizeof *_faces * faceCount)
1040 return NO;
1041 if (includeNormals) {
1042 if ([normData length] != sizeof *_normals * vertexCount)
1043 return NO;
1044 if ([tanData length] != sizeof *_tangents * vertexCount)
1045 return NO;
1046 }
1047
1048 // Retain data.
1049 _vertices = (Vector*)[vertData bytes];
1050 [self setRetainedObject:vertData forKey:@"vertices"];
1051 _faces = (OOMeshFace*)[faceData bytes];
1052 [self setRetainedObject:faceData forKey:@"faces"];
1053 if (includeNormals) {
1054 _normals = (Vector*)[normData bytes];
1055 [self setRetainedObject:normData forKey:@"normals"];
1056 _tangents = (Vector*)[tanData bytes];
1057 [self setRetainedObject:tanData forKey:@"tangents"];
1058 } else {
1059 _normals = NULL;
1060 _tangents = NULL;
1061 }
1062
1063 // Copy material keys.
1064 materialCount = [mtlKeys count];
1065 for (i = 0; i != materialCount; ++i) {
1066 key = [mtlKeys oo_stringAtIndex:i];
1067 if (key != nil)
1068 materialKeys[i] = [key copy];
1069 else {
1070 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad cache data for mesh \"%@\".", fileName);
1071 return NO;
1072 }
1073 }
1074
1075 return YES;
1076
1078}
1079
1080- (BOOL)loadData:(NSString*)filename scaleFactor:(float)scale
1081{
1083
1084 NSScanner* scanner;
1085 NSDictionary* cacheData = nil;
1086 BOOL failFlag = NO;
1087 NSString* failString = @"***** ";
1088 unsigned i, j;
1089 NSMutableDictionary* texFileName2Idx = nil;
1090 NSString* cacheKey = nil;
1091 BOOL using_preloaded = NO;
1092
1093 cacheKey = [NSString stringWithFormat:@"%@:%u:%.3f", filename, _normalMode, scale];
1094 cacheData = [OOCacheManager meshDataForName:cacheKey];
1095 if (cacheData != nil) {
1096 if ([self setModelFromModelData:cacheData name:filename]) {
1097 using_preloaded = YES;
1098 PROFILE(@"loaded from cache");
1099 OOLog(@"mesh.load.cached", @"Retrieved mesh \"%@\" from cache.", filename);
1100 }
1101 }
1102
1103 if (!using_preloaded) {
1104 OOLog(@"mesh.load.uncached", @"Mesh \"%@\" is not in cache, loading.", cacheKey);
1105
1106 NSCharacterSet* whitespaceCharSet = [NSCharacterSet whitespaceCharacterSet];
1107 NSCharacterSet* whitespaceAndNewlineCharSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
1108#if OOLITE_MAC_OS_X
1109 NSCharacterSet* newlineCharSet = [NSCharacterSet newlineCharacterSet];
1110#else
1111 static NSCharacterSet* newlineCharSet = nil;
1112 if (newlineCharSet == nil) {
1113 NSMutableCharacterSet* temp = [[whitespaceAndNewlineCharSet mutableCopy] autorelease];
1114 [temp formIntersectionWithCharacterSet:[whitespaceCharSet invertedSet]];
1115 newlineCharSet = [temp copy];
1116 }
1117#endif
1118
1119 texFileName2Idx = [NSMutableDictionary dictionary];
1120
1121 {
1122 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
1123 NSString* data = [ResourceManager stringFromFilesNamed:filename inFolder:@"Models" cache:NO];
1124 if (data == nil) {
1125 // Model not found
1126 OOLog(kOOLogMeshDataNotFound, @"***** ERROR: could not find %@", filename);
1127 OOStandardsError(@"Model file not found");
1128 return NO;
1129 }
1130
1131 // strip out comments and commas between values
1132 NSMutableArray* lines = [NSMutableArray arrayWithArray:[data componentsSeparatedByString:@"\n"]];
1133 for (i = 0; i < [lines count]; i++) {
1134 NSString* line = [lines objectAtIndex:i];
1135 NSArray* parts;
1136 //
1137 // comments
1138 //
1139 parts = [line componentsSeparatedByString:@"#"];
1140 line = [parts objectAtIndex:0];
1141 parts = [line componentsSeparatedByString:@"//"];
1142 line = [parts objectAtIndex:0];
1143 //
1144 // commas
1145 //
1146 line = [[line componentsSeparatedByString:@","] componentsJoinedByString:@" "];
1147 //
1148 [lines replaceObjectAtIndex:i withObject:line];
1149 }
1150
1151 data = [lines componentsJoinedByString:@"\n"];
1152 scanner = [NSScanner scannerWithString:data];
1153
1154 [scanner retain];
1155 [pool release];
1156 [scanner autorelease];
1157 }
1158
1159 PROFILE(@"finished preprocessing");
1160
1161 // get number of vertices
1162 //
1163 [scanner setScanLocation:0]; // reset
1164 if ([scanner scanString:@"NVERTS" intoString:NULL]) {
1165 int n_v;
1166 if ([scanner scanInt:&n_v])
1167 vertexCount = n_v;
1168 else {
1169 failFlag = YES;
1170 failString = [NSString stringWithFormat:@"%@Failed to read value of NVERTS\n", failString];
1171 }
1172 } else {
1173 failFlag = YES;
1174 failString = [NSString stringWithFormat:@"%@Failed to read NVERTS\n", failString];
1175 }
1176
1177 if (![self allocateVertexBuffersWithCount:vertexCount]) {
1178 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1179 return NO;
1180 }
1181
1182 // get number of faces
1183 if ([scanner scanString:@"NFACES" intoString:NULL]) {
1184 int n_f;
1185 if ([scanner scanInt:&n_f]) {
1186 faceCount = n_f;
1187 } else {
1188 failFlag = YES;
1189 failString = [NSString stringWithFormat:@"%@Failed to read value of NFACES\n", failString];
1190 }
1191 } else {
1192 failFlag = YES;
1193 failString = [NSString stringWithFormat:@"%@Failed to read NFACES\n", failString];
1194 }
1195
1196 // Allocate face->vertex table.
1197 size_t faceRefSize = sizeof(VertexFaceRef) * vertexCount;
1198 VertexFaceRef* faceRefs = calloc(1, faceRefSize);
1199 if (faceRefs != NULL) {
1200 // use an NSData to effectively autorelease it.
1201 NSData* faceRefHolder = [NSData dataWithBytesNoCopy:faceRefs length:faceRefSize freeWhenDone:YES];
1202 if (faceRefHolder == nil) {
1203 free(faceRefs);
1204 faceRefs = NULL;
1205 }
1206 }
1207
1208 if (faceRefs == NULL || ![self allocateFaceBuffersWithCount:faceCount]) {
1209 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices, %u faces).", filename, vertexCount, faceCount);
1210 return NO;
1211 }
1212
1213 // get vertex data
1214 if ([scanner scanString:@"VERTEX" intoString:NULL]) {
1215 for (j = 0; j < vertexCount; j++) {
1216 float x, y, z;
1217 if (!failFlag) {
1218 if (![scanner scanFloat:&x])
1219 failFlag = YES;
1220 if (![scanner scanFloat:&y])
1221 failFlag = YES;
1222 if (![scanner scanFloat:&z])
1223 failFlag = YES;
1224 if (!failFlag) {
1225 _vertices[j] = make_vector(x * scale, y * scale, z * scale);
1226 } else {
1227 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"VERTEX"];
1228 }
1229 }
1230 }
1231 } else {
1232 failFlag = YES;
1233 failString = [NSString stringWithFormat:@"%@Failed to find VERTEX data\n", failString];
1234 }
1235
1236 // get face data
1237 if ([scanner scanString:@"FACES" intoString:NULL]) {
1238 for (j = 0; j < faceCount; j++) {
1239 int r, g, b;
1240 float nx, ny, nz;
1241 int n_v;
1242 if (!failFlag) {
1243 // colors
1244 if (![scanner scanInt:&r])
1245 failFlag = YES;
1246 if (![scanner scanInt:&g])
1247 failFlag = YES;
1248 if (![scanner scanInt:&b])
1249 failFlag = YES;
1250 if (!failFlag) {
1251 _faces[j].smoothGroup = r;
1252 } else {
1253 failString = [NSString stringWithFormat:@"%@Failed to read a color for face[%d] in FACES\n", failString, j];
1254 }
1255
1256 // normal
1257 if (![scanner scanFloat:&nx])
1258 failFlag = YES;
1259 if (![scanner scanFloat:&ny])
1260 failFlag = YES;
1261 if (![scanner scanFloat:&nz])
1262 failFlag = YES;
1263 if (!failFlag) {
1264 _faces[j].normal = vector_normal(make_vector(nx, ny, nz));
1265 } else {
1266 failString = [NSString stringWithFormat:@"%@Failed to read a normal for face[%d] in FACES\n", failString, j];
1267 }
1268
1269 // vertices
1270 if ([scanner scanInt:&n_v]) {
1271 if (n_v < 3) {
1272 failFlag = YES;
1273 failString = [NSString stringWithFormat:@"%@Face[%u] has fewer than three vertices.\n", failString, j];
1274 } else if (n_v > 3) {
1275 OOLogWARN(@"mesh.load.warning.nonTriangular", @"Face[%u] of %@ has %u vertices specified. Only the first three will be used.", j, baseFile, n_v);
1276 n_v = 3;
1277 }
1278 } else {
1279 failFlag = YES;
1280 failString = [NSString stringWithFormat:@"%@Failed to read number of vertices for face[%d] in FACES\n", failString, j];
1281 }
1282
1283 if (!failFlag) {
1284 int vi;
1285 for (i = 0; (int)i < n_v; i++) {
1286 if ([scanner scanInt:&vi]) {
1287 _faces[j].vertex[i] = vi;
1288 if (faceRefs != NULL)
1289 VFRAddFace(&faceRefs[vi], j);
1290 } else {
1291 failFlag = YES;
1292 failString = [NSString stringWithFormat:@"%@Failed to read vertex[%d] for face[%d] in FACES\n", failString, i, j];
1293 }
1294 }
1295 }
1296 }
1297 }
1298 } else {
1299 failFlag = YES;
1300 failString = [NSString stringWithFormat:@"%@Failed to find FACES data\n", failString];
1301 }
1302
1303 // Get textures data.
1304 if ([scanner scanString:@"TEXTURES" intoString:NULL]) {
1305 for (j = 0; j < faceCount; j++) {
1306 NSString* materialKey;
1307 float max_x, max_y;
1308 float s, t;
1309 if (!failFlag) {
1310 // materialKey
1311 //
1312 [scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1313 if (![scanner scanUpToCharactersFromSet:whitespaceCharSet intoString:&materialKey]) {
1314 failFlag = YES;
1315 failString = [NSString stringWithFormat:@"%@Failed to read texture filename for face[%d] in TEXTURES\n", failString, j];
1316 } else {
1317 NSNumber* index = [texFileName2Idx objectForKey:materialKey];
1318 if (index != nil) {
1319 _faces[j].materialIndex = [index unsignedIntValue];
1320 } else {
1321 if (materialCount == kOOMeshMaxMaterials) {
1322 OOLog(kOOLogMeshTooManyMaterials, @"***** ERROR: model %@ has too many materials (maximum is %d)", filename, kOOMeshMaxMaterials);
1323 return NO;
1324 }
1325 _faces[j].materialIndex = materialCount;
1326 materialKeys[materialCount] = [materialKey retain];
1327 index = [NSNumber numberWithUnsignedInt:materialCount];
1328 [texFileName2Idx setObject:index forKey:materialKey];
1329 ++materialCount;
1330 }
1331 }
1332
1333 // texture size
1334 //
1335 if (!failFlag) {
1336 if (![scanner scanFloat:&max_x])
1337 failFlag = YES;
1338 if (![scanner scanFloat:&max_y])
1339 failFlag = YES;
1340 if (failFlag)
1341 failString = [NSString stringWithFormat:@"%@Failed to read texture size for max_x and max_y in face[%d] in TEXTURES\n", failString, j];
1342 }
1343
1344 // vertices
1345 //
1346 if (!failFlag) {
1347 for (i = 0; i < 3; i++) {
1348 if (![scanner scanFloat:&s])
1349 failFlag = YES;
1350 if (![scanner scanFloat:&t])
1351 failFlag = YES;
1352 if (!failFlag) {
1353 _faces[j].s[i] = s / max_x;
1354 _faces[j].t[i] = t / max_y;
1355 } else
1356 failString = [NSString stringWithFormat:@"%@Failed to read s t coordinates for vertex[%d] in face[%d] in TEXTURES\n", failString, i, j];
1357 }
1358 }
1359 }
1360 }
1361 } else {
1362 failFlag = YES;
1363 failString = [failString stringByAppendingString:@"Failed to find TEXTURES data (will use placeholder material)\n"];
1364 materialKeys[0] = @"_oo_placeholder_material";
1365 materialCount = 1;
1366
1367 for (j = 0; j < faceCount; j++) {
1368 _faces[j].materialIndex = 0;
1369 }
1370 }
1371
1372 if ([scanner scanString:@"NAMES" intoString:NULL]) {
1373 unsigned int count;
1374 if (![scanner scanInt:(int*)&count]) {
1375 failFlag = YES;
1376 failString = [failString stringByAppendingString:@"Expected count after NAMES\n"];
1377 } else {
1378 for (j = 0; j < count; j++) {
1379 NSString* name = nil;
1380 [scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1381 if (![scanner scanUpToCharactersFromSet:newlineCharSet intoString:&name]) {
1382 failFlag = YES;
1383 failString = [failString stringByAppendingString:@"Expected file name\n"];
1384 } else {
1385 [self renameTexturesFrom:[NSString stringWithFormat:@"%u", j] to:name];
1386 }
1387 }
1388 }
1389 }
1390
1391 BOOL explicitTangents = NO;
1392
1393 // Get explicit normals.
1394 if ([scanner scanString:@"NORMALS" intoString:NULL]) {
1395 _normalMode = kNormalModeExplicit;
1396 if (![self allocateNormalBuffersWithCount:vertexCount]) {
1397 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1398 return NO;
1399 }
1400
1401 for (j = 0; j < vertexCount; j++) {
1402 float x, y, z;
1403 if (!failFlag) {
1404 if (![scanner scanFloat:&x])
1405 failFlag = YES;
1406 if (![scanner scanFloat:&y])
1407 failFlag = YES;
1408 if (![scanner scanFloat:&z])
1409 failFlag = YES;
1410 if (!failFlag) {
1411 _normals[j] = vector_normal(make_vector(x, y, z));
1412 } else {
1413 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"NORMALS"];
1414 }
1415 }
1416 }
1417
1418 // Get explicit tangents (only together with vertices).
1419 if ([scanner scanString:@"TANGENTS" intoString:NULL]) {
1420 for (j = 0; j < vertexCount; j++) {
1421 float x, y, z;
1422 if (!failFlag) {
1423 if (![scanner scanFloat:&x])
1424 failFlag = YES;
1425 if (![scanner scanFloat:&y])
1426 failFlag = YES;
1427 if (![scanner scanFloat:&z])
1428 failFlag = YES;
1429 if (!failFlag) {
1430 _tangents[j] = vector_normal(make_vector(x, y, z));
1431 } else {
1432 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"TANGENTS"];
1433 }
1434 }
1435 }
1436 }
1437 }
1438
1439 PROFILE(@"finished parsing");
1440
1441 if (IsLegacyNormalMode(_normalMode)) {
1443 PROFILE(@"finished checkNormalsAndAdjustWinding");
1444 }
1445 if (!explicitTangents) {
1446 [self generateFaceTangents];
1447 PROFILE(@"finished generateFaceTangents");
1448 }
1449
1450 // check for smooth shading and recalculate normals
1451 if (_normalMode == kNormalModeSmooth) {
1452 if (![self allocateNormalBuffersWithCount:vertexCount]) {
1453 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1454 return NO;
1455 }
1457 PROFILE(@"finished calculateVertexNormalsAndTangents");
1458
1459 } else if (IsPerVertexNormalMode(_normalMode) && !explicitTangents) {
1461 PROFILE(@"finished calculateVertexTangents");
1462 }
1463
1464 // save the resulting data for possible reuse
1465 if (EXPECT(_cacheWriteable)) {
1466 [OOCacheManager setMeshData:[self modelData] forName:cacheKey];
1467 PROFILE(@"saved to cache");
1468 }
1469
1470 if (failFlag) {
1471 OOLog(@"mesh.error", @"%@ ..... from %@ %@", failString, filename, (using_preloaded) ? @"(from preloaded data)" : @"(from file)");
1472 }
1473 }
1474
1476 PROFILE(@"finished calculateBoundingVolumes");
1477
1478 // set up vertex arrays for drawing
1479 if (![self setUpVertexArrays])
1480 return NO;
1481 PROFILE(@"finished setUpVertexArrays");
1482
1483 return YES;
1484
1486}
1487
1489{
1491
1492 Vector calculatedNormal;
1494
1495 NSParameterAssert(_normalMode != kNormalModeExplicit);
1496
1497 for (i = 0; i < faceCount; i++) {
1498 Vector v0, v1, v2, norm;
1499 v0 = _vertices[_faces[i].vertex[0]];
1500 v1 = _vertices[_faces[i].vertex[1]];
1501 v2 = _vertices[_faces[i].vertex[2]];
1502 norm = _faces[i].normal;
1503
1504 calculatedNormal = normal_to_surface(v2, v1, v0);
1505 if (vector_equal(norm, kZeroVector)) {
1506 norm = vector_flip(calculatedNormal);
1507 _faces[i].normal = norm;
1508 }
1509
1510 /* FIXME: for 2.0, either require explicit normals for every model
1511 or change to: if (dot_product(norm, calculatedNormal) < 0.0f)
1512 -- Ahruman 2010-01-23
1513 */
1514 if (norm.x * calculatedNormal.x < 0 || norm.y * calculatedNormal.y < 0 || norm.z * calculatedNormal.z < 0) {
1515 // normal lies in the WRONG direction!
1516 // reverse the winding
1517 int v0 = _faces[i].vertex[0];
1518 _faces[i].vertex[0] = _faces[i].vertex[2];
1519 _faces[i].vertex[2] = v0;
1520
1521 GLfloat f0 = _faces[i].s[0];
1522 _faces[i].s[0] = _faces[i].s[2];
1523 _faces[i].s[2] = f0;
1524
1525 f0 = _faces[i].t[0];
1526 _faces[i].t[0] = _faces[i].t[2];
1527 _faces[i].t[2] = f0;
1528 }
1529 }
1530
1532}
1533
1535{
1537
1539 for (i = 0; i < faceCount; i++) {
1540 OOMeshFace* face = _faces + i;
1541
1542 /* Generate tangents, i.e. vectors that run in the direction of the s
1543 texture coordinate. Based on code I found in a forum somewhere and
1544 then lost track of. Sorry to whomever I should be crediting.
1545 -- Ahruman 2008-11-23
1546 */
1547 Vector vAB = vector_subtract(_vertices[face->vertex[1]], _vertices[face->vertex[0]]);
1548 Vector vAC = vector_subtract(_vertices[face->vertex[2]], _vertices[face->vertex[0]]);
1549 Vector nA = face->normal;
1550
1551 // projAB = aB - (nA . vAB) * nA
1552 Vector vProjAB = vector_subtract(vAB, vector_multiply_scalar(nA, dot_product(nA, vAB)));
1553 Vector vProjAC = vector_subtract(vAC, vector_multiply_scalar(nA, dot_product(nA, vAC)));
1554
1555 // delta s/t
1556 GLfloat dsAB = face->s[1] - face->s[0];
1557 GLfloat dsAC = face->s[2] - face->s[0];
1558 GLfloat dtAB = face->t[1] - face->t[0];
1559 GLfloat dtAC = face->t[2] - face->t[0];
1560
1561 if (dsAC * dtAB > dsAB * dtAC) {
1563 } else {
1565 }
1566 }
1567
1569}
1570
1571static float FaceArea(GLuint* vertIndices, Vector* vertices)
1572{
1573 /* Calculate areas using Heron's formula. */
1574 float a2 = distance2(vertices[vertIndices[0]], vertices[vertIndices[1]]);
1575 float b2 = distance2(vertices[vertIndices[1]], vertices[vertIndices[2]]);
1576 float c2 = distance2(vertices[vertIndices[2]], vertices[vertIndices[0]]);
1577 return sqrt((2.0f * (a2 * b2 + b2 * c2 + c2 * a2) - (a2 * a2 + b2 * b2 + c2 * c2)) * 0.0625f);
1578}
1579
1580- (void)calculateVertexNormalsAndTangentsWithFaceRefs:(VertexFaceRef*)faceRefs
1581{
1583
1584 NSParameterAssert(faceRefs != NULL);
1585
1586 NSUInteger i, j;
1587 float triangle_area[faceCount];
1588
1589 NSAssert1(_normals != NULL && _tangents != NULL, @"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1590
1591 for (i = 0; i < faceCount; i++) {
1592 triangle_area[i] = FaceArea(_faces[i].vertex, _vertices);
1593 }
1594 for (i = 0; i < vertexCount; i++) {
1595 Vector normal_sum = kZeroVector;
1596 Vector tangent_sum = kZeroVector;
1597
1598 VertexFaceRef* vfr = &faceRefs[i];
1599 NSUInteger fIter, fCount = VFRGetCount(vfr);
1600 for (fIter = 0; fIter < fCount; fIter++) {
1601 j = VFRGetFaceAtIndex(vfr, fIter);
1602
1603 float t = triangle_area[j]; // weight sum by area
1604 normal_sum = vector_add(normal_sum, vector_multiply_scalar(_faces[j].normal, t));
1605 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, t));
1606 }
1607
1608 normal_sum = vector_normal_or_fallback(normal_sum, kBasisZVector);
1609 tangent_sum = vector_subtract(tangent_sum, vector_multiply_scalar(normal_sum, dot_product(tangent_sum, normal_sum)));
1610 tangent_sum = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1611
1612 _normals[i] = normal_sum;
1613 _tangents[i] = tangent_sum;
1614 }
1615
1617}
1618
1619static float FaceAreaCorrect(GLuint* vertIndices, Vector* vertices)
1620{
1621 /* Calculate area of triangle.
1622 The magnitude of the cross product of two vectors is the area of
1623 the parallelogram they span. The area of a triangle is half the
1624 area of a parallelogram sharing two of its sides.
1625 Since we only use the area of the triangle as a weight factor,
1626 constant terms are irrelevant, so we don't bother halving the
1627 value.
1628 */
1629 Vector AB = vector_subtract(vertices[vertIndices[1]], vertices[vertIndices[0]]);
1630 Vector AC = vector_subtract(vertices[vertIndices[2]], vertices[vertIndices[0]]);
1631 return magnitude(true_cross_product(AB, AC));
1632}
1633
1634- (void)calculateVertexTangentsWithFaceRefs:(VertexFaceRef*)faceRefs
1635{
1637
1638 NSParameterAssert(faceRefs != NULL);
1639
1640 /* This is conceptually broken.
1641 At the moment, it's calculating one tangent per "input" vertex. It should
1642 be calculating one tangent per "real" vertex, where a "real" vertex is
1643 defined as a combination of position, normal, material and texture
1644 coordinates.
1645 Currently, we don't have a format with unique "real" vertices.
1646 This basically means explicit-normal models without explicit tangents
1647 can't usefully be normal mapped.
1648 I don't intend to do anything about this pre-MSNR, although it might be
1649 possible to fix it by moving tangent generation to the same stage as
1650 smooth-grouped normal generation.
1651 -- Ahruman 2010-05-22
1652 */
1653 NSUInteger i, j;
1654 float triangle_area[faceCount];
1655 for (i = 0; i < faceCount; i++) {
1656 triangle_area[i] = FaceAreaCorrect(_faces[i].vertex, _vertices);
1657 }
1658 for (i = 0; i < vertexCount; i++) {
1659 Vector tangent_sum = kZeroVector;
1660
1661 VertexFaceRef* vfr = &faceRefs[i];
1662 NSUInteger fIter, fCount = VFRGetCount(vfr);
1663 for (fIter = 0; fIter < fCount; fIter++) {
1664 j = VFRGetFaceAtIndex(vfr, fIter);
1665
1666 float t = triangle_area[j]; // weight sum by area
1667 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, t));
1668 }
1669
1670 tangent_sum = vector_subtract(tangent_sum, vector_multiply_scalar(_normals[i], dot_product(_normals[i], tangent_sum)));
1671 tangent_sum = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1672
1673 _tangents[i] = tangent_sum;
1674 }
1675
1677}
1678
1679/* profiling suggests this function takes a lot of time - almost all
1680 * the overhead of setting up a new ship is here. - CIM */
1681- (void)getNormal:(Vector*)outNormal andTangent:(Vector*)outTangent forVertex:(OOMeshVertexCount)v_index inSmoothGroup:(OOMeshSmoothGroup)smoothGroup
1682{
1684
1685 assert(outNormal != NULL && outTangent != NULL);
1686
1687 NSUInteger j;
1688 Vector normal_sum = kZeroVector;
1689 Vector tangent_sum = kZeroVector;
1690 for (j = 0; j < faceCount; j++) {
1691 if (_faces[j].smoothGroup == smoothGroup) {
1692 if ((_faces[j].vertex[0] == v_index) || (_faces[j].vertex[1] == v_index) || (_faces[j].vertex[2] == v_index)) {
1693 float area = FaceArea(_faces[j].vertex, _vertices);
1694 normal_sum = vector_add(normal_sum, vector_multiply_scalar(_faces[j].normal, area));
1695 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, area));
1696 }
1697 }
1698 }
1699
1700 *outNormal = vector_normal_or_fallback(normal_sum, kBasisZVector);
1701 *outTangent = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1702
1704}
1705
1707{
1709
1710 NSUInteger fi, vi, mi;
1711
1712 if (![self allocateVertexArrayBuffersWithCount:faceCount])
1713 return NO;
1714
1715 // if smoothed, find any vertices that are between faces of different
1716 // smoothing groups and mark them as being on an edge and therefore NOT
1717 // smooth shaded
1718 BOOL is_edge_vertex[vertexCount];
1719 GLfloat smoothGroup[vertexCount];
1720 for (vi = 0; vi < vertexCount; vi++) {
1721 is_edge_vertex[vi] = NO;
1722 smoothGroup[vi] = -1;
1723 }
1724 if (_normalMode == kNormalModeSmooth) {
1725 for (fi = 0; fi < faceCount; fi++) {
1726 GLfloat rv = _faces[fi].smoothGroup;
1727 int i;
1728 for (i = 0; i < 3; i++) {
1729 vi = _faces[fi].vertex[i];
1730 if (smoothGroup[vi] < 0.0) // unassigned
1731 smoothGroup[vi] = rv;
1732 else if (smoothGroup[vi] != rv) // a different colour
1733 is_edge_vertex[vi] = YES;
1734 }
1735 }
1736 }
1737
1738 // base model, flat or smooth shaded, all triangles
1739 int tri_index = 0;
1740 int uv_index = 0;
1741 int vertex_index = 0;
1742
1743 // Iterate over material names
1744 for (mi = 0; mi != materialCount; ++mi) {
1745 triangle_range[mi].location = tri_index;
1746
1747 for (fi = 0; fi < faceCount; fi++) {
1748 Vector normal, tangent;
1749
1750 if (_faces[fi].materialIndex == mi) {
1751 for (vi = 0; vi < 3; vi++) {
1752 int v = _faces[fi].vertex[vi];
1753 if (IsPerVertexNormalMode(_normalMode)) {
1754 if (is_edge_vertex[v]) {
1755 [self getNormal:&normal andTangent:&tangent forVertex:v inSmoothGroup:_faces[fi].smoothGroup];
1756 } else {
1757 NSAssert1(_normals != NULL && _tangents != NULL, @"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1758
1759 normal = _normals[v];
1760 tangent = _tangents[v];
1761 }
1762 } else {
1763 normal = _faces[fi].normal;
1764 tangent = _faces[fi].tangent;
1765 }
1766
1767 // FIXME: avoid redundant vertices so index array is actually useful.
1768 _displayLists.indexArray[tri_index++] = vertex_index;
1769 _displayLists.normalArray[vertex_index] = normal;
1770 _displayLists.tangentArray[vertex_index] = tangent;
1771 _displayLists.vertexArray[vertex_index++] = _vertices[v];
1772 _displayLists.textureUVArray[uv_index++] = _faces[fi].s[vi];
1773 _displayLists.textureUVArray[uv_index++] = _faces[fi].t[vi];
1774 }
1775 }
1776 }
1777 triangle_range[mi].length = tri_index - triangle_range[mi].location;
1778 }
1779
1780 _displayLists.count = tri_index; // total number of triangle vertices
1781 return YES;
1782
1784}
1785
1787{
1789
1791 float d_squared, length_longest_axis, length_shortest_axis;
1792 GLfloat result;
1793
1794 result = 0.0f;
1795 if (vertexCount)
1797 else
1799
1800 for (i = 0; i < vertexCount; i++) {
1801 d_squared = magnitude2(_vertices[i]);
1802 if (d_squared > result)
1803 result = d_squared;
1804 bounding_box_add_vector(&boundingBox, _vertices[i]);
1805 }
1806
1807 length_longest_axis = boundingBox.max.x - boundingBox.min.x;
1808 if (boundingBox.max.y - boundingBox.min.y > length_longest_axis)
1809 length_longest_axis = boundingBox.max.y - boundingBox.min.y;
1810 if (boundingBox.max.z - boundingBox.min.z > length_longest_axis)
1811 length_longest_axis = boundingBox.max.z - boundingBox.min.z;
1812
1813 length_shortest_axis = boundingBox.max.x - boundingBox.min.x;
1814 if (boundingBox.max.y - boundingBox.min.y < length_shortest_axis)
1815 length_shortest_axis = boundingBox.max.y - boundingBox.min.y;
1816 if (boundingBox.max.z - boundingBox.min.z < length_shortest_axis)
1817 length_shortest_axis = boundingBox.max.z - boundingBox.min.z;
1818
1819 d_squared = (length_longest_axis + length_shortest_axis) * (length_longest_axis + length_shortest_axis) * 0.25; // square of average length
1820 maxDrawDistance = d_squared * NO_DRAW_DISTANCE_FACTOR * NO_DRAW_DISTANCE_FACTOR; // no longer based on the collision radius
1821
1822 collisionRadius = sqrtf(result);
1823
1825}
1826
1827- (void)rescaleByFactor:(GLfloat)factor
1828{
1829 // Rescale base vertices used for geometry calculations.
1831 Vector* vertex = NULL;
1832
1833 for (i = 0; i < vertexCount; i++) {
1834 vertex = &_vertices[i];
1835 *vertex = vector_multiply_scalar(*vertex, factor);
1836 }
1837
1838 // Rescale actual display vertices.
1839 for (i = 0; i < _displayLists.count; i++) {
1840 vertex = &_displayLists.vertexArray[i];
1841 *vertex = vector_multiply_scalar(*vertex, factor);
1842 }
1843
1845 DESTROY(octree);
1846 DESTROY(baseFile); // Avoid octree cache.
1847 DESTROY(baseFileOctreeCacheRef);
1848}
1849
1851{
1852 return boundingBox;
1853}
1854
1855#ifdef OO_DEBUG_MONITOR_ENABLED
1856- (void)debugDrawNormals
1857{
1858 GLuint i;
1859 Vector v, n, t, b;
1860 float length, blend;
1861 GLfloat color[3];
1862 OODebugWFState state;
1863
1865
1866 state = OODebugBeginWireframe(NO);
1867
1868 // Draw
1869 OOGLBEGIN(GL_LINES);
1870 for (i = 0; i < _displayLists.count; ++i) {
1871 v = _displayLists.vertexArray[i];
1872 n = _displayLists.normalArray[i];
1873 t = _displayLists.tangentArray[i];
1874 b = true_cross_product(n, t);
1875
1876 // Draw normal
1877 length = magnitude2(n);
1878 blend = fabs(length - 1) * 5.0;
1879 color[0] = MIN(blend, 1.0f);
1880 color[1] = 1.0f - color[0];
1881 color[2] = color[1];
1882 glColor3fv(color);
1883
1884 glVertex3f(v.x, v.y, v.z);
1885 scale_vector(&n, 5.0f);
1886 n = vector_add(n, v);
1887 glVertex3f(n.x, n.y, n.z);
1888
1889 // Draw tangent
1890 glColor3f(1.0f, 1.0f, 0.0f);
1891 t = vector_add(v, vector_multiply_scalar(t, 3.0f));
1892 glVertex3f(v.x, v.y, v.z);
1893 glVertex3f(t.x, t.y, t.z);
1894
1895 // Draw bitangent
1896 glColor3f(0.0f, 1.0f, 0.0f);
1897 b = vector_add(v, vector_multiply_scalar(b, 3.0f));
1898 glVertex3f(v.x, v.y, v.z);
1899 glVertex3f(b.x, b.y, b.z);
1900 }
1901 OOGLEND();
1902
1903 OODebugEndWireframe(state);
1904}
1905#endif
1906
1907- (void)setRetainedObject:(id)object forKey:(NSString*)key
1908{
1909 assert(key != nil);
1910
1911 if (object != nil) {
1912 if (_retainedObjects == nil)
1913 _retainedObjects = [[NSMutableDictionary alloc] init];
1914 [_retainedObjects setObject:object forKey:key];
1915 }
1916}
1917
1918#if SCRIBBLE
1919static void Scribble(void* bytes, size_t size)
1920{
1921#if OOLITE_BIG_ENDIAN
1922 enum { kScribble = 0xFEEDFACE };
1923#else
1924 enum { kScribble = 0xCEFAEDFE };
1925#endif
1926
1927 size /= sizeof(uint32_t);
1928 uint32_t* mem = bytes;
1929 while (size--)
1930 *mem++ = kScribble;
1931}
1932#else
1933#define Scribble(bytes, size) \
1934 do { \
1935 } while (0)
1936#endif
1937
1938/* valgrind complains that the memory allocated here isn't initialised
1939 at the time OOCacheManager::writeDict is pushing it to the
1940 cache. Not sure if that's a problem or not. - CIM */
1941- (void*)allocateBytesWithSize:(size_t)size count:(NSUInteger)count key:(NSString*)key
1942{
1943 if (count == 0) {
1944 count = 1;
1945 }
1946 size *= count;
1947 void* bytes = malloc(size);
1948 if (bytes != NULL) {
1949 Scribble(bytes, size);
1950 NSData* holder = [NSData dataWithBytesNoCopy:bytes length:size freeWhenDone:YES];
1951 [self setRetainedObject:holder forKey:key];
1952 }
1953 return bytes;
1954}
1955
1956- (BOOL)allocateVertexBuffersWithCount:(NSUInteger)count
1957{
1958 _vertices = [self allocateBytesWithSize:sizeof *_vertices count:vertexCount key:@"vertices"];
1959 return _vertices != NULL;
1960}
1961
1962- (BOOL)allocateNormalBuffersWithCount:(NSUInteger)count
1963{
1964 _normals = [self allocateBytesWithSize:sizeof *_normals count:vertexCount key:@"normals"];
1965 _tangents = [self allocateBytesWithSize:sizeof *_tangents count:vertexCount key:@"tangents"];
1966 return _normals != NULL && _tangents != NULL;
1967}
1968
1969- (BOOL)allocateFaceBuffersWithCount:(NSUInteger)count
1970{
1971 _faces = [self allocateBytesWithSize:sizeof *_faces count:faceCount key:@"faces"];
1972 return _faces != NULL;
1973}
1974
1975- (BOOL)allocateVertexArrayBuffersWithCount:(NSUInteger)count
1976{
1977 _displayLists.indexArray = [self allocateBytesWithSize:sizeof *_displayLists.indexArray count:count * 3 key:@"indexArray"];
1978 _displayLists.textureUVArray = [self allocateBytesWithSize:sizeof *_displayLists.textureUVArray count:count * 6 key:@"textureUVArray"];
1979 _displayLists.vertexArray = [self allocateBytesWithSize:sizeof *_displayLists.vertexArray count:count * 3 key:@"vertexArray"];
1980 _displayLists.normalArray = [self allocateBytesWithSize:sizeof *_displayLists.normalArray count:count * 3 key:@"normalArray"];
1981 _displayLists.tangentArray = [self allocateBytesWithSize:sizeof *_displayLists.tangentArray count:count * 3 key:@"tangentArray"];
1982
1983 return _faces != NULL && _displayLists.indexArray != NULL && _displayLists.textureUVArray != NULL && _displayLists.vertexArray != NULL && _displayLists.normalArray != NULL && _displayLists.tangentArray != NULL;
1984}
1985
1986- (void)renameTexturesFrom:(NSString*)from to:(NSString*)to
1987{
1988 /* IMPORTANT: this has to be called before setUpMaterials..., so it can
1989 only be used during loading.
1990 */
1992 for (i = 0; i != materialCount; i++) {
1993 if ([materialKeys[i] isEqualToString:from]) {
1994 [materialKeys[i] release];
1995 materialKeys[i] = [to copy];
1996 }
1997 }
1998}
1999
2000@end
2001
2002static NSString* const kOOCacheMeshes = @"OOMesh";
2003
2004@implementation OOCacheManager (OOMesh)
2005
2006+ (NSDictionary*)meshDataForName:(NSString*)inShipName
2007{
2008 return [[self sharedCache] objectForKey:inShipName inCache:kOOCacheMeshes];
2009}
2010
2011+ (void)setMeshData:(NSDictionary*)inData forName:(NSString*)inShipName
2012{
2013 if (inData != nil && inShipName != nil) {
2014 [[self sharedCache] setObject:inData forKey:inShipName inCache:kOOCacheMeshes];
2015 }
2016}
2017
2018@end
2019
2020static NSString* const kOOCacheOctrees = @"octrees";
2021
2022@implementation OOCacheManager (Octree)
2023
2024+ (Octree*)octreeForModel:(NSString*)inKey
2025{
2026 NSDictionary* dict = nil;
2027 Octree* result = nil;
2028
2029 if (inKey == nil)
2030 return nil;
2031
2032 dict = [[self sharedCache] objectForKey:inKey inCache:kOOCacheOctrees];
2033 if (dict != nil) {
2034 result = [[Octree alloc] initWithDictionary:dict];
2035 [result autorelease];
2036 }
2037
2038 return result;
2039}
2040
2041+ (void)setOctree:(Octree*)inOctree forModel:(NSString*)inKey
2042{
2043 if (inOctree != nil && inKey != nil) {
2044 [[self sharedCache] setObject:[inOctree dictionaryRepresentation] forKey:inKey inCache:kOOCacheOctrees];
2045 }
2046}
2047
2048static void VFRAddFace(VertexFaceRef* vfr, NSUInteger index)
2049{
2050 NSCParameterAssert(vfr != NULL);
2051
2052 if (index < UINT16_MAX && vfr->internCount < kVertexFaceDefInternalCount) {
2053 vfr->internFaces[vfr->internCount++] = index;
2054 } else {
2055 if (vfr->extra == nil)
2056 vfr->extra = [NSMutableArray array];
2057 [vfr->extra addObject:[NSNumber numberWithInteger:index]];
2058 }
2059}
2060
2061static NSUInteger VFRGetCount(VertexFaceRef* vfr)
2062{
2063 NSCParameterAssert(vfr != NULL);
2064
2065 return vfr->internCount + [vfr->extra count];
2066}
2067
2068static NSUInteger VFRGetFaceAtIndex(VertexFaceRef* vfr, NSUInteger index)
2069{
2070 NSCParameterAssert(vfr != NULL && index < VFRGetCount(vfr));
2071
2072 if (index < vfr->internCount)
2073 return vfr->internFaces[index];
2074 else
2075 return [vfr->extra oo_unsignedIntegerAtIndex:index - vfr->internCount];
2076}
2077
2078@end
#define NO_DRAW_DISTANCE_FACTOR
Definition Entity.h:49
const BoundingBox kZeroBoundingBox
Definition OOVector.m:36
OOINLINE void bounding_box_reset_to_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE void bounding_box_add_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE void bounding_box_get_dimensions(BoundingBox bb, GLfloat *xSize, GLfloat *ySize, GLfloat *zSize) ALWAYS_INLINE_FUNC
OOINLINE void bounding_box_reset(BoundingBox *box) NONNULL_FUNC
#define gDebugFlags
@ DEBUG_OCTREE_DRAW
@ DEBUG_DRAW_NORMALS
void OOStandardsError(NSString *message)
#define DESTROY(x)
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_PROFILE_ENTER
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
NSString *const kOOLogException
Definition OOLogging.m:600
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogAllocationFailure
Definition OOLogging.m:598
#define OO_ENTER_OPENGL()
#define MIN(A, B)
Definition OOMaths.h:91
const OOMatrix kZeroMatrix
Definition OOMatrix.m:33
Vector OOVectorMultiplyMatrix(Vector v, OOMatrix m) CONST_FUNC
Definition OOMatrix.m:121
bool OOMatrixEqual(OOMatrix a, OOMatrix b) CONST_FUNC
Definition OOMatrix.m:91
@ kOOMeshMaxMaterials
Definition OOMesh.h:50
uint16_t OOMeshSmoothGroup
Definition OOMesh.h:53
uint32_t OOMeshFaceCount
Definition OOMesh.h:56
uint32_t OOMeshVertexCount
Definition OOMesh.h:55
uint8_t OOMeshMaterialIndex
Definition OOMesh.h:54
uint8_t OOMeshMaterialCount
Definition OOMesh.h:54
static void VFRAddFace(VertexFaceRef *vfr, NSUInteger index)
static NSUInteger VFRGetCount(VertexFaceRef *vfr)
static BOOL IsLegacyNormalMode(OOMeshNormalMode mode)
Definition OOMesh.m:180
static NSString *const kOOLogMeshTooManyMaterials
Definition OOMesh.m:80
static NSString *const kOOCacheOctrees
Definition OOMesh.m:2020
static NSString *const kOOLogMeshDataNotFound
Definition OOMesh.m:79
#define PROFILE(tag)
Definition OOMesh.m:94
static BOOL IsPerVertexNormalMode(OOMeshNormalMode mode)
Definition OOMesh.m:201
@ kBaseOctreeDepth
Definition OOMesh.m:66
@ kOctreeSmallSizeThreshold
Definition OOMesh.m:70
@ kSmallOctreeDepth
Definition OOMesh.m:68
@ kOctreeSizeThreshold
Definition OOMesh.m:69
OOMeshNormalMode
Definition OOMesh.m:73
@ kNormalModeExplicit
Definition OOMesh.m:76
@ kNormalModeSmooth
Definition OOMesh.m:75
@ kNormalModePerFace
Definition OOMesh.m:74
#define Scribble(bytes, size)
Definition OOMesh.m:1933
static NSUInteger VFRGetFaceAtIndex(VertexFaceRef *vfr, NSUInteger index)
@ kVertexFaceDefInternalCount
Definition OOMesh.m:110
static NSString *const kOOCacheMeshes
Definition OOMesh.m:2002
#define OOGLBEGIN
Definition OOOpenGL.h:269
@ OPENGL_STATE_OPAQUE
Definition OOOpenGL.h:121
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
BOOL OOCheckOpenGLErrors(NSString *format,...)
Definition OOOpenGL.m:38
#define OOSetOpenGLState(STATE)
Definition OOOpenGL.h:132
#define OOGL(statement)
Definition OOOpenGL.h:262
#define OOGLEND
Definition OOOpenGL.h:270
unsigned count
return nil
float y
float x
double OOTimeDelta
Definition OOTypes.h:193
OOINLINE Vector vector_flip(Vector v) INLINE_CONST_FUNC
Definition OOVector.h:227
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:195
OOINLINE Vector vector_subtract(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:218
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:242
OOINLINE OOScalar distance2(Vector v1, Vector v2) INLINE_CONST_FUNC
Definition OOVector.h:275
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
struct Vector Vector
OOINLINE OOScalar dot_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:299
OOINLINE Vector vector_normal_or_fallback(Vector vec, Vector fallback) INLINE_CONST_FUNC
Definition OOVector.h:247
OOINLINE Vector true_cross_product(Vector first, Vector second) CONST_FUNC
Definition OOVector.h:285
const Vector kZeroVector
Definition OOVector.m:27
OOINLINE Vector normal_to_surface(Vector v1, Vector v2, Vector v3) CONST_FUNC
Definition OOVector.h:309
OOINLINE bool vector_equal(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:232
OOINLINE void scale_vector(Vector *outVector, OOScalar factor) ALWAYS_INLINE_FUNC NONNULL_FUNC
Definition OOVector.h:166
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:237
const Vector kBasisZVector
Definition OOVector.h:47
const Vector kBasisXVector
Definition OOVector.h:45
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
OOINLINE Vector vector_normal(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:270
@ kMaxOctreeDepth
Definition Octree.h:82
static void VFRAddFace(VertexFaceRef *vfr, NSUInteger index)
Definition OOMesh.m:2048
static NSUInteger VFRGetFaceAtIndex(VertexFaceRef *vfr, NSUInteger index)
Definition OOMesh.m:2068
static NSUInteger VFRGetCount(VertexFaceRef *vfr)
Definition OOMesh.m:2061
BOOL setUpVertexArrays()
Definition OOMesh.m:1706
void deleteDisplayLists()
Definition OOMesh.m:913
void generateFaceTangents()
Definition OOMesh.m:1534
void checkNormalsAndAdjustWinding()
Definition OOMesh.m:1488
void resetGraphicsState()
Definition OOMesh.m:923
static float FaceAreaCorrect(GLuint *vertIndices, Vector *vertices)
Definition OOMesh.m:1619
NSDictionary * modelData()
Definition OOMesh.m:930
BoundingBox boundingBox()
Definition OOMesh.m:1850
void calculateBoundingVolumes()
Definition OOMesh.m:1786
static float FaceArea(GLuint *vertIndices, Vector *vertices)
Definition OOMesh.m:1571
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
void setMeshData:forName:(NSDictionary *inData,[forName] NSString *inShipName)
Definition OOMesh.m:2011
void setOctree:forModel:(Octree *inOctree,[forModel] NSString *inKey)
Definition OOMesh.m:2041
NSDictionary * meshDataForName:(NSString *inShipName)
Definition OOMesh.m:2006
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
Octree * octreeForModel:(NSString *inKey)
Definition OOMesh.m:2024
OOCacheManager * sharedCache()
void registerClient:(id< OOGraphicsResetClient > client)
void unregisterClient:(id< OOGraphicsResetClient > client)
OOGraphicsResetManager * sharedManager()
void apply()
Definition OOMaterial.m:61
void ensureFinishedLoading()
Definition OOMaterial.m:84
OOMaterial * materialWithName:cacheKey:materialDictionary:shadersDictionary:macros:bindingTarget:forSmoothedMesh:(NSString *name,[cacheKey] NSString *cacheKey,[materialDictionary] NSDictionary *materialDict,[shadersDictionary] NSDictionary *shadersDict,[macros] NSDictionary *macros,[bindingTarget] id< OOWeakReferenceSupport > object,[forSmoothedMesh] BOOL smooth)
void setBindingTarget:(id< OOWeakReferenceSupport > target)
Definition OOMaterial.m:93
void applyNone()
Definition OOMaterial.m:72
BOOL wantsNormalsAsTextureCoordinates()
Definition OOMaterial.m:97
Octree * findOctreeToDepth:(NSUInteger depth)
instancetype converterWithCapacity:(NSUInteger capacity)
void deleteDisplayLists()
Definition OOMesh.m:913
Vector * _vertices
Definition OOMesh.h:96
NSString * descriptionComponents()
Definition OOMesh.m:340
NSDictionary * shaders()
Definition OOMesh.m:570
static NSString * NormalModeDescription(OOMeshNormalMode mode)
Definition OOMesh.m:326
void rebindMaterials()
Definition OOMesh.m:530
NSMutableDictionary * _retainedObjects
Definition OOMesh.h:115
void renderOpaqueParts()
Definition OOMesh.m:368
NSDictionary * _shaderMacros
Definition OOMesh.h:120
uint8_t brokenInRender
Definition OOMesh.h:85
OOMaterial * placeholderMaterial()
Definition OOMesh.m:263
OOMaterial * materials[kOOMeshMaxMaterials]
Definition OOMesh.m:565
id _shaderBindingTarget
Definition OOMesh.h:121
GLfloat maxDrawDistance
Definition OOMesh.m:585
NSString * materialKeys[kOOMeshMaxMaterials]
Definition OOMesh.h:105
Octree * octree
Definition OOMesh.m:631
GLuint displayList0
Definition OOMesh.h:107
uint8_t listsReady
Definition OOMesh.h:86
void setRetainedObject:forKey:(id object,[forKey] NSString *key)
Definition OOMesh.m:1907
OOMeshFace * _faces
Definition OOMesh.h:99
void generateFaceTangents()
Definition OOMesh.m:1534
OOMeshMaterialCount materialCount
Definition OOMesh.h:88
NSRange triangle_range[kOOMeshMaxMaterials]
Definition OOMesh.h:104
void checkNormalsAndAdjustWinding()
Definition OOMesh.m:1488
id init()
Definition OOMesh.m:274
Vector _lastPosition
Definition OOMesh.h:123
BOOL hasOpaqueParts()
Definition OOMesh.m:575
Vector * _tangents
Definition OOMesh.h:98
NSString * _cacheKey
Definition OOMesh.h:119
NSDictionary * modelData()
Definition OOMesh.m:930
BoundingBox _lastBoundingBox
Definition OOMesh.h:125
BOOL _cacheWriteable
Definition OOMesh.h:94
void renameTexturesFrom:to:(NSString *from,[to] NSString *to)
Definition OOMesh.m:1986
NSDictionary * _materialDict
Definition OOMesh.h:117
NSDictionary * _shadersDict
Definition OOMesh.h:118
void dealloc()
Definition OOMesh.m:294
BoundingBox boundingBox
Definition OOMesh.h:111
NSString * baseFileOctreeCacheRef
Definition OOMesh.h:93
NSString * baseFile
Definition OOMesh.h:92
void calculateVertexTangentsWithFaceRefs:(VertexFaceRef *faceRefs)
Definition OOMesh.m:1634
unsigned octreeDepth()
Definition OOMesh.m:591
OOMeshVertexCount vertexCount
Definition OOMesh.m:358
OOMatrix _lastRotMatrix
Definition OOMesh.h:124
Vector * _normals
Definition OOMesh.h:97
void calculateBoundingVolumes()
Definition OOMesh.m:1786
OOMeshDisplayLists _displayLists
Definition OOMesh.h:102
BOOL suppressClangStuff()
Definition OOMesh.m:808
void calculateVertexNormalsAndTangentsWithFaceRefs:(VertexFaceRef *faceRefs)
Definition OOMesh.m:1580
GLfloat collisionRadius
Definition OOMesh.m:580
void * allocateBytesWithSize:count:key:(size_t size,[count] NSUInteger count,[key] NSString *key)
Definition OOMesh.m:1941
id mutableCopyWithZone:(NSZone *zone)
Definition OOMesh.m:881
NSString * modelName()
Definition OOMesh.m:353
OOMeshFaceCount faceCount
Definition OOMesh.m:363
void getNormal:andTangent:forVertex:inSmoothGroup:(Vector *outNormal,[andTangent] Vector *outTangent,[forVertex] OOMeshVertexCount v_index,[inSmoothGroup] OOMeshSmoothGroup smoothGroup)
Definition OOMesh.m:1681
NSDictionary * dictionaryRepresentation()
Definition Octree.m:626
NSDictionary * materialDefaults()
NSString * stringFromFilesNamed:inFolder:cache:(NSString *fileName,[inFolder] NSString *folderName,[cache] BOOL useCache)
voidpf void uLong size
Definition ioapi.h:126
const char * filename
Definition ioapi.h:125
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
const char int mode
Definition ioapi.h:125
Vector tangent
Definition OOMesh.h:66
GLuint vertex[3]
Definition OOMesh.h:63
Vector normal
Definition OOMesh.h:65
GLfloat t[3]
Definition OOMesh.h:68
GLfloat s[3]
Definition OOMesh.h:67
Vector v[3]
Definition OOTriangle.h:29
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34
uint16_t internCount
Definition OOMesh.m:115
uint16_t internFaces[kVertexFaceDefInternalCount]
Definition OOMesh.m:116
NSMutableArray * extra
Definition OOMesh.m:117