Oolite
Loading...
Searching...
No Matches
Octree.m
Go to the documentation of this file.
1/*
2
3Octree.m
4
5Oolite
6Copyright (C) 2004-2013 Giles C Williams and contributors
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#import "Octree.h"
26#import "Entity.h"
29#import "OODebugFlags.h"
30#import "OODebugGLDrawing.h"
31#import "OOMacroOpenGL.h"
32#import "OOMaths.h"
33#import "OOOpenGL.h"
34
35#ifdef OO_DEBUG_MONITOR_ENABLED
36#define OctreeDebugLog(format, ...) \
37 do { \
38 if (EXPECT_NOT(gDebugFlags & DEBUG_OCTREE_LOGGING)) \
39 OOLog(@"octree.debug", format, ##__VA_ARGS__); \
40 } while (0)
41#else
42#define OctreeDebugLog(...) \
43 do { \
44 } while (0)
45#endif
46
47typedef struct
48{
49 GLfloat radius;
50 const int* octree;
51 unsigned char* octree_collision;
53
54@interface Octree (Private)
55
56#ifndef OODEBUGLDRAWING_DISABLE
57
58- (void)drawOctreeFromLocation:(uint32_t)loc scale:(GLfloat)scale offset:(Vector)offset;
59- (void)drawOctreeCollisionFromLocation:(uint32_t)loc scale:(GLfloat)scale offset:(Vector)offset;
60
61- (BOOL)hasCollision;
62- (void)setHasCollision:(BOOL)value;
63
64#endif
65
67
68@end
69
70static const int change_oct[] = { 0, 1, 2, 4, 3, 5, 6, 7 }; // used to move from nearest to furthest octant
71
72static BOOL isHitByLine(const int* octbuffer, unsigned char* collbuffer, int level, GLfloat rad, Vector v0, Vector v1, Vector off, int face_hit);
73static GLfloat volumeOfOctree(Octree_details octree_details, unsigned depthLimit);
75
76static BOOL isHitByOctree(Octree_details axialDetails, Octree_details otherDetails, Vector delta, Triangle other_ijk);
77
78@implementation Octree
79
80- (id)init
81{
82 // -init makes no sense, since octrees are immutable.
83 [self release];
84 [NSException raise:NSInternalInconsistencyException format:@"Call of invalid initializer %s", __FUNCTION__];
85 return nil;
86}
87
88// Designated initializer.
89- (id)initWithData:(NSData*)data
90 radius:(GLfloat)radius
91{
92 if ((self = [super init])) {
93 _data = [data copy];
94 _radius = radius;
95
96 NSUInteger nodeCount = [_data length] / sizeof *_octree;
97 NSParameterAssert(nodeCount < UINT32_MAX);
98 _nodeCount = (uint32_t)nodeCount;
99
100 _octree = [_data bytes];
101
102 _collisionOctree = calloc(1, _nodeCount);
103 if (_octree == NULL || _collisionOctree == NULL) {
104 [self release];
105 return nil;
106 }
107 }
108
109 return self;
110}
111
112- (id)initWithDictionary:(NSDictionary*)dict
113{
114 NSData* data = [dict objectForKey:@"octree"];
115 if (![data isKindOfClass:[NSData class]] || ([data length] % sizeof(int)) != 0) {
116 // Invalid representation.
117 [self release];
118 return nil;
119 }
120
121 return [self initWithData:data radius:[dict oo_floatForKey:@"radius"]];
122}
123
124- (void)dealloc
125{
126 DESTROY(_data);
127 free(_collisionOctree);
128
129 [super dealloc];
130}
131
133{
134 return _hasCollision;
135}
136
137- (void)setHasCollision:(BOOL)value
138{
139 _hasCollision = !!value;
140}
141
143{
144 Octree_details details = {
145 .octree = _octree,
146 .radius = _radius,
147 .octree_collision = _collisionOctree
148 };
149 return details;
150}
151
152- (Octree*)octreeScaledBy:(GLfloat)factor
153{
154 // Since octree data is immutable, we can share.
155 return [[[Octree alloc] initWithData:_data radius:_radius * factor] autorelease];
156}
157
158static Vector offsetForOctant(int oct, GLfloat r)
159{
160 return make_vector((0.5f - (GLfloat)((oct >> 2) & 1)) * r, (0.5f - (GLfloat)((oct >> 1) & 1)) * r, (0.5f - (GLfloat)(oct & 1)) * r);
161}
162
163#ifndef OODEBUGLDRAWING_DISABLE
164
165- (void)drawOctree
166{
167 OODebugWFState state = OODebugBeginWireframe(NO);
168
170 OOGL(glEnable(GL_BLEND));
171 OOGLBEGIN(GL_LINES);
172 glColor4f(0.4f, 0.4f, 0.4f, 0.5f);
173
174 // it's a series of cubes
175 [self drawOctreeFromLocation:0 scale:_radius offset:kZeroVector];
176
177 OOGLEND();
178
179 OODebugEndWireframe(state);
180 OOCheckOpenGLErrors(@"Octree after drawing %@", self);
181}
182
183#if 0
184#define OCTREE_COLOR(r, g, b, a) glColor4f(r, g, b, a)
185#else
186#define OCTREE_COLOR(r, g, b, a) \
187 do { \
188 } while (0)
189#endif
190
191- (void)drawOctreeFromLocation:(uint32_t)loc scale:(GLfloat)scale offset:(Vector)offset
192{
193 if (_octree[loc] == 0) {
194 return;
195 }
196
198
199 if (_octree[loc] == -1) // full
200 {
201 // draw a cube
202 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
203 glVertex3f(-scale + offset.x, scale + offset.y, -scale + offset.z);
204 glVertex3f(-scale + offset.x, scale + offset.y, -scale + offset.z);
205 glVertex3f(scale + offset.x, scale + offset.y, -scale + offset.z);
206 glVertex3f(scale + offset.x, scale + offset.y, -scale + offset.z);
207 glVertex3f(scale + offset.x, -scale + offset.y, -scale + offset.z);
208 glVertex3f(scale + offset.x, -scale + offset.y, -scale + offset.z);
209 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
210
211 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
212 glVertex3f(-scale + offset.x, scale + offset.y, scale + offset.z);
213 glVertex3f(-scale + offset.x, scale + offset.y, scale + offset.z);
214 glVertex3f(scale + offset.x, scale + offset.y, scale + offset.z);
215 glVertex3f(scale + offset.x, scale + offset.y, scale + offset.z);
216 glVertex3f(scale + offset.x, -scale + offset.y, scale + offset.z);
217 glVertex3f(scale + offset.x, -scale + offset.y, scale + offset.z);
218 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
219
220 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
221 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
222
223 glVertex3f(-scale + offset.x, scale + offset.y, -scale + offset.z);
224 glVertex3f(-scale + offset.x, scale + offset.y, scale + offset.z);
225
226 glVertex3f(scale + offset.x, scale + offset.y, -scale + offset.z);
227 glVertex3f(scale + offset.x, scale + offset.y, scale + offset.z);
228
229 glVertex3f(scale + offset.x, -scale + offset.y, -scale + offset.z);
230 glVertex3f(scale + offset.x, -scale + offset.y, scale + offset.z);
231 } else if (_octree[loc] > 0) {
232 GLfloat sc = 0.5f * scale;
233 OCTREE_COLOR(0.4f, 0.4f, 0.4f, 0.5f);
234 [self drawOctreeFromLocation:loc + _octree[loc] + 0 scale:sc offset:make_vector(offset.x - sc, offset.y - sc, offset.z - sc)];
235 OCTREE_COLOR(0.0f, 0.0f, 1.0f, 0.5f);
236 [self drawOctreeFromLocation:loc + _octree[loc] + 1 scale:sc offset:make_vector(offset.x - sc, offset.y - sc, offset.z + sc)];
237 OCTREE_COLOR(0.0f, 1.0f, 0.0f, 0.5f);
238 [self drawOctreeFromLocation:loc + _octree[loc] + 2 scale:sc offset:make_vector(offset.x - sc, offset.y + sc, offset.z - sc)];
239 OCTREE_COLOR(0.0f, 1.0f, 1.0f, 0.5f);
240 [self drawOctreeFromLocation:loc + _octree[loc] + 3 scale:sc offset:make_vector(offset.x - sc, offset.y + sc, offset.z + sc)];
241 OCTREE_COLOR(1.0f, 0.0f, 0.0f, 0.5f);
242 [self drawOctreeFromLocation:loc + _octree[loc] + 4 scale:sc offset:make_vector(offset.x + sc, offset.y - sc, offset.z - sc)];
243 OCTREE_COLOR(1.0f, 0.0f, 1.0f, 0.5f);
244 [self drawOctreeFromLocation:loc + _octree[loc] + 5 scale:sc offset:make_vector(offset.x + sc, offset.y - sc, offset.z + sc)];
245 OCTREE_COLOR(1.0f, 1.0f, 0.0f, 0.5f);
246 [self drawOctreeFromLocation:loc + _octree[loc] + 6 scale:sc offset:make_vector(offset.x + sc, offset.y + sc, offset.z - sc)];
247 OCTREE_COLOR(1.0f, 1.0f, 1.0f, 0.5f);
248 [self drawOctreeFromLocation:loc + _octree[loc] + 7 scale:sc offset:make_vector(offset.x + sc, offset.y + sc, offset.z + sc)];
249 }
250}
251
252static BOOL drawTestForCollisions;
253
254- (void)drawOctreeCollisions
255{
256 OODebugWFState state = OODebugBeginWireframe(NO);
257
258 // it's a series of cubes
259 drawTestForCollisions = NO;
260 if (_hasCollision) {
261 [self drawOctreeCollisionFromLocation:0 scale:_radius offset:kZeroVector];
262 }
263 _hasCollision = drawTestForCollisions;
264
265 OODebugEndWireframe(state);
266 OOCheckOpenGLErrors(@"Octree after drawing collisions for %@", self);
267}
268
269- (void)drawOctreeCollisionFromLocation:(uint32_t)loc scale:(GLfloat)scale offset:(Vector)offset
270{
271 if (_octree[loc] == 0) {
272 return;
273 }
274
275 if ((_octree[loc] != 0) && (_collisionOctree[loc] != (unsigned char)0)) // full - draw
276 {
278
279 GLfloat red = (GLfloat)(_collisionOctree[loc]) / 255.0;
280 glColor4f(1.0, 0.0, 0.0, red); // 50% translucent
281
282 drawTestForCollisions = YES;
283 _collisionOctree[loc]--;
284
285 // draw a cube
286 OOGL(glDisable(GL_CULL_FACE)); // face culling
287
288 OOGL(glDisable(GL_TEXTURE_2D));
289
290 OOGLBEGIN(GL_LINE_STRIP);
291 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
292 glVertex3f(-scale + offset.x, scale + offset.y, -scale + offset.z);
293 glVertex3f(scale + offset.x, scale + offset.y, -scale + offset.z);
294 glVertex3f(scale + offset.x, -scale + offset.y, -scale + offset.z);
295 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
296 OOGLEND();
297
298 OOGLBEGIN(GL_LINE_STRIP);
299 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
300 glVertex3f(-scale + offset.x, scale + offset.y, scale + offset.z);
301 glVertex3f(scale + offset.x, scale + offset.y, scale + offset.z);
302 glVertex3f(scale + offset.x, -scale + offset.y, scale + offset.z);
303 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
304 OOGLEND();
305
306 OOGLBEGIN(GL_LINES);
307 glVertex3f(-scale + offset.x, -scale + offset.y, -scale + offset.z);
308 glVertex3f(-scale + offset.x, -scale + offset.y, scale + offset.z);
309
310 glVertex3f(-scale + offset.x, scale + offset.y, -scale + offset.z);
311 glVertex3f(-scale + offset.x, scale + offset.y, scale + offset.z);
312
313 glVertex3f(scale + offset.x, scale + offset.y, -scale + offset.z);
314 glVertex3f(scale + offset.x, scale + offset.y, scale + offset.z);
315
316 glVertex3f(scale + offset.x, -scale + offset.y, -scale + offset.z);
317 glVertex3f(scale + offset.x, -scale + offset.y, scale + offset.z);
318 OOGLEND();
319
320 OOGL(glEnable(GL_CULL_FACE)); // face culling
321 }
322 if (_octree[loc] > 0) {
323 GLfloat sc = 0.5f * scale;
324 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 0 scale:sc offset:make_vector(offset.x - sc, offset.y - sc, offset.z - sc)];
325 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 1 scale:sc offset:make_vector(offset.x - sc, offset.y - sc, offset.z + sc)];
326 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 2 scale:sc offset:make_vector(offset.x - sc, offset.y + sc, offset.z - sc)];
327 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 3 scale:sc offset:make_vector(offset.x - sc, offset.y + sc, offset.z + sc)];
328 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 4 scale:sc offset:make_vector(offset.x + sc, offset.y - sc, offset.z - sc)];
329 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 5 scale:sc offset:make_vector(offset.x + sc, offset.y - sc, offset.z + sc)];
330 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 6 scale:sc offset:make_vector(offset.x + sc, offset.y + sc, offset.z - sc)];
331 [self drawOctreeCollisionFromLocation:loc + _octree[loc] + 7 scale:sc offset:make_vector(offset.x + sc, offset.y + sc, offset.z + sc)];
332 }
333}
334#endif // OODEBUGLDRAWING_DISABLE
335
336static BOOL isHitByLineSub(const int* octbuffer, unsigned char* collbuffer, int nextLevel, GLfloat rad, GLfloat rd2, Vector v0, Vector v1, int octantMask)
337{
338 if (octbuffer[nextLevel + octantMask]) {
339 Vector moveLine = offsetForOctant(octantMask, rad);
340 return isHitByLine(octbuffer, collbuffer, nextLevel + octantMask, rd2, v0, v1, moveLine, 0);
341 } else
342 return NO;
343}
344
345static BOOL hasCollided = NO;
346static GLfloat hit_dist = 0.0;
347static BOOL isHitByLine(const int* octbuffer, unsigned char* collbuffer, int level, GLfloat rad, Vector v0, Vector v1, Vector off, int face_hit)
348{
349 // displace the line by the offset
350 Vector u0 = make_vector(v0.x + off.x, v0.y + off.y, v0.z + off.z);
351 Vector u1 = make_vector(v1.x + off.x, v1.y + off.y, v1.z + off.z);
352
353 OctreeDebugLog(@"DEBUG octant: [%d] radius: %.2f vs. line: (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f)",
354 level, rad, u0.x, u0.y, u0.z, u1.x, u1.y, u1.z);
355
356 if (octbuffer[level] == 0) {
357 OctreeDebugLog(@"DEBUG Hit an empty octant: [%d]", level);
358 return NO;
359 }
360
361 if (octbuffer[level] == -1) {
362 OctreeDebugLog(@"DEBUG Hit a solid octant: [%d]", level);
363 collbuffer[level] = 2; // green
364 hit_dist = sqrt(u0.x * u0.x + u0.y * u0.y + u0.z * u0.z);
365 return YES;
366 }
367
368 int faces = face_hit;
369 if (faces == 0)
370 faces = lineCubeIntersection(u0, u1, rad);
371
372 if (faces == 0) {
373 OctreeDebugLog(@"----> Line misses octant: [%d].", level);
374 return NO;
375 }
376
377 int octantIntersected = 0;
378
379 if (faces > 0) {
380 Vector vi = lineIntersectionWithFace(u0, u1, faces, rad);
381
382 if (CUBE_FACE_FRONT & faces)
383 octantIntersected = ((vi.x < 0.0) ? 1 : 5) + ((vi.y < 0.0) ? 0 : 2);
384 if (CUBE_FACE_BACK & faces)
385 octantIntersected = ((vi.x < 0.0) ? 0 : 4) + ((vi.y < 0.0) ? 0 : 2);
386
387 if (CUBE_FACE_RIGHT & faces)
388 octantIntersected = ((vi.y < 0.0) ? 4 : 6) + ((vi.z < 0.0) ? 0 : 1);
389 if (CUBE_FACE_LEFT & faces)
390 octantIntersected = ((vi.y < 0.0) ? 0 : 2) + ((vi.z < 0.0) ? 0 : 1);
391
392 if (CUBE_FACE_TOP & faces)
393 octantIntersected = ((vi.x < 0.0) ? 2 : 6) + ((vi.z < 0.0) ? 0 : 1);
394 if (CUBE_FACE_BOTTOM & faces)
395 octantIntersected = ((vi.x < 0.0) ? 0 : 4) + ((vi.z < 0.0) ? 0 : 1);
396
397 OctreeDebugLog(@"----> found intersection with face 0x%2x of cube of radius %.2f at (%.2f, %.2f, %.2f) octant:%d",
398 faces, rad, vi.x, vi.y, vi.z, octantIntersected);
399 } else {
400 OctreeDebugLog(@"----> inside cube of radius %.2f octant:%d", rad, octantIntersected);
401 }
402
403 hasCollided = YES;
404
405 collbuffer[level] = 1; // red
406
407 OctreeDebugLog(@"%@", @"----> testing octants...");
408
409 int nextLevel = level + octbuffer[level];
410
411 GLfloat rd2 = 0.5f * rad;
412
413 // first test the intersected octant, then the three adjacent, then the next three adjacent, the finally the diagonal octant
414 int oct0, oct1, oct2, oct3; // test oct0 then oct1, oct2, oct3 then (7 - oct1), (7 - oct2), (7 - oct3) then (7 - oct0)
415 oct0 = octantIntersected;
416 oct1 = oct0 ^ 0x01; // adjacent x
417 oct2 = oct0 ^ 0x02; // adjacent y
418 oct3 = oct0 ^ 0x04; // adjacent z
419
420 OctreeDebugLog(@"----> testing first octant hit [+%d]", oct0);
421 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct0))
422 return YES; // first octant
423
424 // test the three adjacent octants
425
426 OctreeDebugLog(@"----> testing next three octants [+%d] [+%d] [+%d]", oct1, oct2, oct3);
427 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct1))
428 return YES; // second octant
429 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct2))
430 return YES; // third octant
431 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct3))
432 return YES; // fourth octant
433
434 // go to the next four octants
435
436 oct0 ^= 0x07;
437 oct1 ^= 0x07;
438 oct2 ^= 0x07;
439 oct3 ^= 0x07;
440
441 OctreeDebugLog(@"----> testing back three octants [+%d] [+%d] [+%d]", oct1, oct2, oct3);
442 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct1))
443 return YES; // fifth octant
444 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct2))
445 return YES; // sixth octant
446 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct3))
447 return YES; // seventh octant
448
449 // and check the last octant
450 OctreeDebugLog(@"----> testing final octant [+%d]", oct0);
451 if (isHitByLineSub(octbuffer, collbuffer, nextLevel, rad, rd2, u0, u1, oct0))
452 return YES; // last octant
453
454 return NO;
455}
456
457- (GLfloat)isHitByLine:(Vector)v0 v1:(Vector)v1
458{
459 memset(_collisionOctree, 0, _nodeCount * sizeof *_collisionOctree);
460 hasCollided = NO;
461
463 OctreeDebugLog(@"DEBUG Hit at distance %.2f", hit_dist);
465 return hit_dist;
466 } else {
467 OctreeDebugLog(@"%@", @"DEBUG Missed!");
469 return 0.0f;
470 }
471}
472
473static BOOL isHitByOctree(Octree_details axialDetails,
474 Octree_details otherDetails, Vector otherPosition, Triangle other_ijk)
475{
476 const int* axialBuffer = axialDetails.octree;
477 const int* otherBuffer = otherDetails.octree;
478
479 if (axialBuffer[0] == 0) {
480 OctreeDebugLog(@"%@", @"DEBUG Axial octree is empty.");
481 return NO;
482 }
483
484 if (!otherBuffer) {
485 OctreeDebugLog(@"%@", @"DEBUG Other octree is undefined.");
486 return NO;
487 }
488
489 if (otherBuffer[0] == 0) {
490 OctreeDebugLog(@"%@", @"DEBUG Other octree is empty.");
491 return NO;
492 }
493
494 GLfloat axialRadius = axialDetails.radius;
495 GLfloat otherRadius = otherDetails.radius;
496
497 if (otherRadius < axialRadius) // test axial cube against other sphere
498 {
499 // 'crude and simple' - test sphere against cube...
500 if ((otherPosition.x + otherRadius < -axialRadius) || (otherPosition.x - otherRadius > axialRadius) || (otherPosition.y + otherRadius < -axialRadius) || (otherPosition.y - otherRadius > axialRadius) || (otherPosition.z + otherRadius < -axialRadius) || (otherPosition.z - otherRadius > axialRadius)) {
501 OctreeDebugLog(@"%@", @"----> Other sphere does not intersect axial cube");
502 return NO;
503 }
504 } else // test axial sphere against other cube
505 {
506 Vector d2 = vector_flip(otherPosition);
507 Vector axialPosition = resolveVectorInIJK(d2, other_ijk);
508 if ((axialPosition.x + axialRadius < -otherRadius) || (axialPosition.x - axialRadius > otherRadius) || (axialPosition.y + axialRadius < -otherRadius) || (axialPosition.y - axialRadius > otherRadius) || (axialPosition.z + axialRadius < -otherRadius) || (axialPosition.z - axialRadius > otherRadius)) {
509 OctreeDebugLog(@"%@", @"----> Axial sphere does not intersect other cube");
510 return NO;
511 }
512 }
513
514 // from here on, this Octree and the other Octree are considered to be intersecting
515 unsigned char* axialCollisionBuffer = axialDetails.octree_collision;
516 unsigned char* otherCollisionBuffer = otherDetails.octree_collision;
517 if (axialBuffer[0] == -1) {
518 // we are SOLID - is the other octree?
519 if (otherBuffer[0] == -1) {
520 // YES so octrees collide
521 axialCollisionBuffer[0] = (unsigned char)255; // mark
522 otherCollisionBuffer[0] = (unsigned char)255; // mark
523
524 OctreeDebugLog(@"%@", @"DEBUG Octrees collide!");
525 return YES;
526 }
527 // the other octree must be decomposed
528 // and each of its octants tested against the axial octree
529 // if any of them collides with this octant
530 // then we have a solid collision
531
532 OctreeDebugLog(@"%@", @"----> testing other octants...");
533
534 // work out the nearest octant to the axial octree
535 int nearest_oct = ((otherPosition.x > 0.0) ? 0 : 4) | ((otherPosition.y > 0.0) ? 0 : 2) | ((otherPosition.z > 0.0) ? 0 : 1);
536
537 int nextLevel = otherBuffer[0];
538 const int* nextBuffer = &otherBuffer[nextLevel];
539 unsigned char* nextCollisionBuffer = &otherCollisionBuffer[nextLevel];
540 Octree_details nextDetails;
541 Vector voff, nextPosition;
542 unsigned i, oct;
543
544 nextDetails.radius = 0.5f * otherRadius;
545 for (i = 0; i < 8; i++) {
546 oct = nearest_oct ^ change_oct[i]; // work from nearest to furthest
547 if (nextBuffer[oct]) // don't test empty octants
548 {
549 nextDetails.octree = &nextBuffer[oct];
550 nextDetails.octree_collision = &nextCollisionBuffer[oct];
551
552 voff = resolveVectorInIJK(offsetForOctant(oct, otherRadius), other_ijk);
553 nextPosition = vector_subtract(otherPosition, voff);
554 if (isHitByOctree(axialDetails, nextDetails, nextPosition, other_ijk)) // test octant
555 return YES;
556 }
557 }
558
559 // otherwise
560 return NO;
561 }
562 // we are not solid
563 // we must test each of our octants against
564 // the other octree, if any of them collide
565 // we have a solid collision
566
567 OctreeDebugLog(@"%@", @"----> testing axial octants...");
568
569 // work out the nearest octant to the other octree
570 int nearest_oct = ((otherPosition.x > 0.0) ? 4 : 0) | ((otherPosition.y > 0.0) ? 2 : 0) | ((otherPosition.z > 0.0) ? 1 : 0);
571
572 int nextLevel = axialBuffer[0];
573 const int* nextBuffer = &axialBuffer[nextLevel];
574 unsigned char* nextCollisionBuffer = &axialCollisionBuffer[nextLevel];
575 Vector nextPosition;
576 Octree_details nextDetails;
577 unsigned i, oct;
578
579 nextDetails.radius = 0.5f * axialRadius;
580 for (i = 0; i < 8; i++) {
581 oct = nearest_oct ^ change_oct[i]; // work from nearest to furthest
582 if (nextBuffer[oct]) // don't test empty octants
583 {
584 nextDetails.octree = &nextBuffer[oct];
585 nextDetails.octree_collision = &nextCollisionBuffer[oct];
586
587 nextPosition = vector_add(otherPosition, offsetForOctant(oct, axialRadius));
588 if (isHitByOctree(nextDetails, otherDetails, nextPosition, other_ijk)) {
589 return YES; // test octant
590 }
591 }
592 }
593 // otherwise we're done!
594 return NO;
595}
596
597- (BOOL)isHitByOctree:(Octree*)other withOrigin:(Vector)v0 andIJK:(Triangle)ijk
598{
599 if (other == nil)
600 return NO;
601
602 BOOL hit = isHitByOctree([self octreeDetails], [other octreeDetails], v0, ijk);
603
606
607 return hit;
608}
609
610- (BOOL)isHitByOctree:(Octree*)other withOrigin:(Vector)v0 andIJK:(Triangle)ijk s1:(GLfloat)s1 s2:(GLfloat)s2
611{
612 Octree_details details1 = [self octreeDetails];
614
615 details1.radius *= s1;
616 details2.radius *= s2;
617
618 BOOL hit = isHitByOctree(details1, details2, v0, ijk);
619
622
623 return hit;
624}
625
627{
628 return [NSDictionary dictionaryWithObjectsAndKeys:
629 _data, @"octree",
630 [NSNumber numberWithFloat:_radius], @"radius",
631 nil];
632}
633
634static GLfloat volumeOfOctree(Octree_details octree_details, unsigned depthLimit)
635{
636 const int* octBuffer = octree_details.octree;
637 GLfloat octRadius = octree_details.radius;
638
639 if (octBuffer[0] == 0) {
640 return 0.0f;
641 }
642
643 if (octBuffer[0] == -1 || depthLimit == 0) {
644 return octRadius * octRadius * octRadius;
645 }
646 depthLimit--;
647
648 // We are not empty or solid.
649 // We sum the volume of each of our octants.
650 GLfloat sumVolume = 0.0f;
651 Octree_details nextDetails;
652 int nextLevel = octBuffer[0];
653 const int* nextBuffer = &octBuffer[nextLevel];
654 unsigned i;
655
656 nextDetails.radius = 0.5f * octRadius;
657 nextDetails.octree_collision = NULL; // Placate static analyzer
658
659 for (i = 0; i < 8; i++) {
660 if (nextBuffer[i]) // don't test empty octants
661 {
662 nextDetails.octree = &nextBuffer[i];
663 sumVolume += volumeOfOctree(nextDetails, depthLimit);
664 }
665 }
666 return sumVolume;
667}
668
669- (GLfloat)volume
670{
671 /* For backwards compatibility, limit octree iteration for volume
672 calculation to five levels. Raising the limit means lower calculated
673 volumes for large ships.
674
675 EMMSTRAN: consider raising the limit but fudging mass lock calculations
676 to compensate. See http://aegidian.org/bb/viewtopic.php?f=3&t=9176 .
677 Then again, five levels of iteration might be fine.
678 -- Ahruman 2011-03-10
679 */
680 return volumeOfOctree([self octreeDetails], 5);
681}
682
684{
685 const int* octBuffer = details.octree;
686 GLfloat octRadius = details.radius;
687
688 if (octBuffer[0] == 0)
689 return offset;
690 if (octBuffer[0] == -1)
691 return offset;
692
693 // We are not empty or solid.
694 // Pick a location from a random octant.
695 Octree_details nextDetails;
696 int nextLevel = octBuffer[0];
697 const int* nextBuffer = &octBuffer[nextLevel];
698 unsigned i, oct;
699
700 nextDetails.radius = 0.5f * octRadius;
701 nextDetails.octree_collision = NULL;
702 oct = Ranrot() & 7;
703
704 for (i = 0; i < 8; i++) {
705 int octant = oct ^ i;
706 if (nextBuffer[octant]) // don't test empty octants
707 {
708 nextDetails.octree = &nextBuffer[octant];
709 Vector voff = vector_add(offset, offsetForOctant(octant, octRadius));
710 return randomFullNodeFrom(nextDetails, voff);
711 }
712 }
713 return offset;
714}
715
720
721#ifdef OO_DEBUG_MONITOR_ENABLED
722- (size_t)totalSize
723{
724 return [self oo_objectSize] + _nodeCount * [_data oo_objectSize] + [_data length] + _nodeCount * sizeof *_collisionOctree;
725}
726#endif
727
728@end
729
730enum {
731 /*
732 Initial capacity of OOOctreeBuilder. 16 KibiEntries is enough to handle
733 all but 2 built-in models; I expect similar results for OXPs, since
734 geometry detail has limited effect on the octree. Large models with
735 higher depth are more likely to need growth.
736 */
738};
739
740@implementation OOOctreeBuilder
741
742// Extract top of state stack.
744{
745 return &self->_stateStack[self->_level];
746}
747
748// SetNode(): set the value of an entry in _octree, making space if needed.
749static void SetNode_slow(OOOctreeBuilder* self, uint32_t index, int value) NO_INLINE_FUNC;
750OOINLINE void SetNode(OOOctreeBuilder* self, uint32_t index, int value)
751{
752 if (index < self->_capacity) {
753 self->_octree[index] = value;
754 } else {
755 SetNode_slow(self, index, value);
756 }
757}
758
759// InsertNode(): set the node at the current insertion point, and increment insertion point.
760OOINLINE void InsertNode(OOOctreeBuilder* self, int value)
761{
762 NSCAssert(State(self)->remaining > 0, @"Attempt to add node to a full parent in octree builder.");
763 State(self)->remaining--;
764
765 SetNode(self, State(self)->insertionPoint++, value);
766}
767
768- (id)init
769{
770 if ((self = [super init])) {
772 _octree = malloc(_capacity * sizeof *_octree);
773 if (_octree == NULL) {
774 [self release];
775 return nil;
776 }
777
778 /*
779 We're initially inserting into the root slot, which must exist and
780 takes a single node.
781 */
782 _nodeCount = 1;
783 State(self)->remaining = 1;
784 }
785 return self;
786}
787
788- (void)dealloc
789{
790 free(_octree);
791
792 [super dealloc];
793}
794
795- (Octree*)buildOctreeWithRadius:(GLfloat)radius
796{
797 NSAssert(State(self)->remaining == 0 && _level == 0, @"Attempt to produce octree from an octree builder in an incomplete state.");
798
799 size_t dataSize = _nodeCount * sizeof *_octree;
800 int* resized = realloc(_octree, dataSize);
801 if (resized == NULL)
802 resized = _octree;
803
804 /* Hand over the bytes to the data object, which will be used directly by
805 the Octree.
806 */
807 NSData* data = [NSData dataWithBytesNoCopy:resized
808 length:dataSize
809 freeWhenDone:YES];
810
811 _octree = NULL;
812 _nodeCount = 0;
813 _capacity = 0;
814
815 return [[[Octree alloc] initWithData:data radius:radius] autorelease];
816}
817
819{
820 InsertNode(self, -1);
821}
822
824{
825 InsertNode(self, 0);
826}
827
829{
830 NSAssert(_level < kMaxOctreeDepth, @"Attempt to build octree exceeding maximum depth.");
831
832 // Insert relative offset to next free space.
833 uint32_t newInsertionPoint = _nodeCount;
834 InsertNode(self, (int)_nodeCount - State(self)->insertionPoint);
835
836 /*
837 Leave space for eight nodes.
838
839 NOTE: this may leave memory uninitialized or leave _nodeCount pointing
840 past the end of the buffer. A valid sequence of eight child insertions
841 will fix both these problems by writing to all of the new slots.
842 */
843 _nodeCount += 8;
844
845 // Push state and set up new "stack frame".
846 _level++;
847 State(self)->insertionPoint = newInsertionPoint;
848 State(self)->remaining = 8;
849}
850
852{
853 NSAssert(State(self)->remaining == 0, @"Attempt to end an inner octree node with fewer than eight children.");
854 NSAssert1(_level > 0, @"Unbalanced call to %s", __FUNCTION__);
855
856 _level--;
857
858 /*
859 Check if the last eight nodes are solid. If so, we just inserted an
860 entirely solid subtree and can fold it into a single solid node. An
861 entirely solid subtree will always use the last eight nodes (any solid
862 subtrees within a child node will have been folded already), so this
863 simple approach to folding will produce an optimal result.
864
865 We could do the same for empty nodes, but OOMeshToOctreeConverter will
866 never recurse into an empty subtree.
867 */
868
869 NSAssert(_nodeCount > 8, @"After ending an inner node, there must be at least eight nodes in buffer.");
870 for (uint32_t node = _nodeCount - 8; node < _nodeCount; node++) {
871 if (_octree[node] != -1)
872 return;
873 }
874
875 // If we got here, subtree is solid; fold it into a solid node.
876 _octree[State(self)->insertionPoint - 1] = -1;
877 _nodeCount -= 8;
878}
879
880// Slow path for SetNode() when writing beyond _capacity: expand, then perform set.
881static void SetNode_slow(OOOctreeBuilder* self, uint32_t index, int value)
882{
883 uint32_t newCapacity = MAX(self->_capacity * 2, (uint32_t)kMinimumBuilderCapacity);
884 newCapacity = MAX(newCapacity, index + 1);
885
886 int* newBuffer = realloc(self->_octree, newCapacity * sizeof *newBuffer);
887 if (EXPECT_NOT(newBuffer == NULL)) {
888 [NSException raise:NSMallocException format:@"Failed to allocate memory for octree."];
889 }
890
891 self->_octree = newBuffer;
892 self->_capacity = newCapacity;
893 self->_octree[index] = value;
894}
895
896#ifndef NDEBUG
897/* This method exists purely to suppress Clang static analyzer warnings that
898 these ivars are unused (but may be used by categories, which they are).
899*/
901{
902 return &_stateStack && 0;
903}
904#endif
905
906@end
#define DESTROY(x)
#define NO_INLINE_FUNC
#define EXPECT_NOT(x)
#define OOINLINE
#define OO_ENTER_OPENGL()
#define MAX(A, B)
Definition OOMaths.h:94
#define OOGLBEGIN
Definition OOOpenGL.h:269
BOOL OOCheckOpenGLErrors(NSString *format,...)
Definition OOOpenGL.m:38
#define OOGL(statement)
Definition OOOpenGL.h:262
#define OOGLEND
Definition OOOpenGL.h:270
return self
return nil
OOINLINE Vector resolveVectorInIJK(Vector v0, Triangle ijk)
Definition OOTriangle.h:58
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 Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
struct Vector Vector
const Vector kZeroVector
Definition OOVector.m:27
Vector lineIntersectionWithFace(Vector p1, Vector p2, long mask, GLfloat rd) CONST_FUNC
Definition OOVoxel.m:101
#define CUBE_FACE_FRONT
Definition OOVoxel.h:33
#define CUBE_FACE_LEFT
Definition OOVoxel.h:30
#define CUBE_FACE_RIGHT
Definition OOVoxel.h:29
#define CUBE_FACE_TOP
Definition OOVoxel.h:31
int lineCubeIntersection(Vector v0, Vector v1, GLfloat rd) CONST_FUNC
Definition OOVoxel.m:164
#define CUBE_FACE_BOTTOM
Definition OOVoxel.h:32
#define CUBE_FACE_BACK
Definition OOVoxel.h:34
@ kMaxOctreeDepth
Definition Octree.h:82
static GLfloat hit_dist
Definition Octree.m:346
static const int change_oct[]
Definition Octree.m:70
@ kMinimumBuilderCapacity
Definition Octree.m:737
static BOOL isHitByLine(const int *octbuffer, unsigned char *collbuffer, int level, GLfloat rad, Vector v0, Vector v1, Vector off, int face_hit)
#define OctreeDebugLog(...)
Definition Octree.m:42
static GLfloat volumeOfOctree(Octree_details octree_details, unsigned depthLimit)
static BOOL isHitByOctree(Octree_details axialDetails, Octree_details otherDetails, Vector delta, Triangle other_ijk)
static BOOL hasCollided
Definition Octree.m:345
static Vector randomFullNodeFrom(Octree_details details, Vector offset)
Octree_details octreeDetails()
Definition Octree.m:142
static void SetNode_slow(OOOctreeBuilder *self, uint32_t index, int value) NO_INLINE_FUNC
Definition Octree.m:881
void writeSolid()
Definition Octree.m:818
uint8_t _level
Definition Octree.h:93
uint32_t _capacity
Definition Octree.h:88
OOINLINE struct OOOctreeBuildState * State(OOOctreeBuilder *self)
Definition Octree.m:743
void beginInnerNode()
Definition Octree.m:828
BOOL suppressClangStuff()
Definition Octree.m:900
void endInnerNode()
Definition Octree.m:851
OOINLINE void InsertNode(OOOctreeBuilder *self, int value)
Definition Octree.m:760
uint32_t _nodeCount
Definition Octree.h:88
struct OOOctreeBuilder::OOOctreeBuildState _stateStack[kMaxOctreeDepth+1]
void writeEmpty()
Definition Octree.m:823
OOINLINE void SetNode(OOOctreeBuilder *self, uint32_t index, int value)
Definition Octree.m:750
int * _octree
Definition Octree.h:87
id init()
Definition Octree.m:80
unsigned char * _collisionOctree
Definition Octree.h:44
Octree_details octreeDetails()
Definition Octree.m:142
void setHasCollision:(BOOL value)
Definition Octree.m:137
static BOOL isHitByLine(const int *octbuffer, unsigned char *collbuffer, int level, GLfloat rad, Vector v0, Vector v1, Vector off, int face_hit)
Definition Octree.m:347
GLfloat _radius
Definition Octree.h:39
const int * _octree
Definition Octree.h:41
uint32_t _nodeCount
Definition Octree.h:40
NSDictionary * dictionaryRepresentation()
Definition Octree.m:626
static BOOL isHitByOctree(Octree_details axialDetails, Octree_details otherDetails, Vector otherPosition, Triangle other_ijk)
Definition Octree.m:473
GLfloat volume()
Definition Octree.m:669
Vector randomPoint()
Definition Octree.m:716
static BOOL isHitByLineSub(const int *octbuffer, unsigned char *collbuffer, int nextLevel, GLfloat rad, GLfloat rd2, Vector v0, Vector v1, int octantMask)
Definition Octree.m:336
static Vector randomFullNodeFrom(Octree_details details, Vector offset)
Definition Octree.m:683
BOOL _hasCollision
Definition Octree.h:42
NSData * _data
Definition Octree.h:46
static GLfloat volumeOfOctree(Octree_details octree_details, unsigned depthLimit)
Definition Octree.m:634
void dealloc()
Definition Octree.m:124
id initWithData:radius:(NSData *data, [radius] GLfloat radius)
Definition Octree.m:89
BOOL hasCollision()
Definition Octree.m:132
static Vector offsetForOctant(int oct, GLfloat r)
Definition Octree.m:158
voidpf uLong offset
Definition ioapi.h:132
unsigned Ranrot(void)
unsigned char * octree_collision
Definition Octree.m:51
GLfloat radius
Definition Octree.m:49
const int * octree
Definition Octree.m:50
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34