57#import "OOJavaScriptEngine.h"
60#define ADAPTIVE_OCTREE_DEPTH 1
85 _stopwatchLastTime = Profile(tag, _stopwatch, _stopwatchLastTime); \
90 OOLog(
@"mesh.profile",
@"Mesh profile: stage %@, %g seconds (delta %g)", tag, now, now - lastTime);
124@interface OOMesh (Private) <NSMutableCopying, OOGraphicsResetClient>
126- (id)initWithName:(NSString*)name
127 cacheKey:(NSString*)cacheKey
128 materialDictionary:(NSDictionary*)materialDict
129 shadersDictionary:(NSDictionary*)shadersDict
131 shaderMacros:(NSDictionary*)macros
132 shaderBindingTarget:(
id<OOWeakReferenceSupport>)object
133 scaleFactor:(
float)scale
134 cacheWriteable:(BOOL)cacheWriteable;
136- (BOOL)loadData:(NSString*)filename scaleFactor:(
float)scale;
139- (void)calculateVertexNormalsAndTangentsWithFaceRefs:(
VertexFaceRef*)faceRefs;
140- (void)calculateVertexTangentsWithFaceRefs:(
VertexFaceRef*)faceRefs;
145- (BOOL)setModelFromModelData:(NSDictionary*)dict name:(NSString*)fileName;
153- (void)rescaleByFactor:(GLfloat)factor;
155#ifdef OO_DEBUG_MONITOR_ENABLED
156- (void)debugDrawNormals;
160- (void)setRetainedObject:(
id)object forKey:(NSString*)key;
161- (void*)allocateBytesWithSize:(
size_t)size count:(NSUInteger)count key:(NSString*)key;
164- (BOOL)allocateVertexBuffersWithCount:(NSUInteger)count;
165- (BOOL)allocateNormalBuffersWithCount:(NSUInteger)count;
166- (BOOL)allocateFaceBuffersWithCount:(NSUInteger)count;
167- (BOOL)allocateVertexArrayBuffersWithCount:(NSUInteger)count;
169- (void)renameTexturesFrom:(NSString*)from to:(NSString*)to;
173@interface OOCacheManager (OOMesh)
175+ (NSDictionary*)meshDataForName:(NSString*)inShipName;
176+ (void)setMeshData:(NSDictionary*)inData forName:(NSString*)inShipName;
195 [NSException raise:NSInvalidArgumentException
196 format:@"Unexpected normal mode in %s", __PRETTY_FUNCTION__];
215 [NSException raise:NSInvalidArgumentException
216 format:@"Unexpected normal mode in %s", __PRETTY_FUNCTION__];
221@implementation OOMesh
223+ (instancetype)meshWithName:(NSString*)name
224 cacheKey:(NSString*)cacheKey
225 materialDictionary:(NSDictionary*)materialDict
226 shadersDictionary:(NSDictionary*)shadersDict
228 shaderMacros:(NSDictionary*)macros
229 shaderBindingTarget:(
id<OOWeakReferenceSupport>)object
231 return [[[
self alloc] initWithName:name
233 materialDictionary:materialDict
234 shadersDictionary:shadersDict
237 shaderBindingTarget:object
239 cacheWriteable:YES] autorelease];
242+ (instancetype)meshWithName:(NSString*)name
243 cacheKey:(NSString*)cacheKey
244 materialDictionary:(NSDictionary*)materialDict
245 shadersDictionary:(NSDictionary*)shadersDict
247 shaderMacros:(NSDictionary*)macros
248 shaderBindingTarget:(
id<OOWeakReferenceSupport>)object
249 scaleFactor:(
float)scale
250 cacheWriteable:(BOOL)cacheWriteable
252 return [[[
self alloc] initWithName:name
254 materialDictionary:materialDict
255 shadersDictionary:shadersDict
258 shaderBindingTarget:object
260 cacheWriteable:cacheWriteable] autorelease];
284 _textureUnitCount = NSNotFound;
345- (id)copyWithZone:(NSZone*)zone
347 if (zone == [
self zone])
348 return [
self retain];
372 BOOL meshBelongsToVisualEffect = [_shaderBindingTarget isVisualEffect];
382 if (meshBelongsToVisualEffect) {
383 OOGL(glEnable(GL_BLEND));
384 OOGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
389 OOGL(glEnableVertexAttribArrayARB(kTangentAttributeIndex));
390 OOGL(glVertexAttribPointerARB(kTangentAttributeIndex, 3, GL_FLOAT, GL_FALSE, 0,
_displayLists.tangentArray));
394 BOOL usingNormalsAsTexCoords = NO;
405 if (_textureUnitCount == NSNotFound) {
406 _textureUnitCount = 0;
409 if (_textureUnitCount <
count)
410 _textureUnitCount =
count;
415 if (_textureUnitCount <= 1) {
416 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
421 NSAssert2([[
OOOpenGLExtensionManager sharedManager] textureCombinersSupported],
@"Mesh %@ uses %zu texture units, but multitexturing is not available.", [
self shortDescription], _textureUnitCount);
423 for (unit = 0; unit < _textureUnitCount; unit++) {
424 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
425 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
429 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
444 if (ti == 0 || wantsNormalsAsTextureCoordinates != usingNormalsAsTexCoords) {
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));
453 if (!wantsNormalsAsTextureCoordinates) {
454 OOGL(glDisable(GL_TEXTURE_CUBE_MAP));
461 OOGL(glEnable(GL_TEXTURE_2D));
463 OOGL(glDisable(GL_TEXTURE_2D));
465 OOGL(glEnable(GL_TEXTURE_CUBE_MAP));
470 usingNormalsAsTexCoords = wantsNormalsAsTextureCoordinates;
480 @catch (NSException* exception) {
482 OOLog(
kOOLogException,
@"***** %s for %@ encountered exception: %@ : %@ *****", __PRETTY_FUNCTION__,
self, [exception name], [exception reason]);
485 if ([[exception name] hasPrefix:
@"Oolite"])
486 [UNIVERSE handleOoliteException:exception];
493 OOGL(glDisableVertexAttribArrayARB(kTangentAttributeIndex));
501 if (_textureUnitCount <= 1) {
502 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
504 for (unit = 0; unit < _textureUnitCount; unit++) {
505 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
506 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
509 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB));
510 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB));
513 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
516#ifdef OO_DEBUG_MONITOR_ENABLED
518 [
self debugDrawNormals];
520 [[
self octree] drawOctree];
524 if (meshBelongsToVisualEffect)
525 OOGL(glDisable(GL_BLEND));
539 if (![
materialKeys[i] isEqualToString:
@"_oo_placeholder_material"]) {
551 if (material !=
nil) {
590#if ADAPTIVE_OCTREE_DEPTH
595 GLfloat xs, ys, zs, t,
size;
609 size = (xs + ys) / 2.0f;
615 if (
size < threshold)
621 OOLog(
@"mesh.load.octree.size",
@"Selected octree depth %u for size %g for %@", result,
size,
baseFile);
625- (unsigned)octreeDepth
668 selfPosition:(
Vector)position
739- (
OOMesh*)meshRescaledBy:(GLfloat)scaleFactor
741 OOMesh* result = [
self mutableCopy];
742 [
result rescaleByFactor:scaleFactor];
743 return [
result autorelease];
746- (void)setBindingTarget:(
id<OOWeakReferenceSupport>)target
755#ifdef OO_DEBUG_MONITOR_ENABLED
758 [
super dumpSelfState];
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));
767#ifdef OO_DEBUG_MONITOR_ENABLED
770 NSMutableSet* result = [NSMutableSet set];
772 for (i = 0; i != materialCount; i++) {
773 [result unionSet:[materials[i] allTextures]];
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;
789 result +=
sizeof *_faces * faceCount;
791 result += _displayLists.
count * (sizeof(GLint) + sizeof(GLfloat) + sizeof(
Vector) * 3);
794 for (i = 0; i != materialCount; i++) {
795 result += [materials[i] oo_objectSize];
798 result += [octree totalSize];
815@implementation OOMesh (Private)
817- (id)initWithName:(NSString*)name
818 cacheKey:(NSString*)cacheKey
819 materialDictionary:(NSDictionary*)materialDict
820 shadersDictionary:(NSDictionary*)shadersDict
822 shaderMacros:(NSDictionary*)macros
823 shaderBindingTarget:(
id<OOWeakReferenceSupport>)target
824 scaleFactor:(
float)scale
825 cacheWriteable:(BOOL)cacheWriteable
835 _cacheWriteable = cacheWriteable;
841 if ([
self loadData:name scaleFactor:scale]) {
843 PROFILE(
@"finished calculateBoundingVolumes (again\?\?)");
845 baseFile = [
name copy];
846 baseFileOctreeCacheRef = [[
NSString stringWithFormat:@"%@-%.3f", baseFile, scale] copy];
855 _shaderMacros = [
macros copy];
856 _shaderBindingTarget = [
target weakRetain];
859 PROFILE(
@"finished material setup");
871 _textureUnitCount = NSNotFound;
881- (id)mutableCopyWithZone:(NSZone*)zone
886 result = (
OOMesh*)NSCopyObject(
self, 0, zone);
889 [
result->baseFile retain];
890 [
result->baseFileOctreeCacheRef 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];
900 [
result->materialKeys[
i] retain];
918 OOGL(glDeleteLists(displayList0, materialCount));
927 _textureUnitCount = NSNotFound;
934 NSNumber *vertCnt =
nil,
936 NSData *vertData =
nil,
940 NSArray* mtlKeys =
nil;
941 NSNumber* normMode =
nil;
946 vertCnt = [
NSNumber numberWithUnsignedInt:vertexCount];
947 faceCnt = [
NSNumber numberWithUnsignedInt:faceCount];
951 if (includeNormals) {
956 if (materialCount != 0) {
957 mtlKeys = [
NSArray arrayWithObjects:materialKeys count:materialCount];
961 normMode = [
NSNumber numberWithUnsignedChar:_normalMode];
964 if (vertCnt ==
nil || faceCnt ==
nil || vertData ==
nil || faceData ==
nil || mtlKeys ==
nil || normMode ==
nil) {
968 if (includeNormals) {
969 if (normData ==
nil || tanData ==
nil)
975 vertCnt, @"vertex count",
976 vertData, @"vertex data",
977 faceCnt, @"face count",
978 faceData, @"face data",
979 mtlKeys, @"material keys",
980 normMode, @"normal mode",
985 normData, @"normal data",
986 tanData, @"tangent data",
992- (BOOL)setModelFromModelData:(NSDictionary*)dict name:(NSString*)fileName
996 NSData *vertData =
nil,
1000 NSArray* mtlKeys =
nil;
1001 NSString* key =
nil;
1004 if (dict ==
nil || ![dict isKindOfClass:[NSDictionary
class]])
1007 vertexCount = [
dict oo_unsignedIntForKey:@"vertex count"];
1008 faceCount = [
dict oo_unsignedIntForKey:@"face count"];
1010 if (vertexCount == 0 || faceCount == 0)
1014 vertData = [
dict oo_dataForKey:@"vertex data"];
1015 faceData = [
dict oo_dataForKey:@"face data"];
1017 mtlKeys = [
dict oo_arrayForKey:@"material keys"];
1018 _normalMode = [
dict oo_unsignedCharForKey:@"normal mode"];
1022 if (vertData ==
nil || faceData ==
nil || mtlKeys ==
nil) {
1023 OOLog(
@"mesh.load.error.badCacheData",
@"Ignoring bad cache data for mesh \"%@\
".", fileName);
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);
1037 if ([vertData length] !=
sizeof *_vertices * vertexCount)
1039 if ([faceData length] !=
sizeof *_faces * faceCount)
1041 if (includeNormals) {
1042 if ([normData length] !=
sizeof *_normals * vertexCount)
1044 if ([tanData length] !=
sizeof *_tangents * vertexCount)
1049 _vertices = (
Vector*)[vertData bytes];
1053 if (includeNormals) {
1054 _normals = (
Vector*)[normData bytes];
1056 _tangents = (
Vector*)[tanData bytes];
1064 materialCount = [
mtlKeys count];
1065 for (i = 0; i != materialCount; ++i) {
1066 key = [
mtlKeys oo_stringAtIndex:i];
1068 materialKeys[
i] = [
key copy];
1070 OOLog(
@"mesh.load.error.badCacheData",
@"Ignoring bad cache data for mesh \"%@\
".", fileName);
1080- (BOOL)loadData:(NSString*)filename scaleFactor:(
float)scale
1085 NSDictionary* cacheData =
nil;
1087 NSString* failString =
@"***** ";
1089 NSMutableDictionary* texFileName2Idx =
nil;
1090 NSString* cacheKey =
nil;
1091 BOOL using_preloaded = NO;
1093 cacheKey = [
NSString stringWithFormat:@"%@:%u:%.3f", filename, _normalMode, scale];
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);
1103 if (!using_preloaded) {
1104 OOLog(
@"mesh.load.uncached",
@"Mesh \"%@\
" is not in cache, loading.", cacheKey);
1106 NSCharacterSet* whitespaceCharSet = [
NSCharacterSet whitespaceCharacterSet];
1107 NSCharacterSet* whitespaceAndNewlineCharSet = [
NSCharacterSet whitespaceAndNewlineCharacterSet];
1109 NSCharacterSet* newlineCharSet = [
NSCharacterSet newlineCharacterSet];
1111 static NSCharacterSet* newlineCharSet =
nil;
1112 if (newlineCharSet ==
nil) {
1115 newlineCharSet = [
temp copy];
1132 NSMutableArray* lines = [
NSMutableArray arrayWithArray:[
data componentsSeparatedByString:@"\n"]];
1133 for (i = 0; i < [
lines count]; i++) {
1134 NSString* line = [
lines objectAtIndex:i];
1139 parts = [
line componentsSeparatedByString:@"#"];
1140 line = [
parts objectAtIndex:0];
1141 parts = [
line componentsSeparatedByString:@"//"];
1142 line = [
parts objectAtIndex:0];
1146 line = [[
line componentsSeparatedByString:@","] componentsJoinedByString:@" "];
1148 [
lines replaceObjectAtIndex:i withObject:line];
1151 data = [
lines componentsJoinedByString:@"\n"];
1152 scanner = [
NSScanner scannerWithString:data];
1159 PROFILE(
@"finished preprocessing");
1164 if ([scanner scanString:
@"NVERTS" intoString:NULL]) {
1166 if ([scanner scanInt:&n_v])
1170 failString = [
NSString stringWithFormat:@"%@Failed to read value of NVERTS\n", failString];
1174 failString = [
NSString stringWithFormat:@"%@Failed to read NVERTS\n", failString];
1177 if (![
self allocateVertexBuffersWithCount:vertexCount]) {
1183 if ([scanner scanString:
@"NFACES" intoString:NULL]) {
1185 if ([scanner scanInt:&n_f]) {
1189 failString = [
NSString stringWithFormat:@"%@Failed to read value of NFACES\n", failString];
1193 failString = [
NSString stringWithFormat:@"%@Failed to read NFACES\n", failString];
1199 if (faceRefs != NULL) {
1201 NSData* faceRefHolder = [
NSData dataWithBytesNoCopy:faceRefs length:faceRefSize freeWhenDone:YES];
1202 if (faceRefHolder ==
nil) {
1208 if (faceRefs == NULL || ![
self allocateFaceBuffersWithCount:faceCount]) {
1214 if ([scanner scanString:
@"VERTEX" intoString:NULL]) {
1215 for (j = 0; j < vertexCount; j++) {
1218 if (![scanner scanFloat:&
x])
1220 if (![scanner scanFloat:&
y])
1222 if (![scanner scanFloat:&z])
1227 failString = [
NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"VERTEX"];
1233 failString = [
NSString stringWithFormat:@"%@Failed to find VERTEX data\n", failString];
1237 if ([scanner scanString:
@"FACES" intoString:NULL]) {
1238 for (j = 0; j < faceCount; j++) {
1244 if (![scanner scanInt:&r])
1246 if (![scanner scanInt:&g])
1248 if (![scanner scanInt:&b])
1251 _faces[
j].smoothGroup = r;
1253 failString = [
NSString stringWithFormat:@"%@Failed to read a color for face[%d] in FACES\n", failString, j];
1257 if (![scanner scanFloat:&nx])
1259 if (![scanner scanFloat:&ny])
1261 if (![scanner scanFloat:&nz])
1266 failString = [
NSString stringWithFormat:@"%@Failed to read a normal for face[%d] in FACES\n", failString, j];
1270 if ([scanner scanInt:&n_v]) {
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);
1280 failString = [
NSString stringWithFormat:@"%@Failed to read number of vertices for face[%d] in FACES\n", failString, j];
1285 for (i = 0; (
int)i < n_v; i++) {
1286 if ([scanner scanInt:&vi]) {
1287 _faces[
j].vertex[
i] = vi;
1288 if (faceRefs != NULL)
1292 failString = [
NSString stringWithFormat:@"%@Failed to read vertex[%d] for face[%d] in FACES\n", failString, i, j];
1300 failString = [
NSString stringWithFormat:@"%@Failed to find FACES data\n", failString];
1304 if ([scanner scanString:
@"TEXTURES" intoString:NULL]) {
1305 for (j = 0; j < faceCount; j++) {
1306 NSString* materialKey;
1312 [
scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1313 if (![scanner scanUpToCharactersFromSet:whitespaceCharSet intoString:&materialKey]) {
1315 failString = [
NSString stringWithFormat:@"%@Failed to read texture filename for face[%d] in TEXTURES\n", failString, j];
1319 _faces[
j].materialIndex = [
index unsignedIntValue];
1325 _faces[
j].materialIndex = materialCount;
1327 index = [
NSNumber numberWithUnsignedInt:materialCount];
1336 if (![scanner scanFloat:&max_x])
1338 if (![scanner scanFloat:&max_y])
1341 failString = [
NSString stringWithFormat:@"%@Failed to read texture size for max_x and max_y in face[%d] in TEXTURES\n", failString, j];
1347 for (i = 0; i < 3; i++) {
1348 if (![scanner scanFloat:&s])
1350 if (![scanner scanFloat:&t])
1353 _faces[
j].s[
i] = s / max_x;
1354 _faces[
j].t[
i] = t / max_y;
1356 failString = [
NSString stringWithFormat:@"%@Failed to read s t coordinates for vertex[%d] in face[%d] in TEXTURES\n", failString, i, j];
1363 failString = [
failString stringByAppendingString:@"Failed to find TEXTURES data (will use placeholder material)\n"];
1364 materialKeys[0] =
@"_oo_placeholder_material";
1367 for (j = 0; j < faceCount; j++) {
1368 _faces[
j].materialIndex = 0;
1372 if ([scanner scanString:
@"NAMES" intoString:NULL]) {
1374 if (![scanner scanInt:(
int*)&
count]) {
1376 failString = [
failString stringByAppendingString:@"Expected count after NAMES\n"];
1378 for (j = 0; j <
count; j++) {
1379 NSString* name =
nil;
1380 [
scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1381 if (![scanner scanUpToCharactersFromSet:newlineCharSet intoString:&name]) {
1383 failString = [
failString stringByAppendingString:@"Expected file name\n"];
1391 BOOL explicitTangents = NO;
1394 if ([scanner scanString:
@"NORMALS" intoString:NULL]) {
1396 if (![
self allocateNormalBuffersWithCount:vertexCount]) {
1401 for (j = 0; j < vertexCount; j++) {
1404 if (![scanner scanFloat:&
x])
1406 if (![scanner scanFloat:&
y])
1408 if (![scanner scanFloat:&z])
1413 failString = [
NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"NORMALS"];
1419 if ([scanner scanString:
@"TANGENTS" intoString:NULL]) {
1420 for (j = 0; j < vertexCount; j++) {
1423 if (![scanner scanFloat:&
x])
1425 if (![scanner scanFloat:&
y])
1427 if (![scanner scanFloat:&z])
1432 failString = [
NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"TANGENTS"];
1443 PROFILE(
@"finished checkNormalsAndAdjustWinding");
1445 if (!explicitTangents) {
1447 PROFILE(
@"finished generateFaceTangents");
1452 if (![
self allocateNormalBuffersWithCount:vertexCount]) {
1457 PROFILE(
@"finished calculateVertexNormalsAndTangents");
1461 PROFILE(
@"finished calculateVertexTangents");
1465 if (
EXPECT(_cacheWriteable)) {
1471 OOLog(
@"mesh.error",
@"%@ ..... from %@ %@", failString,
filename, (using_preloaded) ?
@"(from preloaded data)" :
@"(from file)");
1476 PROFILE(
@"finished calculateBoundingVolumes");
1481 PROFILE(
@"finished setUpVertexArrays");
1497 for (i = 0; i < faceCount; i++) {
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;
1507 _faces[
i].normal = norm;
1514 if (norm.
x * calculatedNormal.x < 0 || norm.
y * calculatedNormal.y < 0 || norm.
z * calculatedNormal.z < 0) {
1517 int v0 = _faces[
i].vertex[0];
1518 _faces[
i].vertex[0] = _faces[
i].vertex[2];
1519 _faces[
i].vertex[2] = v0;
1521 GLfloat f0 = _faces[
i].s[0];
1522 _faces[
i].s[0] = _faces[
i].s[2];
1523 _faces[
i].s[2] = f0;
1525 f0 = _faces[
i].t[0];
1526 _faces[
i].t[0] = _faces[
i].t[2];
1527 _faces[
i].t[2] = f0;
1539 for (i = 0; i < faceCount; i++) {
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];
1561 if (dsAC * dtAB > dsAB * dtAC) {
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);
1584 NSParameterAssert(faceRefs != NULL);
1589 NSAssert1(_normals != NULL && _tangents != NULL,
@"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1591 for (i = 0; i < faceCount; i++) {
1592 triangle_area[
i] =
FaceArea(_faces[i].vertex, _vertices);
1594 for (i = 0; i < vertexCount; i++) {
1600 for (fIter = 0; fIter < fCount; fIter++) {
1603 float t = triangle_area[
j];
1612 _normals[
i] = normal_sum;
1613 _tangents[
i] = tangent_sum;
1638 NSParameterAssert(faceRefs != NULL);
1655 for (i = 0; i < faceCount; i++) {
1658 for (i = 0; i < vertexCount; i++) {
1663 for (fIter = 0; fIter < fCount; fIter++) {
1666 float t = triangle_area[
j];
1673 _tangents[
i] = tangent_sum;
1685 assert(outNormal != NULL && outTangent != NULL);
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);
1710 NSUInteger fi, vi, mi;
1712 if (![
self allocateVertexArrayBuffersWithCount:faceCount])
1720 for (vi = 0; vi < vertexCount; vi++) {
1721 is_edge_vertex[
vi] = NO;
1722 smoothGroup[
vi] = -1;
1725 for (fi = 0; fi < faceCount; fi++) {
1726 GLfloat rv = _faces[
fi].smoothGroup;
1728 for (i = 0; i < 3; i++) {
1729 vi = _faces[
fi].vertex[
i];
1730 if (smoothGroup[vi] < 0.0)
1731 smoothGroup[
vi] = rv;
1732 else if (smoothGroup[vi] != rv)
1733 is_edge_vertex[
vi] = YES;
1741 int vertex_index = 0;
1744 for (mi = 0; mi != materialCount; ++mi) {
1745 triangle_range[
mi].location = tri_index;
1747 for (fi = 0; fi < faceCount; fi++) {
1750 if (_faces[fi].materialIndex == mi) {
1751 for (vi = 0; vi < 3; vi++) {
1752 int v = _faces[
fi].vertex[
vi];
1754 if (is_edge_vertex[v]) {
1757 NSAssert1(_normals != NULL && _tangents != NULL,
@"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1759 normal = _normals[
v];
1760 tangent = _tangents[
v];
1763 normal = _faces[
fi].normal;
1764 tangent = _faces[
fi].tangent;
1768 _displayLists.indexArray[
tri_index++] = vertex_index;
1772 _displayLists.textureUVArray[
uv_index++] = _faces[
fi].s[
vi];
1773 _displayLists.textureUVArray[
uv_index++] = _faces[
fi].t[
vi];
1777 triangle_range[
mi].length = tri_index - triangle_range[
mi].location;
1780 _displayLists.count = tri_index;
1791 float d_squared, length_longest_axis, length_shortest_axis;
1800 for (i = 0; i < vertexCount; i++) {
1802 if (d_squared > result)
1819 d_squared = (length_longest_axis + length_shortest_axis) * (length_longest_axis + length_shortest_axis) * 0.25;
1822 collisionRadius = sqrtf(result);
1827- (void)rescaleByFactor:(GLfloat)factor
1833 for (i = 0; i < vertexCount; i++) {
1834 vertex = &_vertices[
i];
1839 for (i = 0; i < _displayLists.count; i++) {
1840 vertex = &_displayLists.vertexArray[
i];
1847 DESTROY(baseFileOctreeCacheRef);
1855#ifdef OO_DEBUG_MONITOR_ENABLED
1856- (void)debugDrawNormals
1860 float length, blend;
1862 OODebugWFState state;
1866 state = OODebugBeginWireframe(NO);
1870 for (i = 0; i < _displayLists.count; ++i) {
1871 v = _displayLists.vertexArray[i];
1872 n = _displayLists.normalArray[i];
1873 t = _displayLists.tangentArray[i];
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];
1884 glVertex3f(v.
x, v.
y, v.
z);
1887 glVertex3f(n.
x, n.
y, n.
z);
1890 glColor3f(1.0f, 1.0f, 0.0f);
1892 glVertex3f(v.
x, v.
y, v.
z);
1893 glVertex3f(t.
x, t.
y, t.
z);
1896 glColor3f(0.0f, 1.0f, 0.0f);
1898 glVertex3f(v.
x, v.
y, v.
z);
1899 glVertex3f(b.
x, b.
y, b.
z);
1903 OODebugEndWireframe(state);
1907- (void)setRetainedObject:(
id)object forKey:(NSString*)key
1911 if (
object !=
nil) {
1912 if (_retainedObjects ==
nil)
1921#if OOLITE_BIG_ENDIAN
1922 enum { kScribble = 0xFEEDFACE };
1924 enum { kScribble = 0xCEFAEDFE };
1927 size /=
sizeof(uint32_t);
1928 uint32_t* mem = bytes;
1933#define Scribble(bytes, size) \
1941- (void*)allocateBytesWithSize:(
size_t)size count:(NSUInteger)count key:(NSString*)key
1947 void* bytes = malloc(
size);
1948 if (bytes != NULL) {
1950 NSData* holder = [
NSData dataWithBytesNoCopy:bytes length:size freeWhenDone:YES];
1956- (BOOL)allocateVertexBuffersWithCount:(NSUInteger)count
1959 return _vertices != NULL;
1962- (BOOL)allocateNormalBuffersWithCount:(NSUInteger)count
1966 return _normals != NULL && _tangents != NULL;
1969- (BOOL)allocateFaceBuffersWithCount:(NSUInteger)count
1972 return _faces != NULL;
1975- (BOOL)allocateVertexArrayBuffersWithCount:(NSUInteger)count
1983 return _faces != NULL && _displayLists.indexArray != NULL && _displayLists.textureUVArray != NULL && _displayLists.vertexArray != NULL && _displayLists.normalArray != NULL && _displayLists.tangentArray != NULL;
1986- (void)renameTexturesFrom:(NSString*)from to:(NSString*)to
1992 for (i = 0; i != materialCount; i++) {
1993 if ([materialKeys[i] isEqualToString:from]) {
1995 materialKeys[
i] = [
to copy];
2004@implementation OOCacheManager (OOMesh)
2006+ (NSDictionary*)meshDataForName:(NSString*)inShipName
2011+ (void)setMeshData:(NSDictionary*)inData forName:(NSString*)inShipName
2013 if (inData !=
nil && inShipName !=
nil) {
2022@implementation OOCacheManager (Octree)
2026 NSDictionary* dict =
nil;
2034 result = [[
Octree alloc] initWithDictionary:dict];
2041+ (void)setOctree:(
Octree*)inOctree forModel:(NSString*)inKey
2043 if (inOctree !=
nil && inKey !=
nil) {
2050 NSCParameterAssert(vfr != NULL);
2057 [
vfr->extra addObject:[
NSNumber numberWithInteger:index]];
2063 NSCParameterAssert(vfr != NULL);
2070 NSCParameterAssert(vfr != NULL && index <
VFRGetCount(vfr));
2072 if (index < vfr->internCount)
2075 return [
vfr->extra oo_unsignedIntegerAtIndex:index - vfr->internCount];
#define NO_DRAW_DISTANCE_FACTOR
const BoundingBox kZeroBoundingBox
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
void OOStandardsError(NSString *message)
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_PROFILE_ENTER
#define OOLogWARN(class, format,...)
NSString *const kOOLogException
#define OOLog(class, format,...)
NSString *const kOOLogAllocationFailure
#define OO_ENTER_OPENGL()
const OOMatrix kZeroMatrix
Vector OOVectorMultiplyMatrix(Vector v, OOMatrix m) CONST_FUNC
bool OOMatrixEqual(OOMatrix a, OOMatrix b) CONST_FUNC
uint16_t OOMeshSmoothGroup
uint32_t OOMeshVertexCount
uint8_t OOMeshMaterialIndex
uint8_t OOMeshMaterialCount
static void VFRAddFace(VertexFaceRef *vfr, NSUInteger index)
static NSUInteger VFRGetCount(VertexFaceRef *vfr)
static BOOL IsLegacyNormalMode(OOMeshNormalMode mode)
static NSString *const kOOLogMeshTooManyMaterials
static NSString *const kOOCacheOctrees
static NSString *const kOOLogMeshDataNotFound
static BOOL IsPerVertexNormalMode(OOMeshNormalMode mode)
@ kOctreeSmallSizeThreshold
#define Scribble(bytes, size)
static NSUInteger VFRGetFaceAtIndex(VertexFaceRef *vfr, NSUInteger index)
@ kVertexFaceDefInternalCount
static NSString *const kOOCacheMeshes
#define OOVerifyOpenGLState()
BOOL OOCheckOpenGLErrors(NSString *format,...)
#define OOSetOpenGLState(STATE)
OOINLINE Vector vector_flip(Vector v) INLINE_CONST_FUNC
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
OOINLINE Vector vector_subtract(Vector a, Vector b) INLINE_CONST_FUNC
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
OOINLINE OOScalar distance2(Vector v1, Vector v2) INLINE_CONST_FUNC
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
OOINLINE OOScalar dot_product(Vector first, Vector second) INLINE_CONST_FUNC
OOINLINE Vector vector_normal_or_fallback(Vector vec, Vector fallback) INLINE_CONST_FUNC
OOINLINE Vector true_cross_product(Vector first, Vector second) CONST_FUNC
OOINLINE Vector normal_to_surface(Vector v1, Vector v2, Vector v3) CONST_FUNC
OOINLINE bool vector_equal(Vector a, Vector b) INLINE_CONST_FUNC
OOINLINE void scale_vector(Vector *outVector, OOScalar factor) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
const Vector kBasisZVector
const Vector kBasisXVector
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
OOINLINE Vector vector_normal(Vector vec) INLINE_CONST_FUNC
static void VFRAddFace(VertexFaceRef *vfr, NSUInteger index)
static NSUInteger VFRGetFaceAtIndex(VertexFaceRef *vfr, NSUInteger index)
static NSUInteger VFRGetCount(VertexFaceRef *vfr)
void deleteDisplayLists()
void generateFaceTangents()
void checkNormalsAndAdjustWinding()
void resetGraphicsState()
static float FaceAreaCorrect(GLuint *vertIndices, Vector *vertices)
NSDictionary * modelData()
BoundingBox boundingBox()
void calculateBoundingVolumes()
static float FaceArea(GLuint *vertIndices, Vector *vertices)
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
void setMeshData:forName:(NSDictionary *inData,[forName] NSString *inShipName)
void setOctree:forModel:(Octree *inOctree,[forModel] NSString *inKey)
NSDictionary * meshDataForName:(NSString *inShipName)
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
Octree * octreeForModel:(NSString *inKey)
OOCacheManager * sharedCache()
void registerClient:(id< OOGraphicsResetClient > client)
void unregisterClient:(id< OOGraphicsResetClient > client)
OOGraphicsResetManager * sharedManager()
void ensureFinishedLoading()
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)
BOOL wantsNormalsAsTextureCoordinates()
Octree * findOctreeToDepth:(NSUInteger depth)
void addTriangle:(Triangle tri)
instancetype converterWithCapacity:(NSUInteger capacity)
void deleteDisplayLists()
NSString * descriptionComponents()
static NSString * NormalModeDescription(OOMeshNormalMode mode)
NSMutableDictionary * _retainedObjects
NSDictionary * _shaderMacros
OOMaterial * placeholderMaterial()
OOMaterial * materials[kOOMeshMaxMaterials]
NSString * materialKeys[kOOMeshMaxMaterials]
void setRetainedObject:forKey:(id object,[forKey] NSString *key)
void generateFaceTangents()
OOMeshMaterialCount materialCount
NSRange triangle_range[kOOMeshMaxMaterials]
void checkNormalsAndAdjustWinding()
NSDictionary * modelData()
BoundingBox _lastBoundingBox
void renameTexturesFrom:to:(NSString *from,[to] NSString *to)
NSDictionary * _materialDict
NSDictionary * _shadersDict
NSString * baseFileOctreeCacheRef
void calculateVertexTangentsWithFaceRefs:(VertexFaceRef *faceRefs)
OOMeshVertexCount vertexCount
void calculateBoundingVolumes()
OOMeshDisplayLists _displayLists
BOOL suppressClangStuff()
void calculateVertexNormalsAndTangentsWithFaceRefs:(VertexFaceRef *faceRefs)
void * allocateBytesWithSize:count:key:(size_t size,[count] NSUInteger count,[key] NSString *key)
id mutableCopyWithZone:(NSZone *zone)
OOMeshFaceCount faceCount
void getNormal:andTangent:forVertex:inSmoothGroup:(Vector *outNormal,[andTangent] Vector *outTangent,[forVertex] OOMeshVertexCount v_index,[inSmoothGroup] OOMeshSmoothGroup smoothGroup)
OOTimeDelta currentTime()
NSDictionary * dictionaryRepresentation()
NSDictionary * materialDefaults()
NSString * stringFromFilesNamed:inFolder:cache:(NSString *fileName,[inFolder] NSString *folderName,[cache] BOOL useCache)
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
uint16_t internFaces[kVertexFaceDefInternalCount]