Oolite
Loading...
Searching...
No Matches
Universe.m
Go to the documentation of this file.
1/*
2
3Universe.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 "Universe.h"
26#import "AI.h"
27#import "GameController.h"
28#import "GuiDisplayGen.h"
29#import "HeadUpDisplay.h"
30#import "MyOpenGLView.h"
31#import "OOCPUInfo.h"
32#import "OOCacheManager.h"
34#import "OOColor.h"
35#import "OOConstToJSString.h"
36#import "OOConstToString.h"
37#import "OODebugSupport.h"
38#import "OOMaterial.h"
41#import "OORoleSet.h"
42#import "OOShipGroup.h"
43#import "OOSound.h"
44#import "OOStringExpander.h"
45#import "OOStringParsing.h"
46#import "OOTexture.h"
47#import "ResourceManager.h"
48
49#import "CollisionRegion.h"
50#import "OODebugSupport.h"
53#import "Octree.h"
54
55#import "OOCharacter.h"
56#import "OOEquipmentType.h"
57#import "OOProbabilitySet.h"
59#import "OOShipRegistry.h"
60
61#import "DockEntity.h"
62#import "DustEntity.h"
65#import "OODebugFlags.h"
66#import "OODebugStandards.h"
69#import "OOJSEngineTimeManagement.h"
70#import "OOJSFrameCallbacks.h"
71#import "OOJSPopulatorDefinition.h"
72#import "OOJSScript.h"
73#import "OOJoystickManager.h"
75#import "OOLoggingExtended.h"
76#import "OOMusicController.h"
77#import "OOOpenGL.h"
78#import "OOPlanetEntity.h"
80#import "OOScriptTimer.h"
81#import "OOShaderProgram.h"
82#import "OOSunEntity.h"
85#import "OOWaypointEntity.h"
86#import "PlayerEntity.h"
90#import "ProxyPlayerEntity.h"
91#import "ShipEntityAI.h"
92#import "SkyEntity.h"
93#import "StationEntity.h"
94#import "WormholeEntity.h"
95
96#if OO_LOCALIZATION_TOOLS
98#endif
99
100enum {
104};
105
106#define DEMO2_VANISHING_DISTANCE 650.0
107#define DEMO2_FLY_IN_STAGE_TIME 0.4
108
109#define MAX_NUMBER_OF_ENTITIES 200
110#define STANDARD_STATION_ROLL 0.4
111// currently twice scanner radius
112#define LANE_WIDTH 51200.0
113
114static NSString* const kOOLogUniversePopulateError = @"universe.populate.error";
115static NSString* const kOOLogUniversePopulateWitchspace = @"universe.populate.witchspace";
116static NSString* const kOOLogEntityVerificationError = @"entity.linkedList.verify.error";
117static NSString* const kOOLogEntityVerificationRebuild = @"entity.linkedList.verify.rebuild";
118
119const GLfloat framebufferQuadVertices[] = {
120 // positions // texture coords
121 1.0f, 1.0f, 1.0f, 1.0f, // top right
122 1.0f, -1.0f, 1.0f, 0.0f, // bottom right
123 -1.0f, -1.0f, 0.0f, 0.0f, // bottom left
124 -1.0f, 1.0f, 0.0f, 1.0f // top left
125};
126const GLuint framebufferQuadIndices[] = {
127 0, 1, 3, // first triangle
128 1, 2, 3 // second triangle
129};
130
132
135
137OOINLINE BOOL EntityInRange(HPVector p1, Entity* e2, float range);
138
139static OOComparisonResult compareName(id dict1, id dict2, void* context);
140static OOComparisonResult comparePrice(id dict1, id dict2, void* context);
141
142/* TODO: route calculation is really slow - find a way to safely enable this */
143#undef CACHE_ROUTE_FROM_SYSTEM_RESULTS
144
145@interface RouteElement : NSObject {
146@private
150}
151
152+ (instancetype)elementWithLocation:(OOSystemID)location parent:(OOSystemID)parent cost:(double)cost distance:(double)distance time:(double)time jumps:(int)jumps;
153- (OOSystemID)parent;
154- (OOSystemID)location;
155- (double)cost;
156- (double)distance;
157- (double)time;
158- (int)jumps;
159
160@end
161
162@implementation RouteElement
163
164+ (instancetype)elementWithLocation:(OOSystemID)location parent:(OOSystemID)parent cost:(double)cost distance:(double)distance time:(double)time jumps:(int)jumps
165{
166 RouteElement* r = [[RouteElement alloc] init];
167
168 r->_location = location;
169 r->_parent = parent;
170 r->_cost = cost;
171 r->_distance = distance;
172 r->_time = time;
173 r->_jumps = jumps;
174
175 return [r autorelease];
176}
177
179{
180 return _parent;
181}
183{
184 return _location;
185}
186- (double)cost
187{
188 return _cost;
189}
190- (double)distance
191{
192 return _distance;
193}
194- (double)time
195{
196 return _time;
197}
199{
200 return _jumps;
201}
202
203@end
204
205@interface Universe (OOPrivate)
206
207- (void)initTargetFramebufferWithViewSize:(NSSize)viewSize;
208- (void)deleteOpenGLObjects;
209- (void)resizeTargetFramebufferWithViewSize:(NSSize)viewSize;
212
213- (BOOL)doRemoveEntity:(Entity*)entity;
214- (void)setUpCargoPods;
216- (HPVector)fractionalPositionFrom:(HPVector)point0 to:(HPVector)point1 withFraction:(double)routeFraction;
217
219
220- (NSString*)chooseStringForKey:(NSString*)key inDictionary:(NSDictionary*)dictionary;
221
222#if OO_LOCALIZATION_TOOLS
223#if DEBUG_GRAPHVIZ
224- (void)dumpDebugGraphViz;
225- (void)dumpSystemDescriptionGraphViz;
226#endif
227- (void)addNumericRefsInString:(NSString*)string toGraphViz:(NSMutableString*)graphViz fromNode:(NSString*)fromNode nodeCount:(NSUInteger)nodeCount;
228
234#endif
235
236#if NEW_PLANETS
237- (void)prunePreloadingPlanetMaterials;
238#endif
239
240// Set shader effects level without logging or triggering a reset -- should only be used directly during startup.
241- (void)setShaderEffectsLevelDirectly:(OOShaderSetting)value;
242
243- (void)setFirstBeacon:(Entity<OOBeaconEntity>*)beacon;
244- (void)setLastBeacon:(Entity<OOBeaconEntity>*)beacon;
245
246- (void)verifyDescriptions;
247- (void)loadDescriptions;
248- (void)loadScenarios;
249
252- (Vector)randomPlaceWithinScannerFrom:(Vector)pos alongRoute:(Vector)route withOffset:(double)offset;
253
254- (void)setDetailLevelDirectly:(OOGraphicsDetail)value;
255
256- (NSDictionary*)demoShipData;
258
259@end
260
261@implementation Universe
262
263// Flags needed when JS reset fails.
264static int JSResetFlags = 0;
265
266// track the position and status of the lights
267static BOOL object_light_on = NO;
268static BOOL demo_light_on = NO;
269static GLfloat sun_off[4] = { 0.0, 0.0, 0.0, 1.0 };
270static GLfloat demo_light_position[4] = { DEMO_LIGHT_POSITION, 1.0 };
271
272#define DOCKED_AMBIENT_LEVEL 0.2f // Was 0.05, 'temporarily' set to 0.2.
273#define DOCKED_ILLUM_LEVEL 0.7f
276static GLfloat docked_light_specular[4] = { DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL, DOCKED_ILLUM_LEVEL * 0.75f, (GLfloat)1.0f }; // yellow-white
277
278// Weight of sun in ambient light calculation. 1.0 means only sun's diffuse is used for ambient, 0.0 means only sky colour is used.
279// TODO: considering the size of the sun and the number of background stars might be worthwhile. -- Ahruman 20080322
280#define SUN_AMBIENT_INFLUENCE 0.75
281// How dark the default ambient level of 1.0 will be
282#define SKY_AMBIENT_ADJUSTMENT 0.0625
283
284- (BOOL)bloom
285{
286 return _bloom && [self detailLevel] >= DETAIL_LEVEL_EXTRAS;
287}
288
289- (void)setBloom:(BOOL)newBloom
290{
291 _bloom = !!newBloom;
292}
293
295{
296 return _currentPostFX;
297}
298
299- (void)setCurrentPostFX:(int)newCurrentPostFX
300{
301 if (newCurrentPostFX < 1 || newCurrentPostFX > OO_POSTFX_ENDOFLIST - 1) {
302 newCurrentPostFX = OO_POSTFX_NONE;
303 }
304
305 if (OO_POSTFX_NONE <= newCurrentPostFX && newCurrentPostFX <= OO_POSTFX_COLORBLINDNESS_TRITAN) {
306 _colorblindMode = newCurrentPostFX;
307 }
308
309 _currentPostFX = newCurrentPostFX;
310}
311
312- (void)terminatePostFX:(int)postFX
313{
314 if ([self currentPostFX] == postFX) {
315 [self setCurrentPostFX:[self colorblindMode]];
316 }
317}
318
319- (int)nextColorblindMode:(int)index
320{
322 index = OO_POSTFX_NONE;
323
324 return index;
325}
326
327- (int)prevColorblindMode:(int)index
328{
329 if (--index < OO_POSTFX_NONE)
331
332 return index;
333}
334
336{
337 return _colorblindMode;
338}
339
340- (void)initTargetFramebufferWithViewSize:(NSSize)viewSize
341{
342 // liberate us from the 0.0 to 1.0 rgb range!
343 OOGL(glClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE));
344 OOGL(glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE));
345 OOGL(glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE));
346
347 // have to do this because on my machine the default framebuffer is not zero
348 OOGL(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &defaultDrawFBO));
349
350 GLint previousProgramID;
351 OOGL(glGetIntegerv(GL_CURRENT_PROGRAM, &previousProgramID));
352 GLint previousTextureID;
353 OOGL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previousTextureID));
354 GLint previousVAO;
355 OOGL(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &previousVAO));
356 GLint previousArrayBuffer;
357 OOGL(glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &previousArrayBuffer));
358 GLint previousElementBuffer;
359 OOGL(glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &previousElementBuffer));
360
361 // create MSAA framebuffer and attach MSAA texture and depth buffer to framebuffer
362 OOGL(glGenFramebuffers(1, &msaaFramebufferID));
363 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebufferID));
364
365 // creating MSAA texture that should be rendered into
366#if OO_MSAA_COLOR_RENDERBUFFER
367 // No multisample textures in the macOS legacy context; a multisample renderbuffer resolves the same way.
368 OOGL(glGenRenderbuffers(1, &msaaTextureID));
369 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, msaaTextureID));
370 OOGL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
371 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
372 OOGL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaTextureID));
373#else
374 OOGL(glGenTextures(1, &msaaTextureID));
375 OOGL(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msaaTextureID));
376 OOGL(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, GL_TRUE));
377 OOGL(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0));
378 OOGL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, msaaTextureID, 0));
379#endif
380
381 // create necessary MSAA depth render buffer
382 OOGL(glGenRenderbuffers(1, &msaaDepthBufferID));
383 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, msaaDepthBufferID));
384 OOGL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT32F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
385 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
386 OOGL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, msaaDepthBufferID));
387
388 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
389 OOLogERR(@"initTargetFramebufferWithViewSize.result", @"%@", @"***** Error: Multisample framebuffer not complete");
390 }
391
392 // create framebuffer and attach texture and depth buffer to framebuffer
393 OOGL(glGenFramebuffers(1, &targetFramebufferID));
394 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, targetFramebufferID));
395
396 // creating texture that should be rendered into
397 OOGL(glGenTextures(1, &targetTextureID));
398 OOGL(glBindTexture(GL_TEXTURE_2D, targetTextureID));
399 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
400 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
401 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
402 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
403 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
404 OOGL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, targetTextureID, 0));
405
406 // create necessary depth render buffer
407 OOGL(glGenRenderbuffers(1, &targetDepthBufferID));
408 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, targetDepthBufferID));
409 OOGL(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
410 OOGL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, targetDepthBufferID));
411
412 GLenum attachment[1] = { GL_COLOR_ATTACHMENT0 };
413 OOGL(glDrawBuffers(1, attachment));
414
415 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
416 OOLogERR(@"initTargetFramebufferWithViewSize.result", @"%@", @"***** Error: Framebuffer not complete");
417 }
418
419 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
420
421 targetFramebufferSize = viewSize;
422
423 // passthrough buffer
424 // This is a framebuffer whose sole purpose is to pass on the texture rendered from the game to the blur and the final bloom
425 // shaders. We need it in order to be able to use the OpenGL 3.3 layout (location = x) out vec4 outVector; construct, which allows
426 // us to perform multiple render target operations needed for bloom. The alternative would be to not use this and change all our
427 // shaders to be OpenGL 3.3 compatible, but given how Oolite synthesizes them and the work needed to port them over, well yeah no,
428 // not doing it at this time - Nikos 20220814.
429 OOGL(glGenFramebuffers(1, &passthroughFramebufferID));
430 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, passthroughFramebufferID));
431
432 // creating textures that should be rendered into
433 OOGL(glGenTextures(2, passthroughTextureID));
434 for (unsigned int i = 0; i < 2; i++) {
435 OOGL(glBindTexture(GL_TEXTURE_2D, passthroughTextureID[i]));
436 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
437 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
438 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
439 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
440 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
441 OOGL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, passthroughTextureID[i], 0));
442 }
443
444 GLenum attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
445 OOGL(glDrawBuffers(2, attachments));
446
447 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
448 OOLogERR(@"initTargetFramebufferWithViewSize.result", @"%@", @"***** Error: Passthrough framebuffer not complete");
449 }
450 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
451
452 // ping-pong-framebuffer for blurring
453 OOGL(glGenFramebuffers(2, pingpongFBO));
454 OOGL(glGenTextures(2, pingpongColorbuffers));
455 for (unsigned int i = 0; i < 2; i++) {
456 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i]));
457 OOGL(glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[i]));
458 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
459 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
460 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
461 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); // we clamp to the edge as the blur filter would otherwise sample repeated texture values!
462 OOGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
463 OOGL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pingpongColorbuffers[i], 0));
464 // check if framebuffers are complete (no need for depth buffer)
465 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
466 OOLogERR(@"initTargetFramebufferWithViewSize.result", @"%@", @"***** Error: Pingpong framebuffers not complete");
467 }
468 }
469 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
470
471 _bloom = [self detailLevel] >= DETAIL_LEVEL_EXTRAS;
472 _currentPostFX = _colorblindMode = OO_POSTFX_NONE;
473
474 /* TODO: in OOEnvironmentCubeMap.m call these bind functions not with 0 but with "previousXxxID"s:
475 - OOGL(glBindTexture(GL_TEXTURE_CUBE_MAP, 0));
476 - OOGL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
477 - OOGL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0));
478 */
479
480 // shader for drawing a textured quad on the passthrough framebuffer and preparing it for bloom using MRT
481 if (![[OOOpenGLExtensionManager sharedManager] shadersForceDisabled]) {
482 textureProgram = [[OOShaderProgram shaderProgramWithVertexShaderName:@"oolite-texture.vertex"
483 fragmentShaderName:@"oolite-texture.fragment"
484 prefix:@"#version 330\n"
485 attributeBindings:[NSDictionary dictionary]] retain];
486 // shader for blurring the over-threshold brightness image generated from the previous step using Gaussian filter
487 blurProgram = [[OOShaderProgram shaderProgramWithVertexShaderName:@"oolite-blur.vertex"
488 fragmentShaderName:@"oolite-blur.fragment"
489 prefix:@"#version 330\n"
490 attributeBindings:[NSDictionary dictionary]] retain];
491 // shader for applying bloom and any necessary post-proc fx, tonemapping and gamma correction
492 finalProgram = [[OOShaderProgram shaderProgramWithVertexShaderName:@"oolite-final.vertex"
493#if OOLITE_WINDOWS
494 fragmentShaderName:[[UNIVERSE gameView] hdrOutput] ? @"oolite-final-hdr.fragment" : @"oolite-final.fragment"
495#else
496 fragmentShaderName:@"oolite-final.fragment"
497#endif
498 prefix:@"#version 330\n"
499 attributeBindings:[NSDictionary dictionary]] retain];
500 }
501
502 OOGL(glGenVertexArrays(1, &quadTextureVAO));
503 OOGL(glGenBuffers(1, &quadTextureVBO));
504 OOGL(glGenBuffers(1, &quadTextureEBO));
505
506 OOGL(glBindVertexArray(quadTextureVAO));
507
508 OOGL(glBindBuffer(GL_ARRAY_BUFFER, quadTextureVBO));
509 OOGL(glBufferData(GL_ARRAY_BUFFER, sizeof(framebufferQuadVertices), framebufferQuadVertices, GL_STATIC_DRAW));
510
511 OOGL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quadTextureEBO));
512 OOGL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(framebufferQuadIndices), framebufferQuadIndices, GL_STATIC_DRAW));
513
514 OOGL(glEnableVertexAttribArray(0));
515 // position attribute
516 OOGL(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0));
517 OOGL(glEnableVertexAttribArray(1));
518 // texture coord attribute
519 OOGL(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))));
520
521 // restoring previous bindings
522 OOGL(glUseProgram(previousProgramID));
523 OOGL(glBindTexture(GL_TEXTURE_2D, previousTextureID));
524 OOGL(glBindVertexArray(previousVAO));
525 OOGL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, previousElementBuffer));
526 OOGL(glBindBuffer(GL_ARRAY_BUFFER, previousArrayBuffer));
527}
528
530{
531#if OO_MSAA_COLOR_RENDERBUFFER
532 OOGL(glDeleteRenderbuffers(1, &msaaTextureID));
533#else
534 OOGL(glDeleteTextures(1, &msaaTextureID));
535#endif
536 OOGL(glDeleteTextures(1, &targetTextureID));
537 OOGL(glDeleteTextures(2, passthroughTextureID));
538 OOGL(glDeleteTextures(2, pingpongColorbuffers));
539 OOGL(glDeleteRenderbuffers(1, &msaaDepthBufferID));
540 OOGL(glDeleteRenderbuffers(1, &targetDepthBufferID));
541 OOGL(glDeleteFramebuffers(1, &msaaFramebufferID));
542 OOGL(glDeleteFramebuffers(1, &targetFramebufferID));
543 OOGL(glDeleteFramebuffers(2, pingpongFBO));
544 OOGL(glDeleteFramebuffers(1, &passthroughFramebufferID));
545 OOGL(glDeleteVertexArrays(1, &quadTextureVAO));
546 OOGL(glDeleteBuffers(1, &quadTextureVBO));
547 OOGL(glDeleteBuffers(1, &quadTextureEBO));
548 [textureProgram release];
549 [blurProgram release];
550 [finalProgram release];
551}
552
553- (void)resizeTargetFramebufferWithViewSize:(NSSize)viewSize
554{
555 int i;
556 // resize MSAA color attachment
557#if OO_MSAA_COLOR_RENDERBUFFER
558 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, msaaTextureID));
559 OOGL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
560 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
561#else
562 OOGL(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msaaTextureID));
563 OOGL(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, GL_TRUE));
564 OOGL(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0));
565#endif
566
567 // resize MSAA depth attachment
568 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, msaaDepthBufferID));
569 OOGL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT32F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
570 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
571
572 // resize color attachments
573 OOGL(glBindTexture(GL_TEXTURE_2D, targetTextureID));
574 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
575 OOGL(glBindTexture(GL_TEXTURE_2D, 0));
576
577 for (i = 0; i < 2; i++) {
578 OOGL(glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[i]));
579 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
580 OOGL(glBindTexture(GL_TEXTURE_2D, 0));
581 }
582
583 for (i = 0; i < 2; i++) {
584 OOGL(glBindTexture(GL_TEXTURE_2D, passthroughTextureID[i]));
585 OOGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, (GLsizei)viewSize.width, (GLsizei)viewSize.height, 0, GL_RGBA, GL_FLOAT, NULL));
586 OOGL(glBindTexture(GL_TEXTURE_2D, 0));
587 }
588
589 // resize depth attachment
590 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, targetDepthBufferID));
591 OOGL(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, (GLsizei)viewSize.width, (GLsizei)viewSize.height));
592 OOGL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
593
594 targetFramebufferSize.width = viewSize.width;
595 targetFramebufferSize.height = viewSize.height;
596}
597
599{
600 // save previous bindings state
601 GLint previousFBO;
602 OOGL(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previousFBO));
603 GLint previousProgramID;
604 OOGL(glGetIntegerv(GL_CURRENT_PROGRAM, &previousProgramID));
605 GLint previousTextureID;
606 OOGL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previousTextureID));
607 GLint previousVAO;
608 OOGL(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &previousVAO));
609 GLint previousActiveTexture;
610 OOGL(glGetIntegerv(GL_ACTIVE_TEXTURE, &previousActiveTexture));
611
612 OOGL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
613 // fixes transparency issue for some reason
614 OOGL(glDisable(GL_BLEND));
615
616 GLuint program = OOGLProgramName([textureProgram program]);
617 GLuint blur = OOGLProgramName([blurProgram program]);
618 GLuint final = OOGLProgramName([finalProgram program]);
619 NSSize viewSize = [gameView backingViewSize];
620 float fboResolution[2] = { viewSize.width, viewSize.height };
621
622 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, passthroughFramebufferID));
623 OOGL(glClear(GL_COLOR_BUFFER_BIT));
624
625 OOGL(glUseProgram(program));
626 OOGL(glBindTexture(GL_TEXTURE_2D, targetTextureID));
627 OOGL(glUniform1i(glGetUniformLocation(program, "image"), 0));
628
629 OOGL(glBindVertexArray(quadTextureVAO));
630 OOGL(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0));
631 OOGL(glBindVertexArray(0));
632
633 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
634
635 BOOL horizontal = YES, firstIteration = YES;
636 unsigned int amount = [self bloom] ? 10 : 0; // if not blooming, why bother with the heavy calculations?
637 OOGL(glUseProgram(blur));
638 for (unsigned int i = 0; i < amount; i++) {
639 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[horizontal]));
640 OOGL(glUniform1i(glGetUniformLocation(blur, "horizontal"), horizontal));
641 OOGL(glActiveTexture(GL_TEXTURE0));
642 // bind texture of other framebuffer (or scene if first iteration)
643 OOGL(glBindTexture(GL_TEXTURE_2D, firstIteration ? passthroughTextureID[1] : pingpongColorbuffers[!horizontal]));
644 OOGL(glUniform1i(glGetUniformLocation(blur, "imageIn"), 0));
645 OOGL(glBindVertexArray(quadTextureVAO));
646 OOGL(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0));
647 OOGL(glBindVertexArray(0));
648 horizontal = !horizontal;
649 firstIteration = NO;
650 }
651 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
652
653 OOGL(glUseProgram(final));
654
655 OOGL(glActiveTexture(GL_TEXTURE0));
656 OOGL(glBindTexture(GL_TEXTURE_2D, passthroughTextureID[0]));
657 OOGL(glUniform1i(glGetUniformLocation(final, "scene"), 0));
658 OOGL(glUniform1i(glGetUniformLocation(final, "bloom"), [self bloom]));
659 OOGL(glUniform1f(glGetUniformLocation(final, "uTime"), [self getTime]));
660 OOGL(glUniform2fv(glGetUniformLocation(final, "uResolution"), 1, fboResolution));
661 OOGL(glUniform1i(glGetUniformLocation(final, "uPostFX"), [self currentPostFX]));
662#if OOLITE_WINDOWS
663 if ([gameView hdrOutput]) {
664 OOGL(glUniform1f(glGetUniformLocation(final, "uMaxBrightness"), [gameView hdrMaxBrightness]));
665 OOGL(glUniform1f(glGetUniformLocation(final, "uPaperWhiteBrightness"), [gameView hdrPaperWhiteBrightness]));
666 OOGL(glUniform1i(glGetUniformLocation(final, "uHDRToneMapper"), [gameView hdrToneMapper]));
667 }
668#endif
669 OOGL(glUniform1i(glGetUniformLocation(final, "uSDRToneMapper"), [gameView sdrToneMapper]));
670
671 OOGL(glActiveTexture(GL_TEXTURE1));
672 OOGL(glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[!horizontal]));
673 OOGL(glUniform1i(glGetUniformLocation(final, "bloomBlur"), 1));
674 OOGL(glUniform1f(glGetUniformLocation(final, "uSaturation"), [gameView colorSaturation]));
675
676 OOGL(glBindVertexArray(quadTextureVAO));
677 OOGL(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0));
678
679 // restore GL_TEXTURE1 to 0, just in case we are returning from a
680 // DETAIL_LEVEL_NORMAL to DETAIL_LEVEL_SHADERS
681 OOGL(glBindTexture(GL_TEXTURE_2D, 0));
682
683 // restore previous bindings
684 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, previousFBO));
685 OOGL(glActiveTexture(previousActiveTexture));
686 OOGL(glBindTexture(GL_TEXTURE_2D, previousTextureID));
687 OOGL(glUseProgram(previousProgramID));
688 OOGL(glBindVertexArray(previousVAO));
689 OOGL(glEnable(GL_BLEND));
690}
691
692- (id)initWithGameView:(MyOpenGLView*)inGameView
693{
694 if (gSharedUniverse != nil) {
695 [self release];
696 [NSException raise:NSInternalInconsistencyException format:@"%s: expected only one Universe to exist at a time.", __PRETTY_FUNCTION__];
697 }
698
699 OO_DEBUG_PROGRESS(@"%@", @"Universe initWithGameView:");
700
701 self = [super init];
702 if (self == nil)
703 return nil;
704
705 _doingStartUp = YES;
706
707 OOInitReallyRandom([NSDate timeIntervalSinceReferenceDate] * 1e9);
708
709 NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
710
711 // prefs value no longer used - per save game but startup needs to
712 // be non-strict
713 useAddOns = [[NSString alloc] initWithString:SCENARIO_OXP_DEFINITION_ALL];
714
715 [self setGameView:inGameView];
716 gSharedUniverse = self;
717
718 allPlanets = [[NSMutableArray alloc] init];
719 allStations = [[NSMutableSet alloc] init];
720
723
724 // init OpenGL extension manager (must be done before any other threads might use it)
726 [self setDetailLevelDirectly:[prefs oo_intForKey:@"detailLevel"
728
730
732
733 // Preload cache
735
736#if OOLITE_SPEECH_SYNTH
737 OOLog(@"speech.synthesis", @"Spoken messages are %@.", ([prefs oo_boolForKey:@"speech_on" defaultValue:NO] ? @"on" : @"off"));
738#endif
739
740 // init the Resource Manager
741 [ResourceManager setUseAddOns:useAddOns]; // also logs the paths if changed
742
743 // Set up the internal game strings
744 [self loadDescriptions];
745 // DESC expansion is now possible!
746
747 // load starting saves
748 [self loadScenarios];
749
750 autoSave = [prefs oo_boolForKey:@"autosave" defaultValue:NO];
751 wireframeGraphics = [prefs oo_boolForKey:@"wireframe-graphics" defaultValue:NO];
752 doProcedurallyTexturedPlanets = [prefs oo_boolForKey:@"procedurally-textured-planets" defaultValue:YES];
753 [inGameView setMsaa:[prefs oo_boolForKey:@"anti-aliasing" defaultValue:NO]];
754 OOLog(@"MSAA.setup", @"Multisample anti-aliasing %@requested.", [inGameView msaa] ? @"" : @"not ");
755 [inGameView setFov:OOClamp_0_max_f([prefs oo_floatForKey:@"fov-value" defaultValue:57.2f], MAX_FOV_DEG) fromFraction:NO];
756 if ([inGameView fov:NO] < MIN_FOV_DEG)
757 [inGameView setFov:MIN_FOV_DEG fromFraction:NO];
758
759 [self setECMVisualFXEnabled:[prefs oo_boolForKey:@"ecm-visual-fx" defaultValue:YES]];
760
761 // Set up speech synthesizer.
762#if OOLITE_SPEECH_SYNTH
763#if OOLITE_MAC_COCOA_UI
764 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
765 ^{
766 /*
767 NSSpeechSynthesizer can take over a second on an SSD and several
768 seconds on an HDD for a cold start, and a third of a second upward
769 for a warm start. There are no particular thread safety consider-
770 ations documented for NSSpeechSynthesizer, so I'm assuming the
771 default one-thread-at-a-time access rule applies.
772 -- Ahruman 2012-09-13
773 */
774 OOLog(@"speech.setup.begin", @"Starting to set up speech synthesizer.");
775 NSSpeechSynthesizer* synth = [[NSSpeechSynthesizer alloc] init];
776 OOLog(@"speech.setup.end", @"Finished setting up speech synthesizer.");
777 speechSynthesizer = synth;
778 });
779#elif OOLITE_ESPEAK
780 int volume = [OOSound masterVolume] * 100;
781 espeak_SetParameter(espeakPUNCTUATION, espeakPUNCT_NONE, 0);
782 espeak_SetParameter(espeakVOLUME, volume, 0);
783 espeak_voices = espeak_ListVoices(NULL);
784 for (espeak_voice_count = 0;
785 espeak_voices[espeak_voice_count];
786 ++espeak_voice_count)
787 /**/;
788#endif
789#endif
790
791 [[GameController sharedController] logProgress:DESC(@"loading-ships")];
792 // Load ship data
793
795
796 entities = [[NSMutableArray arrayWithCapacity:MAX_NUMBER_OF_ENTITIES] retain];
797
798 [[GameController sharedController] logProgress:OOExpandKeyRandomized(@"loading-miscellany")];
799
800 // this MUST have the default no. of rows else the GUI_ROW macros in PlayerEntity.h need modification
801 gui = [[GuiDisplayGen alloc] init]; // alloc retains
802 comm_log_gui = [[GuiDisplayGen alloc] init]; // alloc retains
803
804 missiontext = [[ResourceManager dictionaryFromFilesNamed:@"missiontext.plist" inFolder:@"Config" andMerge:YES] retain];
805
806 waypoints = [[NSMutableDictionary alloc] init];
807
808 [self setUpSettings];
809
810 // can't do this here as it might lock an OXZ open
811 // [self preloadSounds]; // Must be after setUpSettings.
812
813 // Preload particle effect textures:
816
817 // set up cargopod templates
818 [self setUpCargoPods];
819
822 [self addEntity:player];
823
824 [player setStatus:STATUS_START_GAME];
826
828
829 universeRegion = [[CollisionRegion alloc] initAsUniverse];
830 entitiesDeadThisUpdate = [[NSMutableSet alloc] init];
832 drawCounter = 0;
833
834 [[GameController sharedController] logProgress:DESC(@"initializing-debug-support")];
836
837 [[GameController sharedController] logProgress:DESC(@"running-scripts")];
839
840 [[GameController sharedController] logProgress:DESC(@"populating-space")];
841 [self populateNormalSpace];
842
843 [[GameController sharedController] logProgress:OOExpandKeyRandomized(@"loading-miscellany")];
844
845#if OO_LOCALIZATION_TOOLS
847#if DEBUG_GRAPHVIZ
848 [self dumpDebugGraphViz];
849#endif
850#endif
851
853 _doingStartUp = NO;
854
855 return self;
856}
857
858- (void)dealloc
859{
861
862 [currentMessage release];
863
864 [gui release];
865 [message_gui release];
866 [comm_log_gui release];
867
868 [entities release];
869
870 [commodities release];
871
872 [_descriptions release];
873 [characters release];
874 [customSounds release];
875 [globalSettings release];
876 [systemManager release];
877 [missiontext release];
878 [equipmentData release];
879 [equipmentDataOutfitting release];
880 [demo_ships release];
881 [autoAIMap release];
882 [screenBackgrounds release];
883 [gameView release];
884 [populatorSettings release];
885 [system_repopulator release];
886 [allPlanets release];
887 [allStations release];
888 [explosionSettings release];
889
890 [activeWormholes release];
891 [characterPool release];
892 [universeRegion release];
893 [cargoPods release];
894
898
899 unsigned i;
900 for (i = 0; i < 256; i++)
901 [system_names[i] release];
902
903 [entitiesDeadThisUpdate release];
904
906
907#if OOLITE_SPEECH_SYNTH
908 [speechArray release];
909#if OOLITE_MAC_COCOA_UI
910 [speechSynthesizer release];
911#elif OOLITE_ESPEAK
912 espeak_Cancel();
913#endif
914#endif
915 [conditionScripts release];
916
917 [self deleteOpenGLObjects];
918
919 [super dealloc];
920}
921
922- (NSUInteger)sessionID
923{
924 return _sessionID;
925}
926
928{
929 return _doingStartUp;
930}
931
936
937- (void)setDoProcedurallyTexturedPlanets:(BOOL)value
938{
939 doProcedurallyTexturedPlanets = !!value; // ensure yes or no
940 [[NSUserDefaults standardUserDefaults] setBool:doProcedurallyTexturedPlanets forKey:@"procedurally-textured-planets"];
941}
942
943- (NSString*)useAddOns
944{
945 return useAddOns;
946}
947
948- (BOOL)setUseAddOns:(NSString*)newUse fromSaveGame:(BOOL)saveGame
949{
950 return [self setUseAddOns:newUse fromSaveGame:saveGame forceReinit:NO];
951}
952
953- (BOOL)setUseAddOns:(NSString*)newUse fromSaveGame:(BOOL)saveGame forceReinit:(BOOL)force
954{
955 if (!force && [newUse isEqualToString:useAddOns]) {
956 return YES;
957 }
959 useAddOns = [newUse retain];
960
961 return [self reinitAndShowDemo:!saveGame];
962}
963
964- (NSUInteger)entityCount
965{
966 return [entities count];
967}
968
969#ifdef OO_DEBUG_MONITOR_ENABLED
970- (void)debugDumpEntities
971{
972 int i;
973 int show_count = n_entities;
974
975 if (!OOLogWillDisplayMessagesInClass(@"universe.objectDump"))
976 return;
977
978 OOLog(@"universe.objectDump", @"DEBUG: Entity Dump - [entities count] = %zu,\tn_entities = %u", [entities count], n_entities);
979
980 OOLogIndent();
981 for (i = 0; i < show_count; i++) {
982 OOLog(@"universe.objectDump", @"Ent:%4u %@", i, [sortedEntities[i] descriptionForObjDump]);
983 }
984 OOLogOutdent();
985
986 if ([entities count] != n_entities) {
987 OOLog(@"universe.objectDump", @"entities = %@", [entities description]);
988 }
989}
990
991- (NSArray*)entityList
992{
993 return [NSArray arrayWithArray:entities];
994}
995#endif
996
998{
999 // deal with the machine going to sleep, or player pressing 'p'.
1000 PlayerEntity* player = PLAYER;
1001
1002 [self setPauseMessageVisible:NO];
1003 NSString* pauseKey = [PLAYER keyBindingDescription2:@"key_pausebutton"];
1004
1005 if ([player status] == STATUS_DOCKED) {
1006 if ([gui setForegroundTextureKey:@"paused_docked_overlay"]) {
1007 [gui drawGUI:1.0 drawCursor:NO];
1008 } else {
1009 [self setPauseMessageVisible:YES];
1010 [self addMessage:OOExpandKey(@"game-paused-docked", pauseKey) forCount:1.0];
1011 }
1012 } else {
1013 if ([player guiScreen] != GUI_SCREEN_MAIN && [gui setForegroundTextureKey:@"paused_overlay"]) {
1014 [gui drawGUI:1.0 drawCursor:NO];
1015 } else {
1016 [self setPauseMessageVisible:YES];
1017 [self addMessage:OOExpandKey(@"game-paused", pauseKey) forCount:1.0];
1018 }
1019 }
1020
1021 [[self gameController] setGamePaused:YES];
1022}
1023
1025{
1026 OOLog(@"universe.quit", @"%@", @"Quit command received by Universe.");
1027 [[self gameController] exitAppWithContext:@"Universe Request"];
1028}
1029
1030- (void)carryPlayerOn:(StationEntity*)carrier inWormhole:(WormholeEntity*)wormhole
1031{
1032 PlayerEntity* player = PLAYER;
1034
1035 [player setWormhole:wormhole];
1036 [player addScannedWormhole:wormhole];
1037 JSContext* context = OOJSAcquireContext();
1038 [player setJumpCause:@"carried"];
1040 ShipScriptEvent(context, player, "shipWillEnterWitchspace", OOJSValueFromNativeObject(context, [player jumpCause]), OOJSValueFromDouble(context, dest));
1041 OOJSRelinquishContext(context);
1042
1043 [self allShipsDoScriptEvent:OOJSID("playerWillEnterWitchspace") andReactToAIMessage:@"PLAYER WITCHSPACE"];
1044
1045 [player setRandom_factor:(ranrot_rand() & 255)]; // random factor for market values is reset
1046
1047 // misjump on wormhole sets correct travel time if needed
1049 // clear old entities
1051
1052 // should we add wear-and-tear to the player ship if they're not doing
1053 // the jump themselves? Left out for now. - CIM
1054
1055 if (![wormhole withMisjump]) {
1056 [player setSystemID:dest];
1057 [self setSystemTo:dest];
1058
1059 [self setUpSpace];
1060 [self populateNormalSpace];
1061 [player setBounty:([player legalStatus] / 2) withReason:kOOLegalStatusReasonNewSystem];
1062 if ([player random_factor] < 8)
1063 [player erodeReputation]; // every 32 systems or so, dro
1064 } else {
1066
1068
1069 if (randf() < 0.1)
1070 [player erodeReputation]; // once every 10 misjumps - should be much rarer than successful jumps!
1071 }
1072 // which will kick the ship out of the wormhole with the
1073 // player still aboard
1075
1076 // reset atmospherics in case carrier was in atmosphere
1077 [UNIVERSE setSkyColorRed:0.0f // back to black
1078 green:0.0f
1079 blue:0.0f
1080 alpha:0.0f];
1081
1082 [self setWitchspaceBreakPattern:YES];
1083 [player doScriptEvent:OOJSID("shipWillExitWitchspace") withArgument:[player jumpCause]];
1084 [player doScriptEvent:OOJSID("shipExitedWitchspace") withArgument:[player jumpCause]];
1085 [player setWormhole:nil];
1086}
1087
1089{
1090 if (![self sun]) {
1091 // we're in witchspace...
1092
1093 PlayerEntity* player = PLAYER;
1094 StationEntity* dockedStation = [player dockedStation];
1095 NSPoint coords = [player galaxy_coordinates];
1096 // check the nearest system
1098 BOOL interstel = [dockedStation interstellarUndockingAllowed]; // && (s_seed.d != coords.x || s_seed.b != coords.y); - Nikos 20110623: Do we really need the commented out check?
1100
1101 // remove everything except the player and the docked station
1102 if (dockedStation && !interstel) { // jump to the nearest system
1103 [player setSystemID:sys];
1104 closeSystems = nil;
1105 [self setSystemTo:sys];
1106 int index = 0;
1107 while ([entities count] > 2) {
1108 Entity* ent = [entities objectAtIndex:index];
1109 if ((ent != player) && (ent != dockedStation)) {
1110 if (ent->isStation) // clear out queues
1112 [self removeEntity:ent];
1113 } else {
1114 index++; // leave that one alone
1115 }
1116 }
1117 } else {
1118 if (dockedStation == nil)
1119 [self removeAllEntitiesExceptPlayer]; // get rid of witchspace sky etc. if still extant
1120 }
1121
1122 if (!dockedStation || !interstel) {
1123 [self setUpSpace]; // launching from station that jumped from interstellar space to normal space.
1124 [self populateNormalSpace];
1125 if (dockedStation) {
1126 if ([dockedStation maxFlightSpeed] > 0) // we are a carrier: exit near the WitchspaceExitPosition
1127 {
1128 float d1 = [self randomDistanceWithinScanner];
1129 HPVector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG
1130 Quaternion q1;
1131
1133 if (abs((int)d1) < 2750) {
1134 d1 += ((d1 > 0.0) ? 2750.0f : -2750.0f); // no closer than 2750m. Carriers are bigger than player ships.
1135 }
1137 pos.x += v1.x * d1; // randomise exit position
1138 pos.y += v1.y * d1;
1139 pos.z += v1.z * d1;
1140
1142 }
1143 [self setWitchspaceBreakPattern:YES];
1144 [player setJumpCause:@"carried"];
1145 [player doScriptEvent:OOJSID("shipWillExitWitchspace") withArgument:[player jumpCause]];
1146 [player doScriptEvent:OOJSID("shipExitedWitchspace") withArgument:[player jumpCause]];
1147 }
1148 }
1149 }
1150
1151 if (!autoSaveNow)
1152 [self setViewDirection:VIEW_FORWARD];
1153 displayGUI = NO;
1154
1155 // reset atmospherics in case we ejected while we were in the atmophere
1156 [UNIVERSE setSkyColorRed:0.0f // back to black
1157 green:0.0f
1158 blue:0.0f
1159 alpha:0.0f];
1160}
1161
1163{
1164 PlayerEntity* player;
1165
1166 //
1167 // check the player is still around!
1168 //
1169 if ([entities count] == 0) {
1170 /*- the player ship -*/
1171 player = [[PlayerEntity alloc] init]; // alloc retains!
1172
1173 [self addEntity:player];
1174
1175 /*--*/
1176 } else {
1177 player = [PLAYER retain]; // retained here
1178 }
1179
1180 [self setUpSpace];
1181 [self populateNormalSpace];
1182
1184 [player release]; // released here
1185
1186 [self setViewDirection:VIEW_FORWARD];
1187
1188 [comm_log_gui printLongText:[NSString stringWithFormat:@"%@ %@", [self getSystemName:systemID], [player dial_clock_adjusted]]
1189 align:GUI_ALIGN_CENTER
1191 fadeTime:0
1192 key:nil
1193 addToArray:[player commLog]];
1194
1195 displayGUI = NO;
1196}
1197
1199{
1200 PlayerEntity* player;
1201
1202 //
1203 // check the player is still around!
1204 //
1205 if ([entities count] == 0) {
1206 /*- the player ship -*/
1207 player = [[PlayerEntity alloc] init]; // alloc retains!
1208
1209 [self addEntity:player];
1210
1211 /*--*/
1212 } else {
1213 player = [PLAYER retain]; // retained here
1214 }
1215
1216 [self setUpWitchspace];
1217 // ensure that if we got here from a jump within a planet's atmosphere,
1218 // we don't get any residual air friction
1219 [self setAirResistanceFactor:0.0f];
1220
1222 [player release]; // released here
1223
1224 [self setViewDirection:VIEW_FORWARD];
1225
1226 displayGUI = NO;
1227}
1228
1230{
1231 [self setUpWitchspaceBetweenSystem:[PLAYER systemID] andSystem:[PLAYER nextHopTargetSystemID]];
1232}
1233
1234- (void)setUpWitchspaceBetweenSystem:(OOSystemID)s1 andSystem:(OOSystemID)s2
1235{
1236 // new system is hyper-centric : witchspace exit point is origin
1237
1238 Entity* thing;
1239 PlayerEntity* player = PLAYER;
1240 Quaternion randomQ;
1241
1242 NSString* override_key = [self keyForInterstellarOverridesForSystems:s1 s2:s2 inGalaxy:galaxyID];
1243
1244 NSDictionary* systeminfo = [systemManager getPropertiesForSystemKey:override_key];
1245
1247
1248 // fixed entities (part of the graphics system really) come first...
1249
1250 /*- the sky backdrop -*/
1251 OOColor* col1 = [OOColor colorWithRed:0.0 green:1.0 blue:0.5 alpha:1.0];
1252 OOColor* col2 = [OOColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
1253 thing = [[SkyEntity alloc] initWithColors:col1 col2:col2 andSystemInfo:systeminfo]; // alloc retains!
1254 [thing setScanClass:CLASS_NO_DRAW];
1255 quaternion_set_random(&randomQ);
1256 [thing setOrientation:randomQ];
1257 [self addEntity:thing];
1258 [thing release];
1259
1260 /*- the dust particle system -*/
1261 thing = [[DustEntity alloc] init];
1262 [thing setScanClass:CLASS_NO_DRAW];
1263 [self addEntity:thing];
1264 [thing release];
1265
1266 ambientLightLevel = [systeminfo oo_floatForKey:@"ambient_level" defaultValue:1.0];
1267 [self setLighting]; // also sets initial lights positions.
1268
1269 OOLog(kOOLogUniversePopulateWitchspace, @"%@", @"Populating witchspace ...");
1271
1272 [self clearSystemPopulator];
1273 NSString* populator = [systeminfo oo_stringForKey:@"populator" defaultValue:@"interstellarSpaceWillPopulate"];
1274 [system_repopulator release];
1275 system_repopulator = [[systeminfo oo_stringForKey:@"repopulator" defaultValue:@"interstellarSpaceWillRepopulate"] retain];
1276 JSContext* context = OOJSAcquireContext();
1277 [PLAYER doWorldScriptEvent:OOJSIDFromString(populator) inContext:context withArguments:NULL count:0 timeLimit:kOOJSLongTimeLimit];
1278 OOJSRelinquishContext(context);
1280
1281 // systeminfo might have a 'script_actions' resource we want to activate now...
1282 NSArray* script_actions = [systeminfo oo_arrayForKey:@"script_actions"];
1283 if (script_actions != nil) {
1284 OOStandardsDeprecated([NSString stringWithFormat:@"The script_actions system info key is deprecated for %@.", override_key]);
1285 if (!OOEnforceStandards()) {
1286 [player runUnsanitizedScriptActions:script_actions
1288 withContextName:@"<witchspace script_actions>"
1289 forTarget:nil];
1290 }
1291 }
1292
1294
1296}
1297
1298- (OOPlanetEntity*)setUpPlanet
1299{
1300 // set the system seed for random number generation
1302 seed_for_planet_description(systemSeed);
1303
1304 NSMutableDictionary* planetDict = [NSMutableDictionary dictionaryWithDictionary:[systemManager getPropertiesForCurrentSystem]];
1305 [planetDict oo_setBool:YES forKey:@"mainForLocalSystem"];
1306 OOPlanetEntity* a_planet = [[OOPlanetEntity alloc] initFromDictionary:planetDict withAtmosphere:[planetDict oo_boolForKey:@"has_atmosphere" defaultValue:YES] andSeed:systemSeed forSystem:systemID];
1307
1308 double planet_zpos = [planetDict oo_floatForKey:@"planet_distance" defaultValue:500000];
1309 planet_zpos *= [planetDict oo_floatForKey:@"planet_distance_multiplier" defaultValue:1.0];
1310
1311#ifdef OO_DUMP_PLANETINFO
1312 OOLog(@"planetinfo.record", @"planet zpos = %f", planet_zpos);
1313#endif
1314 [a_planet setPosition:(HPVector) { 0, 0, planet_zpos }];
1315 [a_planet setEnergy:1000000.0];
1316
1317 if ([allPlanets count] > 0) // F7 sets [UNIVERSE planet], which can lead to some trouble! TODO: track down where exactly that happens!
1318 {
1319 OOPlanetEntity* tmp = [allPlanets objectAtIndex:0];
1320 [self addEntity:a_planet];
1321 [allPlanets removeObject:a_planet];
1322 cachedPlanet = a_planet;
1323 [allPlanets replaceObjectAtIndex:0 withObject:a_planet];
1324 [self removeEntity:(Entity*)tmp];
1325 } else {
1326 [self addEntity:a_planet];
1327 }
1328 return [a_planet autorelease];
1329}
1330
1331/* At any time other than game start, any call to this must be followed
1332 * by [self populateNormalSpace]. However, at game start, they need to be
1333 * separated to allow Javascript startUp routines to be run in-between */
1335{
1336 Entity* thing;
1337 // ShipEntity *nav_buoy;
1338 StationEntity* a_station;
1339 OOSunEntity* a_sun;
1340 OOPlanetEntity* a_planet;
1341
1342 HPVector stationPos;
1343
1344 Vector vf;
1345 id dict_object;
1346
1347 NSDictionary* systeminfo = [systemManager getPropertiesForCurrentSystem];
1348 unsigned techlevel = [systeminfo oo_unsignedIntForKey:KEY_TECHLEVEL];
1349 NSString *stationDesc = nil, *defaultStationDesc = nil;
1350 OOColor* bgcolor;
1351 OOColor* pale_bgcolor;
1352 BOOL sunGoneNova;
1353
1355
1356 [[GameController sharedController] logProgress:DESC(@"populating-space")];
1357
1358 sunGoneNova = [systeminfo oo_boolForKey:@"sun_gone_nova" defaultValue:NO];
1359
1360 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - clearSubRegions, sky, dust");
1362
1363 // fixed entities (part of the graphics system really) come first...
1364 [self setSkyColorRed:0.0f
1365 green:0.0f
1366 blue:0.0f
1367 alpha:0.0f];
1368
1369#ifdef OO_DUMP_PLANETINFO
1370 OOLog(@"planetinfo.record", @"seed = %d %d %d %d", system_seed.c, system_seed.d, system_seed.e, system_seed.f);
1371 OOLog(@"planetinfo.record", @"coordinates = %d %d", system_seed.d, system_seed.b);
1372
1373#define SPROP(PROP) OOLog(@"planetinfo.record", @ #PROP " = \"%@\";", [systeminfo oo_stringForKey:@"" #PROP]);
1374#define IPROP(PROP) OOLog(@"planetinfo.record", @ #PROP " = %d;", [systeminfo oo_intForKey:@ #PROP]);
1375#define FPROP(PROP) OOLog(@"planetinfo.record", @ #PROP " = %f;", [systeminfo oo_floatForKey:@"" #PROP]);
1376 IPROP(government);
1377 IPROP(economy);
1378 IPROP(techlevel);
1379 IPROP(population);
1380 IPROP(productivity);
1381 SPROP(name);
1382 SPROP(inhabitant);
1383 SPROP(inhabitants);
1384 SPROP(description);
1385#endif
1386
1387 // set the system seed for random number generation
1388 seed_for_planet_description(systemSeed);
1389
1390 /*- the sky backdrop -*/
1391 // colors...
1392 float h1 = randf();
1393 float h2 = h1 + 1.0 / (1.0 + (Ranrot() % 5));
1394 while (h2 > 1.0)
1395 h2 -= 1.0;
1396 OOColor* col1 = [OOColor colorWithHue:h1 saturation:randf() brightness:0.5 + randf() / 2.0 alpha:1.0];
1397 OOColor* col2 = [OOColor colorWithHue:h2 saturation:0.5 + randf() / 2.0 brightness:0.5 + randf() / 2.0 alpha:1.0];
1398
1399 thing = [[SkyEntity alloc] initWithColors:col1 col2:col2 andSystemInfo:systeminfo]; // alloc retains!
1400 [thing setScanClass:CLASS_NO_DRAW];
1401 [self addEntity:thing];
1402 // bgcolor = [(SkyEntity *)thing skyColor];
1403 //
1404 h1 = randf() / 3.0;
1405 if (h1 > 0.17) {
1406 h1 += 0.33;
1407 }
1408
1409 ambientLightLevel = [systeminfo oo_floatForKey:@"ambient_level" defaultValue:1.0];
1410
1411 // pick a main sequence colour
1412
1413 dict_object = [systeminfo objectForKey:@"sun_color"];
1414 if (dict_object != nil) {
1415 bgcolor = [OOColor colorWithDescription:dict_object];
1416 } else {
1417 bgcolor = [OOColor colorWithHue:h1 saturation:0.75 * randf() brightness:0.65 + randf() / 5.0 alpha:1.0];
1418 }
1419
1421 [thing release];
1422 /*--*/
1423
1424 /*- the dust particle system -*/
1425 thing = [[DustEntity alloc] init]; // alloc retains!
1426 [thing setScanClass:CLASS_NO_DRAW];
1427 [self addEntity:thing];
1428 [(DustEntity*)thing setDustColor:pale_bgcolor];
1429 [thing release];
1430 /*--*/
1431
1432 float defaultSunFlare = randf() * 0.1;
1433 float defaultSunHues = 0.5 + randf() * 0.5;
1435
1436 // actual entities next...
1437
1438 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - planet");
1439 a_planet = [self setUpPlanet]; // resets RNG when called
1440 double planet_radius = [a_planet radius];
1442
1443 // set the system seed for random number generation
1444 seed_for_planet_description(systemSeed);
1445
1446 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - sun");
1447 /*- space sun -*/
1448 double sun_radius;
1449 double sun_distance;
1450 double sunDistanceModifier;
1451 double safeDistance;
1452 HPVector sunPos;
1453
1454 sunDistanceModifier = [systeminfo oo_nonNegativeDoubleForKey:@"sun_distance_modifier" defaultValue:0.0];
1455 if (sunDistanceModifier < 6.0) // <6 isn't valid
1456 {
1457 sun_distance = [systeminfo oo_nonNegativeDoubleForKey:@"sun_distance" defaultValue:(planet_radius * 20)];
1458 // note, old property was _modifier, new property is _multiplier
1459 sun_distance *= [systeminfo oo_nonNegativeDoubleForKey:@"sun_distance_multiplier" defaultValue:1];
1460 } else {
1461 sun_distance = planet_radius * sunDistanceModifier;
1462 }
1463
1464 sun_radius = [systeminfo oo_nonNegativeDoubleForKey:@"sun_radius" defaultValue:2.5 * planet_radius];
1465 // clamp the sun radius
1466 if ((sun_radius < 1000.0) || (sun_radius > sun_distance / 2 && !sunGoneNova)) {
1467 OOLogWARN(@"universe.setup.badSun", @"Sun radius of %f is not valid for this system", sun_radius);
1468 sun_radius = sun_radius < 1000.0 ? 1000.0 : (sun_distance / 2);
1469 }
1470#ifdef OO_DUMP_PLANETINFO
1471 OOLog(@"planetinfo.record", @"sun_radius = %f", sun_radius);
1472#endif
1473 safeDistance = 36 * sun_radius * sun_radius; // 6 times the sun radius
1474
1475 // here we need to check if the sun collides with (or is too close to) the witchpoint
1476 // otherwise at (for example) Maregais in Galaxy 1 we go BANG!
1477 HPVector sun_dir = [systeminfo oo_hpvectorForKey:@"sun_vector"];
1478 sun_distance /= 2.0;
1479 do {
1480 sun_distance *= 2.0;
1481 sunPos = HPvector_subtract([a_planet position],
1482 HPvector_multiply_scalar(sun_dir, sun_distance));
1483
1484 // if not in the safe distance, multiply by two and try again
1485 } while (HPmagnitude2(sunPos) < safeDistance);
1486
1487 // set planetary axial tilt to 0 degrees
1488 // TODO: allow this to vary
1489 [a_planet setOrientation:quaternion_rotation_betweenHP(sun_dir, make_HPvector(1.0, 0.0, 0.0))];
1490
1491#ifdef OO_DUMP_PLANETINFO
1492 OOLog(@"planetinfo.record", @"sun_vector = %.3f %.3f %.3f", vf.x, vf.y, vf.z);
1493 OOLog(@"planetinfo.record", @"sun_distance = %.0f", sun_distance);
1494#endif
1495
1496 NSMutableDictionary* sun_dict = [NSMutableDictionary dictionaryWithCapacity:5];
1497 [sun_dict setObject:[NSNumber numberWithDouble:sun_radius] forKey:@"sun_radius"];
1498 dict_object = [systeminfo objectForKey:@"corona_shimmer"];
1499 if (dict_object != nil)
1500 [sun_dict setObject:dict_object forKey:@"corona_shimmer"];
1501 dict_object = [systeminfo objectForKey:@"corona_hues"];
1502 if (dict_object != nil) {
1503 [sun_dict setObject:dict_object forKey:@"corona_hues"];
1504 } else {
1505 [sun_dict setObject:[NSNumber numberWithFloat:defaultSunHues] forKey:@"corona_hues"];
1506 }
1507 dict_object = [systeminfo objectForKey:@"corona_flare"];
1508 if (dict_object != nil) {
1509 [sun_dict setObject:dict_object forKey:@"corona_flare"];
1510 } else {
1511 [sun_dict setObject:[NSNumber numberWithFloat:defaultSunFlare] forKey:@"corona_flare"];
1512 }
1513 dict_object = [systeminfo objectForKey:KEY_SUNNAME];
1514 if (dict_object != nil) {
1515 [sun_dict setObject:dict_object forKey:KEY_SUNNAME];
1516 }
1517#ifdef OO_DUMP_PLANETINFO
1518 OOLog(@"planetinfo.record", @"corona_flare = %f", [sun_dict oo_floatForKey:@"corona_flare"]);
1519 OOLog(@"planetinfo.record", @"corona_hues = %f", [sun_dict oo_floatForKey:@"corona_hues"]);
1520 OOLog(@"planetinfo.record", @"sun_color = %@", [bgcolor descriptionComponents]);
1521#endif
1522 a_sun = [[OOSunEntity alloc] initSunWithColor:bgcolor andDictionary:sun_dict]; // alloc retains!
1523
1524 [a_sun setStatus:STATUS_ACTIVE];
1525 [a_sun setPosition:sunPos]; // sets also light origin
1526 [a_sun setEnergy:1000000.0];
1527 [self addEntity:a_sun];
1528
1529 if (sunGoneNova) {
1530 [a_sun setRadius:sun_radius andCorona:0.3];
1531 [a_sun setThrowSparks:YES];
1532 [a_sun setVelocity:kZeroVector];
1533 }
1534
1535 // set the lighting only after we know which sun we have.
1536 [self setLighting];
1538
1539 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - main station");
1540 /*- space station -*/
1541 stationPos = [a_planet position];
1542
1543 vf = [systeminfo oo_vectorForKey:@"station_vector"];
1544#ifdef OO_DUMP_PLANETINFO
1545 OOLog(@"planetinfo.record", @"station_vector = %.3f %.3f %.3f", vf.x, vf.y, vf.z);
1546#endif
1547 stationPos = HPvector_subtract(stationPos, vectorToHPVector(vector_multiply_scalar(vf, 2.0 * planet_radius)));
1548
1550 stationDesc = [systeminfo oo_stringForKey:@"station" defaultValue:@"coriolis"];
1551#ifdef OO_DUMP_PLANETINFO
1552 OOLog(@"planetinfo.record", @"station = %@", stationDesc);
1553#endif
1554
1555 a_station = (StationEntity*)[self newShipWithRole:stationDesc]; // retain count = 1
1556
1557 /* Sanity check: ensure that only stations are generated here. This is an
1558 attempt to fix exceptions of the form:
1559 NSInvalidArgumentException : *** -[ShipEntity setPlanet:]: selector
1560 not recognized [self = 0x19b7e000] *****
1561 which I presume to be originating here since all other uses of
1562 setPlanet: are guarded by isStation checks. This error could happen if
1563 a ship that is not a station has a station role, or equivalently if an
1564 OXP sets a system's station role to a role used by non-stations.
1565 -- Ahruman 20080303
1566 */
1567 if (![a_station isStation] || ![a_station validForAddToUniverse]) {
1568 if (a_station == nil) {
1569 // Should have had a more specific error already, just specify context
1570 OOLog(@"universe.setup.badStation", @"Failed to set up a ship for role \"%@\" as system station, trying again with \"%@\".", stationDesc, defaultStationDesc);
1571 } else {
1572 OOLog(@"universe.setup.badStation", @"***** ERROR: Attempt to use non-station ship of type \"%@\" for role \"%@\" as system station, trying again with \"%@\".", [a_station name], stationDesc, defaultStationDesc);
1573 }
1574 [a_station release];
1575 stationDesc = defaultStationDesc;
1576 a_station = (StationEntity*)[self newShipWithRole:stationDesc]; // retain count = 1
1577
1578 if (![a_station isStation] || ![a_station validForAddToUniverse]) {
1579 if (a_station == nil) {
1580 OOLog(@"universe.setup.badStation", @"On retry, failed to set up a ship for role \"%@\" as system station. Trying to fall back to built-in Coriolis station.", stationDesc);
1581 } else {
1582 OOLog(@"universe.setup.badStation", @"***** ERROR: On retry, rolled non-station ship of type \"%@\" for role \"%@\". Non-station ships should not have this role! Trying to fall back to built-in Coriolis station.", [a_station name], stationDesc);
1583 }
1584 [a_station release];
1585
1586 a_station = (StationEntity*)[self newShipWithName:@"coriolis-station"];
1587 if (![a_station isStation] || ![a_station validForAddToUniverse]) {
1588 OOLog(@"universe.setup.badStation", @"%@", @"Could not create built-in Coriolis station! Generating a stationless system.");
1589 DESTROY(a_station);
1590 }
1591 }
1592 }
1593
1594 if (a_station != nil) {
1595 [a_station setOrientation:quaternion_rotation_between(vf, make_vector(0.0, 0.0, 1.0))];
1596 [a_station setPosition:stationPos];
1597 [a_station setPitch:0.0];
1598 [a_station setScanClass:CLASS_STATION];
1599 //[a_station setPlanet:[self planet]]; // done inside addEntity.
1601 [self addEntity:a_station]; // STATUS_IN_FLIGHT, AI state GLOBAL
1602 [a_station setStatus:STATUS_ACTIVE]; // For backward compatibility. Might not be needed.
1603 [a_station setAllowsFastDocking:true]; // Main stations always allow fast docking.
1604 [a_station setAllegiance:@"galcop"]; // Main station is galcop controlled
1605 }
1607
1608 cachedSun = a_sun;
1609 cachedPlanet = a_planet;
1610 cachedStation = a_station;
1611 closeSystems = nil;
1613
1614 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - populate from wormholes");
1617
1618 [a_sun release];
1619 [a_station release];
1620}
1621
1623{
1624 NSDictionary* systeminfo = [systemManager getPropertiesForCurrentSystem];
1625
1626 BOOL sunGoneNova = [systeminfo oo_boolForKey:@"sun_gone_nova"];
1627 // check for nova
1628 if (sunGoneNova) {
1629 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - post-nova");
1630
1631 HPVector v0 = make_HPvector(0, 0, 34567.89);
1632 double min_safe_dist2 = 6000000.0 * 6000000.0;
1633 HPVector sunPos = [cachedSun position];
1634 while (HPmagnitude2(cachedSun->position) < min_safe_dist2) // back off the planetary bodies
1635 {
1636 v0.z *= 2.0;
1637
1638 sunPos = HPvector_add(sunPos, v0);
1639 [cachedSun setPosition:sunPos]; // also sets light origin
1640 }
1641
1642 [self removeEntity:cachedPlanet]; // and Poof! it's gone
1643 cachedPlanet = nil;
1644 [self removeEntity:cachedStation]; // also remove main station
1646 }
1647
1648 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - populate from hyperpoint");
1649 // [self populateSpaceFromHyperPoint:witchPos toPlanetPosition: a_planet->position andSunPosition: a_sun->position];
1650 [self clearSystemPopulator];
1651
1652 if ([PLAYER status] != STATUS_START_GAME) {
1653 NSString* populator = [systeminfo oo_stringForKey:@"populator" defaultValue:(sunGoneNova) ? @"novaSystemWillPopulate" : @"systemWillPopulate"];
1654 [system_repopulator release];
1655 system_repopulator = [[systeminfo oo_stringForKey:@"repopulator" defaultValue:(sunGoneNova) ? @"novaSystemWillRepopulate" : @"systemWillRepopulate"] retain];
1656
1657 JSContext* context = OOJSAcquireContext();
1658 [PLAYER doWorldScriptEvent:OOJSIDFromString(populator) inContext:context withArguments:NULL count:0 timeLimit:kOOJSLongTimeLimit];
1659 OOJSRelinquishContext(context);
1660 [self populateSystemFromDictionariesWithSun:cachedSun andPlanet:cachedPlanet];
1661 }
1662
1664
1665 // systeminfo might have a 'script_actions' resource we want to activate now...
1666 NSArray* script_actions = [systeminfo oo_arrayForKey:@"script_actions"];
1667 if (script_actions != nil) {
1668 OOStandardsDeprecated([NSString stringWithFormat:@"The script_actions system info key is deprecated for %@.", [self getSystemName:systemID]]);
1669 if (!OOEnforceStandards()) {
1670 OO_DEBUG_PUSH_PROGRESS(@"%@", @"setUpSpace - legacy script_actions");
1671 [PLAYER runUnsanitizedScriptActions:script_actions
1672 allowingAIMethods:NO
1673 withContextName:@"<system script_actions>"
1674 forTarget:nil];
1676 }
1677 }
1678
1680}
1681
1683{
1684 [populatorSettings release];
1685 populatorSettings = [[NSMutableDictionary alloc] initWithCapacity:128];
1686}
1687
1688- (NSDictionary*)getPopulatorSettings
1689{
1690 return populatorSettings;
1691}
1692
1693- (void)setPopulatorSetting:(NSString*)key to:(NSDictionary*)setting
1694{
1695 if (setting == nil) {
1696 [populatorSettings removeObjectForKey:key];
1697 } else {
1698 [populatorSettings setObject:setting forKey:key];
1699 }
1700}
1701
1703{
1705}
1706
1707- (void)populateSystemFromDictionariesWithSun:(OOSunEntity*)sun andPlanet:(OOPlanetEntity*)planet
1708{
1710 NSArray* blocks = [populatorSettings allValues];
1711 NSArray* sortedBlocks = [blocks sortedArrayUsingFunction:populatorPrioritySort context:nil];
1712 NSDictionary* populator = nil;
1713 HPVector location = kZeroHPVector;
1714 uint32_t i, locationSeed, groupCount, rndvalue;
1715 RANROTSeed rndcache = RANROTGetFullSeed();
1716 RANROTSeed rndlocal = RANROTGetFullSeed();
1717 NSString* locationCode = nil;
1719 foreach (populator, sortedBlocks) {
1720 deterministic_population = [populator oo_boolForKey:@"deterministic" defaultValue:NO];
1721 if (EXPECT_NOT(sun == nil || planet == nil)) {
1722 // needs to be a non-nova system, and not interstellar space
1724 }
1725
1726 locationSeed = [populator oo_unsignedIntForKey:@"locationSeed" defaultValue:0];
1727 groupCount = [populator oo_unsignedIntForKey:@"groupCount" defaultValue:1];
1728
1729 for (i = 0; i < groupCount; i++) {
1730 locationCode = [populator oo_stringForKey:@"location" defaultValue:@"COORDINATES"];
1731 if ([locationCode isEqualToString:@"COORDINATES"]) {
1732 location = [populator oo_hpvectorForKey:@"coordinates" defaultValue:kZeroHPVector];
1733 } else {
1734 if (locationSeed != 0) {
1735 rndcache = RANROTGetFullSeed();
1736 // different place for each system
1737 rndlocal = RanrotSeedFromRandomSeed(systemSeed);
1738 rndvalue = RanrotWithSeed(&rndlocal);
1739 // ...for location seed
1740 rndlocal = MakeRanrotSeed(rndvalue + locationSeed);
1741 rndvalue = RanrotWithSeed(&rndlocal);
1742 // ...for iteration (63647 is nothing special, just a largish prime)
1743 RANROTSetFullSeed(MakeRanrotSeed(rndvalue + (i * 63647)));
1744 } else {
1745 // not fixed coordinates and not seeded RNG; can't
1746 // be deterministic
1748 }
1749 if (sun == nil || planet == nil) {
1750 // all interstellar space and nova locations equal to WITCHPOINT
1751 location = [self locationByCode:@"WITCHPOINT" withSun:nil andPlanet:nil];
1752 } else {
1753 location = [self locationByCode:locationCode withSun:sun andPlanet:planet];
1754 }
1755 if (locationSeed != 0) {
1756 // go back to the main random sequence
1757 RANROTSetFullSeed(rndcache);
1758 }
1759 }
1760 // location now contains a Vector coordinate, one way or another
1761 pdef = [populator objectForKey:@"callbackObj"];
1762 [pdef runCallback:location];
1763 }
1764 }
1765 // nothing is deterministic once the populator is done
1767}
1768
1769/* Generates a position within one of the named regions:
1770 *
1771 * WITCHPOINT: within scanner of witchpoint
1772 * LANE_*: within two scanner of lane, not too near each end
1773 * STATION_AEGIS: within two scanner of main station, not in planet
1774 * *_ORBIT_*: around the object, in a shell relative to object radius
1775 * TRIANGLE: somewhere in the triangle defined by W, P, S
1776 * INNER_SYSTEM: closer to the sun than the planet is
1777 * OUTER_SYSTEM: further from the sun than the planet is
1778 * *_OFFPLANE: like the above, but not on the orbital plane
1779 *
1780 * Can be called with nil sun or planet, but if so the calling function
1781 * must make sure the location code is WITCHPOINT.
1782 */
1783- (HPVector)locationByCode:(NSString*)code withSun:(OOSunEntity*)sun andPlanet:(OOPlanetEntity*)planet
1784{
1785 HPVector result = kZeroHPVector;
1786 if ([code isEqualToString:@"WITCHPOINT"] || sun == nil || planet == nil || [sun goneNova]) {
1788 }
1789 // past this point, can assume non-nil sun, planet
1790 else {
1791 if ([code isEqualToString:@"LANE_WPS"]) {
1792 // pick position on one of the lanes, weighted by lane length
1793 double l1 = HPmagnitude([planet position]);
1794 double l2 = HPmagnitude(HPvector_subtract([sun position], [planet position]));
1795 double l3 = HPmagnitude([sun position]);
1796 double total = l1 + l2 + l3;
1797 float choice = randf();
1798 if (choice < l1 / total) {
1799 return [self locationByCode:@"LANE_WP" withSun:sun andPlanet:planet];
1800 } else if (choice < (l1 + l2) / total) {
1801 return [self locationByCode:@"LANE_PS" withSun:sun andPlanet:planet];
1802 } else {
1803 return [self locationByCode:@"LANE_WS" withSun:sun andPlanet:planet];
1804 }
1805 } else if ([code isEqualToString:@"LANE_WP"]) {
1807 } else if ([code isEqualToString:@"LANE_WS"]) {
1808 result = OORandomPositionInCylinder(kZeroHPVector, SCANNER_MAX_RANGE, [sun position], [sun radius] * 3, LANE_WIDTH);
1809 } else if ([code isEqualToString:@"LANE_PS"]) {
1810 result = OORandomPositionInCylinder([planet position], [planet radius] * 3, [sun position], [sun radius] * 3, LANE_WIDTH);
1811 } else if ([code isEqualToString:@"STATION_AEGIS"]) {
1812 do {
1813 result = OORandomPositionInShell([[self station] position], [[self station] collisionRadius] * 1.2, SCANNER_MAX_RANGE * 2.0);
1814 } while (HPdistance2(result, [planet position]) < [planet radius] * [planet radius] * 1.5);
1815 // loop to make sure not generated too close to the planet's surface
1816 } else if ([code isEqualToString:@"PLANET_ORBIT_LOW"]) {
1817 result = OORandomPositionInShell([planet position], [planet radius] * 1.1, [planet radius] * 2.0);
1818 } else if ([code isEqualToString:@"PLANET_ORBIT"]) {
1819 result = OORandomPositionInShell([planet position], [planet radius] * 2.0, [planet radius] * 4.0);
1820 } else if ([code isEqualToString:@"PLANET_ORBIT_HIGH"]) {
1821 result = OORandomPositionInShell([planet position], [planet radius] * 4.0, [planet radius] * 8.0);
1822 } else if ([code isEqualToString:@"STAR_ORBIT_LOW"]) {
1823 result = OORandomPositionInShell([sun position], [sun radius] * 1.1, [sun radius] * 2.0);
1824 } else if ([code isEqualToString:@"STAR_ORBIT"]) {
1825 result = OORandomPositionInShell([sun position], [sun radius] * 2.0, [sun radius] * 4.0);
1826 } else if ([code isEqualToString:@"STAR_ORBIT_HIGH"]) {
1827 result = OORandomPositionInShell([sun position], [sun radius] * 4.0, [sun radius] * 8.0);
1828 } else if ([code isEqualToString:@"TRIANGLE"]) {
1829 do {
1830 // pick random point in triangle by algorithm at
1831 // http://adamswaab.wordpress.com/2009/12/11/random-point-in-a-triangle-barycentric-coordinates/
1832 // simplified by using the origin as A
1833 OOScalar r = randf();
1834 OOScalar s = randf();
1835 if (r + s >= 1) {
1836 r = 1 - r;
1837 s = 1 - s;
1838 }
1839 result = HPvector_add(HPvector_multiply_scalar([planet position], r), HPvector_multiply_scalar([sun position], s));
1840 }
1841 // make sure at least 3 radii from vertices
1842 while (HPdistance2(result, [sun position]) < [sun radius] * [sun radius] * 9.0 || HPdistance2(result, [planet position]) < [planet radius] * [planet radius] * 9.0 || HPmagnitude2(result) < SCANNER_MAX_RANGE2 * 9.0);
1843 } else if ([code isEqualToString:@"INNER_SYSTEM"]) {
1844 do {
1845 result = OORandomPositionInShell([sun position], [sun radius] * 3.0, HPdistance([sun position], [planet position]));
1846 result = OOProjectHPVectorToPlane(result, kZeroHPVector, HPcross_product([sun position], [planet position]));
1847 result = HPvector_add(result, OOHPVectorRandomSpatial([planet radius]));
1848 // projection to plane could bring back too close to sun
1849 } while (HPdistance2(result, [sun position]) < [sun radius] * [sun radius] * 9.0);
1850 } else if ([code isEqualToString:@"INNER_SYSTEM_OFFPLANE"]) {
1851 result = OORandomPositionInShell([sun position], [sun radius] * 3.0, HPdistance([sun position], [planet position]));
1852 } else if ([code isEqualToString:@"OUTER_SYSTEM"]) {
1853 result = OORandomPositionInShell([sun position], HPdistance([sun position], [planet position]), HPdistance([sun position], [planet position]) * 10.0); // no more than 10 AU out
1854 result = OOProjectHPVectorToPlane(result, kZeroHPVector, HPcross_product([sun position], [planet position]));
1855 result = HPvector_add(result, OOHPVectorRandomSpatial(0.01 * HPdistance(result, [sun position]))); // within 1% of plane
1856 } else if ([code isEqualToString:@"OUTER_SYSTEM_OFFPLANE"]) {
1857 result = OORandomPositionInShell([sun position], HPdistance([sun position], [planet position]), HPdistance([sun position], [planet position]) * 10.0); // no more than 10 AU out
1858 } else {
1859 OOLog(kOOLogUniversePopulateError, @"Named populator region %@ is not implemented, falling back to WITCHPOINT", code);
1861 }
1862 }
1863 return result;
1864}
1865
1866- (void)setAmbientLightLevel:(float)newValue
1867{
1868 NSAssert(UNIVERSE != nil, @"Attempt to set ambient light level with a non yet existent universe.");
1869
1870 ambientLightLevel = OOClamp_0_max_f(newValue, 10.0f);
1871 return;
1872}
1873
1875{
1876 return ambientLightLevel;
1877}
1878
1880{
1881 /*
1882
1883 GL_LIGHT1 is the sun and is active while a sun exists in space
1884 where there is no sun (witch/interstellar space) this is placed at the origin
1885
1886 Shaders: this light is also used inside the station and needs to have its position reset
1887 relative to the player whenever demo ships or background scenes are to be shown -- 20100111
1888
1889
1890 GL_LIGHT0 is the light for inside the station and needs to have its position reset
1891 relative to the player whenever demo ships or background scenes are to be shown
1892
1893 Shaders: this light is not used. -- 20100111
1894
1895 */
1896
1897 OOSunEntity* the_sun = [self sun];
1898 SkyEntity* the_sky = nil;
1899 GLfloat sun_pos[] = { 0.0, 0.0, 0.0, 1.0 }; // equivalent to kZeroVector - for interstellar space.
1900 GLfloat sun_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; // overridden later in code
1901 int i;
1902
1903 for (i = n_entities - 1; i > 0; i--)
1904 if ((sortedEntities[i]) && ([sortedEntities[i] isKindOfClass:[SkyEntity class]]))
1905 the_sky = (SkyEntity*)sortedEntities[i];
1906
1907 if (the_sun) {
1908 [the_sun getDiffuseComponents:sun_diffuse];
1909 [the_sun getSpecularComponents:sun_specular];
1910 OOGL(glLightfv(GL_LIGHT1, GL_AMBIENT, sun_ambient));
1911 OOGL(glLightfv(GL_LIGHT1, GL_DIFFUSE, sun_diffuse));
1912 OOGL(glLightfv(GL_LIGHT1, GL_SPECULAR, sun_specular));
1913 sun_pos[0] = the_sun->position.x;
1914 sun_pos[1] = the_sun->position.y;
1915 sun_pos[2] = the_sun->position.z;
1916 } else {
1917 // witchspace
1918 stars_ambient[0] = 0.05;
1919 stars_ambient[1] = 0.20;
1920 stars_ambient[2] = 0.05;
1921 stars_ambient[3] = 1.0;
1922 sun_diffuse[0] = 0.85;
1923 sun_diffuse[1] = 1.0;
1924 sun_diffuse[2] = 0.85;
1925 sun_diffuse[3] = 1.0;
1926 sun_specular[0] = 0.95;
1927 sun_specular[1] = 1.0;
1928 sun_specular[2] = 0.95;
1929 sun_specular[3] = 1.0;
1930 OOGL(glLightfv(GL_LIGHT1, GL_AMBIENT, sun_ambient));
1931 OOGL(glLightfv(GL_LIGHT1, GL_DIFFUSE, sun_diffuse));
1932 OOGL(glLightfv(GL_LIGHT1, GL_SPECULAR, sun_specular));
1933 }
1934
1935 OOGL(glLightfv(GL_LIGHT1, GL_POSITION, sun_pos));
1936
1937 if (the_sky) {
1938 // ambient lighting!
1939 GLfloat r, g, b, a;
1940 [[the_sky skyColor] getRed:&r green:&g blue:&b alpha:&a];
1944 GLfloat ambient_level = [self ambientLightLevel];
1945 stars_ambient[0] = ambient_level * SKY_AMBIENT_ADJUSTMENT * (1.0 + r) * (1.0 + r);
1946 stars_ambient[1] = ambient_level * SKY_AMBIENT_ADJUSTMENT * (1.0 + g) * (1.0 + g);
1947 stars_ambient[2] = ambient_level * SKY_AMBIENT_ADJUSTMENT * (1.0 + b) * (1.0 + b);
1948 stars_ambient[3] = 1.0;
1949 }
1950
1951 // light for demo ships display..
1952 OOGL(glLightfv(GL_LIGHT0, GL_AMBIENT, docked_light_ambient));
1953 OOGL(glLightfv(GL_LIGHT0, GL_DIFFUSE, docked_light_diffuse));
1954 OOGL(glLightfv(GL_LIGHT0, GL_SPECULAR, docked_light_specular));
1955 OOGL(glLightfv(GL_LIGHT0, GL_POSITION, demo_light_position));
1956 OOGL(glLightModelfv(GL_LIGHT_MODEL_AMBIENT, stars_ambient));
1957}
1958
1959// Call this method to avoid lighting glich after windowed/fullscreen transition on macs.
1961{
1963}
1964
1965- (void)setMainLightPosition:(Vector)sunPos
1966{
1967 main_light_position[0] = sunPos.x;
1968 main_light_position[1] = sunPos.y;
1969 main_light_position[2] = sunPos.z;
1970 main_light_position[3] = 1.0;
1971}
1972
1973- (ShipEntity*)addShipWithRole:(NSString*)desc launchPos:(HPVector)launchPos rfactor:(GLfloat)rfactor
1974{
1975 if (rfactor != 0.0) {
1976 // Calculate the position as soon as possible, to minimise 'lollipop flash'
1977 launchPos.x += 2 * rfactor * (randf() - 0.5);
1978 launchPos.y += 2 * rfactor * (randf() - 0.5);
1979 launchPos.z += 2 * rfactor * (randf() - 0.5);
1980 }
1981
1982 ShipEntity* ship = [self newShipWithRole:desc]; // retain count = 1
1983
1984 if (ship) {
1985 [ship setPosition:launchPos]; // minimise 'lollipop flash'
1986
1987 // Deal with scripted cargopods and ensure they are filled with something.
1988 if ([ship hasRole:@"cargopod"])
1989 [self fillCargopodWithRandomCargo:ship];
1990
1991 // Ensure piloted ships have pilots.
1992 if (![ship crew] && ![ship isUnpiloted])
1993 [ship setCrew:[NSArray arrayWithObject:
1995 andOriginalSystem:Ranrot() & 255]]];
1996
1997 if ([ship scanClass] == CLASS_NOT_SET) {
1998 [ship setScanClass:CLASS_NEUTRAL];
1999 }
2000 [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL
2001 [ship release];
2002 return ship;
2003 }
2004 return nil;
2005}
2006
2007- (void)addShipWithRole:(NSString*)desc nearRouteOneAt:(double)route_fraction
2008{
2009 // adds a ship within scanner range of a point on route 1
2010
2011 Entity* theStation = [self station];
2012 if (!theStation) {
2013 return;
2014 }
2015
2016 HPVector launchPos = OOHPVectorInterpolate([self getWitchspaceExitPosition], [theStation position], route_fraction);
2017
2018 [self addShipWithRole:desc launchPos:launchPos rfactor:SCANNER_MAX_RANGE];
2019}
2020
2021- (HPVector)coordinatesForPosition:(HPVector)pos withCoordinateSystem:(NSString*)system returningScalar:(GLfloat*)my_scalar
2022{
2023 /* the point is described using a system selected by a string
2024 consisting of a three letter code.
2025
2026 The first letter indicates the feature that is the origin of the coordinate system.
2027 w => witchpoint
2028 s => sun
2029 p => planet
2030
2031 The next letter indicates the feature on the 'z' axis of the coordinate system.
2032 w => witchpoint
2033 s => sun
2034 p => planet
2035
2036 Then the 'y' axis of the system is normal to the plane formed by the planet, sun and witchpoint.
2037 And the 'x' axis of the system is normal to the y and z axes.
2038 So:
2039 ps: z axis = (planet -> sun) y axis = normal to (planet - sun - witchpoint) x axis = normal to y and z axes
2040 pw: z axis = (planet -> witchpoint) y axis = normal to (planet - witchpoint - sun) x axis = normal to y and z axes
2041 sp: z axis = (sun -> planet) y axis = normal to (sun - planet - witchpoint) x axis = normal to y and z axes
2042 sw: z axis = (sun -> witchpoint) y axis = normal to (sun - witchpoint - planet) x axis = normal to y and z axes
2043 wp: z axis = (witchpoint -> planet) y axis = normal to (witchpoint - planet - sun) x axis = normal to y and z axes
2044 ws: z axis = (witchpoint -> sun) y axis = normal to (witchpoint - sun - planet) x axis = normal to y and z axes
2045
2046 The third letter denotes the units used:
2047 m: meters
2048 p: planetary radii
2049 s: solar radii
2050 u: distance between first two features indicated (eg. spu means that u = distance from sun to the planet)
2051
2052 in interstellar space (== no sun) coordinates are absolute irrespective of the system used.
2053
2054 [1.71] The position code "abs" can also be used for absolute coordinates.
2055
2056 */
2057
2058 NSString* l_sys = [system lowercaseString];
2059 if ([l_sys length] != 3)
2060 return kZeroHPVector;
2061 OOPlanetEntity* the_planet = [self planet];
2062 OOSunEntity* the_sun = [self sun];
2063 if (the_planet == nil || the_sun == nil || [l_sys isEqualToString:@"abs"]) {
2064 if (my_scalar)
2065 *my_scalar = 1.0;
2066 return pos;
2067 }
2068 HPVector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG
2069 HPVector p_pos = the_planet->position;
2070 HPVector s_pos = the_sun->position;
2071
2072 const char* c_sys = [l_sys UTF8String];
2073 HPVector p0, p1, p2;
2074
2075 switch (c_sys[0]) {
2076 case 'w':
2077 p0 = w_pos;
2078 switch (c_sys[1]) {
2079 case 'p':
2080 p1 = p_pos;
2081 p2 = s_pos;
2082 break;
2083 case 's':
2084 p1 = s_pos;
2085 p2 = p_pos;
2086 break;
2087 default:
2088 return kZeroHPVector;
2089 }
2090 break;
2091 case 'p':
2092 p0 = p_pos;
2093 switch (c_sys[1]) {
2094 case 'w':
2095 p1 = w_pos;
2096 p2 = s_pos;
2097 break;
2098 case 's':
2099 p1 = s_pos;
2100 p2 = w_pos;
2101 break;
2102 default:
2103 return kZeroHPVector;
2104 }
2105 break;
2106 case 's':
2107 p0 = s_pos;
2108 switch (c_sys[1]) {
2109 case 'w':
2110 p1 = w_pos;
2111 p2 = p_pos;
2112 break;
2113 case 'p':
2114 p1 = p_pos;
2115 p2 = w_pos;
2116 break;
2117 default:
2118 return kZeroHPVector;
2119 }
2120 break;
2121 default:
2122 return kZeroHPVector;
2123 }
2124 HPVector k = HPvector_normal_or_zbasis(HPvector_subtract(p1, p0)); // 'forward'
2125 HPVector v = HPvector_normal_or_xbasis(HPvector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right'
2126
2127 HPVector j = HPcross_product(k, v); // 'up'
2128 HPVector i = HPcross_product(j, k); // 'right'
2129
2130 GLfloat scale = 1.0;
2131 switch (c_sys[2]) {
2132 case 'p':
2133 scale = [the_planet radius];
2134 break;
2135
2136 case 's':
2137 scale = [the_sun radius];
2138 break;
2139
2140 case 'u':
2141 scale = HPmagnitude(HPvector_subtract(p1, p0));
2142 break;
2143
2144 case 'm':
2145 scale = 1.0f;
2146 break;
2147
2148 default:
2149 return kZeroHPVector;
2150 }
2151 if (my_scalar)
2152 *my_scalar = scale;
2153
2154 // result = p0 + ijk
2155 HPVector result = p0; // origin
2156 result.x += scale * (pos.x * i.x + pos.y * j.x + pos.z * k.x);
2157 result.y += scale * (pos.x * i.y + pos.y * j.y + pos.z * k.y);
2158 result.z += scale * (pos.x * i.z + pos.y * j.z + pos.z * k.z);
2159
2160 return result;
2161}
2162
2163- (NSString*)expressPosition:(HPVector)pos inCoordinateSystem:(NSString*)system
2164{
2165 HPVector result = [self legacyPositionFrom:pos asCoordinateSystem:system];
2166 return [NSString stringWithFormat:@"%@ %.2f %.2f %.2f", system, result.x, result.y, result.z];
2167}
2168
2169- (HPVector)legacyPositionFrom:(HPVector)pos asCoordinateSystem:(NSString*)system
2170{
2171 NSString* l_sys = [system lowercaseString];
2172 if ([l_sys length] != 3)
2173 return kZeroHPVector;
2174 OOPlanetEntity* the_planet = [self planet];
2175 OOSunEntity* the_sun = [self sun];
2176 if (the_planet == nil || the_sun == nil || [l_sys isEqualToString:@"abs"]) {
2177 return pos;
2178 }
2179 HPVector w_pos = [self getWitchspaceExitPosition]; // don't reset PRNG
2180 HPVector p_pos = the_planet->position;
2181 HPVector s_pos = the_sun->position;
2182
2183 const char* c_sys = [l_sys UTF8String];
2184 HPVector p0, p1, p2;
2185
2186 switch (c_sys[0]) {
2187 case 'w':
2188 p0 = w_pos;
2189 switch (c_sys[1]) {
2190 case 'p':
2191 p1 = p_pos;
2192 p2 = s_pos;
2193 break;
2194 case 's':
2195 p1 = s_pos;
2196 p2 = p_pos;
2197 break;
2198 default:
2199 return kZeroHPVector;
2200 }
2201 break;
2202 case 'p':
2203 p0 = p_pos;
2204 switch (c_sys[1]) {
2205 case 'w':
2206 p1 = w_pos;
2207 p2 = s_pos;
2208 break;
2209 case 's':
2210 p1 = s_pos;
2211 p2 = w_pos;
2212 break;
2213 default:
2214 return kZeroHPVector;
2215 }
2216 break;
2217 case 's':
2218 p0 = s_pos;
2219 switch (c_sys[1]) {
2220 case 'w':
2221 p1 = w_pos;
2222 p2 = p_pos;
2223 break;
2224 case 'p':
2225 p1 = p_pos;
2226 p2 = w_pos;
2227 break;
2228 default:
2229 return kZeroHPVector;
2230 }
2231 break;
2232 default:
2233 return kZeroHPVector;
2234 }
2235 HPVector k = HPvector_normal_or_zbasis(HPvector_subtract(p1, p0)); // 'z' axis in m
2236 HPVector v = HPvector_normal_or_xbasis(HPvector_subtract(p2, p0)); // temporary vector in plane of 'forward' and 'right'
2237
2238 HPVector j = HPcross_product(k, v); // 'y' axis in m
2239 HPVector i = HPcross_product(j, k); // 'x' axis in m
2240
2241 GLfloat scale = 1.0;
2242 switch (c_sys[2]) {
2243 case 'p': {
2244 scale = 1.0f / [the_planet radius];
2245 break;
2246 }
2247 case 's': {
2248 scale = 1.0f / [the_sun radius];
2249 break;
2250 }
2251
2252 case 'u':
2253 scale = 1.0f / HPdistance(p1, p0);
2254 break;
2255
2256 case 'm':
2257 scale = 1.0f;
2258 break;
2259
2260 default:
2261 return kZeroHPVector;
2262 }
2263
2264 // result = p0 + ijk
2265 HPVector r_pos = HPvector_subtract(pos, p0);
2266 HPVector result = make_HPvector(scale * (r_pos.x * i.x + r_pos.y * i.y + r_pos.z * i.z),
2267 scale * (r_pos.x * j.x + r_pos.y * j.y + r_pos.z * j.z),
2268 scale * (r_pos.x * k.x + r_pos.y * k.y + r_pos.z * k.z)); // scale * dot_products
2269
2270 return result;
2271}
2272
2273- (HPVector)coordinatesFromCoordinateSystemString:(NSString*)system_x_y_z
2274{
2275 NSArray* tokens = ScanTokensFromString(system_x_y_z);
2276 if ([tokens count] != 4) {
2277 // Not necessarily an error.
2278 return make_HPvector(0, 0, 0);
2279 }
2280 GLfloat dummy;
2281 return [self coordinatesForPosition:make_HPvector([tokens oo_floatAtIndex:1], [tokens oo_floatAtIndex:2], [tokens oo_floatAtIndex:3]) withCoordinateSystem:[tokens oo_stringAtIndex:0] returningScalar:&dummy];
2282}
2283
2284- (BOOL)addShipWithRole:(NSString*)desc nearPosition:(HPVector)pos withCoordinateSystem:(NSString*)system
2285{
2286 // initial position
2287 GLfloat scalar = 1.0;
2288 HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar];
2289 // randomise
2290 GLfloat rfactor = scalar;
2291 if (rfactor > SCANNER_MAX_RANGE)
2292 rfactor = SCANNER_MAX_RANGE;
2293 if (rfactor < 1000)
2294 rfactor = 1000;
2295
2296 return ([self addShipWithRole:desc launchPos:launchPos rfactor:rfactor] != nil);
2297}
2298
2299- (BOOL)addShips:(int)howMany withRole:(NSString*)desc atPosition:(HPVector)pos withCoordinateSystem:(NSString*)system
2300{
2301 // initial bounding box
2302 GLfloat scalar = 1.0;
2303 HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar];
2304 GLfloat distance_from_center = 0.0;
2305 HPVector v_from_center, ship_pos;
2306 HPVector ship_positions[howMany];
2307 int i = 0;
2308 int scale_up_after = 0;
2309 int current_shell = 0;
2310 GLfloat walk_factor = 2.0;
2311 while (i < howMany) {
2312 ShipEntity* ship = [self addShipWithRole:desc launchPos:launchPos rfactor:0.0];
2313 if (ship == nil)
2314 return NO;
2315 OOScanClass scanClass = [ship scanClass];
2316 [ship setScanClass:CLASS_NO_DRAW]; // avoid lollipop flash
2317
2318 GLfloat safe_distance2 = ship->collision_radius * ship->collision_radius * SAFE_ADDITION_FACTOR2;
2319 BOOL safe;
2320 int limit_count = 8;
2321
2322 v_from_center = kZeroHPVector;
2323 do {
2324 do {
2325 v_from_center.x += walk_factor * (randf() - 0.5);
2326 v_from_center.y += walk_factor * (randf() - 0.5);
2327 v_from_center.z += walk_factor * (randf() - 0.5); // drunkards walk
2328 } while ((v_from_center.x == 0.0) && (v_from_center.y == 0.0) && (v_from_center.z == 0.0));
2329 v_from_center = HPvector_normal(v_from_center); // guaranteed non-zero
2330
2331 ship_pos = make_HPvector(launchPos.x + distance_from_center * v_from_center.x,
2332 launchPos.y + distance_from_center * v_from_center.y,
2333 launchPos.z + distance_from_center * v_from_center.z);
2334
2335 // check this position against previous ship positions in this shell
2336 safe = YES;
2337 int j = i - 1;
2338 while (safe && (j >= current_shell)) {
2339 safe = (safe && (HPdistance2(ship_pos, ship_positions[j]) > safe_distance2));
2340 j--;
2341 }
2342 if (!safe) {
2343 limit_count--;
2344 if (!limit_count) // give up and expand the shell
2345 {
2346 limit_count = 8;
2347 distance_from_center += sqrt(safe_distance2); // expand to the next distance
2348 }
2349 }
2350
2351 } while (!safe);
2352
2353 [ship setPosition:ship_pos];
2354 [ship setScanClass:scanClass == CLASS_NOT_SET ? CLASS_NEUTRAL : scanClass];
2355
2356 Quaternion qr;
2358 [ship setOrientation:qr];
2359
2360 // [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL
2361
2362 ship_positions[i] = ship_pos;
2363 i++;
2364 if (i > scale_up_after) {
2365 current_shell = i;
2366 scale_up_after += 1 + 2 * i;
2367 distance_from_center += sqrt(safe_distance2); // fill the next shell
2368 }
2369 }
2370 return YES;
2371}
2372
2373- (BOOL)addShips:(int)howMany withRole:(NSString*)desc nearPosition:(HPVector)pos withCoordinateSystem:(NSString*)system
2374{
2375 // initial bounding box
2376 GLfloat scalar = 1.0;
2377 HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar];
2378 GLfloat rfactor = scalar;
2379 if (rfactor > SCANNER_MAX_RANGE)
2380 rfactor = SCANNER_MAX_RANGE;
2381 if (rfactor < 1000)
2382 rfactor = 1000;
2383 BoundingBox launch_bbox;
2384 bounding_box_reset_to_vector(&launch_bbox, make_vector(launchPos.x - rfactor, launchPos.y - rfactor, launchPos.z - rfactor));
2385 bounding_box_add_xyz(&launch_bbox, launchPos.x + rfactor, launchPos.y + rfactor, launchPos.z + rfactor);
2386
2387 return [self addShips:howMany withRole:desc intoBoundingBox:launch_bbox];
2388}
2389
2390- (BOOL)addShips:(int)howMany withRole:(NSString*)desc nearPosition:(HPVector)pos withCoordinateSystem:(NSString*)system withinRadius:(GLfloat)radius
2391{
2392 // initial bounding box
2393 GLfloat scalar = 1.0;
2394 HPVector launchPos = [self coordinatesForPosition:pos withCoordinateSystem:system returningScalar:&scalar];
2395 GLfloat rfactor = radius;
2396 if (rfactor < 1000)
2397 rfactor = 1000;
2398 BoundingBox launch_bbox;
2399 bounding_box_reset_to_vector(&launch_bbox, make_vector(launchPos.x - rfactor, launchPos.y - rfactor, launchPos.z - rfactor));
2400 bounding_box_add_xyz(&launch_bbox, launchPos.x + rfactor, launchPos.y + rfactor, launchPos.z + rfactor);
2401
2402 return [self addShips:howMany withRole:desc intoBoundingBox:launch_bbox];
2403}
2404
2405- (BOOL)addShips:(int)howMany withRole:(NSString*)desc intoBoundingBox:(BoundingBox)bbox
2406{
2407 if (howMany < 1)
2408 return YES;
2409 if (howMany > 1) {
2410 // divide the number of ships in two
2411 int h0 = howMany / 2;
2412 int h1 = howMany - h0;
2413 // split the bounding box into two along its longest dimension
2414 GLfloat lx = bbox.max.x - bbox.min.x;
2415 GLfloat ly = bbox.max.y - bbox.min.y;
2416 GLfloat lz = bbox.max.z - bbox.min.z;
2417 BoundingBox bbox0 = bbox;
2418 BoundingBox bbox1 = bbox;
2419 if ((lx > lz) && (lx > ly)) // longest dimension is x
2420 {
2421 bbox0.min.x += 0.5 * lx;
2422 bbox1.max.x -= 0.5 * lx;
2423 } else {
2424 if (ly > lz) // longest dimension is y
2425 {
2426 bbox0.min.y += 0.5 * ly;
2427 bbox1.max.y -= 0.5 * ly;
2428 } else // longest dimension is z
2429 {
2430 bbox0.min.z += 0.5 * lz;
2431 bbox1.max.z -= 0.5 * lz;
2432 }
2433 }
2434 // place half the ships into each bounding box
2435 return ([self addShips:h0 withRole:desc intoBoundingBox:bbox0] && [self addShips:h1 withRole:desc intoBoundingBox:bbox1]);
2436 }
2437
2438 // randomise within the bounding box (biased towards the center of the box)
2439 HPVector pos = make_HPvector(bbox.min.x, bbox.min.y, bbox.min.z);
2440 pos.x += 0.5 * (randf() + randf()) * (bbox.max.x - bbox.min.x);
2441 pos.y += 0.5 * (randf() + randf()) * (bbox.max.y - bbox.min.y);
2442 pos.z += 0.5 * (randf() + randf()) * (bbox.max.z - bbox.min.z);
2443
2444 return ([self addShipWithRole:desc launchPos:pos rfactor:0.0] != nil);
2445}
2446
2447- (BOOL)spawnShip:(NSString*)shipdesc
2448{
2449 // no need to do any more than log - enforcing modes wouldn't even have
2450 // loaded the legacy script
2451 OOStandardsDeprecated([NSString stringWithFormat:@"'spawn' via legacy script is deprecated as a way of adding ships for %@", shipdesc]);
2452
2453 ShipEntity* ship;
2454 NSDictionary* shipdict = nil;
2455
2456 shipdict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipdesc];
2457 if (shipdict == nil)
2458 return NO;
2459
2460 ship = [self newShipWithName:shipdesc]; // retain count is 1
2461
2462 if (ship == nil)
2463 return NO;
2464
2465 // set any spawning characteristics
2466 NSDictionary* spawndict = [shipdict oo_dictionaryForKey:@"spawn"];
2467 HPVector pos, rpos, spos;
2468 NSString* positionString = nil;
2469
2470 // position
2471 positionString = [spawndict oo_stringForKey:@"position"];
2472 if (positionString != nil) {
2473 if ([positionString hasPrefix:@"abs "] && ([self planet] != nil || [self sun] != nil)) {
2474 OOLogWARN(@"script.deprecated", @"setting %@ for %@ '%@' in 'abs' inside .plists can cause compatibility issues across Oolite versions. Use coordinates relative to main system objects instead.", @"position", @"entity", shipdesc);
2475 }
2476
2477 pos = [self coordinatesFromCoordinateSystemString:positionString];
2478 } else {
2479 // without position defined, the ship will be added on top of the witchpoint buoy.
2481 OOLogERR(@"universe.spawnShip.error", @"***** ERROR: failed to find a spawn position for ship %@.", shipdesc);
2482 }
2483 [ship setPosition:pos];
2484
2485 // facing_position
2486 positionString = [spawndict oo_stringForKey:@"facing_position"];
2487 if (positionString != nil) {
2488 if ([positionString hasPrefix:@"abs "] && ([self planet] != nil || [self sun] != nil)) {
2489 OOLogWARN(@"script.deprecated", @"setting %@ for %@ '%@' in 'abs' inside .plists can cause compatibility issues across Oolite versions. Use coordinates relative to main system objects instead.", @"facing_position", @"entity", shipdesc);
2490 }
2491
2492 spos = [ship position];
2493 Quaternion q1;
2494 rpos = [self coordinatesFromCoordinateSystemString:positionString];
2495 rpos = HPvector_subtract(rpos, spos); // position relative to ship
2496
2497 if (!HPvector_equal(rpos, kZeroHPVector)) {
2498 rpos = HPvector_normal(rpos);
2499
2502 } else {
2503 // for the inverse of the kBasisZVector the rotation is undefined, so we select one.
2504 q1 = make_quaternion(0, 1, 0, 0);
2505 }
2506
2507 [ship setOrientation:q1];
2508 }
2509 }
2510
2511 [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL
2512 [ship release];
2513
2514 return YES;
2515}
2516
2517- (void)witchspaceShipWithPrimaryRole:(NSString*)role
2518{
2519 // adds a ship exiting witchspace (corollary of when ships leave the system)
2520 ShipEntity* ship = nil;
2521 NSDictionary* systeminfo = nil;
2522 OOGovernmentID government;
2523
2524 systeminfo = [self currentSystemData];
2525 government = [systeminfo oo_unsignedCharForKey:KEY_GOVERNMENT];
2526
2527 ship = [self newShipWithRole:role]; // retain count = 1
2528
2529 // Deal with scripted cargopods and ensure they are filled with something.
2530 if (ship && [ship hasRole:@"cargopod"]) {
2531 [self fillCargopodWithRandomCargo:ship];
2532 }
2533
2534 if (ship) {
2535 if (([ship scanClass] == CLASS_NO_DRAW) || ([ship scanClass] == CLASS_NOT_SET))
2536 [ship setScanClass:CLASS_NEUTRAL];
2537 if ([role isEqual:@"trader"]) {
2538 [ship setCargoFlag:CARGO_FLAG_FULL_SCARCE];
2539 if ([ship hasRole:@"sunskim-trader"] && randf() < 0.25) // select 1/4 of the traders suitable for sunskimming.
2540 {
2541 [ship setCargoFlag:CARGO_FLAG_FULL_PLENTIFUL];
2542 [self makeSunSkimmer:ship andSetAI:YES];
2543 } else {
2544 [ship switchAITo:@"oolite-traderAI.js"];
2545 }
2546
2547 if (([ship pendingEscortCount] > 0) && ((Ranrot() % 7) < government)) // remove escorts if we feel safe
2548 {
2549 int nx = [ship pendingEscortCount] - 2 * (1 + (Ranrot() & 3)); // remove 2,4,6, or 8 escorts
2550 [ship setPendingEscortCount:(nx > 0) ? nx : 0];
2551 }
2552 }
2553 if ([role isEqual:@"pirate"]) {
2554 [ship setCargoFlag:CARGO_FLAG_PIRATE];
2555 [ship setBounty:(Ranrot() & 7) + (Ranrot() & 7) + ((randf() < 0.05) ? 63 : 23) withReason:kOOLegalStatusReasonSetup]; // they already have a price on their heads
2556 }
2557 if ([ship crew] == nil && ![ship isUnpiloted])
2558 [ship setCrew:[NSArray arrayWithObject:
2560 andOriginalSystem:Ranrot() & 255]]];
2561 // The following is set inside leaveWitchspace: AI state GLOBAL, STATUS_EXITING_WITCHSPACE, ai message: EXITED_WITCHSPACE, then STATUS_IN_FLIGHT
2563 [ship release];
2564 }
2565}
2566
2567// adds a ship within the collision radius of the other entity
2568- (ShipEntity*)spawnShipWithRole:(NSString*)desc near:(Entity*)entity
2569{
2570 if (entity == nil)
2571 return nil;
2572
2573 ShipEntity* ship = nil;
2574 HPVector spawn_pos;
2575 Quaternion spawn_q;
2576 GLfloat offset = (randf() + randf()) * entity->collision_radius;
2577
2578 quaternion_set_random(&spawn_q);
2580
2581 ship = [self addShipWithRole:desc launchPos:spawn_pos rfactor:0.0];
2582 [ship setOrientation:spawn_q];
2583
2584 return ship;
2585}
2586
2587- (OOVisualEffectEntity*)addVisualEffectAt:(HPVector)pos withKey:(NSString*)key
2588{
2590
2591 // minimise the time between creating ship & assigning position.
2592
2593 OOVisualEffectEntity* vis = [self newVisualEffectWithName:key]; // is retained
2594 BOOL success = NO;
2595 if (vis != nil) {
2596 [vis setPosition:pos];
2597 [vis setOrientation:OORandomQuaternion()];
2598
2599 success = [self addEntity:vis]; // retained globally now
2600
2601 [vis release];
2602 }
2603 return success ? vis : (OOVisualEffectEntity*)nil;
2604
2606}
2607
2608- (ShipEntity*)addShipAt:(HPVector)pos withRole:(NSString*)role withinRadius:(GLfloat)radius
2609{
2611
2612 // minimise the time between creating ship & assigning position.
2613 if (radius == NSNotFound) {
2614 GLfloat scalar = 1.0;
2616 // randomise
2617 GLfloat rfactor = scalar;
2618 if (rfactor > SCANNER_MAX_RANGE)
2619 rfactor = SCANNER_MAX_RANGE;
2620 if (rfactor < 1000)
2621 rfactor = 1000;
2622 pos.x += rfactor * (randf() - randf());
2623 pos.y += rfactor * (randf() - randf());
2624 pos.z += rfactor * (randf() - randf());
2625 } else {
2626 pos = HPvector_add(pos, OOHPVectorRandomSpatial(radius));
2627 }
2628
2629 ShipEntity* ship = [self newShipWithRole:role]; // is retained
2630 BOOL success = NO;
2631
2632 if (ship != nil) {
2633 [ship setPosition:pos];
2634 if ([ship hasRole:@"cargopod"])
2635 [self fillCargopodWithRandomCargo:ship];
2636 OOScanClass scanClass = [ship scanClass];
2637 if (scanClass == CLASS_NOT_SET) {
2638 scanClass = CLASS_NEUTRAL;
2639 [ship setScanClass:scanClass];
2640 }
2641
2642 if ([ship crew] == nil && ![ship isUnpiloted]) {
2643 [ship setCrew:[NSArray arrayWithObject:
2645 andOriginalSystem:Ranrot() & 255]]];
2646 }
2647
2648 [ship setOrientation:OORandomQuaternion()];
2649
2650 BOOL trader = [role isEqualToString:@"trader"];
2651 if (trader) {
2652 // half of traders created anywhere will now have cargo.
2653 if (randf() > 0.5f) {
2654 [ship setCargoFlag:(randf() < 0.66f ? CARGO_FLAG_FULL_PLENTIFUL : CARGO_FLAG_FULL_SCARCE)]; // most of them will carry the cargo produced in-system.
2655 }
2656
2657 uint8_t pendingEscortCount = [ship pendingEscortCount];
2658 if (pendingEscortCount > 0) {
2659 OOGovernmentID government = [[self currentSystemData] oo_unsignedCharForKey:KEY_GOVERNMENT];
2660 if ((Ranrot() % 7) < government) // remove escorts if we feel safe
2661 {
2662 int nx = pendingEscortCount - 2 * (1 + (Ranrot() & 3)); // remove 2,4,6, or 8 escorts
2663 [ship setPendingEscortCount:(nx > 0) ? nx : 0];
2664 }
2665 }
2666 }
2667
2669 // nothing extra to do
2670 success = [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL - ship is retained globally
2671 } else // witchspace incoming traders & pirates need extra settings.
2672 {
2673 if (trader) {
2674 [ship setCargoFlag:CARGO_FLAG_FULL_SCARCE];
2675 if ([ship hasRole:@"sunskim-trader"] && randf() < 0.25) {
2676 [ship setCargoFlag:CARGO_FLAG_FULL_PLENTIFUL];
2677 [self makeSunSkimmer:ship andSetAI:YES];
2678 } else {
2679 [ship switchAITo:@"oolite-traderAI.js"];
2680 }
2681 } else if ([role isEqual:@"pirate"]) {
2682 [ship setBounty:(Ranrot() & 7) + (Ranrot() & 7) + ((randf() < 0.05) ? 63 : 23) withReason:kOOLegalStatusReasonSetup]; // they already have a price on their heads
2683 }
2684
2685 // Status changes inside the following call: AI state GLOBAL, then STATUS_EXITING_WITCHSPACE,
2686 // with the EXITED_WITCHSPACE message sent to the AI. At last we set STATUS_IN_FLIGHT.
2687 // Includes addEntity, so ship is retained globally.
2688 success = [ship witchspaceLeavingEffects];
2689 }
2690
2691 [ship release];
2692 }
2693 return success ? ship : (ShipEntity*)nil;
2694
2696}
2697
2698- (NSArray*)addShipsAt:(HPVector)pos withRole:(NSString*)role quantity:(unsigned)count withinRadius:(GLfloat)radius asGroup:(BOOL)isGroup
2699{
2701
2702 NSMutableArray* ships = [NSMutableArray arrayWithCapacity:count];
2703 ShipEntity* ship = nil;
2704 OOShipGroup* group = nil;
2705
2706 if (isGroup) {
2707 group = [OOShipGroup groupWithName:[NSString stringWithFormat:@"%@ group", role]];
2708 }
2709
2710 while (count--) {
2711 ship = [self addShipAt:pos withRole:role withinRadius:radius];
2712 if (ship != nil) {
2713 // TODO: avoid collisions!!!
2714 if (isGroup)
2715 [ship setGroup:group];
2716 [ships addObject:ship];
2717 }
2718 }
2719
2720 if ([ships count] == 0)
2721 return nil;
2722
2723 return [[ships copy] autorelease];
2724
2726}
2727
2728- (NSArray*)addShipsToRoute:(NSString*)route withRole:(NSString*)role quantity:(unsigned)count routeFraction:(double)routeFraction asGroup:(BOOL)isGroup
2729{
2730 NSMutableArray* ships = [NSMutableArray arrayWithCapacity:count];
2731 ShipEntity* ship = nil;
2732 Entity<OOStellarBody>* entity = nil;
2733 HPVector pos = kZeroHPVector, direction = kZeroHPVector, point0 = kZeroHPVector, point1 = kZeroHPVector;
2734 double radius = 0;
2735
2736 if ([route isEqualToString:@"pw"] || [route isEqualToString:@"sw"] || [route isEqualToString:@"ps"]) {
2737 routeFraction = 1.0f - routeFraction;
2738 }
2739
2740 // which route is it?
2741 if ([route isEqualTo:@"wp"] || [route isEqualTo:@"pw"]) {
2742 point0 = [self getWitchspaceExitPosition];
2743 entity = [self planet];
2744 if (entity == nil)
2745 return nil;
2746 point1 = [entity position];
2747 radius = [entity radius];
2748 } else if ([route isEqualTo:@"ws"] || [route isEqualTo:@"sw"]) {
2749 point0 = [self getWitchspaceExitPosition];
2750 entity = [self sun];
2751 if (entity == nil)
2752 return nil;
2753 point1 = [entity position];
2754 radius = [entity radius];
2755 } else if ([route isEqualTo:@"sp"] || [route isEqualTo:@"ps"]) {
2756 entity = [self sun];
2757 if (entity == nil)
2758 return nil;
2759 point0 = [entity position];
2760 double radius0 = [entity radius];
2761
2762 entity = [self planet];
2763 if (entity == nil)
2764 return nil;
2765 point1 = [entity position];
2766 radius = [entity radius];
2767
2768 // shorten the route by scanner range & sun radius, otherwise ships could be created inside it.
2769 direction = HPvector_normal(HPvector_subtract(point0, point1));
2770 point0 = HPvector_subtract(point0, HPvector_multiply_scalar(direction, radius0 + SCANNER_MAX_RANGE * 1.1f));
2771 } else if ([route isEqualTo:@"st"]) {
2772 point0 = [self getWitchspaceExitPosition];
2773 if ([self station] == nil)
2774 return nil;
2775 point1 = [[self station] position];
2776 radius = [[self station] collisionRadius];
2777 } else
2778 return nil; // no route specifier? We shouldn't be here!
2779
2780 // shorten the route by scanner range & radius, otherwise ships could be created inside the route destination.
2781 direction = HPvector_normal(HPvector_subtract(point1, point0));
2782 point1 = HPvector_subtract(point1, HPvector_multiply_scalar(direction, radius + SCANNER_MAX_RANGE * 1.1f));
2783
2784 pos = [self fractionalPositionFrom:point0 to:point1 withFraction:routeFraction];
2785 if (isGroup) {
2786 return [self addShipsAt:pos withRole:role quantity:count withinRadius:(SCANNER_MAX_RANGE / 10.0f) asGroup:YES];
2787 } else {
2788 while (count--) {
2789 ship = [self addShipAt:pos withRole:role withinRadius:0]; // no radius because pos is already randomised with SCANNER_MAX_RANGE.
2790 if (ship != nil)
2791 [ships addObject:ship];
2792 if (count > 0)
2793 pos = [self fractionalPositionFrom:point0 to:point1 withFraction:routeFraction];
2794 }
2795
2796 if ([ships count] == 0)
2797 return nil;
2798 }
2799
2800 return [[ships copy] autorelease];
2801}
2802
2803- (BOOL)roleIsPirateVictim:(NSString*)role
2804{
2805 return [self role:role isInCategory:@"oolite-pirate-victim"];
2806}
2807
2808- (BOOL)role:(NSString*)role isInCategory:(NSString*)category
2809{
2810 NSSet* categoryInfo = [roleCategories objectForKey:category];
2811 if (categoryInfo == nil) {
2812 return NO;
2813 }
2814 return [categoryInfo containsObject:role];
2815}
2816
2817// used to avoid having lost escorts when player advances clock while docked
2819{
2820 unsigned i;
2821 for (i = 0; i < n_entities; i++) {
2822 if (sortedEntities[i]->isShip) {
2823 ShipEntity* my_ship = (ShipEntity*)sortedEntities[i];
2824 Entity* my_target = [my_ship primaryTarget];
2825 if ([my_target isWormhole]) {
2827 } else if ([[[my_ship getAI] state] isEqualToString:@"ENTER_WORMHOLE"]) {
2829 }
2830 }
2831 }
2832}
2833
2834- (void)addWitchspaceJumpEffectForShip:(ShipEntity*)ship
2835{
2836 // don't add rings when system is being populated
2837 if ([PLAYER status] != STATUS_ENTERING_WITCHSPACE && [PLAYER status] != STATUS_EXITING_WITCHSPACE) {
2840 }
2841}
2842
2844{
2845 for (unsigned i = 0; i < n_entities; i++) {
2846 Entity* e2 = sortedEntities[i];
2847 if ([e2 isShip] && [(ShipEntity*)e2 hasPrimaryRole:@"buoy-witchpoint"]) {
2849 }
2850 }
2851 return MIN_DISTANCE_TO_BUOY;
2852}
2853
2854- (void)setUpBreakPattern:(HPVector)pos orientation:(Quaternion)q forDocking:(BOOL)forDocking
2855{
2856 int i;
2857 OOBreakPatternEntity* ring = nil;
2858 id colorDesc = nil;
2859 OOColor* color = nil;
2860
2861 [self setViewDirection:VIEW_FORWARD];
2862
2863 q.w = -q.w; // reverse the quaternion because this is from the player's viewpoint
2864
2867
2868 // hyperspace colours
2869
2870 OOColor* col1 = [OOColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.5]; // standard tunnel colour
2871 OOColor* col2 = [OOColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.25]; // standard tunnel colour
2872
2873 colorDesc = [[self globalSettings] objectForKey:@"hyperspace_tunnel_color_1"];
2874 if (colorDesc != nil) {
2875 color = [OOColor colorWithDescription:colorDesc];
2876 if (color != nil)
2877 col1 = color;
2878 else
2879 OOLogWARN(@"hyperspaceTunnel.fromDict", @"could not interpret \"%@\" as a colour.", colorDesc);
2880 }
2881
2882 colorDesc = [[self globalSettings] objectForKey:@"hyperspace_tunnel_color_2"];
2883 if (colorDesc != nil) {
2884 color = [OOColor colorWithDescription:colorDesc];
2885 if (color != nil)
2886 col2 = color;
2887 else
2888 OOLogWARN(@"hyperspaceTunnel.fromDict", @"could not interpret \"%@\" as a colour.", colorDesc);
2889 }
2890
2891 unsigned sides = kOOBreakPatternMaxSides;
2892 GLfloat startAngle = 0;
2893 GLfloat aspectRatio = 1;
2894
2895 if (forDocking) {
2896 NSDictionary* info = [[PLAYER dockedStation] shipInfoDictionary];
2897 sides = [info oo_unsignedIntForKey:@"tunnel_corners" defaultValue:4];
2898 startAngle = [info oo_floatForKey:@"tunnel_start_angle" defaultValue:45.0f];
2899 aspectRatio = [info oo_floatForKey:@"tunnel_aspect_ratio" defaultValue:2.67f];
2900 }
2901
2902 for (i = 1; i < 11; i++) {
2903 ring = [OOBreakPatternEntity breakPatternWithPolygonSides:sides startAngle:startAngle aspectRatio:aspectRatio];
2904 if (!forDocking) {
2905 [ring setInnerColor:col1 outerColor:col2];
2906 }
2907
2909 [ring setPosition:HPvector_add(pos, vectorToHPVector(offset))]; // ahead of the player
2910 [ring setOrientation:q];
2911 [ring setVelocity:vel];
2912 [ring setLifetime:i * BREAK_PATTERN_RING_SPACING];
2913
2914 // FIXME: better would be to have break pattern timing not depend on
2915 // these ring objects existing in the first place. - CIM
2916 if (forDocking && ![[PLAYER dockedStation] hasBreakPattern]) {
2917 ring->isImmuneToBreakPatternHide = NO;
2918 } else if (!forDocking && ![self witchspaceBreakPattern]) {
2919 ring->isImmuneToBreakPatternHide = NO;
2920 }
2921 [self addEntity:ring];
2923 }
2924}
2925
2927{
2929}
2930
2931- (void)setWitchspaceBreakPattern:(BOOL)newValue
2932{
2933 _witchspaceBreakPattern = !!newValue;
2934}
2935
2940
2941- (void)setDockingClearanceProtocolActive:(BOOL)newValue
2942{
2945
2946 /* CIM: picking a random ship type which can take the same primary
2947 * role as the station to determine whether it has no set docking
2948 * clearance requirements seems unlikely to work entirely
2949 * correctly. To be fixed. */
2950
2951 foreach (station, allStations) {
2952 NSString* stationKey = [registry randomShipKeyForRole:[station primaryRole]];
2953 if (![[[registry shipInfoForKey:stationKey] allKeys] containsObject:@"requires_docking_clearance"]) {
2955 }
2956 }
2957
2959}
2960
2962{
2963 if ([[self gameController] playerFileToLoad]) {
2965 } else {
2966 [self setUseAddOns:SCENARIO_OXP_DEFINITION_ALL fromSaveGame:NO forceReinit:YES]; // calls reinitAndShowDemo
2967 }
2968}
2969
2970- (void)setupIntroFirstGo:(BOOL)justCobra
2971{
2972 PlayerEntity* player = PLAYER;
2973 ShipEntity* ship = nil;
2974 Quaternion q2 = { 0.0f, 0.0f, 1.0f, 0.0f }; // w,x,y,z
2975
2976 // in status demo draw ships and display text
2977 if (!justCobra) {
2980 // always, even if it's the cobra, because it's repositioned
2981 [self removeDemoShips];
2982 }
2983 if (justCobra) {
2984 [player setStatus:STATUS_START_GAME];
2985 }
2987 displayGUI = YES;
2988
2989 if (justCobra) {
2990 /*- cobra - intro1 -*/
2991 ship = [self newShipWithName:PLAYER_SHIP_DESC usePlayerProxy:YES];
2992 } else {
2993 /*- demo ships - intro2 -*/
2994
2995 demo_ship_index = 0;
2997
2998 /* Try to set the initial list position to Cobra III if
2999 * available, and at least the Ships category. */
3000 NSArray* subList = nil;
3001 foreach (subList, demo_ships) {
3002 if ([[[subList oo_dictionaryAtIndex:0] oo_stringForKey:kOODemoShipClass] isEqualToString:@"ship"]) {
3003 demo_ship_index = [demo_ships indexOfObject:subList];
3004 NSDictionary* shipEntry = nil;
3005 foreach (shipEntry, subList) {
3006 if ([[shipEntry oo_stringForKey:kOODemoShipKey] isEqualToString:@"cobra3-trader"]) {
3007 demo_ship_subindex = [subList indexOfObject:shipEntry];
3008 break;
3009 }
3010 }
3011 break;
3012 }
3013 }
3014
3015 if (!demo_ship)
3016 ship = [self newShipWithName:[[[demo_ships oo_arrayAtIndex:demo_ship_index] oo_dictionaryAtIndex:demo_ship_subindex] oo_stringForKey:kOODemoShipKey] usePlayerProxy:NO];
3017 // stop consistency problems on the ship library screen
3018 [ship removeEquipmentItem:@"EQ_SHIELD_BOOSTER"];
3019 [ship removeEquipmentItem:@"EQ_SHIELD_ENHANCER"];
3020 }
3021
3022 if (ship) {
3023 [ship setOrientation:q2];
3024 if (!justCobra) {
3025 [ship setPositionX:0.0f y:0.0f z:DEMO2_VANISHING_DISTANCE * ship->collision_radius * 0.01];
3026 [ship setDestination:ship->position]; // ideal position
3027 } else {
3028 // main screen Cobra is closer
3029 [ship setPositionX:0.0f y:0.0f z:3.6 * ship->collision_radius];
3030 }
3031 [ship setDemoShip:1.0f];
3032 [ship setDemoStartTime:universal_time];
3033 [ship setScanClass:CLASS_NO_DRAW];
3034 [ship switchAITo:@"nullAI.plist"];
3035 if ([ship pendingEscortCount] > 0)
3037 [self addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL
3038 // now override status
3039 [ship setStatus:STATUS_COCKPIT_DISPLAY];
3040 demo_ship = ship;
3041
3042 [ship release];
3043 }
3044
3045 if (!justCobra) {
3046 // [gui setText:[demo_ship displayName] forRow:19 align:GUI_ALIGN_CENTER];
3048 }
3049
3051 if (!justCobra) {
3054 }
3055}
3056
3057- (NSDictionary*)demoShipData
3058{
3059 return [[demo_ships oo_arrayAtIndex:demo_ship_index] oo_dictionaryAtIndex:demo_ship_subindex];
3060}
3061
3063{
3064 OOGUITabSettings tab_stops;
3065 tab_stops[0] = 0;
3066 tab_stops[1] = 170;
3067 tab_stops[2] = 340;
3068 [gui setTabStops:tab_stops];
3069
3070 /* [gui setText:[demo_ship displayName] forRow:19 align:GUI_ALIGN_CENTER];
3071 [gui setColor:[OOColor whiteColor] forRow:19]; */
3072
3073 NSDictionary* librarySettings = [self demoShipData];
3074
3075 OOGUIRow descRow = 7;
3076
3077 NSString* field1 = nil;
3078 NSString* field2 = nil;
3079 NSString* field3 = nil;
3080 NSString* override = nil;
3081
3082 // clear rows
3083 for (NSUInteger i = 1; i <= 26; i++) {
3084 [gui setText:@"" forRow:i];
3085 }
3086
3087 /* Row 1: ScanClass, Name, Summary */
3088 override = [librarySettings oo_stringForKey:kOODemoShipClass defaultValue:@"ship"];
3089 field1 = OOShipLibraryCategorySingular(override);
3090
3091 field2 = [demo_ship shipClassName];
3092
3093 override = [librarySettings oo_stringForKey:kOODemoShipSummary defaultValue:nil];
3094 if (override != nil) {
3095 field3 = OOExpand(override);
3096 } else {
3097 field3 = @"";
3098 }
3099 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:1];
3100 [gui setColor:[OOColor greenColor] forRow:1];
3101
3102 // ship_data defaults to true for "ship" class, false for everything else
3103 if (![librarySettings oo_boolForKey:kOODemoShipShipData defaultValue:[[librarySettings oo_stringForKey:kOODemoShipClass defaultValue:@"ship"] isEqualToString:@"ship"]]) {
3104 descRow = 3;
3105 } else {
3106 /* Row 2: Speed, Turn Rate, Cargo */
3107
3108 override = [librarySettings oo_stringForKey:kOODemoShipSpeed defaultValue:nil];
3109 if (override != nil) {
3110 if ([override length] == 0) {
3111 field1 = @"";
3112 } else {
3113 field1 = [NSString stringWithFormat:DESC(@"oolite-ship-library-speed-custom"), OOExpand(override)];
3114 }
3115 } else {
3116 field1 = OOShipLibrarySpeed(demo_ship);
3117 }
3118
3119 override = [librarySettings oo_stringForKey:kOODemoShipTurnRate defaultValue:nil];
3120 if (override != nil) {
3121 if ([override length] == 0) {
3122 field2 = @"";
3123 } else {
3124 field2 = [NSString stringWithFormat:DESC(@"oolite-ship-library-turn-custom"), OOExpand(override)];
3125 }
3126 } else {
3127 field2 = OOShipLibraryTurnRate(demo_ship);
3128 }
3129
3130 override = [librarySettings oo_stringForKey:kOODemoShipCargo defaultValue:nil];
3131 if (override != nil) {
3132 if ([override length] == 0) {
3133 field3 = @"";
3134 } else {
3135 field3 = [NSString stringWithFormat:DESC(@"oolite-ship-library-cargo-custom"), OOExpand(override)];
3136 }
3137 } else {
3138 field3 = OOShipLibraryCargo(demo_ship);
3139 }
3140
3141 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:3];
3142
3143 /* Row 3: recharge rate, energy banks, witchspace */
3144 override = [librarySettings oo_stringForKey:kOODemoShipGenerator defaultValue:nil];
3145 if (override != nil) {
3146 if ([override length] == 0) {
3147 field1 = @"";
3148 } else {
3149 field1 = [NSString stringWithFormat:DESC(@"oolite-ship-library-generator-custom"), OOExpand(override)];
3150 }
3151 } else {
3152 field1 = OOShipLibraryGenerator(demo_ship);
3153 }
3154
3155 override = [librarySettings oo_stringForKey:kOODemoShipShields defaultValue:nil];
3156 if (override != nil) {
3157 if ([override length] == 0) {
3158 field2 = @"";
3159 } else {
3160 field2 = [NSString stringWithFormat:DESC(@"oolite-ship-library-shields-custom"), OOExpand(override)];
3161 }
3162 } else {
3163 field2 = OOShipLibraryShields(demo_ship);
3164 }
3165
3166 override = [librarySettings oo_stringForKey:kOODemoShipWitchspace defaultValue:nil];
3167 if (override != nil) {
3168 if ([override length] == 0) {
3169 field3 = @"";
3170 } else {
3171 field3 = [NSString stringWithFormat:DESC(@"oolite-ship-library-witchspace-custom"), OOExpand(override)];
3172 }
3173 } else {
3174 field3 = OOShipLibraryWitchspace(demo_ship);
3175 }
3176
3177 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:4];
3178
3179 /* Row 4: weapons, turrets, size */
3180 override = [librarySettings oo_stringForKey:kOODemoShipWeapons defaultValue:nil];
3181 if (override != nil) {
3182 if ([override length] == 0) {
3183 field1 = @"";
3184 } else {
3185 field1 = [NSString stringWithFormat:DESC(@"oolite-ship-library-weapons-custom"), OOExpand(override)];
3186 }
3187 } else {
3188 field1 = OOShipLibraryWeapons(demo_ship);
3189 }
3190
3191 override = [librarySettings oo_stringForKey:kOODemoShipTurrets defaultValue:nil];
3192 if (override != nil) {
3193 if ([override length] == 0) {
3194 field2 = @"";
3195 } else {
3196 field2 = [NSString stringWithFormat:DESC(@"oolite-ship-library-turrets-custom"), OOExpand(override)];
3197 }
3198 } else {
3199 field2 = OOShipLibraryTurrets(demo_ship);
3200 }
3201
3202 override = [librarySettings oo_stringForKey:kOODemoShipSize defaultValue:nil];
3203 if (override != nil) {
3204 if ([override length] == 0) {
3205 field3 = @"";
3206 } else {
3207 field3 = [NSString stringWithFormat:DESC(@"oolite-ship-library-size-custom"), OOExpand(override)];
3208 }
3209 } else {
3210 field3 = OOShipLibrarySize(demo_ship);
3211 }
3212
3213 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:5];
3214 }
3215
3216 override = [librarySettings oo_stringForKey:kOODemoShipDescription defaultValue:nil];
3217 if (override != nil) {
3218 [gui addLongText:OOExpand(override) startingAtRow:descRow align:GUI_ALIGN_LEFT];
3219 }
3220
3221 // line 19: ship categories
3222 field1 = [NSString stringWithFormat:@"<-- %@", OOShipLibraryCategoryPlural([[[demo_ships objectAtIndex:((demo_ship_index + [demo_ships count] - 1) % [demo_ships count])] objectAtIndex:0] oo_stringForKey:kOODemoShipClass])];
3223 field2 = OOShipLibraryCategoryPlural([[[demo_ships objectAtIndex:demo_ship_index] objectAtIndex:0] oo_stringForKey:kOODemoShipClass]);
3224 field3 = [NSString stringWithFormat:@"%@ -->", OOShipLibraryCategoryPlural([[[demo_ships objectAtIndex:((demo_ship_index + 1) % [demo_ships count])] objectAtIndex:0] oo_stringForKey:kOODemoShipClass])];
3225
3226 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:19];
3227 [gui setColor:[OOColor greenColor] forRow:19];
3228
3229 // lines 21-25: ship names
3230 NSArray* subList = [demo_ships objectAtIndex:demo_ship_index];
3231 NSUInteger i, start = demo_ship_subindex - (demo_ship_subindex % 5);
3232 NSUInteger end = start + 4;
3233 if (end >= [subList count]) {
3234 end = [subList count] - 1;
3235 }
3236 OOGUIRow row = 21;
3237 field1 = @"";
3238 field3 = @"";
3239 for (i = start; i <= end; i++) {
3240 field2 = [[subList objectAtIndex:i] oo_stringForKey:kOODemoShipName];
3241 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:row];
3242 if (i == demo_ship_subindex) {
3243 [gui setColor:[OOColor yellowColor] forRow:row];
3244 } else {
3245 [gui setColor:[OOColor whiteColor] forRow:row];
3246 }
3247 row++;
3248 }
3249
3250 field2 = @"...";
3251 if (start > 0) {
3252 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:20];
3253 [gui setColor:[OOColor whiteColor] forRow:20];
3254 }
3255 if (end < [subList count] - 1) {
3256 [gui setArray:[NSArray arrayWithObjects:field1, field2, field3, nil] forRow:26];
3257 [gui setColor:[OOColor whiteColor] forRow:26];
3258 }
3259}
3260
3262{
3264 NSUInteger subcount = [[demo_ships objectAtIndex:demo_ship_index] count];
3265 demo_ship_subindex = (demo_ship_subindex + subcount - 2) % subcount;
3266 demo_stage_time = universal_time - 1.0; // force change
3267}
3268
3270{
3272 demo_ship_index = (demo_ship_index + [demo_ships count] - 1) % [demo_ships count];
3273 demo_ship_subindex = [[demo_ships objectAtIndex:demo_ship_index] count] - 1;
3274 demo_stage_time = universal_time - 1.0; // force change
3275}
3276
3278{
3281 demo_ship_subindex = [[demo_ships objectAtIndex:demo_ship_index] count] - 1;
3282 demo_stage_time = universal_time - 1.0; // force change
3283}
3284
3286{
3288 demo_stage_time = universal_time - 1.0; // force change
3289}
3290
3291static BOOL IsCandidateMainStationPredicate(Entity* entity, void* parameter)
3292{
3293 return [entity isStation] && !entity->isExplicitlyNotMainStation;
3294}
3295
3296static BOOL IsFriendlyStationPredicate(Entity* entity, void* parameter)
3297{
3298 return [entity isStation] && ![(ShipEntity*)entity isHostileTo:parameter];
3299}
3300
3302{
3303 if (cachedSun != nil && cachedStation == nil) {
3304 cachedStation = [self findOneEntityMatchingPredicate:IsCandidateMainStationPredicate
3305 parameter:nil];
3306 }
3307 return cachedStation;
3308}
3309
3310- (StationEntity*)stationWithRole:(NSString*)role andPosition:(HPVector)position
3311{
3312 if ([role isEqualToString:@""]) {
3313 return nil;
3314 }
3315
3316 float range = 1000000; // allow a little variation in position
3317
3318 NSArray* stations = [self stations];
3320 foreach (station, stations) {
3321 if (HPdistance2(position, [station position]) < range) {
3322 if ([[station primaryRole] isEqualToString:role]) {
3323 return station;
3324 }
3325 }
3326 }
3327 return nil;
3328}
3329
3330- (StationEntity*)stationFriendlyTo:(ShipEntity*)ship
3331{
3332 // In interstellar space we select a random friendly carrier as mainStation.
3333 // No caching: friendly status can change!
3334 return [self findOneEntityMatchingPredicate:IsFriendlyStationPredicate parameter:ship];
3335}
3336
3337- (OOPlanetEntity*)planet
3338{
3339 if (cachedPlanet == nil && [allPlanets count] > 0) {
3340 cachedPlanet = [allPlanets objectAtIndex:0];
3341 }
3342 return cachedPlanet;
3343}
3344
3346{
3347 if (cachedSun == nil) {
3348 cachedSun = [self findOneEntityMatchingPredicate:IsSunPredicate parameter:nil];
3349 }
3350 return cachedSun;
3351}
3352
3353- (NSArray*)planets
3354{
3355 return allPlanets;
3356}
3357
3358- (NSArray*)stations
3359{
3360 return [allStations allObjects];
3361}
3362
3363- (NSArray*)wormholes
3364{
3365 return activeWormholes;
3366}
3367
3369{
3370 /* During the demo screens, the player must remain docked in order for the
3371 UI to work. This means either enforcing invulnerability or launching
3372 the player when the station is destroyed even if on the "new game Y/N"
3373 screen.
3374
3375 The latter is a) weirder and b) harder. If your OXP relies on being
3376 able to destroy the main station before the game has even started,
3377 your OXP sucks.
3378 */
3379 OOEntityStatus playerStatus = [PLAYER status];
3380 if (playerStatus == STATUS_START_GAME)
3381 return;
3382
3383 StationEntity* theStation = [self station];
3384 if (theStation != nil)
3385 theStation->isExplicitlyNotMainStation = YES;
3387}
3388
3390{
3391 Entity<OOBeaconEntity>*beaconShip = [self firstBeacon], *next = nil;
3392 while (beaconShip) {
3393 next = [beaconShip nextBeacon];
3394 [beaconShip setPrevBeacon:nil];
3395 [beaconShip setNextBeacon:nil];
3396 beaconShip = next;
3397 }
3398
3399 [self setFirstBeacon:nil];
3400 [self setLastBeacon:nil];
3401}
3402
3403- (Entity<OOBeaconEntity>*)firstBeacon
3404{
3406}
3407
3408- (void)setFirstBeacon:(Entity<OOBeaconEntity>*)beacon
3409{
3410 if (beacon != [self firstBeacon]) {
3411 [beacon setPrevBeacon:nil];
3412 [beacon setNextBeacon:[self firstBeacon]];
3413 [[self firstBeacon] setPrevBeacon:beacon];
3414 [_firstBeacon release];
3415 _firstBeacon = [beacon weakRetain];
3416 }
3417}
3418
3419- (Entity<OOBeaconEntity>*)lastBeacon
3420{
3422}
3423
3424- (void)setLastBeacon:(Entity<OOBeaconEntity>*)beacon
3425{
3426 if (beacon != [self lastBeacon]) {
3427 [beacon setNextBeacon:nil];
3428 [beacon setPrevBeacon:[self lastBeacon]];
3429 [[self lastBeacon] setNextBeacon:beacon];
3430 [_lastBeacon release];
3431 _lastBeacon = [beacon weakRetain];
3432 }
3433}
3434
3435- (void)setNextBeacon:(Entity<OOBeaconEntity>*)beaconShip
3436{
3437 if ([beaconShip isBeacon]) {
3438 [self setLastBeacon:beaconShip];
3439 if ([self firstBeacon] == nil)
3440 [self setFirstBeacon:beaconShip];
3441 } else {
3442 OOLog(@"universe.beacon.error", @"***** ERROR: Universe setNextBeacon '%@'. The ship has no beacon code set.", beaconShip);
3443 }
3444}
3445
3446- (void)clearBeacon:(Entity<OOBeaconEntity>*)beaconShip
3447{
3449
3450 if ([beaconShip isBeacon]) {
3451 if ([self firstBeacon] == beaconShip) {
3452 tmp = [[beaconShip nextBeacon] nextBeacon];
3453 [self setFirstBeacon:[beaconShip nextBeacon]];
3454 [[beaconShip prevBeacon] setNextBeacon:tmp];
3455 } else if ([self lastBeacon] == beaconShip) {
3456 tmp = [[beaconShip prevBeacon] prevBeacon];
3457 [self setLastBeacon:[beaconShip prevBeacon]];
3458 [[beaconShip nextBeacon] setPrevBeacon:tmp];
3459 } else {
3460 [[beaconShip nextBeacon] setPrevBeacon:[beaconShip prevBeacon]];
3461 [[beaconShip prevBeacon] setNextBeacon:[beaconShip nextBeacon]];
3462 }
3463 [beaconShip setBeaconCode:nil];
3464 }
3465}
3466
3467- (NSDictionary*)currentWaypoints
3468{
3469 return waypoints;
3470}
3471
3472- (void)defineWaypoint:(NSDictionary*)definition forKey:(NSString*)key
3473{
3474 OOWaypointEntity* waypoint = nil;
3475 BOOL preserveCompass = NO;
3476 waypoint = [waypoints objectForKey:key];
3477 if (waypoint != nil) {
3478 if ([PLAYER compassTarget] == waypoint) {
3479 preserveCompass = YES;
3480 }
3481 [self removeEntity:waypoint];
3482 [waypoints removeObjectForKey:key];
3483 }
3484 if (definition != nil) {
3485 waypoint = [OOWaypointEntity waypointWithDictionary:definition];
3486 if (waypoint != nil) {
3487 [self addEntity:waypoint];
3488 [waypoints setObject:waypoint forKey:key];
3489 if (preserveCompass) {
3490 [PLAYER setCompassTarget:waypoint];
3491 [PLAYER setNextBeacon:waypoint];
3492 }
3493 }
3494 }
3495}
3496
3497- (GLfloat*)skyClearColor
3498{
3499 return skyClearColor;
3500}
3501
3502- (void)setSkyColorRed:(GLfloat)red green:(GLfloat)green blue:(GLfloat)blue alpha:(GLfloat)alpha
3503{
3504 skyClearColor[0] = red;
3505 skyClearColor[1] = green;
3506 skyClearColor[2] = blue;
3507 skyClearColor[3] = alpha;
3508 [self setAirResistanceFactor:alpha];
3509}
3510
3512{
3513 return (breakPatternCounter == 0);
3514}
3515
3517{
3518 Entity* player = PLAYER;
3519 return ((breakPatternCounter > 5) || (!player) || ([player status] == STATUS_DOCKING));
3520}
3521
3522#define PROFILE_SHIP_SELECTION 0
3523
3524- (BOOL)canInstantiateShip:(NSString*)shipKey
3525{
3526 NSDictionary* shipInfo = nil;
3527 NSArray* conditions = nil;
3528 NSString* condition_script = nil;
3529 shipInfo = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
3530
3531 condition_script = [shipInfo oo_stringForKey:@"condition_script"];
3532 if (condition_script != nil) {
3533 OOJSScript* condScript = [self getConditionScript:condition_script];
3534 if (condScript != nil) // should always be non-nil, but just in case
3535 {
3536 JSContext* context = OOJSAcquireContext();
3537 BOOL OK;
3538 BOOL allow_instantiation = NO;
3539 OOJSVal result = OOJSUndefinedValue();
3540 OOJSVal args[] = { OOJSValueFromNativeObject(context, shipKey) };
3541
3542 OK = [condScript callMethod:OOJSID("allowSpawnShip")
3543 inContext:context
3544 withArguments:args
3545 count:sizeof args / sizeof *args
3546 result:&result];
3547
3548 if (OK)
3549 allow_instantiation = OOJSValueToBOOL(context, result);
3550
3551 OOJSFreeValue(context, result);
3552 OOJSFreeValue(context, args[0]);
3553 OOJSRelinquishContext(context);
3554
3555 if (OK && !allow_instantiation) {
3556 /* if the script exists, the function exists, the function
3557 * returns a bool, and that bool is false, block
3558 * instantiation. Otherwise allow it as default */
3559 return NO;
3560 }
3561 }
3562 }
3563
3564 conditions = [shipInfo oo_arrayForKey:@"conditions"];
3565 if (conditions == nil)
3566 return YES;
3567
3568 // Check conditions
3569 return [PLAYER scriptTestConditions:conditions];
3570}
3571
3572- (NSString*)randomShipKeyForRoleRespectingConditions:(NSString*)role
3573{
3575
3577 NSString* shipKey = nil;
3579
3580#if PROFILE_SHIP_SELECTION
3581 static unsigned long profTotal = 0, profSlowPath = 0;
3582 ++profTotal;
3583#endif
3584
3585 // Select a ship, check conditions and return it if possible.
3586 shipKey = [registry randomShipKeyForRole:role];
3587 if ([self canInstantiateShip:shipKey])
3588 return shipKey;
3589
3590 /* If we got here, condition check failed.
3591 We now need to keep trying until we either find an acceptable ship or
3592 run out of candidates.
3593 This is special-cased because it has more overhead than the more
3594 common conditionless lookup.
3595 */
3596
3597#if PROFILE_SHIP_SELECTION
3598 ++profSlowPath;
3599 if ((profSlowPath % 10) == 0) // Only print every tenth slow path, to reduce spamminess.
3600 {
3601 OOLog(@"shipRegistry.selection.profile", @"Hit slow path in ship selection for role \"%@\", having selected ship \"%@\". Now %zu of %zu on slow path (%f%%).", role, shipKey, profSlowPath, profTotal, ((double)profSlowPath) / ((double)profTotal) * 100.0f);
3602 }
3603#endif
3604
3605 pset = [[[registry probabilitySetForRole:role] mutableCopy] autorelease];
3606
3607 while ([pset count] > 0) {
3608 // Select a ship, check conditions and return it if possible.
3609 shipKey = [pset randomObject];
3610 if ([self canInstantiateShip:shipKey])
3611 return shipKey;
3612
3613 // Condition failed -> remove ship from consideration.
3614 [pset removeObject:shipKey];
3615 }
3616
3617 // If we got here, some ships existed but all failed conditions test.
3618 return nil;
3619
3621}
3622
3623- (ShipEntity*)newShipWithRole:(NSString*)role
3624{
3626
3627 ShipEntity* ship = nil;
3628 NSString* shipKey = nil;
3629 NSDictionary* shipInfo = nil;
3630 NSString* autoAI = nil;
3631
3632 shipKey = [self randomShipKeyForRoleRespectingConditions:role];
3633 if (shipKey != nil) {
3634 ship = [self newShipWithName:shipKey];
3635 if (ship != nil) {
3636 [ship setPrimaryRole:role];
3637
3638 shipInfo = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
3639 if ([shipInfo oo_fuzzyBooleanForKey:@"auto_ai" defaultValue:YES]) {
3640 // Set AI based on role
3641 autoAI = [self defaultAIForRole:role];
3642 if (autoAI != nil) {
3643 [ship setAITo:autoAI];
3644 // Nikos 20090604
3645 // Pirate, trader or police with auto_ai? Follow populator rules for them.
3646 if ([role isEqualToString:@"pirate"])
3647 [ship setBounty:20 + randf() * 50 withReason:kOOLegalStatusReasonSetup];
3648 if ([role isEqualToString:@"trader"])
3649 [ship setBounty:0 withReason:kOOLegalStatusReasonSetup];
3650 if ([role isEqualToString:@"police"])
3651 [ship setScanClass:CLASS_POLICE];
3652 if ([role isEqualToString:@"interceptor"]) {
3653 [ship setScanClass:CLASS_POLICE];
3654 [ship setPrimaryRole:@"police"]; // to make sure interceptors get the correct pilot later on.
3655 }
3656 }
3657 if ([role isEqualToString:@"thargoid"])
3658 [ship setScanClass:CLASS_THARGOID]; // thargoids are not on the autoAIMap
3659 }
3660 }
3661 }
3662
3663 return ship;
3664
3666}
3667
3668- (OOVisualEffectEntity*)newVisualEffectWithName:(NSString*)effectKey
3669{
3671
3672 NSDictionary* effectDict = nil;
3673 OOVisualEffectEntity* effect = nil;
3674
3675 effectDict = [[OOShipRegistry sharedRegistry] effectInfoForKey:effectKey];
3676 if (effectDict == nil)
3677 return nil;
3678
3679 @try {
3680 effect = [[OOVisualEffectEntity alloc] initWithKey:effectKey definition:effectDict];
3681 }
3682 @catch (NSException* exception) {
3683 if ([[exception name] isEqual:OOLITE_EXCEPTION_DATA_NOT_FOUND]) {
3684 OOLog(kOOLogException, @"***** Oolite Exception : '%@' in [Universe newVisualEffectWithName: %@ ] *****", [exception reason], effectKey);
3685 } else
3686 @throw exception;
3687 }
3688
3689 return effect;
3690
3692}
3693
3694- (ShipEntity*)newSubentityWithName:(NSString*)shipKey andScaleFactor:(float)scale
3695{
3696 return [self newShipWithName:shipKey usePlayerProxy:NO isSubentity:YES andScaleFactor:scale];
3697}
3698
3699- (ShipEntity*)newShipWithName:(NSString*)shipKey usePlayerProxy:(BOOL)usePlayerProxy
3700{
3701 return [self newShipWithName:shipKey usePlayerProxy:usePlayerProxy isSubentity:NO];
3702}
3703
3704- (ShipEntity*)newShipWithName:(NSString*)shipKey usePlayerProxy:(BOOL)usePlayerProxy isSubentity:(BOOL)isSubentity
3705{
3706 return [self newShipWithName:shipKey usePlayerProxy:usePlayerProxy isSubentity:isSubentity andScaleFactor:1.0f];
3707}
3708
3709- (ShipEntity*)newShipWithName:(NSString*)shipKey usePlayerProxy:(BOOL)usePlayerProxy isSubentity:(BOOL)isSubentity andScaleFactor:(float)scale
3710{
3712
3713 NSDictionary* shipDict = nil;
3714 ShipEntity* ship = nil;
3715
3716 shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
3717 if (shipDict == nil)
3718 return nil;
3719
3720 volatile Class shipClass = nil;
3721 if (isSubentity) {
3722 shipClass = [ShipEntity class];
3723 } else {
3724 shipClass = [self shipClassForShipDictionary:shipDict];
3725 if (usePlayerProxy && shipClass == [ShipEntity class]) {
3726 shipClass = [ProxyPlayerEntity class];
3727 }
3728 }
3729
3730 @try {
3731 if (scale != 1.0f) {
3732 NSMutableDictionary* mShipDict = [shipDict mutableCopy];
3733 [mShipDict setObject:[NSNumber numberWithFloat:scale] forKey:@"model_scale_factor"];
3734 shipDict = [NSDictionary dictionaryWithDictionary:mShipDict];
3735 [mShipDict release];
3736 }
3737 ship = [[shipClass alloc] initWithKey:shipKey definition:shipDict];
3738 }
3739 @catch (NSException* exception) {
3740 if ([[exception name] isEqual:OOLITE_EXCEPTION_DATA_NOT_FOUND]) {
3741 OOLog(kOOLogException, @"***** Oolite Exception : '%@' in [Universe newShipWithName: %@ ] *****", [exception reason], shipKey);
3742 } else
3743 @throw exception;
3744 }
3745
3746 // Set primary role to same as ship name, if ship name is also a role.
3747 // Otherwise, if caller doesn't set a role, one will be selected randomly.
3748 if ([ship hasRole:shipKey])
3749 [ship setPrimaryRole:shipKey];
3750
3751 return ship;
3752
3754}
3755
3756- (DockEntity*)newDockWithName:(NSString*)shipDataKey andScaleFactor:(float)scale
3757{
3759
3760 NSDictionary* shipDict = nil;
3761 DockEntity* dock = nil;
3762
3763 shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipDataKey];
3764 if (shipDict == nil)
3765 return nil;
3766
3767 @try {
3768 if (scale != 1.0f) {
3769 NSMutableDictionary* mShipDict = [shipDict mutableCopy];
3770 [mShipDict setObject:[NSNumber numberWithFloat:scale] forKey:@"model_scale_factor"];
3771 shipDict = [NSDictionary dictionaryWithDictionary:mShipDict];
3772 [mShipDict release];
3773 }
3774 dock = [[DockEntity alloc] initWithKey:shipDataKey definition:shipDict];
3775 }
3776 @catch (NSException* exception) {
3777 if ([[exception name] isEqual:OOLITE_EXCEPTION_DATA_NOT_FOUND]) {
3778 OOLog(kOOLogException, @"***** Oolite Exception : '%@' in [Universe newDockWithName: %@ ] *****", [exception reason], shipDataKey);
3779 } else
3780 @throw exception;
3781 }
3782
3783 // Set primary role to same as name, if ship name is also a role.
3784 // Otherwise, if caller doesn't set a role, one will be selected randomly.
3785 if ([dock hasRole:shipDataKey])
3786 [dock setPrimaryRole:shipDataKey];
3787
3788 return dock;
3789
3791}
3792
3793- (ShipEntity*)newShipWithName:(NSString*)shipKey
3794{
3795 return [self newShipWithName:shipKey usePlayerProxy:NO];
3796}
3797
3798- (Class)shipClassForShipDictionary:(NSDictionary*)dict
3799{
3801
3802 if (dict == nil)
3803 return Nil;
3804
3805 BOOL isStation = NO;
3806 NSString* shipRoles = [dict oo_stringForKey:@"roles"];
3807
3808 if (shipRoles != nil) {
3809 isStation = [shipRoles rangeOfString:@"station"].location != NSNotFound ||
3810 [shipRoles rangeOfString:@"carrier"].location != NSNotFound;
3811 }
3812
3813 // Note priority here: is_carrier overrides isCarrier which overrides roles.
3814 isStation = [dict oo_boolForKey:@"isCarrier" defaultValue:isStation];
3815 isStation = [dict oo_boolForKey:@"is_carrier" defaultValue:isStation];
3816
3817 return isStation ? [StationEntity class] : [ShipEntity class];
3818
3820}
3821
3822- (NSString*)defaultAIForRole:(NSString*)role
3823{
3824 return [autoAIMap oo_stringForKey:role];
3825}
3826
3827- (OOCargoQuantity)maxCargoForShip:(NSString*)desc
3828{
3829 return [[[OOShipRegistry sharedRegistry] shipInfoForKey:desc] oo_unsignedIntForKey:@"max_cargo" defaultValue:0];
3830}
3831
3832/*
3833 * Price for an item expressed in 10ths of credits (divide by 10 to get credits)
3834 */
3835- (OOCreditsQuantity)getEquipmentPriceForKey:(NSString*)eq_key
3836{
3837 NSArray* itemData;
3838 foreach (itemData, equipmentData) {
3839 NSString* itemType = [itemData oo_stringAtIndex:EQUIPMENT_KEY_INDEX];
3840
3841 if ([itemType isEqual:eq_key]) {
3842 return [itemData oo_unsignedLongLongAtIndex:EQUIPMENT_PRICE_INDEX];
3843 }
3844 }
3845 return 0;
3846}
3847
3849{
3850 return commodities;
3851}
3852
3853/* Converts template cargo pods to real ones */
3854- (ShipEntity*)reifyCargoPod:(ShipEntity*)cargoObj
3855{
3856 if ([cargoObj isTemplateCargoPod]) {
3857 return [UNIVERSE cargoPodFromTemplate:cargoObj];
3858 } else {
3859 return cargoObj;
3860 }
3861}
3862
3863- (ShipEntity*)cargoPodFromTemplate:(ShipEntity*)cargoObj
3864{
3865 ShipEntity* container = nil;
3866 // this is a template container, so we need to make a real one
3868 OOCargoQuantity co_amount = [UNIVERSE getRandomAmountOfCommodity:co_type];
3869 if (randf() < 0.5) // stops OXP monopolising pods for commodities
3870 {
3871 container = [UNIVERSE newShipWithRole:co_type]; // newShipWithRole returns retained object
3872 }
3873 if (container == nil) {
3874 container = [UNIVERSE newShipWithRole:@"cargopod"];
3875 }
3876 [container setCommodity:co_type andAmount:co_amount];
3877 return [container autorelease];
3878}
3879
3880- (NSArray*)getContainersOfGoods:(OOCargoQuantity)how_many scarce:(BOOL)scarce legal:(BOOL)legal
3881{
3882 /* build list of goods allocating 0..100 for each based on how much of
3883 each quantity there is. Use a ratio of n x 100/64 for plentiful goods;
3884 reverse the probabilities for scarce goods.
3885 */
3886 NSMutableArray* accumulator = [NSMutableArray arrayWithCapacity:how_many];
3887 NSUInteger i = 0, commodityCount = [commodityMarket count];
3888 OOCargoQuantity quantities[commodityCount];
3889 OOCargoQuantity total_quantity = 0;
3890
3891 NSArray* goodsKeys = [commodityMarket goods];
3892 NSString* goodsKey = nil;
3893
3894 foreach (goodsKey, goodsKeys) {
3896 if (scarce) {
3897 if (q < 64)
3898 q = 64 - q;
3899 else
3900 q = 0;
3901 }
3902 // legal YES restricts (almost) only to legal goods
3903 // legal NO allows illegal goods, but not necessarily a full hold
3904 if (legal && [commodityMarket exportLegalityForGood:goodsKey] > 0) {
3905 q &= 1; // keep a very small chance, sometimes
3906 }
3907 if (q > 64)
3908 q = 64;
3909 q *= 100;
3910 q /= 64;
3911 quantities[i++] = q;
3912 total_quantity += q;
3913 }
3914 // quantities is now used to determine which good get into the containers
3915 for (i = 0; i < how_many; i++) {
3916 NSUInteger co_type = 0;
3917
3918 int qr = 0;
3919 if (total_quantity) {
3920 qr = 1 + (Ranrot() % total_quantity);
3921 co_type = 0;
3922 while (qr > 0) {
3923 NSAssert((NSUInteger)co_type < commodityCount, @"Commodity type index out of range.");
3924 qr -= quantities[co_type++];
3925 }
3926 co_type--;
3927 }
3928
3929 ShipEntity* container = [cargoPods objectForKey:[goodsKeys oo_stringAtIndex:co_type]];
3930
3931 if (container != nil) {
3932 [accumulator addObject:container];
3933 } else {
3934 OOLog(@"universe.createContainer.failed", @"***** ERROR: failed to find a container to fill with %@ (%zu).", [goodsKeys oo_stringAtIndex:co_type], co_type);
3935 }
3936 }
3937 return [NSArray arrayWithArray:accumulator];
3938}
3939
3940- (NSArray*)getContainersOfCommodity:(OOCommodityType)commodity_name how_much:(OOCargoQuantity)how_much
3941{
3942 NSMutableArray* accumulator = [NSMutableArray arrayWithCapacity:how_much];
3943 if (![commodities goodDefined:commodity_name]) {
3944 return [NSArray array]; // empty array
3945 }
3946
3947 ShipEntity* container = [cargoPods objectForKey:commodity_name];
3948 while (how_much > 0) {
3949 if (container) {
3950 [accumulator addObject:container];
3951 } else {
3952 OOLog(@"universe.createContainer.failed", @"***** ERROR: failed to find a container to fill with %@", commodity_name);
3953 }
3954
3955 how_much--;
3956 }
3957 return [NSArray arrayWithArray:accumulator];
3958}
3959
3960- (void)fillCargopodWithRandomCargo:(ShipEntity*)cargopod
3961{
3962 if (cargopod == nil || ![cargopod hasRole:@"cargopod"] || [cargopod cargoType] == CARGO_SCRIPTED_ITEM)
3963 return;
3964
3965 if ([cargopod commodityType] == nil || ![cargopod commodityAmount]) {
3966 NSString* aCommodity = [self getRandomCommodity];
3967 OOCargoQuantity aQuantity = [self getRandomAmountOfCommodity:aCommodity];
3968 [cargopod setCommodity:aCommodity andAmount:aQuantity];
3969 }
3970}
3971
3973{
3975}
3976
3977- (OOCargoQuantity)getRandomAmountOfCommodity:(OOCommodityType)co_type
3978{
3979 OOMassUnit units;
3980
3981 if (co_type == nil) {
3982 return 0;
3983 }
3984
3985 units = [commodities massUnitForGood:co_type];
3986 switch (units) {
3987 case 0: // TONNES
3988 return 1;
3989 case 1: // KILOGRAMS
3990 return 1 + (Ranrot() % 6) + (Ranrot() % 6) + (Ranrot() % 6);
3991 case 2: // GRAMS
3992 return 4 + (Ranrot() % 16) + (Ranrot() % 11) + (Ranrot() % 6);
3993 }
3994 OOLog(@"universe.commodityAmount.warning", @"Commodity %@ has an unrecognised mass unit, assuming tonnes", co_type);
3995 return 1;
3996}
3997
3998- (NSDictionary*)commodityDataForType:(OOCommodityType)type
3999{
4000 return [commodityMarket definitionForGood:type];
4001}
4002
4003- (NSString*)displayNameForCommodity:(OOCommodityType)co_type
4004{
4005 return [commodityMarket nameForGood:co_type];
4006}
4007
4008- (NSString*)describeCommodity:(OOCommodityType)co_type amount:(OOCargoQuantity)co_amount
4009{
4010 int units;
4011 NSString *unitDesc = nil, *typeDesc = nil;
4012 NSDictionary* commodity = [self commodityDataForType:co_type];
4013
4014 if (commodity == nil)
4015 return @"";
4016
4017 units = [commodityMarket massUnitForGood:co_type];
4018 if (co_amount == 1) {
4019 switch (units) {
4020 case UNITS_KILOGRAMS: // KILOGRAM
4021 unitDesc = DESC(@"cargo-kilogram");
4022 break;
4023 case UNITS_GRAMS: // GRAM
4024 unitDesc = DESC(@"cargo-gram");
4025 break;
4026 case UNITS_TONS: // TONNE
4027 default:
4028 unitDesc = DESC(@"cargo-ton");
4029 break;
4030 }
4031 } else {
4032 switch (units) {
4033 case UNITS_KILOGRAMS: // KILOGRAMS
4034 unitDesc = DESC(@"cargo-kilograms");
4035 break;
4036 case UNITS_GRAMS: // GRAMS
4037 unitDesc = DESC(@"cargo-grams");
4038 break;
4039 case UNITS_TONS: // TONNES
4040 default:
4041 unitDesc = DESC(@"cargo-tons");
4042 break;
4043 }
4044 }
4045
4046 typeDesc = [commodityMarket nameForGood:co_type];
4047
4048 return [NSString stringWithFormat:@"%d %@ %@", co_amount, unitDesc, typeDesc];
4049}
4050
4052
4053- (void)setGameView:(MyOpenGLView*)view
4054{
4055 [gameView release];
4056 gameView = [view retain];
4057}
4058
4060{
4061 return gameView;
4062}
4063
4065{
4066 return [[self gameView] gameController];
4067}
4068
4069- (NSDictionary*)gameSettings
4070{
4071#if OOLITE_SDL
4072 NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:12];
4073#else
4074 NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:10];
4075#endif
4076
4077 [result oo_setInteger:[PLAYER isSpeechOn]
4078 forKey:@"speechOn"];
4079 [result oo_setBool:autoSave forKey:@"autosave"];
4080 [result oo_setBool:wireframeGraphics forKey:@"wireframeGraphics"];
4081 [result oo_setBool:doProcedurallyTexturedPlanets forKey:@"procedurallyTexturedPlanets"];
4082
4083 [result oo_setFloat:[gameView fov:NO] forKey:@"fovValue"];
4084
4085#if OOLITE_WINDOWS
4086 if ([gameView hdrOutput]) {
4087 [result oo_setFloat:[gameView hdrMaxBrightness] forKey:@"hdr-max-brightness"];
4088 [result oo_setFloat:[gameView hdrPaperWhiteBrightness] forKey:@"hdr-paperwhite-brightness"];
4089 [result setObject:OOStringFromHDRToneMapper([gameView hdrToneMapper]) forKey:@"hdr-tone-mapper"];
4090 }
4091#endif
4092
4093 [result setObject:OOStringFromSDRToneMapper([gameView sdrToneMapper])
4094 forKey:@"sdr-tone-mapper"];
4095
4096 [result setObject:OOStringFromGraphicsDetail([self detailLevel]) forKey:@"detailLevel"];
4097
4098 NSString* desc = @"UNDEFINED";
4099 switch ([[OOMusicController sharedController] mode]) {
4100 case kOOMusicOff:
4101 desc = @"MUSIC_OFF";
4102 break;
4103 case kOOMusicOn:
4104 desc = @"MUSIC_ON";
4105 break;
4106 case kOOMusicITunes:
4107 desc = @"MUSIC_ITUNES";
4108 break;
4109 }
4110 [result setObject:desc forKey:@"musicMode"];
4111
4112 NSDictionary* gameWindow = [NSDictionary dictionaryWithObjectsAndKeys:
4113 [NSNumber numberWithFloat:[gameView backingViewSize].width], @"width",
4114 [NSNumber numberWithFloat:[gameView backingViewSize].height], @"height",
4115 [NSNumber numberWithBool:[[self gameController] inFullScreenMode]], @"fullScreen",
4116 nil];
4117 [result setObject:gameWindow forKey:@"gameWindow"];
4118
4119 [result setObject:[PLAYER keyConfig] forKey:@"keyConfig"];
4120
4121 return [[result copy] autorelease];
4122}
4123
4124- (void)useGUILightSource:(BOOL)GUILight
4125{
4126 if (GUILight != demo_light_on) {
4127 if (![self useShaders]) {
4128 if (GUILight) {
4129 OOGL(glEnable(GL_LIGHT0));
4130 OOGL(glDisable(GL_LIGHT1));
4131 } else {
4132 OOGL(glEnable(GL_LIGHT1));
4133 OOGL(glDisable(GL_LIGHT0));
4134 }
4135 }
4136 // There should be nothing to do for shaders, they use the same (always on) light source
4137 // both in flight & in gui mode. According to the standard, shaders should treat lights as
4138 // always enabled. At least one non-standard shader implementation (windows' X3100 Intel
4139 // core with GM965 chipset and version 6.14.10.4990 driver) does _not_ use glDisabled lights,
4140 // making the following line necessary.
4141
4142 else
4143 OOGL(glEnable(GL_LIGHT1)); // make sure we have a light, even with shaders (!)
4144
4145 demo_light_on = GUILight;
4146 }
4147}
4148
4149- (void)lightForEntity:(BOOL)isLit
4150{
4151 if (isLit != object_light_on) {
4152 if ([self useShaders]) {
4153 if (isLit) {
4154 OOGL(glLightfv(GL_LIGHT1, GL_DIFFUSE, sun_diffuse));
4155 OOGL(glLightfv(GL_LIGHT1, GL_SPECULAR, sun_specular));
4156 } else {
4157 OOGL(glLightfv(GL_LIGHT1, GL_DIFFUSE, sun_off));
4158 OOGL(glLightfv(GL_LIGHT1, GL_SPECULAR, sun_off));
4159 }
4160 } else {
4161 if (!demo_light_on) {
4162 if (isLit)
4163 OOGL(glEnable(GL_LIGHT1));
4164 else
4165 OOGL(glDisable(GL_LIGHT1));
4166 } else {
4167 // If we're in demo/GUI mode we should always have a lit object.
4168 OOGL(glEnable(GL_LIGHT0));
4169
4170 // Redundant, see above.
4171 // if (isLit) OOGL(glEnable(GL_LIGHT0));
4172 // else OOGL(glDisable(GL_LIGHT0));
4173 }
4174 }
4175
4176 object_light_on = isLit;
4177 }
4178}
4179
4180// global rotation matrix definitions
4181static const OOMatrix fwd_matrix = { { { 1.0f, 0.0f, 0.0f, 0.0f },
4182 { 0.0f, 1.0f, 0.0f, 0.0f },
4183 { 0.0f, 0.0f, 1.0f, 0.0f },
4184 { 0.0f, 0.0f, 0.0f, 1.0f } } };
4185static const OOMatrix aft_matrix = { { { -1.0f, 0.0f, 0.0f, 0.0f },
4186 { 0.0f, 1.0f, 0.0f, 0.0f },
4187 { 0.0f, 0.0f, -1.0f, 0.0f },
4188 { 0.0f, 0.0f, 0.0f, 1.0f } } };
4189static const OOMatrix port_matrix = { { { 0.0f, 0.0f, -1.0f, 0.0f },
4190 { 0.0f, 1.0f, 0.0f, 0.0f },
4191 { 1.0f, 0.0f, 0.0f, 0.0f },
4192 { 0.0f, 0.0f, 0.0f, 1.0f } } };
4193static const OOMatrix starboard_matrix = { { { 0.0f, 0.0f, 1.0f, 0.0f },
4194 { 0.0f, 1.0f, 0.0f, 0.0f },
4195 { -1.0f, 0.0f, 0.0f, 0.0f },
4196 { 0.0f, 0.0f, 0.0f, 1.0f } } };
4197
4198- (void)getActiveViewMatrix:(OOMatrix*)outMatrix forwardVector:(Vector*)outForward upVector:(Vector*)outUp
4199{
4200 assert(outMatrix != NULL && outForward != NULL && outUp != NULL);
4201
4202 PlayerEntity* player = nil;
4203
4204 switch (viewDirection) {
4205 case VIEW_AFT:
4206 *outMatrix = aft_matrix;
4207 *outForward = vector_flip(kBasisZVector);
4208 *outUp = kBasisYVector;
4209 return;
4210
4211 case VIEW_PORT:
4212 *outMatrix = port_matrix;
4213 *outForward = vector_flip(kBasisXVector);
4214 *outUp = kBasisYVector;
4215 return;
4216
4217 case VIEW_STARBOARD:
4218 *outMatrix = starboard_matrix;
4219 *outForward = kBasisXVector;
4220 *outUp = kBasisYVector;
4221 return;
4222
4223 case VIEW_CUSTOM:
4224 player = PLAYER;
4225 *outMatrix = [player customViewMatrix];
4226 *outForward = [player customViewForwardVector];
4227 *outUp = [player customViewUpVector];
4228 return;
4229
4230 case VIEW_FORWARD:
4231 case VIEW_NONE:
4232 case VIEW_GUI_DISPLAY:
4233 case VIEW_BREAK_PATTERN:;
4234 }
4235
4236 *outMatrix = fwd_matrix;
4237 *outForward = kBasisZVector;
4238 *outUp = kBasisYVector;
4239}
4240
4242{
4243 OOMatrix m;
4244 Vector f, u;
4245
4247 return m;
4248}
4249
4250/* Code adapted from http://www.crownandcutlass.com/features/technicaldetails/frustum.html
4251 * Original license is: "This page and its contents are Copyright 2000 by Mark Morley
4252 * Unless otherwise noted, you may use any and all code examples provided herein in any way you want."
4253 */
4254
4256{
4257 OOMatrix clip;
4258 GLfloat rt;
4259
4261
4262 /* Extract the numbers for the RIGHT plane */
4263 frustum[0][0] = clip.m[0][3] - clip.m[0][0];
4264 frustum[0][1] = clip.m[1][3] - clip.m[1][0];
4265 frustum[0][2] = clip.m[2][3] - clip.m[2][0];
4266 frustum[0][3] = clip.m[3][3] - clip.m[3][0];
4267
4268 /* Normalize the result */
4269 rt = 1.0f / sqrt(frustum[0][0] * frustum[0][0] + frustum[0][1] * frustum[0][1] + frustum[0][2] * frustum[0][2]);
4270 frustum[0][0] *= rt;
4271 frustum[0][1] *= rt;
4272 frustum[0][2] *= rt;
4273 frustum[0][3] *= rt;
4274
4275 /* Extract the numbers for the LEFT plane */
4276 frustum[1][0] = clip.m[0][3] + clip.m[0][0];
4277 frustum[1][1] = clip.m[1][3] + clip.m[1][0];
4278 frustum[1][2] = clip.m[2][3] + clip.m[2][0];
4279 frustum[1][3] = clip.m[3][3] + clip.m[3][0];
4280
4281 /* Normalize the result */
4282 rt = 1.0f / sqrt(frustum[1][0] * frustum[1][0] + frustum[1][1] * frustum[1][1] + frustum[1][2] * frustum[1][2]);
4283 frustum[1][0] *= rt;
4284 frustum[1][1] *= rt;
4285 frustum[1][2] *= rt;
4286 frustum[1][3] *= rt;
4287
4288 /* Extract the BOTTOM plane */
4289 frustum[2][0] = clip.m[0][3] + clip.m[0][1];
4290 frustum[2][1] = clip.m[1][3] + clip.m[1][1];
4291 frustum[2][2] = clip.m[2][3] + clip.m[2][1];
4292 frustum[2][3] = clip.m[3][3] + clip.m[3][1];
4293
4294 /* Normalize the result */
4295 rt = 1.0 / sqrt(frustum[2][0] * frustum[2][0] + frustum[2][1] * frustum[2][1] + frustum[2][2] * frustum[2][2]);
4296 frustum[2][0] *= rt;
4297 frustum[2][1] *= rt;
4298 frustum[2][2] *= rt;
4299 frustum[2][3] *= rt;
4300
4301 /* Extract the TOP plane */
4302 frustum[3][0] = clip.m[0][3] - clip.m[0][1];
4303 frustum[3][1] = clip.m[1][3] - clip.m[1][1];
4304 frustum[3][2] = clip.m[2][3] - clip.m[2][1];
4305 frustum[3][3] = clip.m[3][3] - clip.m[3][1];
4306
4307 /* Normalize the result */
4308 rt = 1.0 / sqrt(frustum[3][0] * frustum[3][0] + frustum[3][1] * frustum[3][1] + frustum[3][2] * frustum[3][2]);
4309 frustum[3][0] *= rt;
4310 frustum[3][1] *= rt;
4311 frustum[3][2] *= rt;
4312 frustum[3][3] *= rt;
4313
4314 /* Extract the FAR plane */
4315 frustum[4][0] = clip.m[0][3] - clip.m[0][2];
4316 frustum[4][1] = clip.m[1][3] - clip.m[1][2];
4317 frustum[4][2] = clip.m[2][3] - clip.m[2][2];
4318 frustum[4][3] = clip.m[3][3] - clip.m[3][2];
4319
4320 /* Normalize the result */
4321 rt = sqrt(frustum[4][0] * frustum[4][0] + frustum[4][1] * frustum[4][1] + frustum[4][2] * frustum[4][2]);
4322 frustum[4][0] *= rt;
4323 frustum[4][1] *= rt;
4324 frustum[4][2] *= rt;
4325 frustum[4][3] *= rt;
4326
4327 /* Extract the NEAR plane */
4328 frustum[5][0] = clip.m[0][3] + clip.m[0][2];
4329 frustum[5][1] = clip.m[1][3] + clip.m[1][2];
4330 frustum[5][2] = clip.m[2][3] + clip.m[2][2];
4331 frustum[5][3] = clip.m[3][3] + clip.m[3][2];
4332
4333 /* Normalize the result */
4334 rt = sqrt(frustum[5][0] * frustum[5][0] + frustum[5][1] * frustum[5][1] + frustum[5][2] * frustum[5][2]);
4335 frustum[5][0] *= rt;
4336 frustum[5][1] *= rt;
4337 frustum[5][2] *= rt;
4338 frustum[5][3] *= rt;
4339}
4340
4341- (BOOL)viewFrustumIntersectsSphereAt:(Vector)position withRadius:(GLfloat)radius
4342{
4343 // position is the relative position between the camera and the object
4344 int p;
4345 for (p = 0; p < 6; p++) {
4346 if (frustum[p][0] * position.x + frustum[p][1] * position.y + frustum[p][2] * position.z + frustum[p][3] <= -radius) {
4347 return NO;
4348 }
4349 }
4350 return YES;
4351}
4352
4354{
4355 int currentPostFX = [self currentPostFX];
4356 BOOL hudSeparateRenderPass = [self useShaders] && (currentPostFX == OO_POSTFX_NONE || ((currentPostFX == OO_POSTFX_CLOAK || currentPostFX == OO_POSTFX_CRTBADSIGNAL) && [self colorblindMode] == OO_POSTFX_NONE));
4357 NSSize viewSize = [gameView backingViewSize];
4358 OOLog(@"universe.profile.draw", @"%@", @"Begin draw");
4359
4360 if (!no_update) {
4361 if ((int)targetFramebufferSize.width != (int)viewSize.width || (int)targetFramebufferSize.height != (int)viewSize.height) {
4363 }
4364
4365 if ([self useShaders]) {
4366 if ([gameView msaa]) {
4367 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebufferID));
4368 } else {
4369 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, targetFramebufferID));
4370 }
4371 }
4372 @try {
4373 no_update = YES; // block other attempts to draw
4374
4375 int i, v_status, vdist;
4376 Vector view_dir, view_up;
4377 OOMatrix view_matrix;
4378 int ent_count = n_entities;
4379 Entity* my_entities[ent_count];
4380 int draw_count = 0;
4381 PlayerEntity* player = PLAYER;
4382 Entity* drawthing = nil;
4383 BOOL demoShipMode = [player showDemoShips];
4384
4385 float aspect = viewSize.height / viewSize.width;
4386
4387 if (!displayGUI && wasDisplayGUI) {
4388 // reset light1 position for the shaders
4389 if (cachedSun)
4390 [UNIVERSE setMainLightPosition:HPVectorToVector([cachedSun position])]; // the main light is the sun.
4391 else
4392 [UNIVERSE setMainLightPosition:kZeroVector];
4393 }
4395 // use a non-mutable copy so this can't be changed under us.
4396 for (i = 0; i < ent_count; i++) {
4397 /* BUG: this list is ordered nearest to furthest from
4398 * the player, and we just assume that the camera is
4399 * on/near the player. So long as everything uses
4400 * depth tests, we'll get away with it; it'll just
4401 * occasionally be inefficient. - CIM */
4402 Entity* e = sortedEntities[i]; // ordered NEAREST -> FURTHEST AWAY
4403 if ([e isVisible]) {
4404 my_entities[draw_count++] = [[e retain] autorelease];
4405 }
4406 }
4407
4408 v_status = [player status];
4409
4410 OOCheckOpenGLErrors(@"Universe before doing anything");
4411
4412 OOSetOpenGLState(OPENGL_STATE_OPAQUE); // FIXME: should be redundant.
4413
4414 OOGL(glClear(GL_COLOR_BUFFER_BIT));
4415
4416 if (!displayGUI) {
4417 OOGL(glClearColor(skyClearColor[0], skyClearColor[1], skyClearColor[2], skyClearColor[3]));
4418 } else {
4419 OOGL(glClearColor(0.0, 0.0, 0.0, 0.0));
4420 // If set, display background GUI image. Must be done before enabling lights to avoid dim backgrounds
4422 OOGLFrustum(-0.5, 0.5, -aspect * 0.5, aspect * 0.5, 1.0, MAX_CLEAR_DEPTH);
4424 }
4425
4426 BOOL fogging, bpHide = [self breakPatternHide];
4427
4428 drawCounter++;
4429 float breakPlane = INTERMEDIATE_CLEAR_DEPTH;
4430 for (int i = 0; i < draw_count; i++) {
4431 if ([my_entities[i] cameraRangeFront] > breakPlane) {
4432 continue;
4433 }
4434 if ([my_entities[i] cameraRangeBack] > breakPlane) {
4435 breakPlane = [my_entities[i] cameraRangeBack];
4436 }
4437 }
4438
4439 // We need to bring forward the near plane of the frustum on the long distance pass by this factor to avoid clipping objects at the corner of the window
4440 float distanceFactor = sqrt(1 + ([gameView fov:YES] * [gameView fov:YES] * (1.0 + 1.0 / (aspect * aspect))));
4441
4442 for (vdist = 0; vdist <= 1; vdist++) {
4443 float nearPlane = vdist ? 1.0 : INTERMEDIATE_CLEAR_DEPTH;
4444 float farPlane = vdist ? breakPlane : MAX_CLEAR_DEPTH;
4445 float ratio = (displayGUI ? 0.5 : [gameView fov:YES]) * nearPlane / distanceFactor; // 0.5 is field of view ratio for GUIs
4446
4448 if ((displayGUI && 4 * aspect >= 3) || (!displayGUI && 4 * aspect <= 3)) {
4449 OOGLFrustum(-ratio, ratio, -aspect * ratio, aspect * ratio, nearPlane / distanceFactor, farPlane);
4450 } else {
4451 OOGLFrustum(-3 * ratio / aspect / 4, 3 * ratio / aspect / 4, -3 * ratio / 4, 3 * ratio / 4, nearPlane / distanceFactor, farPlane);
4452 }
4453
4454 [self getActiveViewMatrix:&view_matrix forwardVector:&view_dir upVector:&view_up];
4455
4456 OOGLResetModelView(); // reset matrix
4458
4459 // HACK BUSTED
4460 OOGLMultModelView(OOMatrixForScale(-1.0, 1.0, 1.0)); // flip left and right
4461 OOGLPushModelView(); // save this flat viewpoint
4462
4463 /* OpenGL viewpoints:
4464 *
4465 * Oolite used to transform the viewpoint by the inverse of the
4466 * view position, and then transform the objects by the inverse
4467 * of their position, to get the correct view. However, as
4468 * OpenGL only uses single-precision floats, this causes
4469 * noticeable display inaccuracies relatively close to the
4470 * origin.
4471 *
4472 * Instead, we now calculate the difference between the view
4473 * position and the object using high-precision vectors, convert
4474 * the difference to a low-precision vector (since if you can
4475 * see it, it's close enough for the loss of precision not to
4476 * matter) and use that relative vector for the OpenGL transform
4477 *
4478 * Objects which reset the view matrix in their display need to be
4479 * handled a little more carefully than before.
4480 */
4481
4483 // clearing the depth buffer waits until we've set
4484 // STATE_OPAQUE so that depth writes are definitely
4485 // available.
4486 OOGL(glClear(GL_DEPTH_BUFFER_BIT));
4487
4488 // Set up view transformation matrix
4489 OOMatrix flipMatrix = kIdentityMatrix;
4490 flipMatrix.m[2][2] = -1;
4491 view_matrix = OOMatrixMultiply(view_matrix, flipMatrix);
4492 Vector viewOffset = [player viewpointOffset];
4493
4494 OOGLLookAt(view_dir, kZeroVector, view_up);
4495
4496 if (EXPECT(!displayGUI || demoShipMode)) {
4497 if (EXPECT(!demoShipMode)) // we're in flight
4498 {
4499 // rotate the view
4500 OOGLMultModelView([player rotationMatrix]);
4501 // translate the view
4502 // HPVect: camera-relative position
4503 OOGL(glLightModelfv(GL_LIGHT_MODEL_AMBIENT, stars_ambient));
4504 // main light position, no shaders, in-flight / shaders, in-flight and docked.
4505 if (cachedSun) {
4507 } else {
4508 // in witchspace
4509 [self setMainLightPosition:HPVectorToVector(HPvector_flip([PLAYER viewpointPosition]))];
4510 }
4511 OOGL(glLightfv(GL_LIGHT1, GL_POSITION, main_light_position));
4512 } else {
4513 OOGL(glLightModelfv(GL_LIGHT_MODEL_AMBIENT, docked_light_ambient));
4514 // main_light_position no shaders, docked/GUI.
4515 OOGL(glLightfv(GL_LIGHT0, GL_POSITION, main_light_position));
4516 // main light position, no shaders, in-flight / shaders, in-flight and docked.
4517 OOGL(glLightfv(GL_LIGHT1, GL_POSITION, main_light_position));
4518 }
4519
4520 OOGL([self useGUILightSource:demoShipMode]);
4521
4522 // HACK: store view matrix for absolute drawing of active subentities (i.e., turrets, flashers).
4524
4525 int furthest = draw_count - 1;
4526 int nearest = 0;
4527 BOOL inAtmosphere = airResistanceFactor > 0.01;
4528 GLfloat fogFactor = 0.5 / airResistanceFactor;
4529 double fog_scale, half_scale;
4530 GLfloat flat_ambdiff[4] = { 1.0, 1.0, 1.0, 1.0 }; // for alpha
4531 GLfloat mat_no[4] = { 0.0, 0.0, 0.0, 1.0 }; // nothing
4532 GLfloat fog_blend;
4533
4534 OOGL(glHint(GL_FOG_HINT, [self reducedDetail] ? GL_FASTEST : GL_NICEST));
4535
4536 [self defineFrustum]; // camera is set up for this frame
4537
4539 OOCheckOpenGLErrors(@"Universe after setting up for opaque pass");
4540 OOLog(@"universe.profile.draw", @"%@", @"Begin opaque pass");
4541
4542 // DRAW ALL THE OPAQUE ENTITIES
4543 for (i = furthest; i >= nearest; i--) {
4544 drawthing = my_entities[i];
4545 OOEntityStatus d_status = [drawthing status];
4546
4547 if (bpHide && !drawthing->isImmuneToBreakPatternHide)
4548 continue;
4549 if ([drawthing lastDrawCounter] == drawCounter)
4550 continue;
4551 if (vdist == 0 && [drawthing cameraRangeFront] < nearPlane) {
4552 continue;
4553 }
4554
4555 if (!((d_status == STATUS_COCKPIT_DISPLAY) ^ demoShipMode)) // either demo ship mode or in flight
4556 {
4557 // reset material properties
4558 // FIXME: should be part of SetState
4559 OOGL(glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, flat_ambdiff));
4560 OOGL(glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_no));
4561
4563 if (EXPECT(drawthing != player)) {
4564 // translate the object
4565 // HPVect: camera relative
4567 OOGLTranslateModelView([drawthing cameraRelativePosition]);
4568 // rotate the object
4569 OOGLMultModelView([drawthing drawRotationMatrix]);
4570 } else {
4571 // Load transformation matrix
4572 OOGLLoadModelView(view_matrix);
4573 // translate the object from the viewpoint
4575 }
4576
4577 // atmospheric fog
4578 fogging = (inAtmosphere && ![drawthing isStellarObject]);
4579
4580 if (fogging) {
4581 fog_scale = BILLBOARD_DEPTH * fogFactor;
4582 half_scale = fog_scale * 0.50;
4583 OOGL(glEnable(GL_FOG));
4584 OOGL(glFogi(GL_FOG_MODE, GL_LINEAR));
4585 OOGL(glFogfv(GL_FOG_COLOR, skyClearColor));
4586 OOGL(glFogf(GL_FOG_START, half_scale));
4587 OOGL(glFogf(GL_FOG_END, fog_scale));
4588 fog_blend = OOClamp_0_1_f((magnitude([drawthing cameraRelativePosition]) - half_scale) / half_scale);
4589 [drawthing setAtmosphereFogging:[OOColor colorWithRed:skyClearColor[0] green:skyClearColor[1] blue:skyClearColor[2] alpha:fog_blend]];
4590 }
4591
4592 [self lightForEntity:demoShipMode || drawthing->isSunlit];
4593
4594 // draw the thing
4595 [drawthing setLastDrawCounter:drawCounter];
4596 [drawthing drawImmediate:false translucent:false];
4597
4599
4600 // atmospheric fog
4601 if (fogging) {
4603 OOGL(glDisable(GL_FOG));
4604 }
4605 }
4606
4607 if (!((d_status == STATUS_COCKPIT_DISPLAY) ^ demoShipMode)) // either in flight or in demo ship mode
4608 {
4610 if (EXPECT(drawthing != player)) {
4611 // translate the object
4612 // HPVect: camera relative positions
4614 OOGLTranslateModelView([drawthing cameraRelativePosition]);
4615 // rotate the object
4616 OOGLMultModelView([drawthing drawRotationMatrix]);
4617 } else {
4618 // Load transformation matrix
4619 OOGLLoadModelView(view_matrix);
4620 // translate the object from the viewpoint
4622 }
4623
4624 // experimental - atmospheric fog
4625 fogging = (inAtmosphere && ![drawthing isStellarObject]);
4626
4627 if (fogging) {
4628 fog_scale = BILLBOARD_DEPTH * fogFactor;
4629 half_scale = fog_scale * 0.50;
4630 OOGL(glEnable(GL_FOG));
4631 OOGL(glFogi(GL_FOG_MODE, GL_LINEAR));
4632 OOGL(glFogfv(GL_FOG_COLOR, skyClearColor));
4633 OOGL(glFogf(GL_FOG_START, half_scale));
4634 OOGL(glFogf(GL_FOG_END, fog_scale));
4635 fog_blend = OOClamp_0_1_f((magnitude([drawthing cameraRelativePosition]) - half_scale) / half_scale);
4636 [drawthing setAtmosphereFogging:[OOColor colorWithRed:skyClearColor[0] green:skyClearColor[1] blue:skyClearColor[2] alpha:fog_blend]];
4637 }
4638
4639 // draw the thing
4640 [drawthing setLastDrawCounter:drawCounter];
4641 [drawthing drawImmediate:false translucent:true];
4642
4643 // atmospheric fog
4644 if (fogging) {
4646 OOGL(glDisable(GL_FOG));
4647 }
4648
4650 }
4651 }
4652 }
4653
4655 }
4656
4657 // glare effects covering the entire game window
4659 OOGLFrustum(-0.5, 0.5, -aspect * 0.5, aspect * 0.5, 1.0, MAX_CLEAR_DEPTH);
4660 OOSetOpenGLState(OPENGL_STATE_OVERLAY); // FIXME: should be redundant.
4661 if (EXPECT(!displayGUI)) {
4662 if (!bpHide && cachedSun) {
4665 }
4666 }
4667
4668 // actions when the HUD should be rendered separately from the 3d universe
4669 if (hudSeparateRenderPass) {
4670 OOCheckOpenGLErrors(@"Universe after drawing entities");
4671 OOSetOpenGLState(OPENGL_STATE_OVERLAY); // FIXME: should be redundant.
4672
4674 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
4675
4676 OOLog(@"universe.profile.secondPassDraw", @"%@", @"Begin second pass draw");
4678 OOCheckOpenGLErrors(@"Universe after drawing from custom framebuffer to screen framebuffer");
4679 OOLog(@"universe.profile.secondPassDraw", @"%@", @"End second pass drawing");
4680
4681 OOLog(@"universe.profile.drawHUD", @"%@", @"Begin HUD drawing");
4682 }
4683
4684 /* Reset for HUD drawing */
4685 OOCheckOpenGLErrors(@"Universe after drawing entities");
4686 OOLog(@"universe.profile.draw", @"%@", @"Begin HUD");
4687
4688 GLfloat lineWidth = [gameView backingViewSize].width / 1024.0; // restore line size
4689 if (lineWidth < 1.0)
4690 lineWidth = 1.0;
4691 if (lineWidth > 1.5)
4692 lineWidth = 1.5; // don't overscale; think of ultra-wide screen setups
4693 OOGL(GLScaledLineWidth(lineWidth));
4694
4695 HeadUpDisplay* theHUD = [player hud];
4696
4697 // If the HUD has a non-nil deferred name string, it means that a HUD switch was requested while it was being rendered.
4698 // If so, execute the deferred HUD switch now - Nikos 20110628
4699 if ([theHUD deferredHudName] != nil) {
4700 NSString* deferredName = [[theHUD deferredHudName] retain];
4701 [player switchHudTo:deferredName];
4702 [deferredName release];
4703 theHUD = [player hud]; // HUD has been changed, so point to its new address
4704 }
4705
4706 // Hiding HUD: has been a regular - non-debug - feature as of r2749, about 2 yrs ago! --Kaks 2011.10.14
4707 static float sPrevHudAlpha = -1.0f;
4708 if ([theHUD isHidden]) {
4709 if (sPrevHudAlpha < 0.0f) {
4710 sPrevHudAlpha = [theHUD overallAlpha];
4711 }
4712 [theHUD setOverallAlpha:0.0f];
4713 } else if (sPrevHudAlpha >= 0.0f) {
4714 [theHUD setOverallAlpha:sPrevHudAlpha];
4715 sPrevHudAlpha = -1.0f;
4716 }
4717
4718 switch (v_status) {
4719 case STATUS_DEAD:
4720 case STATUS_ESCAPE_SEQUENCE:
4721 case STATUS_START_GAME:
4722 // no HUD rendering in these modes
4723 break;
4724 default:
4725 switch ([player guiScreen]) {
4726 // case GUI_SCREEN_KEYBOARD:
4727 // no HUD rendering on this screen
4728 // break;
4729 default:
4730 [theHUD setLineWidth:lineWidth];
4731 [theHUD renderHUD];
4732 }
4733 }
4734
4735 // should come after the HUD to avoid it being overlapped by it
4736 [self drawMessage];
4737
4738#if (defined(DEV_RELEASE))
4739 [self drawWatermarkString:@"Development version " @OO_VERSION_FULL];
4740#endif
4741
4742 OOLog(@"universe.profile.drawHUD", @"%@", @"End HUD drawing");
4743 OOCheckOpenGLErrors(@"Universe after drawing HUD");
4744
4745 OOGL(glFlush()); // don't wait around for drawing to complete
4746
4747 no_update = NO; // allow other attempts to draw
4748
4749 // frame complete, when it is time to update the fps_counter, updateClocks:delta_t
4750 // in PlayerEntity.m will take care of resetting the processed frames number to 0.
4751 if (![[self gameController] isGamePaused]) {
4753 }
4754 }
4755 @catch (NSException* exception) {
4756 no_update = NO; // make sure we don't get stuck in all subsequent frames.
4757
4758 if ([[exception name] hasPrefix:@"Oolite"]) {
4759 [self handleOoliteException:exception];
4760 } else {
4761 OOLog(kOOLogException, @"***** Exception: %@ : %@ *****", [exception name], [exception reason]);
4762 @throw exception;
4763 }
4764 }
4765 }
4766
4767 OOLog(@"universe.profile.draw", @"%@", @"End drawing");
4768
4769 // actions when the HUD should be rendered together with the 3d universe
4770 if (!hudSeparateRenderPass) {
4771 if ([self useShaders]) {
4773 OOGL(glBindFramebuffer(GL_FRAMEBUFFER, defaultDrawFBO));
4774
4775 OOLog(@"universe.profile.secondPassDraw", @"%@", @"Begin second pass draw");
4777 OOLog(@"universe.profile.secondPassDraw", @"%@", @"End second pass drawing");
4778 }
4779 }
4780}
4781
4783{
4784 NSSize viewSize = [gameView backingViewSize];
4785 if ([self useShaders]) {
4786 if ([gameView msaa]) {
4787 // resolve MSAA framebuffer to target framebuffer
4788 OOGL(glBindFramebuffer(GL_READ_FRAMEBUFFER, msaaFramebufferID));
4789 OOGL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, targetFramebufferID));
4790 OOGL(glBlitFramebuffer(0, 0, (GLint)viewSize.width, (GLint)viewSize.height, 0, 0, (GLint)viewSize.width, (GLint)viewSize.height, GL_COLOR_BUFFER_BIT, GL_NEAREST));
4791 }
4792 }
4793}
4794
4799
4804
4806{
4807 return viewMatrix;
4808}
4809
4811{
4813
4814 OOGL(glDisable(GL_TEXTURE_2D)); // for background sheets
4815
4816 float overallAlpha = [[PLAYER hud] overallAlpha];
4817 if (displayGUI) {
4818 if ([[self gameController] mouseInteractionMode] == MOUSE_MODE_UI_SCREEN_WITH_INTERACTION) {
4819 cursor_row = [gui drawGUI:1.0 drawCursor:YES];
4820 } else {
4821 [gui drawGUI:1.0 drawCursor:NO];
4822 }
4823 }
4824
4825 [message_gui drawGUI:[message_gui alpha] * overallAlpha drawCursor:NO];
4826 [comm_log_gui drawGUI:[comm_log_gui alpha] * overallAlpha drawCursor:NO];
4827
4829}
4830
4831- (void)drawWatermarkString:(NSString*)watermarkString
4832{
4833 NSSize watermarkStringSize = OORectFromString(watermarkString, 0.0f, 0.0f, NSMakeSize(10, 10)).size;
4834
4835 OOGL(glColor4f(0.0, 1.0, 0.0, 1.0));
4836 // position the watermark string on the top right hand corner of the game window and right-align it
4837 OODrawString(watermarkString, MAIN_GUI_PIXEL_WIDTH / 2 - watermarkStringSize.width + 80,
4838 MAIN_GUI_PIXEL_HEIGHT / 2 - watermarkStringSize.height, [gameView display_z], NSMakeSize(10, 10));
4839}
4840
4841- (id)entityForUniversalID:(OOUniversalID)u_id
4842{
4843 if (u_id == 100)
4844 return PLAYER; // the player
4845
4846 if (MAX_ENTITY_UID < u_id) {
4847 OOLog(@"universe.badUID", @"Attempt to retrieve entity for out-of-range UID %u. (This is an internal programming error, please report it.)", u_id);
4848 return nil;
4849 }
4850
4851 if ((u_id == NO_TARGET) || (!entity_for_uid[u_id]))
4852 return nil;
4853
4854 Entity* ent = entity_for_uid[u_id];
4855 if ([ent isEffect]) // effects SHOULD NOT HAVE U_IDs!
4856 {
4857 return nil;
4858 }
4859
4860 if ([ent status] == STATUS_DEAD || [ent status] == STATUS_DOCKED) {
4861 return nil;
4862 }
4863
4864 return ent;
4865}
4866
4868{
4869 NSCParameterAssert(uni != NULL);
4870 BOOL result = YES;
4871
4872 // DEBUG check for loops and short lists
4873 if (uni->n_entities > 0) {
4874 int n;
4875 Entity *checkEnt, *last;
4876
4877 last = nil;
4878
4879 n = uni->n_entities;
4880 checkEnt = uni->x_list_start;
4881 while ((n--) && (checkEnt)) {
4882 last = checkEnt;
4883 checkEnt = checkEnt->x_next;
4884 }
4885 if ((checkEnt) || (n > 0)) {
4886 OOExtraLog(kOOLogEntityVerificationError, @"Broken x_next %@ list (%d) ***", uni->x_list_start, n);
4887 result = NO;
4888 }
4889
4890 n = uni->n_entities;
4891 checkEnt = last;
4892 while ((n--) && (checkEnt))
4893 checkEnt = checkEnt->x_previous;
4894 if ((checkEnt) || (n > 0)) {
4895 OOExtraLog(kOOLogEntityVerificationError, @"Broken x_previous %@ list (%d) ***", uni->x_list_start, n);
4896 if (result) {
4897 OOExtraLog(kOOLogEntityVerificationRebuild, @"%@", @"REBUILDING x_previous list from x_next list");
4898 checkEnt = uni->x_list_start;
4899 checkEnt->x_previous = nil;
4900 while (checkEnt->x_next) {
4901 last = checkEnt;
4902 checkEnt = checkEnt->x_next;
4903 checkEnt->x_previous = last;
4904 }
4905 }
4906 }
4907
4908 n = uni->n_entities;
4909 checkEnt = uni->y_list_start;
4910 while ((n--) && (checkEnt)) {
4911 last = checkEnt;
4912 checkEnt = checkEnt->y_next;
4913 }
4914 if ((checkEnt) || (n > 0)) {
4915 OOExtraLog(kOOLogEntityVerificationError, @"Broken *** broken y_next %@ list (%d) ***", uni->y_list_start, n);
4916 result = NO;
4917 }
4918
4919 n = uni->n_entities;
4920 checkEnt = last;
4921 while ((n--) && (checkEnt))
4922 checkEnt = checkEnt->y_previous;
4923 if ((checkEnt) || (n > 0)) {
4924 OOExtraLog(kOOLogEntityVerificationError, @"Broken y_previous %@ list (%d) ***", uni->y_list_start, n);
4925 if (result) {
4926 OOExtraLog(kOOLogEntityVerificationRebuild, @"%@", @"REBUILDING y_previous list from y_next list");
4927 checkEnt = uni->y_list_start;
4928 checkEnt->y_previous = nil;
4929 while (checkEnt->y_next) {
4930 last = checkEnt;
4931 checkEnt = checkEnt->y_next;
4932 checkEnt->y_previous = last;
4933 }
4934 }
4935 }
4936
4937 n = uni->n_entities;
4938 checkEnt = uni->z_list_start;
4939 while ((n--) && (checkEnt)) {
4940 last = checkEnt;
4941 checkEnt = checkEnt->z_next;
4942 }
4943 if ((checkEnt) || (n > 0)) {
4944 OOExtraLog(kOOLogEntityVerificationError, @"Broken z_next %@ list (%d) ***", uni->z_list_start, n);
4945 result = NO;
4946 }
4947
4948 n = uni->n_entities;
4949 checkEnt = last;
4950 while ((n--) && (checkEnt))
4951 checkEnt = checkEnt->z_previous;
4952 if ((checkEnt) || (n > 0)) {
4953 OOExtraLog(kOOLogEntityVerificationError, @"Broken z_previous %@ list (%d) ***", uni->z_list_start, n);
4954 if (result) {
4955 OOExtraLog(kOOLogEntityVerificationRebuild, @"%@", @"REBUILDING z_previous list from z_next list");
4956 checkEnt = uni->z_list_start;
4957 NSCAssert(checkEnt != nil, @"Expected z-list to be non-empty."); // Previously an implicit assumption. -- Ahruman 2011-01-25
4958 checkEnt->z_previous = nil;
4959 while (checkEnt->z_next) {
4960 last = checkEnt;
4961 checkEnt = checkEnt->z_next;
4962 checkEnt->z_previous = last;
4963 }
4964 }
4965 }
4966 }
4967
4968 if (!result) {
4969 OOExtraLog(kOOLogEntityVerificationRebuild, @"%@", @"Rebuilding all linked lists from scratch");
4970 NSArray* allEntities = uni->entities;
4971 uni->x_list_start = nil;
4972 uni->y_list_start = nil;
4973 uni->z_list_start = nil;
4974
4975 Entity* ent = nil;
4976 foreach (ent, allEntities) {
4977 ent->x_next = nil;
4978 ent->x_previous = nil;
4979 ent->y_next = nil;
4980 ent->y_previous = nil;
4981 ent->z_next = nil;
4982 ent->z_previous = nil;
4984 }
4985 }
4986
4987 return result;
4988}
4989
4990- (BOOL)addEntity:(Entity*)entity
4991{
4992 if (entity) {
4993 ShipEntity* se = nil;
4995 OOWaypointEntity* wp = nil;
4996
4997 if (![entity validForAddToUniverse])
4998 return NO;
4999
5000 // don't add things twice!
5001 if ([entities containsObject:entity])
5002 return YES;
5003
5004 if (n_entities >= UNIVERSE_MAX_ENTITIES - 1) {
5005 // throw an exception here...
5006 OOLog(@"universe.addEntity.failed", @"***** Universe cannot addEntity:%@ -- Universe is full (%d entities out of %d)", entity, n_entities, UNIVERSE_MAX_ENTITIES);
5007#ifndef NDEBUG
5008 if (OOLogWillDisplayMessagesInClass(@"universe.maxEntitiesDump"))
5009 [self debugDumpEntities];
5010#endif
5011 return NO;
5012 }
5013
5014 if (![entity isEffect]) {
5015 unsigned limiter = UNIVERSE_MAX_ENTITIES;
5016 while (entity_for_uid[next_universal_id] != nil) // skip allocated numbers
5017 {
5018 next_universal_id++; // increment keeps idkeys unique
5021 }
5022 if (limiter-- == 0) {
5023 // Every slot has been tried! This should not happen due to previous test, but there was a problem here in 1.70.
5024 OOLog(@"universe.addEntity.failed", @"***** Universe cannot addEntity:%@ -- Could not find free slot for entity.", entity);
5025 return NO;
5026 }
5027 }
5028 [entity setUniversalID:next_universal_id];
5029 entity_for_uid[next_universal_id] = entity;
5030 if ([entity isShip]) {
5031 se = (ShipEntity*)entity;
5032 if ([se isBeacon]) {
5033 [self setNextBeacon:se];
5034 }
5035 if ([se isStation]) {
5036 // check if it is a proper rotating station (ie. roles contains the word "station")
5037 if ([(StationEntity*)se isRotatingStation]) {
5038 double stationRoll = 0.0;
5039 // check for station_roll override
5040 id definedRoll = [[se shipInfoDictionary] objectForKey:@"station_roll"];
5041
5042 if (definedRoll != nil) {
5043 stationRoll = OODoubleFromObject(definedRoll, stationRoll);
5044 } else {
5045 stationRoll = [[self currentSystemData] oo_doubleForKey:@"station_roll" defaultValue:STANDARD_STATION_ROLL];
5046 }
5047
5048 [se setRoll:stationRoll];
5049 } else {
5050 [se setRoll:0.0];
5051 }
5052 [(StationEntity*)se setPlanet:[self planet]];
5053 if ([se maxFlightSpeed] > 0)
5054 se->isExplicitlyNotMainStation = YES; // we never want carriers to become main stations.
5055 }
5056 // stations used to have STATUS_ACTIVE, they're all STATUS_IN_FLIGHT now.
5057 if ([se status] != STATUS_COCKPIT_DISPLAY) {
5058 [se setStatus:STATUS_IN_FLIGHT];
5059 }
5060 }
5061 } else {
5062 [entity setUniversalID:NO_TARGET];
5063 if ([entity isVisualEffect]) {
5064 ve = (OOVisualEffectEntity*)entity;
5065 if ([ve isBeacon]) {
5066 [self setNextBeacon:ve];
5067 }
5068 } else if ([entity isWaypoint]) {
5069 wp = (OOWaypointEntity*)entity;
5070 if ([wp isBeacon]) {
5071 [self setNextBeacon:wp];
5072 }
5073 }
5074 }
5075
5076 // lighting considerations
5077 entity->isSunlit = YES;
5078 entity->shadingEntityID = NO_TARGET;
5079
5080 // add it to the universe
5081 [entities addObject:entity];
5082 [entity wasAddedToUniverse];
5083
5084 // maintain sorted list (and for the scanner relative position)
5085 HPVector entity_pos = entity->position;
5086 HPVector delta = HPvector_between(entity_pos, PLAYER->position);
5087 double z_distance = HPmagnitude2(delta);
5088 entity->zero_distance = z_distance;
5089 unsigned index = n_entities;
5090 sortedEntities[index] = entity;
5091 entity->zero_index = index;
5092 while ((index > 0) && (z_distance < sortedEntities[index - 1]->zero_distance)) // bubble into place
5093 {
5095 sortedEntities[index]->zero_index = index;
5096 index--;
5097 sortedEntities[index] = entity;
5098 entity->zero_index = index;
5099 }
5100
5101 // increase n_entities...
5102 n_entities++;
5103
5104 // add entity to linked lists
5105 [entity addToLinkedLists]; // position and universe have been set - so we can do this
5106 if ([entity canCollide]) // filter only collidables disappearing
5107 {
5109 }
5110
5111 if ([entity isWormhole]) {
5112 [activeWormholes addObject:entity];
5113 } else if ([entity isPlanet]) {
5114 [allPlanets addObject:entity];
5115 } else if ([entity isShip]) {
5116 [[se getAI] setOwner:se];
5117 [[se getAI] setState:@"GLOBAL"];
5118 if ([entity isStation]) {
5119 [allStations addObject:entity];
5120 }
5121 }
5122
5123 return YES;
5124 }
5125 return NO;
5126}
5127
5128- (BOOL)removeEntity:(Entity*)entity
5129{
5130 if (entity != nil && ![entity isPlayer]) {
5131 /* Ensure entity won't actually be dealloced until the end of this
5132 update (or the next update if none is in progress), because
5133 there may be things pointing to it but not retaining it.
5134 */
5135 [entitiesDeadThisUpdate addObject:entity];
5136 if ([entity isStation]) {
5137 [allStations removeObject:entity];
5138 if ([PLAYER getTargetDockStation] == entity) {
5139 [PLAYER setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
5140 }
5141 }
5142 return [self doRemoveEntity:entity];
5143 }
5144 return NO;
5145}
5146
5147- (void)ensureEntityReallyRemoved:(Entity*)entity
5148{
5149 if ([entity universalID] != NO_TARGET) {
5150 OOLog(@"universe.unremovedEntity", @"Entity %@ dealloced without being removed from universe! (This is an internal programming error, please report it.)", entity);
5151 [self doRemoveEntity:entity];
5152 }
5153}
5154
5156{
5157 BOOL updating = no_update;
5158 no_update = YES; // no drawing while we do this!
5159
5160#ifndef NDEBUG
5161 Entity* p0 = [entities objectAtIndex:0];
5162 if (!(p0->isPlayer)) {
5163 OOLog(kOOLogInconsistentState, @"%@", @"***** First entity is not the player in Universe.removeAllEntitiesExceptPlayer - exiting.");
5164 exit(EXIT_FAILURE);
5165 }
5166#endif
5167
5168 // preserve wormholes
5169 NSMutableArray* savedWormholes = [activeWormholes mutableCopy];
5170
5171 while ([entities count] > 1) {
5172 Entity* ent = [entities objectAtIndex:1];
5173 if (ent->isStation) // clear out queues
5175 if (EXPECT(![ent isVisualEffect])) {
5176 [self removeEntity:ent];
5177 } else {
5178 // this will ensure the effectRemoved script event will run
5180 }
5181 }
5182
5183 [activeWormholes release];
5184 activeWormholes = savedWormholes; // will be cleared out by populateSpaceFromActiveWormholes
5185
5186 // maintain sorted list
5187 n_entities = 1;
5188
5189 cachedSun = nil;
5190 cachedPlanet = nil;
5192 [closeSystems release];
5193 closeSystems = nil;
5194
5195 [self resetBeacons];
5196 [waypoints removeAllObjects];
5197
5198 no_update = updating; // restore drawing
5199}
5200
5202{
5203 int i;
5204 int ent_count = n_entities;
5205 if (ent_count > 0) {
5206 Entity* ent;
5207 for (i = 0; i < ent_count; i++) {
5208 ent = sortedEntities[i];
5209 if ([ent status] == STATUS_COCKPIT_DISPLAY && ![ent isPlayer]) {
5210 [self removeEntity:ent];
5211 }
5212 }
5213 }
5214 demo_ship = nil;
5215}
5216
5217- (ShipEntity*)makeDemoShipWithRole:(NSString*)role spinning:(BOOL)spinning
5218{
5219 if ([PLAYER dockedStation] == nil)
5220 return nil;
5221
5222 [self removeDemoShips]; // get rid of any pre-existing models on display
5223
5224 [PLAYER setShowDemoShips:YES];
5225 Quaternion q2 = { (GLfloat)M_SQRT1_2, (GLfloat)M_SQRT1_2, (GLfloat)0.0, (GLfloat)0.0 };
5226
5227 ShipEntity* ship = [self newShipWithRole:role]; // retain count = 1
5228 if (ship) {
5229 double cr = [ship collisionRadius];
5230 [ship setOrientation:q2];
5231 [ship setPositionX:0.0f y:0.0f z:3.6f * cr];
5232 [ship setScanClass:CLASS_NO_DRAW];
5233 [ship switchAITo:@"nullAI.plist"];
5235
5236 [UNIVERSE addEntity:ship]; // STATUS_IN_FLIGHT, AI state GLOBAL
5237
5238 if (spinning) {
5239 [ship setDemoShip:1.0f];
5240 } else {
5241 [ship setDemoShip:0.0f];
5242 }
5243 [ship setStatus:STATUS_COCKPIT_DISPLAY];
5244 // stop problems on the ship library screen
5245 // demo ships shouldn't have this equipment
5246 [ship removeEquipmentItem:@"EQ_SHIELD_BOOSTER"];
5247 [ship removeEquipmentItem:@"EQ_SHIELD_ENHANCER"];
5248 }
5249
5250 return [ship autorelease];
5251}
5252
5253- (BOOL)isVectorClearFromEntity:(Entity*)e1 toDistance:(double)dist fromPoint:(HPVector)p2
5254{
5255 if (!e1)
5256 return NO;
5257
5258 HPVector f1;
5259 HPVector p1 = e1->position;
5260 HPVector v1 = p2;
5261 v1.x -= p1.x;
5262 v1.y -= p1.y;
5263 v1.z -= p1.z; // vector from entity to p2
5264
5265 double nearest = sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z) - dist; // length of vector
5266
5267 if (nearest < 0.0)
5268 return YES; // within range already!
5269
5270 int i;
5271 int ent_count = n_entities;
5272 Entity* my_entities[ent_count];
5273 for (i = 0; i < ent_count; i++)
5274 my_entities[i] = [sortedEntities[i] retain]; // retained
5275
5276 if (v1.x || v1.y || v1.z)
5277 f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1
5278 else
5279 f1 = make_HPvector(0, 0, 1);
5280
5281 for (i = 0; i < ent_count; i++) {
5282 Entity* e2 = my_entities[i];
5283 if ((e2 != e1) && ([e2 canCollide])) {
5284 HPVector epos = e2->position;
5285 epos.x -= p1.x;
5286 epos.y -= p1.y;
5287 epos.z -= p1.z; // epos now holds vector from p1 to this entities position
5288
5289 double d_forward = HPdot_product(epos, f1); // distance along f1 which is nearest to e2's position
5290
5291 if ((d_forward > 0) && (d_forward < nearest)) {
5292 double cr = 1.10 * (e2->collision_radius + e1->collision_radius); // 10% safety margin
5293 HPVector p0 = e1->position;
5294 p0.x += d_forward * f1.x;
5295 p0.y += d_forward * f1.y;
5296 p0.z += d_forward * f1.z;
5297 // p0 holds nearest point on current course to center of incident object
5298 HPVector epos = e2->position;
5299 p0.x -= epos.x;
5300 p0.y -= epos.y;
5301 p0.z -= epos.z;
5302 // compare with center of incident object
5303 double dist2 = p0.x * p0.x + p0.y * p0.y + p0.z * p0.z;
5304 if (dist2 < cr * cr) {
5305 for (i = 0; i < ent_count; i++)
5306 [my_entities[i] release]; // released
5307 return NO;
5308 }
5309 }
5310 }
5311 }
5312 for (i = 0; i < ent_count; i++)
5313 [my_entities[i] release]; // released
5314 return YES;
5315}
5316
5317- (Entity*)hazardOnRouteFromEntity:(Entity*)e1 toDistance:(double)dist fromPoint:(HPVector)p2
5318{
5319 if (!e1)
5320 return nil;
5321
5322 HPVector f1;
5323 HPVector p1 = e1->position;
5324 HPVector v1 = p2;
5325 v1.x -= p1.x;
5326 v1.y -= p1.y;
5327 v1.z -= p1.z; // vector from entity to p2
5328
5329 double nearest = HPmagnitude(v1) - dist; // length of vector
5330
5331 if (nearest < 0.0)
5332 return nil; // within range already!
5333
5334 Entity* result = nil;
5335 int i;
5336 int ent_count = n_entities;
5337 Entity* my_entities[ent_count];
5338 for (i = 0; i < ent_count; i++)
5339 my_entities[i] = [sortedEntities[i] retain]; // retained
5340
5341 if (v1.x || v1.y || v1.z)
5342 f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1
5343 else
5344 f1 = make_HPvector(0, 0, 1);
5345
5346 for (i = 0; (i < ent_count) && (!result); i++) {
5347 Entity* e2 = my_entities[i];
5348 if ((e2 != e1) && ([e2 canCollide])) {
5349 HPVector epos = e2->position;
5350 epos.x -= p1.x;
5351 epos.y -= p1.y;
5352 epos.z -= p1.z; // epos now holds vector from p1 to this entities position
5353
5354 double d_forward = HPdot_product(epos, f1); // distance along f1 which is nearest to e2's position
5355
5356 if ((d_forward > 0) && (d_forward < nearest)) {
5357 double cr = 1.10 * (e2->collision_radius + e1->collision_radius); // 10% safety margin
5358 HPVector p0 = e1->position;
5359 p0.x += d_forward * f1.x;
5360 p0.y += d_forward * f1.y;
5361 p0.z += d_forward * f1.z;
5362 // p0 holds nearest point on current course to center of incident object
5363 HPVector epos = e2->position;
5364 p0.x -= epos.x;
5365 p0.y -= epos.y;
5366 p0.z -= epos.z;
5367 // compare with center of incident object
5368 double dist2 = HPmagnitude2(p0);
5369 if (dist2 < cr * cr)
5370 result = e2;
5371 }
5372 }
5373 }
5374 for (i = 0; i < ent_count; i++)
5375 [my_entities[i] release]; // released
5376 return result;
5377}
5378
5379- (HPVector)getSafeVectorFromEntity:(Entity*)e1 toDistance:(double)dist fromPoint:(HPVector)p2
5380{
5381 // heuristic three
5382
5383 if (!e1) {
5384 OOLog(kOOLogParameterError, @"%@", @"***** No entity set in Universe getSafeVectorFromEntity:toDistance:fromPoint:");
5385 return kZeroHPVector;
5386 }
5387
5388 HPVector f1;
5389 HPVector result = p2;
5390 int i;
5391 int ent_count = n_entities;
5392 Entity* my_entities[ent_count];
5393 for (i = 0; i < ent_count; i++)
5394 my_entities[i] = [sortedEntities[i] retain]; // retained
5395 HPVector p1 = e1->position;
5396 HPVector v1 = p2;
5397 v1.x -= p1.x;
5398 v1.y -= p1.y;
5399 v1.z -= p1.z; // vector from entity to p2
5400
5401 double nearest = sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z) - dist; // length of vector
5402
5403 if (v1.x || v1.y || v1.z)
5404 f1 = HPvector_normal(v1); // unit vector in direction of p2 from p1
5405 else
5406 f1 = make_HPvector(0, 0, 1);
5407
5408 for (i = 0; i < ent_count; i++) {
5409 Entity* e2 = my_entities[i];
5410 if ((e2 != e1) && ([e2 canCollide])) {
5411 HPVector epos = e2->position;
5412 epos.x -= p1.x;
5413 epos.y -= p1.y;
5414 epos.z -= p1.z;
5415 double d_forward = HPdot_product(epos, f1);
5416 if ((d_forward > 0) && (d_forward < nearest)) {
5417 double cr = 1.20 * (e2->collision_radius + e1->collision_radius); // 20% safety margin
5418
5419 HPVector p0 = e1->position;
5420 p0.x += d_forward * f1.x;
5421 p0.y += d_forward * f1.y;
5422 p0.z += d_forward * f1.z;
5423 // p0 holds nearest point on current course to center of incident object
5424
5425 HPVector epos = e2->position;
5426 p0.x -= epos.x;
5427 p0.y -= epos.y;
5428 p0.z -= epos.z;
5429 // compare with center of incident object
5430
5431 double dist2 = p0.x * p0.x + p0.y * p0.y + p0.z * p0.z;
5432
5433 if (dist2 < cr * cr) {
5434 result = e2->position; // center of incident object
5435 nearest = d_forward;
5436
5437 if (dist2 == 0.0) {
5438 // ie. we're on a line through the object's center !
5439 // jitter the position somewhat!
5440 result.x += ((int)(Ranrot() % 1024) - 512) / 512.0; // -1.0 .. +1.0
5441 result.y += ((int)(Ranrot() % 1024) - 512) / 512.0; // -1.0 .. +1.0
5442 result.z += ((int)(Ranrot() % 1024) - 512) / 512.0; // -1.0 .. +1.0
5443 }
5444
5445 HPVector nearest_point = p1;
5446 nearest_point.x += d_forward * f1.x;
5447 nearest_point.y += d_forward * f1.y;
5448 nearest_point.z += d_forward * f1.z;
5449 // nearest point now holds nearest point on line to center of incident object
5450
5451 HPVector outward = nearest_point;
5452 outward.x -= result.x;
5453 outward.y -= result.y;
5454 outward.z -= result.z;
5455 if (outward.x || outward.y || outward.z)
5456 outward = HPvector_normal(outward);
5457 else
5458 outward.y = 1.0;
5459 // outward holds unit vector through the nearest point on the line from the center of incident object
5460
5461 HPVector backward = p1;
5462 backward.x -= result.x;
5463 backward.y -= result.y;
5464 backward.z -= result.z;
5465 if (backward.x || backward.y || backward.z)
5466 backward = HPvector_normal(backward);
5467 else
5468 backward.z = -1.0;
5469 // backward holds unit vector from center of the incident object to the center of the ship
5470
5471 HPVector dd = result;
5472 dd.x -= p1.x;
5473 dd.y -= p1.y;
5474 dd.z -= p1.z;
5475 double current_distance = HPmagnitude(dd);
5476
5477 // sanity check current_distance
5478 if (current_distance < cr * 1.25) // 25% safety margin
5479 current_distance = cr * 1.25;
5480 if (current_distance > cr * 5.0) // up to 2 diameters away
5481 current_distance = cr * 5.0;
5482
5483 // choose a point that's three parts backward and one part outward
5484
5485 result.x += 0.25 * (outward.x * current_distance) + 0.75 * (backward.x * current_distance); // push 'out' by this amount
5486 result.y += 0.25 * (outward.y * current_distance) + 0.75 * (backward.y * current_distance);
5487 result.z += 0.25 * (outward.z * current_distance) + 0.75 * (backward.z * current_distance);
5488 }
5489 }
5490 }
5491 }
5492 for (i = 0; i < ent_count; i++)
5493 [my_entities[i] release]; // released
5494 return result;
5495}
5496
5497- (ShipEntity*)addWreckageFrom:(ShipEntity*)ship withRole:(NSString*)wreckRole at:(HPVector)rpos scale:(GLfloat)scale lifetime:(GLfloat)lifetime
5498{
5499 ShipEntity* wreck = [UNIVERSE newShipWithRole:wreckRole]; // retain count = 1
5500 Quaternion q;
5501 if (wreck) {
5502 GLfloat expected_mass = 0.1f * [ship mass] * (0.75 + 0.5 * randf());
5503 GLfloat wreck_mass = [wreck mass];
5504 GLfloat scale_factor = powf(expected_mass / wreck_mass, 0.33333333f) * scale; // cube root of volume ratio
5505 [wreck rescaleBy:scale_factor writeToCache:NO];
5506
5507 [wreck setPosition:rpos];
5508
5510
5513
5514 [wreck setTemperature:1000.0]; // take 1000e heat damage per second
5515 [wreck setHeatInsulation:1.0e7]; // very large! so it won't cool down
5516 [wreck setEnergy:lifetime];
5517
5518 [wreck setIsWreckage:YES];
5519
5520 [UNIVERSE addEntity:wreck]; // STATUS_IN_FLIGHT, AI state GLOBAL
5522 // [wreck rescaleBy: 1.0/scale_factor];
5523 [wreck release];
5524 }
5525 return wreck;
5526}
5527
5528- (void)addLaserHitEffectsAt:(HPVector)pos against:(ShipEntity*)target damage:(float)damage color:(OOColor*)color
5529{
5530 // low energy, start getting small surface explosions
5531 if ([target showDamage] && [target energy] < [target maxEnergy] / 2) {
5532 NSString* key = (randf() < 0.5) ? @"oolite-hull-spark" : @"oolite-hull-spark-b";
5533 NSDictionary* settings = [UNIVERSE explosionSetting:key];
5535 [burst setPosition:pos];
5536 [self addEntity:burst];
5537 if ([target energy] * randf() < damage) {
5538 ShipEntity* wreck = [self addWreckageFrom:target withRole:@"oolite-wreckage-chunk" at:pos scale:0.05 lifetime:(125.0 + (randf() * 200.0))];
5539 if (wreck) {
5540 Vector direction = HPVectorToVector(HPvector_normal(HPvector_subtract(pos, [target position])));
5541 [wreck setVelocity:vector_add([wreck velocity], vector_multiply_scalar(direction, 10 + 20 * randf()))];
5542 }
5543 }
5544 } else {
5546 }
5547}
5548
5549- (ShipEntity*)firstShipHitByLaserFromShip:(ShipEntity*)srcEntity inDirection:(OOWeaponFacing)direction offset:(Vector)offset gettingRangeFound:(GLfloat*)range_ptr
5550{
5551 if (srcEntity == nil)
5552 return nil;
5553
5554 ShipEntity* hit_entity = nil;
5555 ShipEntity* hit_subentity = nil;
5558 ShipEntity* parent = [srcEntity parentEntity];
5559
5560 if (parent) {
5561 // we're a subentity!
5563 HPVector midfrontplane = make_HPvector(0.5 * (bbox.max.x + bbox.min.x), 0.5 * (bbox.max.y + bbox.min.y), bbox.max.z);
5564 p0 = [srcEntity absolutePositionForSubentityOffset:midfrontplane];
5565 q1 = [parent orientation];
5566 if ([parent isPlayer])
5567 q1.w = -q1.w;
5568 }
5569
5570 double nearest = [srcEntity weaponRange];
5571 int i;
5572 int ent_count = n_entities;
5573 int ship_count = 0;
5574 ShipEntity* my_entities[ent_count];
5575
5576 for (i = 0; i < ent_count; i++) {
5577 Entity* ent = sortedEntities[i];
5578 if (ent != srcEntity && ent != parent && [ent isShip] && [ent canCollide]) {
5579 my_entities[ship_count++] = [(ShipEntity*)ent retain];
5580 }
5581 }
5582
5583 Vector u1, f1, r1;
5584 basis_vectors_from_quaternion(q1, &r1, &u1, &f1);
5586
5587 switch (direction) {
5589 case WEAPON_FACING_NONE:
5590 break;
5591
5592 case WEAPON_FACING_AFT:
5594 break;
5595
5596 case WEAPON_FACING_PORT:
5597 quaternion_rotate_about_axis(&q1, u1, M_PI / 2.0);
5598 break;
5599
5601 quaternion_rotate_about_axis(&q1, u1, -M_PI / 2.0);
5602 break;
5603 }
5604
5605 basis_vectors_from_quaternion(q1, &r1, NULL, &f1);
5606 HPVector p1 = HPvector_add(p0, vectorToHPVector(vector_multiply_scalar(f1, nearest))); // endpoint
5607
5608 for (i = 0; i < ship_count; i++) {
5609 ShipEntity* e2 = my_entities[i];
5610
5611 // check outermost bounding sphere
5612 GLfloat cr = e2->collision_radius;
5614 Vector v_off = make_vector(dot_product(rpos, r1), dot_product(rpos, u1), dot_product(rpos, f1));
5615 if (v_off.z > 0.0 && v_off.z < nearest + cr && // ahead AND within range
5616 v_off.x < cr && v_off.x > -cr && v_off.y < cr && v_off.y > -cr && // AND not off to one side or another
5617 v_off.x * v_off.x + v_off.y * v_off.y < cr * cr) // AND not off to both sides
5618 {
5619 ShipEntity* entHit = nil;
5620 GLfloat hit = [(ShipEntity*)e2 doesHitLine:p0 v1:p1 hitEntity:&entHit]; // octree detection
5621
5622 if (hit > 0.0 && hit < nearest) {
5623 if ([entHit isSubEntity]) {
5624 hit_subentity = entHit;
5625 }
5626 hit_entity = e2;
5627 nearest = hit;
5629 }
5630 }
5631 }
5632
5633 if (hit_entity) {
5634 // I think the above code does not guarantee that the closest hit_subentity belongs to the closest hit_entity.
5635 if (hit_subentity && [hit_subentity owner] == hit_entity)
5636 [hit_entity setSubEntityTakingDamage:hit_subentity];
5637
5638 if (range_ptr != NULL) {
5639 *range_ptr = nearest;
5640 }
5641 }
5642
5643 for (i = 0; i < ship_count; i++)
5644 [my_entities[i] release]; // released
5645
5646 return hit_entity;
5647}
5648
5650{
5651 PlayerEntity* player = PLAYER;
5652 Entity* hit_entity = nil;
5653 OOScalar nearest2 = SCANNER_MAX_RANGE - 100; // 100m shorter than range at which target is lost
5654 nearest2 *= nearest2;
5655 int i;
5656 int ent_count = n_entities;
5657 int ship_count = 0;
5658 Entity* my_entities[ent_count];
5659
5660 for (i = 0; i < ent_count; i++) {
5661 if (([sortedEntities[i] isShip] && ![sortedEntities[i] isPlayer]) || [sortedEntities[i] isWormhole]) {
5662 my_entities[ship_count++] = [sortedEntities[i] retain];
5663 }
5664 }
5665
5667 Vector u1, f1, r1;
5668 basis_vectors_from_quaternion(q1, &r1, &u1, &f1);
5670
5672
5673 // Note: deliberately tied to view direction, not weapon facing. All custom views count as forward for targeting.
5674 switch (viewDirection) {
5675 case VIEW_AFT:
5677 break;
5678 case VIEW_PORT:
5679 quaternion_rotate_about_axis(&q1, u1, 0.5 * M_PI);
5680 break;
5681 case VIEW_STARBOARD:
5682 quaternion_rotate_about_axis(&q1, u1, -0.5 * M_PI);
5683 break;
5684 default:
5685 break;
5686 }
5687 basis_vectors_from_quaternion(q1, &r1, NULL, &f1);
5688
5689 for (i = 0; i < ship_count; i++) {
5690 Entity* e2 = my_entities[i];
5691 if ([e2 canCollide] && [e2 scanClass] != CLASS_NO_DRAW) {
5692 Vector rp = HPVectorToVector(HPvector_subtract([e2 position], p1));
5693 OOScalar dist2 = magnitude2(rp);
5694 if (dist2 < nearest2) {
5695 OOScalar df = dot_product(f1, rp);
5696 if (df > 0.0 && df * df < nearest2) {
5697 OOScalar du = dot_product(u1, rp);
5698 OOScalar dr = dot_product(r1, rp);
5700 if (du * du + dr * dr < cr * cr) {
5701 hit_entity = e2;
5702 nearest2 = dist2;
5703 }
5704 }
5705 }
5706 }
5707 }
5708 // check for MASC'M
5709 if (hit_entity != nil && [hit_entity isShip]) {
5710 ShipEntity* ship = (ShipEntity*)hit_entity;
5711 if ([ship isJammingScanning] && ![player hasMilitaryScannerFilter]) {
5712 hit_entity = nil;
5713 }
5714 }
5715
5716 for (i = 0; i < ship_count; i++) {
5717 [my_entities[i] release];
5718 }
5719
5720 return hit_entity;
5721}
5722
5724{
5725 OOWeaponFacing targetFacing;
5726 Vector laserPortOffset = kZeroVector;
5727 PlayerEntity* player = PLAYER;
5728
5729 switch (viewDirection) {
5730 case VIEW_FORWARD:
5731 targetFacing = WEAPON_FACING_FORWARD;
5732 laserPortOffset = [[player forwardWeaponOffset] oo_vectorAtIndex:0];
5733 break;
5734
5735 case VIEW_AFT:
5736 targetFacing = WEAPON_FACING_AFT;
5737 laserPortOffset = [[player aftWeaponOffset] oo_vectorAtIndex:0];
5738 break;
5739
5740 case VIEW_PORT:
5741 targetFacing = WEAPON_FACING_PORT;
5742 laserPortOffset = [[player portWeaponOffset] oo_vectorAtIndex:0];
5743 break;
5744
5745 case VIEW_STARBOARD:
5746 targetFacing = WEAPON_FACING_STARBOARD;
5747 laserPortOffset = [[player starboardWeaponOffset] oo_vectorAtIndex:0];
5748 break;
5749
5750 default:
5751 // Match behaviour of -firstEntityTargetedByPlayer.
5752 targetFacing = WEAPON_FACING_FORWARD;
5753 laserPortOffset = [[player forwardWeaponOffset] oo_vectorAtIndex:0];
5754 }
5755
5756 return [self firstShipHitByLaserFromShip:PLAYER inDirection:targetFacing offset:laserPortOffset gettingRangeFound:NULL];
5757}
5758
5759- (NSArray*)entitiesWithinRange:(double)range ofEntity:(Entity*)entity
5760{
5761 if (entity == nil)
5762 return nil;
5763
5764 return [self findShipsMatchingPredicate:YESPredicate
5765 parameter:NULL
5766 inRange:range
5767 ofEntity:entity];
5768}
5769
5770- (unsigned)countShipsWithRole:(NSString*)role inRange:(double)range ofEntity:(Entity*)entity
5771{
5772 return [self countShipsMatchingPredicate:HasRolePredicate
5773 parameter:role
5774 inRange:range
5775 ofEntity:entity];
5776}
5777
5778- (unsigned)countShipsWithRole:(NSString*)role
5779{
5780 return [self countShipsWithRole:role inRange:-1 ofEntity:nil];
5781}
5782
5783- (unsigned)countShipsWithPrimaryRole:(NSString*)role inRange:(double)range ofEntity:(Entity*)entity
5784{
5785 return [self countShipsMatchingPredicate:HasPrimaryRolePredicate
5786 parameter:role
5787 inRange:range
5788 ofEntity:entity];
5789}
5790
5791- (unsigned)countShipsWithScanClass:(OOScanClass)scanClass inRange:(double)range ofEntity:(Entity*)entity
5792{
5793 return [self countShipsMatchingPredicate:HasScanClassPredicate
5794 parameter:[NSNumber numberWithInt:scanClass]
5795 inRange:range
5796 ofEntity:entity];
5797}
5798
5799- (unsigned)countShipsWithPrimaryRole:(NSString*)role
5800{
5801 return [self countShipsWithPrimaryRole:role inRange:-1 ofEntity:nil];
5802}
5803
5804- (unsigned)countEntitiesMatchingPredicate:(EntityFilterPredicate)predicate
5805 parameter:(void*)parameter
5806 inRange:(double)range
5807 ofEntity:(Entity*)e1
5808{
5809 unsigned i, found = 0;
5810 HPVector p1;
5811 double distance, cr;
5812
5813 if (predicate == NULL)
5814 predicate = YESPredicate;
5815
5816 if (e1 != nil)
5817 p1 = e1->position;
5818 else
5819 p1 = kZeroHPVector;
5820
5821 for (i = 0; i < n_entities; i++) {
5822 Entity* e2 = sortedEntities[i];
5823 if (e2 != e1 && predicate(e2, parameter)) {
5824 if (range < 0)
5825 distance = -1; // Negative range means infinity
5826 else {
5827 cr = range + e2->collision_radius;
5828 distance = HPdistance2(e2->position, p1) - cr * cr;
5829 }
5830 if (distance < 0) {
5831 found++;
5832 }
5833 }
5834 }
5835
5836 return found;
5837}
5838
5839- (unsigned)countShipsMatchingPredicate:(EntityFilterPredicate)predicate
5840 parameter:(void*)parameter
5841 inRange:(double)range
5842 ofEntity:(Entity*)entity
5843{
5844 if (predicate != NULL) {
5846 IsShipPredicate, NULL,
5847 predicate, parameter
5848 };
5849
5850 return [self countEntitiesMatchingPredicate:ANDPredicate
5851 parameter:&param
5852 inRange:range
5853 ofEntity:entity];
5854 } else {
5855 return [self countEntitiesMatchingPredicate:IsShipPredicate
5856 parameter:NULL
5857 inRange:range
5858 ofEntity:entity];
5859 }
5860}
5861
5862OOINLINE BOOL EntityInRange(HPVector p1, Entity* e2, float range)
5863{
5864 if (range < 0)
5865 return YES;
5866 float cr = range + e2->collision_radius;
5867 return HPdistance2(e2->position, p1) < cr * cr;
5868}
5869
5870// NOTE: OOJSSystem relies on this returning entities in distance-from-player order.
5871// This can be easily changed by removing the [reference isPlayer] conditions in FindJSVisibleEntities().
5872- (NSMutableArray*)findEntitiesMatchingPredicate:(EntityFilterPredicate)predicate
5873 parameter:(void*)parameter
5874 inRange:(double)range
5875 ofEntity:(Entity*)e1
5876{
5878
5879 unsigned i;
5880 HPVector p1;
5881 NSMutableArray* result = nil;
5882
5884
5885 if (predicate == NULL)
5886 predicate = YESPredicate;
5887
5888 result = [NSMutableArray arrayWithCapacity:n_entities];
5889
5890 if (e1 != nil)
5891 p1 = [e1 position];
5892 else
5893 p1 = kZeroHPVector;
5894
5895 for (i = 0; i < n_entities; i++) {
5896 Entity* e2 = sortedEntities[i];
5897
5898 if (e1 != e2 && EntityInRange(p1, e2, range) && predicate(e2, parameter)) {
5899 [result addObject:e2];
5900 }
5901 }
5902
5904
5905 return result;
5906
5908}
5909
5910- (id)findOneEntityMatchingPredicate:(EntityFilterPredicate)predicate
5911 parameter:(void*)parameter
5912{
5913 unsigned i;
5914 Entity* candidate = nil;
5915
5917
5918 if (predicate == NULL)
5919 predicate = YESPredicate;
5920
5921 for (i = 0; i < n_entities; i++) {
5922 candidate = sortedEntities[i];
5923 if (predicate(candidate, parameter))
5924 return candidate;
5925 }
5926
5928
5929 return nil;
5930}
5931
5932- (NSMutableArray*)findShipsMatchingPredicate:(EntityFilterPredicate)predicate
5933 parameter:(void*)parameter
5934 inRange:(double)range
5935 ofEntity:(Entity*)entity
5936{
5937 if (predicate != NULL) {
5939 IsShipPredicate, NULL,
5940 predicate, parameter
5941 };
5942
5943 return [self findEntitiesMatchingPredicate:ANDPredicate
5944 parameter:&param
5945 inRange:range
5946 ofEntity:entity];
5947 } else {
5948 return [self findEntitiesMatchingPredicate:IsShipPredicate
5949 parameter:NULL
5950 inRange:range
5951 ofEntity:entity];
5952 }
5953}
5954
5955- (NSMutableArray*)findVisualEffectsMatchingPredicate:(EntityFilterPredicate)predicate
5956 parameter:(void*)parameter
5957 inRange:(double)range
5958 ofEntity:(Entity*)entity
5959{
5960 if (predicate != NULL) {
5963 predicate, parameter
5964 };
5965
5966 return [self findEntitiesMatchingPredicate:ANDPredicate
5967 parameter:&param
5968 inRange:range
5969 ofEntity:entity];
5970 } else {
5971 return [self findEntitiesMatchingPredicate:IsVisualEffectPredicate
5972 parameter:NULL
5973 inRange:range
5974 ofEntity:entity];
5975 }
5976}
5977
5978- (id)nearestEntityMatchingPredicate:(EntityFilterPredicate)predicate
5979 parameter:(void*)parameter
5980 relativeToEntity:(Entity*)entity
5981{
5982 unsigned i;
5983 HPVector p1;
5984 float rangeSq = INFINITY;
5985 id result = nil;
5986
5987 if (predicate == NULL)
5988 predicate = YESPredicate;
5989
5990 if (entity != nil)
5991 p1 = [entity position];
5992 else
5993 p1 = kZeroHPVector;
5994
5995 for (i = 0; i < n_entities; i++) {
5996 Entity* e2 = sortedEntities[i];
5997 float distanceToReferenceEntitySquared = (float)HPdistance2(p1, [e2 position]);
5998
5999 if (entity != e2 && distanceToReferenceEntitySquared < rangeSq && predicate(e2, parameter)) {
6000 result = e2;
6001 rangeSq = distanceToReferenceEntitySquared;
6002 }
6003 }
6004
6005 return [[result retain] autorelease];
6006}
6007
6008- (id)nearestShipMatchingPredicate:(EntityFilterPredicate)predicate
6009 parameter:(void*)parameter
6010 relativeToEntity:(Entity*)entity
6011{
6012 if (predicate != NULL) {
6014 IsShipPredicate, NULL,
6015 predicate, parameter
6016 };
6017
6018 return [self nearestEntityMatchingPredicate:ANDPredicate
6019 parameter:&param
6020 relativeToEntity:entity];
6021 } else {
6022 return [self nearestEntityMatchingPredicate:IsShipPredicate
6023 parameter:NULL
6024 relativeToEntity:entity];
6025 }
6026}
6027
6029{
6030 return universal_time;
6031}
6032
6034{
6035 return time_delta;
6036}
6037
6039{
6040 unsigned i;
6041
6043
6044 for (i = 0; i < n_entities; i++) {
6045 [universeRegion checkEntity:sortedEntities[i]]; // sorts out which region it's in
6046 }
6047
6048 if (![[self gameController] isGamePaused]) {
6050 }
6051
6052 // do check for entities that can't see the sun!
6054}
6055
6057{
6058 if (universeRegion != nil)
6060 else
6061 return @"-";
6062}
6063
6065{
6066 dumpCollisionInfo = YES;
6067}
6068
6070{
6071 return viewDirection;
6072}
6073
6074- (void)setViewDirection:(OOViewID)vd
6075{
6076 NSString* ms = nil;
6077 BOOL guiSelected = NO;
6078
6079 if ((viewDirection == vd) && (vd != VIEW_CUSTOM) && (!displayGUI))
6080 return;
6081
6082 switch (vd) {
6083 case VIEW_FORWARD:
6084 ms = DESC(@"forward-view-string");
6085 break;
6086
6087 case VIEW_AFT:
6088 ms = DESC(@"aft-view-string");
6089 break;
6090
6091 case VIEW_PORT:
6092 ms = DESC(@"port-view-string");
6093 break;
6094
6095 case VIEW_STARBOARD:
6096 ms = DESC(@"starboard-view-string");
6097 break;
6098
6099 case VIEW_CUSTOM:
6100 ms = [PLAYER customViewDescription];
6101 break;
6102
6103 case VIEW_GUI_DISPLAY:
6104 [self setDisplayText:YES];
6105 [self setMainLightPosition:(Vector) { DEMO_LIGHT_POSITION }];
6106 guiSelected = YES;
6107 break;
6108
6109 default:
6110 guiSelected = YES;
6111 break;
6112 }
6113
6114 if (guiSelected) {
6116 } else {
6117 displayGUI = NO; // switch off any text displays
6119 }
6120
6121 if (viewDirection != vd || viewDirection == VIEW_CUSTOM) {
6122#if (ALLOW_CUSTOM_VIEWS_WHILE_PAUSED)
6123 BOOL gamePaused = [[self gameController] isGamePaused];
6124#else
6125 BOOL gamePaused = NO;
6126#endif
6127 // view notifications for when the player switches to/from gui!
6128 // if (EXPECT(viewDirection == VIEW_GUI_DISPLAY || vd == VIEW_GUI_DISPLAY )) [PLAYER noteViewDidChangeFrom:viewDirection toView:vd];
6129 viewDirection = vd;
6130 if (ms && !gamePaused) {
6131 [self addMessage:ms forCount:3];
6132 } else if (gamePaused) {
6134 }
6135 }
6136}
6137
6138- (void)enterGUIViewModeWithMouseInteraction:(BOOL)mouseInteraction
6139{
6141 [self setViewDirection:VIEW_GUI_DISPLAY];
6142 if (viewDirection != vd) {
6143 PlayerEntity* player = PLAYER;
6144 JSContext* context = OOJSAcquireContext();
6145 ShipScriptEvent(context, player, "viewDirectionChanged", OOJSValueFromViewID(context, viewDirection), OOJSValueFromViewID(context, vd));
6146 OOJSRelinquishContext(context);
6147 }
6149}
6150
6151- (NSString*)soundNameForCustomSoundKey:(NSString*)key
6152{
6153 NSString* result = nil;
6154 NSMutableSet* seen = nil;
6155 id object = [customSounds objectForKey:key];
6156
6157 if ([object isKindOfClass:[NSArray class]] && [object count] > 0) {
6158 key = [object oo_stringAtIndex:Ranrot() % [object count]];
6159 } else {
6160 object = nil;
6161 }
6162
6163 result = [[OOCacheManager sharedCache] objectForKey:key inCache:@"resolved custom sounds"];
6164 if (result == nil) {
6165 // Resolve sound, allowing indirection within customsounds.plist
6166 seen = [NSMutableSet set];
6167 result = key;
6168 if (object == nil || ([result hasPrefix:@"["] && [result hasSuffix:@"]"])) {
6169 for (;;) {
6170 [seen addObject:result];
6171 object = [customSounds objectForKey:result];
6172 if ([object isKindOfClass:[NSArray class]] && [object count] > 0) {
6173 result = [object oo_stringAtIndex:Ranrot() % [object count]];
6174 if ([key hasPrefix:@"["] && [key hasSuffix:@"]"])
6175 key = result;
6176 } else {
6177 if ([object isKindOfClass:[NSString class]])
6178 result = object;
6179 else
6180 result = nil;
6181 }
6182 if (result == nil || ![result hasPrefix:@"["] || ![result hasSuffix:@"]"])
6183 break;
6184 if ([seen containsObject:result]) {
6185 OOLogERR(@"sound.customSounds.recursion", @"recursion in customsounds.plist for '%@' (at '%@'), no sound will be played.", key, result);
6186 result = nil;
6187 break;
6188 }
6189 }
6190 }
6191
6192 if (result == nil)
6193 result = @"__oolite-no-sound";
6194 [[OOCacheManager sharedCache] setObject:result forKey:key inCache:@"resolved custom sounds"];
6195 }
6196
6197 if ([result isEqualToString:@"__oolite-no-sound"]) {
6198 OOLog(@"sound.customSounds", @"Could not resolve sound name in customsounds.plist for '%@', no sound will be played.", key);
6199 result = nil;
6200 }
6201 return result;
6202}
6203
6204- (NSDictionary*)screenTextureDescriptorForKey:(NSString*)key
6205{
6206 id value = [screenBackgrounds objectForKey:key];
6207 while ([value isKindOfClass:[NSArray class]])
6208 value = [value objectAtIndex:Ranrot() % [value count]];
6209
6210 if ([value isKindOfClass:[NSString class]])
6211 value = [NSDictionary dictionaryWithObject:value forKey:@"name"];
6212 else if (![value isKindOfClass:[NSDictionary class]])
6213 value = nil;
6214
6215 // Start loading the texture, and return nil if it doesn't exist.
6216 if (![[self gui] preloadGUITexture:value])
6217 value = nil;
6218
6219 return value;
6220}
6221
6222- (void)setScreenTextureDescriptorForKey:(NSString*)key descriptor:(NSDictionary*)desc
6223{
6224 NSMutableDictionary* sbCopy = [screenBackgrounds mutableCopy];
6225 if (desc == nil) {
6226 [sbCopy removeObjectForKey:key];
6227 } else {
6228 [sbCopy setObject:desc forKey:key];
6229 }
6230 [screenBackgrounds release];
6231 screenBackgrounds = [sbCopy copy];
6232 [sbCopy release];
6233}
6234
6236{
6237 if (currentMessage)
6238 [currentMessage release];
6240}
6241
6242- (void)setMessageGuiBackgroundColor:(OOColor*)some_color
6243{
6244 [message_gui setBackgroundColor:some_color];
6245}
6246
6247- (void)displayMessage:(NSString*)text forCount:(OOTimeDelta)count
6248{
6249 if (![currentMessage isEqual:text] || universal_time >= messageRepeatTime) {
6250 if (currentMessage)
6251 [currentMessage release];
6252 currentMessage = [text retain];
6254 [self showGUIMessage:text withScroll:YES andColor:[message_gui textColor] overDuration:count];
6255 }
6256}
6257
6258- (void)displayCountdownMessage:(NSString*)text forCount:(OOTimeDelta)count
6259{
6260 if (![currentMessage isEqual:text] && universal_time >= countdown_messageRepeatTime) {
6261 if (currentMessage)
6262 [currentMessage release];
6263 currentMessage = [text retain];
6265 [self showGUIMessage:text withScroll:NO andColor:[message_gui textColor] overDuration:count];
6266 }
6267}
6268
6269- (void)addDelayedMessage:(NSString*)text forCount:(OOTimeDelta)count afterDelay:(double)delay
6270{
6271 NSMutableDictionary* msgDict = [NSMutableDictionary dictionaryWithCapacity:2];
6272 [msgDict setObject:text forKey:@"message"];
6273 [msgDict setObject:[NSNumber numberWithDouble:count] forKey:@"duration"];
6274 [self performSelector:@selector(addDelayedMessage:) withObject:msgDict afterDelay:delay];
6275}
6276
6277- (void)addDelayedMessage:(NSDictionary*)textdict
6278{
6279 NSString* msg = nil;
6280 OOTimeDelta msg_duration;
6281
6282 msg = [textdict oo_stringForKey:@"message"];
6283 if (msg == nil)
6284 return;
6285 msg_duration = [textdict oo_nonNegativeDoubleForKey:@"duration" defaultValue:3.0];
6286
6287 [self addMessage:msg forCount:msg_duration];
6288}
6289
6290- (void)addMessage:(NSString*)text forCount:(OOTimeDelta)count
6291{
6292 [self addMessage:text forCount:count forceDisplay:NO];
6293}
6294
6295- (void)speakWithSubstitutions:(NSString*)text
6296{
6297#if OOLITE_SPEECH_SYNTH
6298 // speech synthesis
6299
6300 PlayerEntity* player = PLAYER;
6301 if ([player isSpeechOn] > OOSPEECHSETTINGS_OFF) {
6302 NSString* systemSaid = nil;
6303 NSString* h_systemSaid = nil;
6304
6305 NSString* systemName = [self getSystemName:systemID];
6306
6307 systemSaid = systemName;
6308
6309 NSString* h_systemName = [self getSystemName:[player targetSystemID]];
6310 h_systemSaid = h_systemName;
6311
6312 NSString* spokenText = text;
6313 if (speechArray != nil) {
6314 NSArray* thePair = nil;
6315
6316 foreach (thePair, speechArray) {
6317 NSString* original_phrase = [thePair oo_stringAtIndex:0];
6318
6319 NSUInteger replacementIndex;
6320#if OOLITE_MAC_COCOA_UI
6321 replacementIndex = 1;
6322#elif OOLITE_ESPEAK
6323 replacementIndex = [thePair count] > 2 ? 2 : 1;
6324#endif
6325
6326 NSString* replacement_phrase = [thePair oo_stringAtIndex:replacementIndex];
6327 if (![replacement_phrase isEqualToString:@"_"]) {
6328 spokenText = [spokenText stringByReplacingOccurrencesOfString:original_phrase withString:replacement_phrase];
6329 }
6330 }
6331 spokenText = [spokenText stringByReplacingOccurrencesOfString:systemName withString:systemSaid];
6332 spokenText = [spokenText stringByReplacingOccurrencesOfString:h_systemName withString:h_systemSaid];
6333 }
6334 [self stopSpeaking];
6335 [self startSpeakingString:spokenText];
6336 }
6337#endif // OOLITE_SPEECH_SYNTH
6338}
6339
6340- (void)addMessage:(NSString*)text forCount:(OOTimeDelta)count forceDisplay:(BOOL)forceDisplay
6341{
6342 if (![currentMessage isEqual:text] || forceDisplay || universal_time >= messageRepeatTime) {
6343 if ([PLAYER isSpeechOn] == OOSPEECHSETTINGS_ALL) {
6344 [self speakWithSubstitutions:text];
6345 }
6346
6347 [self showGUIMessage:text withScroll:YES andColor:[message_gui textColor] overDuration:count];
6348
6349 [PLAYER doScriptEvent:OOJSID("consoleMessageReceived") withArgument:text];
6350
6351 [currentMessage release];
6352 currentMessage = [text retain];
6354 }
6355}
6356
6357- (void)addCommsMessage:(NSString*)text forCount:(OOTimeDelta)count
6358{
6359 [self addCommsMessage:text forCount:count andShowComms:_autoCommLog logOnly:NO];
6360}
6361
6362- (void)addCommsMessage:(NSString*)text forCount:(OOTimeDelta)count andShowComms:(BOOL)showComms logOnly:(BOOL)logOnly
6363{
6364 if ([PLAYER showDemoShips])
6365 return;
6366
6367 NSString* expandedMessage = OOExpand(text);
6368
6369 if (![currentMessage isEqualToString:expandedMessage] || universal_time >= messageRepeatTime) {
6370 PlayerEntity* player = PLAYER;
6371
6372 if (!logOnly) {
6373 if ([player isSpeechOn] >= OOSPEECHSETTINGS_COMMS) {
6374 // EMMSTRAN: should say "Incoming message from ..." when prefixed with sender name.
6375 NSString* format = OOExpandKey(@"speech-synthesis-incoming-message-@");
6376 [self speakWithSubstitutions:[NSString stringWithFormat:format, expandedMessage]];
6377 }
6378
6379 [self showGUIMessage:expandedMessage withScroll:YES andColor:[message_gui textCommsColor] overDuration:count];
6380
6381 [currentMessage release];
6384 }
6385
6386 [comm_log_gui printLongText:expandedMessage align:GUI_ALIGN_LEFT color:nil fadeTime:0.0 key:nil addToArray:[player commLog]];
6387
6388 if (showComms)
6389 [self showCommsLog:6.0];
6390 }
6391}
6392
6393- (void)showCommsLog:(OOTimeDelta)how_long
6394{
6395 [comm_log_gui setAlpha:1.0];
6396 if (![self permanentCommLog])
6398}
6399
6400- (void)showGUIMessage:(NSString*)text withScroll:(BOOL)scroll andColor:(OOColor*)selectedColor overDuration:(OOTimeDelta)how_long
6401{
6402 if (scroll) {
6403 [message_gui printLongText:text align:GUI_ALIGN_CENTER color:selectedColor fadeTime:how_long key:nil addToArray:nil];
6404 } else {
6405 [message_gui printLineNoScroll:text align:GUI_ALIGN_CENTER color:selectedColor fadeTime:how_long key:nil addToArray:nil];
6406 }
6407 [message_gui setAlpha:1.0f];
6408}
6409
6411{
6412 if (EXPECT_NOT([PLAYER status] == STATUS_START_GAME)) {
6413 return; // no need to be adding ships as this is not a "real" game
6414 }
6415 JSContext* context = OOJSAcquireContext();
6416 [PLAYER doWorldScriptEvent:OOJSIDFromString(system_repopulator) inContext:context withArguments:NULL count:0 timeLimit:kOOJSLongTimeLimit];
6417 OOJSRelinquishContext(context);
6419}
6420
6421- (void)update:(OOTimeDelta)inDeltaT
6422{
6423 volatile OOTimeDelta delta_t = inDeltaT * [self timeAccelerationFactor];
6424 NSUInteger sessionID = _sessionID;
6425 OOLog(@"universe.profile.update", @"%@", @"Begin update");
6426 if (EXPECT(!no_update)) {
6427 next_repopulation -= delta_t;
6428 if (next_repopulation < 0) {
6429 [self repopulateSystem];
6430 }
6431
6432 unsigned i, ent_count = n_entities;
6433 Entity* my_entities[ent_count];
6434
6436
6437 // use a retained copy so this can't be changed under us.
6438 for (i = 0; i < ent_count; i++) {
6439 my_entities[i] = [sortedEntities[i] retain]; // explicitly retain each one
6440 }
6441
6442 NSString* volatile update_stage = @"initialisation";
6443#ifndef NDEBUG
6444 id volatile update_stage_param = nil;
6445#endif
6446
6447 @try {
6448 PlayerEntity* player = PLAYER;
6449
6450 skyClearColor[0] = 0.0;
6451 skyClearColor[1] = 0.0;
6452 skyClearColor[2] = 0.0;
6453 skyClearColor[3] = 0.0;
6454
6455 time_delta = delta_t;
6456 universal_time += delta_t;
6457
6458 if (EXPECT_NOT([player showDemoShips] && [player guiScreen] == GUI_SCREEN_SHIPLIBRARY)) {
6459 update_stage = @"demo management";
6460
6462 if (ent_count > 1) {
6463 Vector vel;
6465
6467
6468 switch (demo_stage) {
6469 case DEMO_FLY_IN:
6470 [demo_ship setPosition:[demo_ship destination]]; // ideal position
6473 break;
6474 case DEMO_SHOW_THING:
6475 vel = make_vector(0, 0, DEMO2_VANISHING_DISTANCE * demo_ship->collision_radius * 6.0);
6476 [demo_ship setVelocity:vel];
6479 break;
6480 case DEMO_FLY_OUT:
6481 // change the demo_ship here
6482 [self removeEntity:demo_ship];
6483 demo_ship = nil;
6484
6485 /* NSString *shipDesc = nil;
6486 NSString *shipName = nil;
6487 NSDictionary *shipDict = nil; */
6488
6490 demo_ship = [self newShipWithName:[[self demoShipData] oo_stringForKey:kOODemoShipKey] usePlayerProxy:NO];
6491
6492 if (demo_ship != nil) {
6493 [demo_ship removeEquipmentItem:@"EQ_SHIELD_BOOSTER"];
6494 [demo_ship removeEquipmentItem:@"EQ_SHIELD_ENHANCER"];
6495
6496 [demo_ship switchAITo:@"nullAI.plist"];
6498 [demo_ship setScanClass:CLASS_NO_DRAW];
6499 [demo_ship setStatus:STATUS_COCKPIT_DISPLAY]; // prevents it getting escorts on addition
6500 [demo_ship setDemoShip:1.0f];
6501 [demo_ship setDemoStartTime:universal_time];
6502 if ([self addEntity:demo_ship]) {
6503 [demo_ship release]; // We now own a reference through the entity list.
6504 [demo_ship setStatus:STATUS_COCKPIT_DISPLAY];
6505 demo_start_z = DEMO2_VANISHING_DISTANCE * demo_ship->collision_radius;
6506 [demo_ship setPositionX:0.0f y:0.0f z:demo_start_z];
6507 [demo_ship setDestination:make_HPvector(0.0f, 0.0f, demo_start_z * 0.01f)]; // ideal position
6508 [demo_ship setVelocity:kZeroVector];
6509 [demo_ship setScanClass:CLASS_NO_DRAW];
6510 // [gui setText:shipName != nil ? shipName : [demo_ship displayName] forRow:19 align:GUI_ALIGN_CENTER];
6511
6513
6517 } else {
6518 demo_ship = nil;
6519 }
6520 }
6521 break;
6522 }
6523 }
6524 } else if (demo_stage == DEMO_FLY_IN) {
6526 [demo_ship setPositionX:0.0f y:[demo_ship destination].y * delta z:demo_start_z + ([demo_ship destination].z - demo_start_z) * delta];
6527 }
6528 }
6529
6530 update_stage = @"update:entity";
6531 NSMutableSet* zombies = nil;
6532 OOLog(@"universe.profile.update", @"%@", update_stage);
6533 for (i = 0; i < ent_count; i++) {
6534 Entity* thing = my_entities[i];
6535#ifndef NDEBUG
6536 update_stage_param = thing;
6537 update_stage = @"update:entity [%@]";
6538#endif
6539 // Game Over code depends on regular delta_t updates to the dead player entity. Ignore the player entity, even when dead.
6540 if (EXPECT_NOT([thing status] == STATUS_DEAD && ![entitiesDeadThisUpdate containsObject:thing] && ![thing isPlayer])) {
6541 if (zombies == nil)
6542 zombies = [NSMutableSet set];
6543 [zombies addObject:thing];
6544 continue;
6545 }
6546
6547 [thing update:delta_t];
6549 // Game was reset (in player update); end this update: cycle.
6550 break;
6551 }
6552
6553#ifndef NDEBUG
6554 update_stage = @"update:list maintenance [%@]";
6555#endif
6556
6557 // maintain distance-from-player list
6558 GLfloat z_distance = thing->zero_distance;
6559
6560 int index = thing->zero_index;
6561 while (index > 0 && z_distance < sortedEntities[index - 1]->zero_distance) {
6562 sortedEntities[index] = sortedEntities[index - 1]; // bubble up the list, usually by just one position
6563 sortedEntities[index - 1] = thing;
6564 thing->zero_index = index - 1;
6565 sortedEntities[index]->zero_index = index;
6566 index--;
6567 }
6568
6569 // update deterministic AI
6570 if ([thing isShip]) {
6571#ifndef NDEBUG
6572 update_stage = @"update:think [%@]";
6573#endif
6574 AI* theShipsAI = [(ShipEntity*)thing getAI];
6575 if (theShipsAI) {
6576 double thinkTime = [theShipsAI nextThinkTime];
6577 if ((universal_time > thinkTime) || (thinkTime == 0.0)) {
6579 [theShipsAI think];
6580 }
6581 }
6582 }
6583 }
6584#ifndef NDEBUG
6585 update_stage_param = nil;
6586#endif
6587
6588 if (zombies != nil) {
6589 update_stage = @"shootin' zombies";
6590 Entity* zombie = nil;
6591 foreach (zombie, zombies) {
6592 OOLogERR(@"universe.zombie", @"Found dead entity %@ in active entity list, removing. This is an internal error, please report it.", zombie);
6593 [self removeEntity:zombie];
6594 }
6595 }
6596
6597 // Maintain x/y/z order lists
6598 update_stage = @"updating linked lists";
6599 OOLog(@"universe.profile.update", @"%@", update_stage);
6600 for (i = 0; i < ent_count; i++) {
6602 }
6603
6604 // detect collisions and light ships that can see the sun
6605
6606 update_stage = @"collision and shadow detection";
6607 OOLog(@"universe.profile.update", @"%@", update_stage);
6608 [self filterSortedLists];
6610
6611 // do any required check and maintenance of linked lists
6612
6614 MaintainLinkedLists(self);
6616 }
6617 }
6618 @catch (NSException* exception) {
6619 if ([[exception name] hasPrefix:@"Oolite"]) {
6620 [self handleOoliteException:exception];
6621 } else {
6622#ifndef NDEBUG
6623 if (update_stage_param != nil)
6624 update_stage = [NSString stringWithFormat:update_stage, update_stage_param];
6625#endif
6626 OOLog(kOOLogException, @"***** Exception during [%@] in [Universe update:] : %@ : %@ *****", update_stage, [exception name], [exception reason]);
6627 @throw exception;
6628 }
6629 }
6630
6631 // dispose of the non-mutable copy and everything it references neatly
6632 update_stage = @"clean up";
6633 OOLog(@"universe.profile.update", @"%@", update_stage);
6634 for (i = 0; i < ent_count; i++) {
6635 [my_entities[i] release]; // explicitly release each one
6636 }
6637 /* Garbage collection is going to result in a significant
6638 * pause when it happens. Doing it here is better than doing
6639 * it in the middle of the update when it might slow a
6640 * function into the timelimiter through no fault of its
6641 * own. JS_MaybeGC will only run a GC when it's
6642 * necessary. Merely checking is not significant in terms of
6643 * time. - CIM: 4/8/2013
6644 */
6645 update_stage = @"JS Garbage Collection";
6646 OOLog(@"universe.profile.update", @"%@", update_stage);
6647#if !defined(NDEBUG) && !OOJS_QUICKJS
6648 /* TODO (port): unplanned collection logging is not available with
6649 QuickJS, which has no cheap heap size query (JS_ComputeMemoryUsage()
6650 walks the whole heap, too slow to call every frame).
6651 */
6652 JSContext* context = OOJSAcquireContext();
6653 uint32 gcbytes1 = JS_GetGCParameter(JS_GetRuntime(context), JSGC_BYTES);
6654 OOJSRelinquishContext(context);
6655#endif
6657#if !defined(NDEBUG) && !OOJS_QUICKJS
6658 context = OOJSAcquireContext();
6659 uint32 gcbytes2 = JS_GetGCParameter(JS_GetRuntime(context), JSGC_BYTES);
6660 OOJSRelinquishContext(context);
6661 if (gcbytes2 < gcbytes1) {
6662 OOLog(@"universe.profile.jsgc", @"Unplanned JS Garbage Collection from %d to %d", gcbytes1, gcbytes2);
6663 }
6664#endif
6665
6666 } else {
6667 // always perform player's dead updates: allows deferred JS resets.
6668 if ([PLAYER status] == STATUS_DEAD)
6669 [PLAYER update:delta_t];
6670 }
6671
6672 [entitiesDeadThisUpdate autorelease];
6674 entitiesDeadThisUpdate = [[NSMutableSet alloc] initWithCapacity:n_entities];
6675
6676#if NEW_PLANETS
6677 [self prunePreloadingPlanetMaterials];
6678#endif
6679
6680 OOLog(@"universe.profile.update", @"%@", @"Update complete");
6681}
6682
6683#ifdef OO_DEBUG_MONITOR_ENABLED
6684- (double)timeAccelerationFactor
6685{
6686 return timeAccelerationFactor;
6687}
6688
6689- (void)setTimeAccelerationFactor:(double)newTimeAccelerationFactor
6690{
6691 if (newTimeAccelerationFactor < TIME_ACCELERATION_FACTOR_MIN || newTimeAccelerationFactor > TIME_ACCELERATION_FACTOR_MAX) {
6692 newTimeAccelerationFactor = TIME_ACCELERATION_FACTOR_DEFAULT;
6693 }
6694 timeAccelerationFactor = newTimeAccelerationFactor;
6695}
6696#else
6698{
6699 return 1.0;
6700}
6701
6702- (void)setTimeAccelerationFactor:(double)newTimeAccelerationFactor
6703{
6704}
6705#endif
6706
6708{
6709 return ECMVisualFXEnabled;
6710}
6711
6712- (void)setECMVisualFXEnabled:(BOOL)isEnabled
6713{
6714 ECMVisualFXEnabled = isEnabled;
6715}
6716
6718{
6719 /*
6720 Eric, 17-10-2010: raised the area to be not filtered out, from the combined collision size to 2x this size.
6721 This allows this filtered list to be used also for proximity_alert and not only for collisions. Before the
6722 proximity_alert could only trigger when already very near a collision. To late for ships to react.
6723 This does raise the number of entities in the collision chain with as result that the number of pairs to compair
6724 becomes significant larger. However, almost all of these extra pairs are dealt with by a simple distance check.
6725 I currently see no noticeable negative effect while playing, but this change might still give some trouble I missed.
6726 */
6727 Entity *e0, *next, *prev;
6728 OOHPScalar start, finish, next_start, next_finish, prev_start, prev_finish;
6729
6730 // using the z_list - set or clear collisionTestFilter and clear collision_chain
6731 e0 = z_list_start;
6732 while (e0) {
6733 e0->collisionTestFilter = [e0 canCollide] ? 0 : 3;
6734 e0->collision_chain = nil;
6735 e0 = e0->z_next;
6736 }
6737 // done.
6738
6739 /* We need to check the lists in both ascending and descending order
6740 * to catch some cases with interposition of entities. We set cTF =
6741 * 1 on the way up, and |= 2 on the way down. Therefore it's only 3
6742 * at the end of the list if it was caught both ways on the same
6743 * list. - CIM: 7/11/2012 */
6744
6745 // start with the z_list
6746 e0 = z_list_start;
6747 while (e0) {
6748 // here we are either at the start of the list or just past a gap
6749 start = e0->position.z - 2.0f * e0->collision_radius;
6750 finish = start + 4.0f * e0->collision_radius;
6751 next = e0->z_next;
6752 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6753 next = next->z_next;
6754 if (next) {
6755 next_start = next->position.z - 2.0f * next->collision_radius;
6756 if (next_start < finish) {
6757 // e0 and next overlap
6758 while ((next) && (next_start < finish)) {
6759 // skip forward to the next gap or the end of the list
6760 next_finish = next_start + 4.0f * next->collision_radius;
6761 if (next_finish > finish)
6762 finish = next_finish;
6763 e0 = next;
6764 next = e0->z_next;
6765 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated - so skip it
6766 next = next->z_next;
6767 if (next)
6768 next_start = next->position.z - 2.0f * next->collision_radius;
6769 }
6770 // now either (next == nil) or (next_start >= finish)-which would imply a gap!
6771 } else {
6772 // e0 is a singleton
6773 e0->collisionTestFilter = 1;
6774 }
6775 } else // (next == nil)
6776 {
6777 // at the end of the list so e0 is a singleton
6778 e0->collisionTestFilter = 1;
6779 }
6780 e0 = next;
6781 }
6782 // list filtered upwards, now filter downwards
6783 // e0 currently = end of z list
6784 while (e0) {
6785 // here we are either at the start of the list or just past a gap
6786 start = e0->position.z + 2.0f * e0->collision_radius;
6787 finish = start - 4.0f * e0->collision_radius;
6788 prev = e0->z_previous;
6789 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6790 prev = prev->z_previous;
6791 if (prev) {
6792 prev_start = prev->position.z + 2.0f * prev->collision_radius;
6793 if (prev_start > finish) {
6794 // e0 and next overlap
6795 while ((prev) && (prev_start > finish)) {
6796 // skip forward to the next gap or the end of the list
6797 prev_finish = prev_start - 4.0f * prev->collision_radius;
6798 if (prev_finish < finish)
6799 finish = prev_finish;
6800 e0 = prev;
6801 prev = e0->z_previous;
6802 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated - so skip it
6803 prev = prev->z_previous;
6804 if (prev)
6805 prev_start = prev->position.z + 2.0f * prev->collision_radius;
6806 }
6807 // now either (prev == nil) or (prev_start <= finish)-which would imply a gap!
6808 } else {
6809 // e0 is a singleton
6810 e0->collisionTestFilter |= 2;
6811 }
6812 } else // (prev == nil)
6813 {
6814 // at the end of the list so e0 is a singleton
6815 e0->collisionTestFilter |= 2;
6816 }
6817 e0 = prev;
6818 }
6819 // done! list filtered
6820
6821 // then with the y_list, z_list singletons now create more gaps..
6822 e0 = y_list_start;
6823 while (e0) {
6824 // here we are either at the start of the list or just past a gap
6825 start = e0->position.y - 2.0f * e0->collision_radius;
6826 finish = start + 4.0f * e0->collision_radius;
6827 next = e0->y_next;
6828 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6829 next = next->y_next;
6830 if (next) {
6831
6832 next_start = next->position.y - 2.0f * next->collision_radius;
6833 if (next_start < finish) {
6834 // e0 and next overlap
6835 while ((next) && (next_start < finish)) {
6836 // skip forward to the next gap or the end of the list
6837 next_finish = next_start + 4.0f * next->collision_radius;
6838 if (next_finish > finish)
6839 finish = next_finish;
6840 e0 = next;
6841 next = e0->y_next;
6842 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated - so skip it
6843 next = next->y_next;
6844 if (next)
6845 next_start = next->position.y - 2.0f * next->collision_radius;
6846 }
6847 // now either (next == nil) or (next_start >= finish)-which would imply a gap!
6848 } else {
6849 // e0 is a singleton
6850 e0->collisionTestFilter = 1;
6851 }
6852 } else // (next == nil)
6853 {
6854 // at the end of the list so e0 is a singleton
6855 e0->collisionTestFilter = 1;
6856 }
6857 e0 = next;
6858 }
6859 // list filtered upwards, now filter downwards
6860 // e0 currently = end of y list
6861 while (e0) {
6862 // here we are either at the start of the list or just past a gap
6863 start = e0->position.y + 2.0f * e0->collision_radius;
6864 finish = start - 4.0f * e0->collision_radius;
6865 prev = e0->y_previous;
6866 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6867 prev = prev->y_previous;
6868 if (prev) {
6869 prev_start = prev->position.y + 2.0f * prev->collision_radius;
6870 if (prev_start > finish) {
6871 // e0 and next overlap
6872 while ((prev) && (prev_start > finish)) {
6873 // skip forward to the next gap or the end of the list
6874 prev_finish = prev_start - 4.0f * prev->collision_radius;
6875 if (prev_finish < finish)
6876 finish = prev_finish;
6877 e0 = prev;
6878 prev = e0->y_previous;
6879 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated - so skip it
6880 prev = prev->y_previous;
6881 if (prev)
6882 prev_start = prev->position.y + 2.0f * prev->collision_radius;
6883 }
6884 // now either (prev == nil) or (prev_start <= finish)-which would imply a gap!
6885 } else {
6886 // e0 is a singleton
6887 e0->collisionTestFilter |= 2;
6888 }
6889 } else // (prev == nil)
6890 {
6891 // at the end of the list so e0 is a singleton
6892 e0->collisionTestFilter |= 2;
6893 }
6894 e0 = prev;
6895 }
6896 // done! list filtered
6897
6898 // finish with the x_list
6899 e0 = x_list_start;
6900 while (e0) {
6901 // here we are either at the start of the list or just past a gap
6902 start = e0->position.x - 2.0f * e0->collision_radius;
6903 finish = start + 4.0f * e0->collision_radius;
6904 next = e0->x_next;
6905 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6906 next = next->x_next;
6907 if (next) {
6908 next_start = next->position.x - 2.0f * next->collision_radius;
6909 if (next_start < finish) {
6910 // e0 and next overlap
6911 while ((next) && (next_start < finish)) {
6912 // skip forward to the next gap or the end of the list
6913 next_finish = next_start + 4.0f * next->collision_radius;
6914 if (next_finish > finish)
6915 finish = next_finish;
6916 e0 = next;
6917 next = e0->x_next;
6918 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated - so skip it
6919 next = next->x_next;
6920 if (next)
6921 next_start = next->position.x - 2.0f * next->collision_radius;
6922 }
6923 // now either (next == nil) or (next_start >= finish)-which would imply a gap!
6924 } else {
6925 // e0 is a singleton
6926 e0->collisionTestFilter = 1;
6927 }
6928 } else // (next == nil)
6929 {
6930 // at the end of the list so e0 is a singleton
6931 e0->collisionTestFilter = 1;
6932 }
6933 e0 = next;
6934 }
6935 // list filtered upwards, now filter downwards
6936 // e0 currently = end of x list
6937 while (e0) {
6938 // here we are either at the start of the list or just past a gap
6939 start = e0->position.x + 2.0f * e0->collision_radius;
6940 finish = start - 4.0f * e0->collision_radius;
6941 prev = e0->x_previous;
6942 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6943 prev = prev->x_previous;
6944 if (prev) {
6945 prev_start = prev->position.x + 2.0f * prev->collision_radius;
6946 if (prev_start > finish) {
6947 // e0 and next overlap
6948 while ((prev) && (prev_start > finish)) {
6949 // skip forward to the next gap or the end of the list
6950 prev_finish = prev_start - 4.0f * prev->collision_radius;
6951 if (prev_finish < finish)
6952 finish = prev_finish;
6953 e0 = prev;
6954 prev = e0->x_previous;
6955 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated - so skip it
6956 prev = prev->x_previous;
6957 if (prev)
6958 prev_start = prev->position.x + 2.0f * prev->collision_radius;
6959 }
6960 // now either (prev == nil) or (prev_start <= finish)-which would imply a gap!
6961 } else {
6962 // e0 is a singleton
6963 e0->collisionTestFilter |= 2;
6964 }
6965 } else // (prev == nil)
6966 {
6967 // at the end of the list so e0 is a singleton
6968 e0->collisionTestFilter |= 2;
6969 }
6970 e0 = prev;
6971 }
6972 // done! list filtered
6973
6974 // repeat the y_list - so gaps from the x_list influence singletons
6975 e0 = y_list_start;
6976 while (e0) {
6977 // here we are either at the start of the list or just past a gap
6978 start = e0->position.y - 2.0f * e0->collision_radius;
6979 finish = start + 4.0f * e0->collision_radius;
6980 next = e0->y_next;
6981 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
6982 next = next->y_next;
6983 if (next) {
6984 next_start = next->position.y - 2.0f * next->collision_radius;
6985 if (next_start < finish) {
6986 // e0 and next overlap
6987 while ((next) && (next_start < finish)) {
6988 // skip forward to the next gap or the end of the list
6989 next_finish = next_start + 4.0f * next->collision_radius;
6990 if (next_finish > finish)
6991 finish = next_finish;
6992 e0 = next;
6993 next = e0->y_next;
6994 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated - so skip it
6995 next = next->y_next;
6996 if (next)
6997 next_start = next->position.y - 2.0f * next->collision_radius;
6998 }
6999 // now either (next == nil) or (next_start >= finish)-which would imply a gap!
7000 } else {
7001 // e0 is a singleton
7002 e0->collisionTestFilter = 1;
7003 }
7004 } else // (next == nil)
7005 {
7006 // at the end of the list so e0 is a singleton
7007 e0->collisionTestFilter = 1;
7008 }
7009 e0 = next;
7010 }
7011 // e0 currently = end of y list
7012 while (e0) {
7013 // here we are either at the start of the list or just past a gap
7014 start = e0->position.y + 2.0f * e0->collision_radius;
7015 finish = start - 4.0f * e0->collision_radius;
7016 prev = e0->y_previous;
7017 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
7018 prev = prev->y_previous;
7019 if (prev) {
7020 prev_start = prev->position.y + 2.0f * prev->collision_radius;
7021 if (prev_start > finish) {
7022 // e0 and next overlap
7023 while ((prev) && (prev_start > finish)) {
7024 // skip forward to the next gap or the end of the list
7025 prev_finish = prev_start - 4.0f * prev->collision_radius;
7026 if (prev_finish < finish)
7027 finish = prev_finish;
7028 e0 = prev;
7029 prev = e0->y_previous;
7030 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated - so skip it
7031 prev = prev->y_previous;
7032 if (prev)
7033 prev_start = prev->position.y + 2.0f * prev->collision_radius;
7034 }
7035 // now either (prev == nil) or (prev_start <= finish)-which would imply a gap!
7036 } else {
7037 // e0 is a singleton
7038 e0->collisionTestFilter |= 2;
7039 }
7040 } else // (prev == nil)
7041 {
7042 // at the end of the list so e0 is a singleton
7043 e0->collisionTestFilter |= 2;
7044 }
7045 e0 = prev;
7046 }
7047 // done! list filtered
7048
7049 // finally, repeat the z_list - this time building collision chains...
7050 e0 = z_list_start;
7051 while (e0) {
7052 // here we are either at the start of the list or just past a gap
7053 start = e0->position.z - 2.0f * e0->collision_radius;
7054 finish = start + 4.0f * e0->collision_radius;
7055 next = e0->z_next;
7056 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
7057 next = next->z_next;
7058 if (next) {
7059 next_start = next->position.z - 2.0f * next->collision_radius;
7060 if (next_start < finish) {
7061 // e0 and next overlap
7062 while ((next) && (next_start < finish)) {
7063 // chain e0 to next in collision
7064 e0->collision_chain = next;
7065 // skip forward to the next gap or the end of the list
7066 next_finish = next_start + 4.0f * next->collision_radius;
7067 if (next_finish > finish)
7068 finish = next_finish;
7069 e0 = next;
7070 next = e0->z_next;
7071 while ((next) && (next->collisionTestFilter == 3)) // next has been eliminated - so skip it
7072 next = next->z_next;
7073 if (next)
7074 next_start = next->position.z - 2.0f * next->collision_radius;
7075 }
7076 // now either (next == nil) or (next_start >= finish)-which would imply a gap!
7077 e0->collision_chain = nil; // end the collision chain
7078 } else {
7079 // e0 is a singleton
7080 e0->collisionTestFilter = 1;
7081 }
7082 } else // (next == nil)
7083 {
7084 // at the end of the list so e0 is a singleton
7085 e0->collisionTestFilter = 1;
7086 }
7087 e0 = next;
7088 }
7089 // e0 currently = end of z list
7090 while (e0) {
7091 // here we are either at the start of the list or just past a gap
7092 start = e0->position.z + 2.0f * e0->collision_radius;
7093 finish = start - 4.0f * e0->collision_radius;
7094 prev = e0->z_previous;
7095 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated from the list of possible colliders - so skip it
7096 prev = prev->z_previous;
7097 if (prev) {
7098 prev_start = prev->position.z + 2.0f * prev->collision_radius;
7099 if (prev_start > finish) {
7100 // e0 and next overlap
7101 while ((prev) && (prev_start > finish)) {
7102 // e0 probably already in collision chain at this point, but if it
7103 // isn't we have to insert it
7104 if (prev->collision_chain != e0) {
7105 if (prev->collision_chain == nil) {
7106 // easy, just add it onto the start of the chain
7107 prev->collision_chain = e0;
7108 } else {
7109 /* not nil and not e0 shouldn't be possible, I think.
7110 * if it is, that implies that e0->collision_chain is nil, though
7111 * so: */
7112 if (e0->collision_chain == nil) {
7113 e0->collision_chain = prev->collision_chain;
7114 prev->collision_chain = e0;
7115 } else {
7116 /* This shouldn't happen... If it does, we accept
7117 * missing collision checks and move on */
7118 OOLog(@"general.error.inconsistentState", @"Unexpected state in collision chain builder prev=%@, prev->c=%@, e0=%@, e0->c=%@", prev, prev->collision_chain, e0, e0->collision_chain);
7119 }
7120 }
7121 }
7122 // skip forward to the next gap or the end of the list
7123 prev_finish = prev_start - 4.0f * prev->collision_radius;
7124 if (prev_finish < finish)
7125 finish = prev_finish;
7126 e0 = prev;
7127 prev = e0->z_previous;
7128 while ((prev) && (prev->collisionTestFilter == 3)) // next has been eliminated - so skip it
7129 prev = prev->z_previous;
7130 if (prev)
7131 prev_start = prev->position.z + 2.0f * prev->collision_radius;
7132 }
7133 // now either (prev == nil) or (prev_start <= finish)-which would imply a gap!
7134
7135 // all the collision chains are already terminated somewhere
7136 // at this point so no need to set e0->collision_chain = nil
7137 } else {
7138 // e0 is a singleton
7139 e0->collisionTestFilter |= 2;
7140 }
7141 } else // (prev == nil)
7142 {
7143 // at the end of the list so e0 is a singleton
7144 e0->collisionTestFilter |= 2;
7145 }
7146 e0 = prev;
7147 }
7148 // done! list filtered
7149}
7150
7151- (void)setGalaxyTo:(OOGalaxyID)g
7152{
7153 [self setGalaxyTo:g andReinit:NO];
7154}
7155
7156- (void)setGalaxyTo:(OOGalaxyID)g andReinit:(BOOL)forced
7157{
7158 int i;
7159 NSAutoreleasePool* pool = nil;
7160
7161 if (galaxyID != g || forced) {
7162 galaxyID = g;
7163
7164 // systems
7165 pool = [[NSAutoreleasePool alloc] init];
7166
7167 for (i = 0; i < 256; i++) {
7168 if (system_names[i]) {
7169 [system_names[i] release];
7170 }
7171 system_names[i] = [[systemManager getProperty:@"name" forSystem:i inGalaxy:g] retain];
7172 }
7173 [pool release];
7174 }
7175}
7176
7177- (void)setSystemTo:(OOSystemID)s
7178{
7179 NSDictionary* systemData;
7180 PlayerEntity* player = PLAYER;
7181 OOEconomyID economy;
7182 NSString* scriptName;
7183
7185
7186 systemID = s;
7187 targetSystemID = s;
7188
7189 systemData = [self generateSystemData:targetSystemID];
7190 economy = [systemData oo_unsignedCharForKey:KEY_ECONOMY];
7191 scriptName = [systemData oo_stringForKey:@"market_script" defaultValue:nil];
7192
7195}
7196
7198{
7199 return systemID;
7200}
7201
7202- (NSDictionary*)descriptions
7203{
7204 if (_descriptions == nil) {
7205 // Load internal descriptions.plist for use in early init, OXP verifier etc.
7206 // It will be replaced by merged version later if running the game normally.
7207 _descriptions = [NSDictionary dictionaryWithContentsOfFile:[[[ResourceManager builtInPath]
7208 stringByAppendingPathComponent:@"Config"]
7209 stringByAppendingPathComponent:@"descriptions.plist"]];
7210
7211 [self verifyDescriptions];
7212 }
7213 return _descriptions;
7214}
7215
7216static void VerifyDesc(NSString* key, id desc);
7217
7218static void VerifyDescString(NSString* key, NSString* desc)
7219{
7220 if ([desc rangeOfString:@"%n"].location != NSNotFound) {
7221 OOLog(@"descriptions.verify.percentN", @"***** FATAL: descriptions.plist entry \"%@\" contains the dangerous control sequence %%n.", key);
7222 exit(EXIT_FAILURE);
7223 }
7224}
7225
7226static void VerifyDescArray(NSString* key, NSArray* desc)
7227{
7228 id subDesc = nil;
7229 foreach (subDesc, desc) {
7230 VerifyDesc(key, subDesc);
7231 }
7232}
7233
7234static void VerifyDesc(NSString* key, id desc)
7235{
7236 if ([desc isKindOfClass:[NSString class]]) {
7237 VerifyDescString(key, desc);
7238 } else if ([desc isKindOfClass:[NSArray class]]) {
7239 VerifyDescArray(key, desc);
7240 } else if ([desc isKindOfClass:[NSNumber class]]) {
7241 // No verification needed.
7242 } else {
7243 OOLogERR(@"descriptions.verify.badType", @"***** FATAL: descriptions.plist entry for \"%@\" is neither a string nor an array.", key);
7244 exit(EXIT_FAILURE);
7245 }
7246}
7247
7249{
7250 /*
7251 Ensure that no descriptions.plist entries contain the %n format code,
7252 which can be used to smash the stack and potentially call arbitrary
7253 functions.
7254
7255 %n is deliberately not supported in Foundation/CoreFoundation under
7256 Mac OS X, but unfortunately GNUstep implements it.
7257 -- Ahruman 2011-05-05
7258 */
7259
7260 NSString* key = nil;
7261 if (_descriptions == nil) {
7262 OOLog(@"descriptions.verify", @"%@", @"***** FATAL: Tried to verify descriptions, but descriptions was nil - unable to load any descriptions.plist file.");
7263 exit(EXIT_FAILURE);
7264 }
7265 foreachkey(key, _descriptions)
7266 {
7267 VerifyDesc(key, [_descriptions objectForKey:key]);
7268 }
7269}
7270
7272{
7273 [_descriptions autorelease];
7274 _descriptions = [[ResourceManager dictionaryFromFilesNamed:@"descriptions.plist" inFolder:@"Config" andMerge:YES] retain];
7275 [self verifyDescriptions];
7276}
7277
7278- (NSDictionary*)explosionSetting:(NSString*)explosion
7279{
7280 return [explosionSettings oo_dictionaryForKey:explosion defaultValue:nil];
7281}
7282
7283- (NSArray*)scenarios
7284{
7285 return _scenarios;
7286}
7287
7289{
7290 [_scenarios autorelease];
7291 _scenarios = [[ResourceManager arrayFromFilesNamed:@"scenarios.plist" inFolder:@"Config" andMerge:YES] retain];
7292}
7293
7294- (NSDictionary*)characters
7295{
7296 return characters;
7297}
7298
7299- (NSDictionary*)missiontext
7300{
7301 return missiontext;
7302}
7303
7304- (NSString*)descriptionForKey:(NSString*)key
7305{
7306 return [self chooseStringForKey:key inDictionary:[self descriptions]];
7307}
7308
7309- (NSString*)descriptionForArrayKey:(NSString*)key index:(unsigned)index
7310{
7311 NSArray* array = [[self descriptions] oo_arrayForKey:key];
7312 if ([array count] <= index)
7313 return nil; // Catches nil array
7314 return [array objectAtIndex:index];
7315}
7316
7317- (BOOL)descriptionBooleanForKey:(NSString*)key
7318{
7319 return [[self descriptions] oo_boolForKey:key];
7320}
7321
7326
7327- (NSString*)keyForPlanetOverridesForSystem:(OOSystemID)s inGalaxy:(OOGalaxyID)g
7328{
7329 return [NSString stringWithFormat:@"%d %d", g, s];
7330}
7331
7332- (NSString*)keyForInterstellarOverridesForSystems:(OOSystemID)s1 s2:(OOSystemID)s2 inGalaxy:(OOGalaxyID)g
7333{
7334 return [NSString stringWithFormat:@"interstellar: %d %d %d", g, s1, s2];
7335}
7336
7337- (NSDictionary*)generateSystemData:(OOSystemID)s
7338{
7339 return [self generateSystemData:s useCache:YES];
7340}
7341
7342// cache isn't handled this way any more
7343- (NSDictionary*)generateSystemData:(OOSystemID)s useCache:(BOOL)useCache
7344{
7346
7347 // TODO: At the moment this method is only called for systems in the
7348 // same galaxy. At some point probably needs generalising to have a
7349 // galaxynumber parameter.
7350 NSString* systemKey = [NSString stringWithFormat:@"%u %u", [PLAYER galaxyNumber], s];
7351
7352 return [systemManager getPropertiesForSystemKey:systemKey];
7353
7355}
7356
7357- (NSDictionary*)currentSystemData
7358{
7360
7361 if (![self inInterstellarSpace]) {
7362 return [self generateSystemData:systemID];
7363 } else {
7364 static NSDictionary* interstellarDict = nil;
7365 if (interstellarDict == nil) {
7366 NSString* interstellarName = DESC(@"interstellar-space");
7367 NSString* notApplicable = DESC(@"not-applicable");
7368 NSNumber* minusOne = [NSNumber numberWithInt:-1];
7369 NSNumber* zero = [NSNumber numberWithInt:0];
7370 interstellarDict = [[NSDictionary alloc] initWithObjectsAndKeys:
7371 interstellarName, KEY_NAME,
7372 minusOne, KEY_GOVERNMENT,
7373 minusOne, KEY_ECONOMY,
7374 minusOne, KEY_TECHLEVEL,
7375 zero, KEY_POPULATION,
7376 zero, KEY_PRODUCTIVITY,
7377 zero, KEY_RADIUS,
7378 notApplicable, KEY_INHABITANTS,
7379 notApplicable, KEY_DESCRIPTION,
7380 nil];
7381 }
7382
7383 return interstellarDict;
7384 }
7385
7387}
7388
7390{
7391 return [self sun] == nil;
7392}
7393
7394// layer 2
7395// used by legacy script engine and sun going nova
7396- (void)setSystemDataKey:(NSString*)key value:(NSObject*)object fromManifest:(NSString*)manifest
7397{
7398 [self setSystemDataForGalaxy:galaxyID planet:systemID key:key value:object fromManifest:manifest forLayer:OO_LAYER_OXP_DYNAMIC];
7399}
7400
7401- (void)setSystemDataForGalaxy:(OOGalaxyID)gnum planet:(OOSystemID)pnum key:(NSString*)key value:(id)object fromManifest:(NSString*)manifest forLayer:(OOSystemLayer)layer
7402{
7403 static BOOL sysdataLocked = NO;
7404 if (sysdataLocked) {
7405 OOLogERR(@"script.error", @"%@", @"System properties cannot be set during 'systemInformationChanged' events to avoid infinite loops.");
7406 return;
7407 }
7408
7409 BOOL sameGalaxy = (gnum == [PLAYER currentGalaxyID]);
7410 BOOL sameSystem = (sameGalaxy && pnum == [self currentSystemID]);
7411
7412 // trying to set unsettable properties?
7413 if ([key isEqualToString:KEY_RADIUS] && sameGalaxy && sameSystem) // buggy if we allow this key to be set while in the system
7414 {
7415 OOLogERR(@"script.error", @"System property '%@' cannot be set while in the system.", key);
7416 return;
7417 }
7418
7419 if ([key isEqualToString:@"coordinates"]) // setting this in game would be very confusing
7420 {
7421 OOLogERR(@"script.error", @"System property '%@' cannot be set.", key);
7422 return;
7423 }
7424
7425 NSString* overrideKey = [NSString stringWithFormat:@"%u %u", gnum, pnum];
7426 NSDictionary* sysInfo = nil;
7427
7428 // short range map fix
7430
7431 if (object != nil) {
7432 // long range map fixes
7433 if ([key isEqualToString:KEY_NAME]) {
7434 object = (id)[[(NSString*)object lowercaseString] capitalizedString];
7435 if (sameGalaxy) {
7436 if (system_names[pnum])
7437 [system_names[pnum] release];
7438 system_names[pnum] = [(NSString*)object retain];
7439 }
7440 } else if ([key isEqualToString:@"sun_radius"]) {
7441 if ([object doubleValue] < 1000.0 || [object doubleValue] > 10000000.0) {
7442 object = ([object doubleValue] < 1000.0 ? (id) @"1000.0" : (id) @"10000000.0"); // works!
7443 }
7444 } else if ([key hasPrefix:@"corona_"]) {
7445 object = (id)[NSString stringWithFormat:@"%f", OOClamp_0_1_f([object floatValue])];
7446 }
7447 }
7448
7449 [systemManager setProperty:key forSystemKey:overrideKey andLayer:layer toValue:object fromManifest:manifest];
7450
7451 // Apply changes that can be effective immediately, issue warning if they can't be changed just now
7452 if (sameSystem) {
7454
7455 OOSunEntity* the_sun = [self sun];
7456 /* KEY_ECONOMY used to be here, but resetting the main station
7457 * market while the player is in the system is likely to cause
7458 * more trouble than it's worth. Let them leave and come back
7459 * - CIM */
7460 if ([key isEqualToString:KEY_TECHLEVEL]) {
7461 if ([self station]) {
7462 [[self station] setEquivalentTechLevel:[object intValue]];
7463 [[self station] setLocalShipyard:[self shipsForSaleForSystem:systemID
7464 withTL:[object intValue]
7465 atTime:[PLAYER clockTime]]];
7466 }
7467 } else if ([key isEqualToString:@"sun_color"] || [key isEqualToString:@"star_count_multiplier"] ||
7468 [key isEqualToString:@"nebula_count_multiplier"] || [key hasPrefix:@"sky_"]) {
7469 SkyEntity* the_sky = nil;
7470 int i;
7471
7472 for (i = n_entities - 1; i > 0; i--)
7473 if ((sortedEntities[i]) && ([sortedEntities[i] isKindOfClass:[SkyEntity class]]))
7474 the_sky = (SkyEntity*)sortedEntities[i];
7475
7476 if (the_sky != nil) {
7478
7479 if ([key isEqualToString:@"sun_color"]) {
7480 OOColor* color = [the_sky skyColor];
7481 if (the_sun != nil) {
7482 [the_sun setSunColor:color];
7483 [the_sun getDiffuseComponents:sun_diffuse];
7484 [the_sun getSpecularComponents:sun_specular];
7485 }
7486 for (i = n_entities - 1; i > 0; i--)
7487 if ((sortedEntities[i]) && ([sortedEntities[i] isKindOfClass:[DustEntity class]]))
7489 }
7490 }
7491 } else if (the_sun != nil && ([key hasPrefix:@"sun_"] || [key hasPrefix:@"corona_"])) {
7493 } else if ([key isEqualToString:@"texture"]) {
7494 [[self planet] setUpPlanetFromTexture:(NSString*)object];
7495 } else if ([key isEqualToString:@"texture_hsb_color"]) {
7496 [[self planet] setUpPlanetFromTexture:[[self planet] textureFileName]];
7497 } else if ([key isEqualToString:@"air_color"]) {
7498 [[self planet] setAirColor:[OOColor brightColorWithDescription:object]];
7499 } else if ([key isEqualToString:@"illumination_color"]) {
7500 [[self planet] setIlluminationColor:[OOColor colorWithDescription:object]];
7501 } else if ([key isEqualToString:@"air_color_mix_ratio"]) {
7502 [[self planet] setAirColorMixRatio:[sysInfo oo_floatForKey:key]];
7503 }
7504 }
7505
7506 sysdataLocked = YES;
7507 [PLAYER doScriptEvent:OOJSID("systemInformationChanged") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithInt:gnum], [NSNumber numberWithInt:pnum], key, object, nil]];
7508 sysdataLocked = NO;
7509}
7510
7511- (NSDictionary*)generateSystemDataForGalaxy:(OOGalaxyID)gnum planet:(OOSystemID)pnum
7512{
7513 NSString* systemKey = [self keyForPlanetOverridesForSystem:pnum inGalaxy:gnum];
7514 return [systemManager getPropertiesForSystemKey:systemKey];
7515}
7516
7517- (NSArray*)systemDataKeysForGalaxy:(OOGalaxyID)gnum planet:(OOSystemID)pnum
7518{
7519 return [[self generateSystemDataForGalaxy:gnum planet:pnum] allKeys];
7520}
7521
7522/* Only called from OOJSSystemInfo. */
7523- (id)systemDataForGalaxy:(OOGalaxyID)gnum planet:(OOSystemID)pnum key:(NSString*)key
7524{
7525 return [systemManager getProperty:key forSystem:pnum inGalaxy:gnum];
7526}
7527
7528- (NSString*)getSystemName:(OOSystemID)sys
7529{
7530 return [self getSystemName:sys forGalaxy:galaxyID];
7531}
7532
7533- (NSString*)getSystemName:(OOSystemID)sys forGalaxy:(OOGalaxyID)gnum
7534{
7535 return [systemManager getProperty:@"name" forSystem:sys inGalaxy:gnum];
7536}
7537
7538- (OOGovernmentID)getSystemGovernment:(OOSystemID)sys
7539{
7540 return [[systemManager getProperty:@"government" forSystem:sys inGalaxy:galaxyID] unsignedCharValue];
7541}
7542
7543- (NSString*)getSystemInhabitants:(OOSystemID)sys
7544{
7545 return [self getSystemInhabitants:sys plural:YES];
7546}
7547
7548- (NSString*)getSystemInhabitants:(OOSystemID)sys plural:(BOOL)plural
7549{
7550 NSString* ret = nil;
7551 if (!plural) {
7552 ret = [systemManager getProperty:KEY_INHABITANT forSystem:sys inGalaxy:galaxyID];
7553 }
7554 if (ret != nil) // the singular form might be absent.
7555 {
7556 return ret;
7557 } else {
7558 return [systemManager getProperty:KEY_INHABITANTS forSystem:sys inGalaxy:galaxyID];
7559 }
7560}
7561
7562- (NSPoint)coordinatesForSystem:(OOSystemID)s
7563{
7565}
7566
7567- (OOSystemID)findSystemFromName:(NSString*)sysName
7568{
7569 if (sysName == nil)
7570 return -1; // no match found!
7571
7572 NSString* system_name = nil;
7573 NSString* match = [sysName lowercaseString];
7574 int i;
7575 for (i = 0; i < 256; i++) {
7576 system_name = [system_names[i] lowercaseString];
7577 if ([system_name isEqualToString:match]) {
7578 return i;
7579 }
7580 }
7581 return -1; // no match found!
7582}
7583
7584- (OOSystemID)findSystemAtCoords:(NSPoint)coords withGalaxy:(OOGalaxyID)g
7585{
7586 OOLog(@"deprecated.function", @"%@", @"findSystemAtCoords");
7587 return [self findSystemNumberAtCoords:coords withGalaxy:g includingHidden:YES];
7588}
7589
7590- (NSMutableArray*)nearbyDestinationsWithinRange:(double)range
7591{
7592 NSMutableArray* result = [NSMutableArray arrayWithCapacity:16];
7593
7594 range = OOClamp_0_max_d(range, MAX_JUMP_RANGE); // limit to systems within 7LY
7595 NSPoint here = [PLAYER galaxy_coordinates];
7596
7597 for (unsigned short i = 0; i < 256; i++) {
7598 NSPoint there = [self coordinatesForSystem:i];
7599 double dist = distanceBetweenPlanetPositions(here.x, here.y, there.x, there.y);
7600 if (dist <= range && (i != systemID || [self inInterstellarSpace])) // if we are in interstellar space, it's OK to include the system we (mis)jumped from
7601 {
7602 [result addObject:[NSDictionary dictionaryWithObjectsAndKeys:
7603 [NSNumber numberWithDouble:dist], @"distance",
7604 [NSNumber numberWithInt:i], @"sysID",
7605 [[self generateSystemData:i] oo_stringForKey:@"sun_gone_nova"
7606 defaultValue:@"0"],
7607 @"nova",
7608 nil]];
7609 }
7610 }
7611
7612 return result;
7613}
7614
7615- (OOSystemID)findNeighbouringSystemToCoords:(NSPoint)coords withGalaxy:(OOGalaxyID)g
7616{
7617
7618 double distance;
7619 int n, i, j;
7620 double min_dist = 10000.0;
7621
7622 // make list of connected systems
7623 BOOL connected[256];
7624 for (i = 0; i < 256; i++)
7625 connected[i] = NO;
7626 connected[0] = YES; // system zero is always connected (true for galaxies 0..7)
7627 for (n = 0; n < 3; n++) // repeat three times for surety
7628 {
7629 for (i = 0; i < 256; i++) // flood fill out from system zero
7630 {
7631 NSPoint ipos = [systemManager getCoordinatesForSystem:i inGalaxy:g];
7632 for (j = 0; j < 256; j++) {
7633 NSPoint jpos = [systemManager getCoordinatesForSystem:j inGalaxy:g];
7634 double dist = distanceBetweenPlanetPositions(ipos.x, ipos.y, jpos.x, jpos.y);
7635 if (dist <= MAX_JUMP_RANGE) {
7636 connected[j] |= connected[i];
7637 connected[i] |= connected[j];
7638 }
7639 }
7640 }
7641 }
7642 OOSystemID system = 0;
7643 for (i = 0; i < 256; i++) {
7644 NSPoint ipos = [systemManager getCoordinatesForSystem:i inGalaxy:g];
7645 distance = distanceBetweenPlanetPositions((int)coords.x, (int)coords.y, ipos.x, ipos.y);
7646 if ((connected[i]) && (distance < min_dist) && (distance != 0.0)) {
7647 min_dist = distance;
7648 system = i;
7649 }
7650 }
7651
7652 return system;
7653}
7654
7655/* This differs from the above function in that it can return a system
7656 * exactly at the specified coordinates */
7657- (OOSystemID)findConnectedSystemAtCoords:(NSPoint)coords withGalaxy:(OOGalaxyID)g
7658{
7659
7660 double distance;
7661 int n, i, j;
7662 double min_dist = 10000.0;
7663
7664 // make list of connected systems
7665 BOOL connected[256];
7666 for (i = 0; i < 256; i++)
7667 connected[i] = NO;
7668 connected[0] = YES; // system zero is always connected (true for galaxies 0..7)
7669 for (n = 0; n < 3; n++) // repeat three times for surety
7670 {
7671 for (i = 0; i < 256; i++) // flood fill out from system zero
7672 {
7673 NSPoint ipos = [systemManager getCoordinatesForSystem:i inGalaxy:g];
7674 for (j = 0; j < 256; j++) {
7675 NSPoint jpos = [systemManager getCoordinatesForSystem:j inGalaxy:g];
7676 double dist = distanceBetweenPlanetPositions(ipos.x, ipos.y, jpos.x, jpos.y);
7677 if (dist <= MAX_JUMP_RANGE) {
7678 connected[j] |= connected[i];
7679 connected[i] |= connected[j];
7680 }
7681 }
7682 }
7683 }
7684 OOSystemID system = 0;
7685 for (i = 0; i < 256; i++) {
7686 NSPoint ipos = [systemManager getCoordinatesForSystem:i inGalaxy:g];
7687 distance = distanceBetweenPlanetPositions((int)coords.x, (int)coords.y, ipos.x, ipos.y);
7688 if ((connected[i]) && (distance < min_dist)) {
7689 min_dist = distance;
7690 system = i;
7691 }
7692 }
7693
7694 return system;
7695}
7696
7697- (OOSystemID)findSystemNumberAtCoords:(NSPoint)coords withGalaxy:(OOGalaxyID)g includingHidden:(BOOL)hidden
7698{
7699 /*
7700 NOTE: this previously used NSNotFound as the default value, but
7701 returned an int, which would truncate on 64-bit systems. I assume
7702 no-one was using it in a context where the default value was returned.
7703 -- Ahruman 2012-08-25
7704 */
7706 unsigned distance, dx, dy;
7707 OOSystemID i;
7708 unsigned min_dist = 10000;
7709
7710 for (i = 0; i < 256; i++) {
7711 if (!hidden) {
7712 NSDictionary* systemInfo = [systemManager getPropertiesForSystem:i inGalaxy:g];
7713 NSInteger concealment = [systemInfo oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7714 if (concealment >= OO_SYSTEMCONCEALMENT_NOTHING) {
7715 // system is not known
7716 continue;
7717 }
7718 }
7719 NSPoint ipos = [systemManager getCoordinatesForSystem:i inGalaxy:g];
7720 dx = ABS(coords.x - ipos.x);
7721 dy = ABS(coords.y - ipos.y);
7722
7723 if (dx > dy)
7724 distance = (dx + dx + dy) / 2;
7725 else
7726 distance = (dx + dy + dy) / 2;
7727
7728 if (distance < min_dist) {
7729 min_dist = distance;
7730 system = i;
7731 }
7732 // with coincident systems choose only if ABOVE
7733 if ((distance == min_dist) && (coords.y > ipos.y)) {
7734 system = i;
7735 }
7736 // or if EQUAL but already selected
7737 else if ((distance == min_dist) && (coords.y == ipos.y) && (i == [PLAYER targetSystemID])) {
7738 system = i;
7739 }
7740 }
7741 return system;
7742}
7743
7744- (NSPoint)findSystemCoordinatesWithPrefix:(NSString*)p_fix
7745{
7746 return [self findSystemCoordinatesWithPrefix:p_fix exactMatch:NO];
7747}
7748
7749- (NSPoint)findSystemCoordinatesWithPrefix:(NSString*)p_fix exactMatch:(BOOL)exactMatch
7750{
7751 NSString* system_name = nil;
7752 NSPoint system_coords = NSMakePoint(-1.0, -1.0);
7753 int i;
7754 int result = -1;
7755 for (i = 0; i < 256; i++) {
7756 system_found[i] = NO;
7757 system_name = [system_names[i] lowercaseString];
7758 if ((exactMatch && [system_name isEqualToString:p_fix]) || (!exactMatch && [system_name hasPrefix:p_fix])) {
7759 /* Only used in player-based search routines */
7760 NSDictionary* systemInfo = [systemManager getPropertiesForSystem:i inGalaxy:galaxyID];
7761 NSInteger concealment = [systemInfo oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7762 if (concealment >= OO_SYSTEMCONCEALMENT_NONAME) {
7763 // system is not known
7764 continue;
7765 }
7766
7767 system_found[i] = YES;
7768 if (result < 0) {
7769 system_coords = [systemManager getCoordinatesForSystem:i inGalaxy:galaxyID];
7770 result = i;
7771 }
7772 }
7773 }
7774 return system_coords;
7775}
7776
7778{
7779 return (BOOL*)system_found;
7780}
7781
7782- (NSString*)systemNameIndex:(OOSystemID)index
7783{
7784 return system_names[index & 255];
7785}
7786
7787- (NSDictionary*)routeFromSystem:(OOSystemID)start toSystem:(OOSystemID)goal optimizedBy:(OORouteType)optimizeBy
7788{
7789 /*
7790 time_cost = distance * distance
7791 jump_cost = jumps * max_total_distance + distance = max_total_tistance + distance
7792
7793 max_total_distance is 7 * 256
7794
7795 max_time_cost = max_planets * max_time_cost = 256 * (7 * 7)
7796 max_jump_cost = max_planets * max_jump_cost = 256 * (7 * 256 + 7)
7797 */
7798
7799 // no interstellar space for start and/or goal please
7800 if (start == -1 || goal == -1)
7801 return nil;
7802
7803#ifdef CACHE_ROUTE_FROM_SYSTEM_RESULTS
7804
7805 static NSDictionary* c_route = nil;
7806 static OOSystemID c_start, c_goal;
7807 static OORouteType c_optimizeBy;
7808
7809 if (c_route != nil && c_start == start && c_goal == goal && c_optimizeBy == optimizeBy) {
7810 return c_route;
7811 }
7812
7813#endif
7814
7815 unsigned i, j;
7816
7817 if (start > 255 || goal > 255)
7818 return nil;
7819
7820 NSArray* neighbours[256];
7821 BOOL concealed[256];
7822 for (i = 0; i < 256; i++) {
7823 NSDictionary* systemInfo = [systemManager getPropertiesForSystem:i inGalaxy:galaxyID];
7824 NSInteger concealment = [systemInfo oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7825 if (concealment >= OO_SYSTEMCONCEALMENT_NOTHING) {
7826 // system is not known
7827 neighbours[i] = [NSArray array];
7828 concealed[i] = YES;
7829 } else {
7830 neighbours[i] = [self neighboursToSystem:i];
7831 concealed[i] = NO;
7832 }
7833 }
7834
7835 RouteElement* cheapest[256] = { 0 };
7836
7837 double maxCost = optimizeBy == OPTIMIZED_BY_TIME ? 256 * (7 * 7) : 256 * (7 * 256 + 7);
7838
7839 NSMutableArray* curr = [NSMutableArray arrayWithCapacity:256];
7840 [curr addObject:cheapest[start] = [RouteElement elementWithLocation:start parent:-1 cost:0 distance:0 time:0 jumps:0]];
7841
7842 NSMutableArray* next = [NSMutableArray arrayWithCapacity:256];
7843 while ([curr count] != 0) {
7844 for (i = 0; i < [curr count]; i++) {
7845 RouteElement* elemI = [curr objectAtIndex:i];
7846 NSArray* ns = neighbours[[elemI location]];
7847 for (j = 0; j < [ns count]; j++) {
7848 RouteElement* ce = cheapest[[elemI location]];
7849 OOSystemID n = [ns oo_intAtIndex:j];
7850 if (concealed[n]) {
7851 continue;
7852 }
7853 OOSystemID c = [ce location];
7854
7855 NSPoint cpos = [systemManager getCoordinatesForSystem:c inGalaxy:galaxyID];
7856 NSPoint npos = [systemManager getCoordinatesForSystem:n inGalaxy:galaxyID];
7857
7858 double lastDistance = distanceBetweenPlanetPositions(npos.x, npos.y, cpos.x, cpos.y);
7859 double lastTime = lastDistance * lastDistance;
7860
7861 double distance = [ce distance] + lastDistance;
7862 double time = [ce time] + lastTime;
7863 double cost = [ce cost] + (optimizeBy == OPTIMIZED_BY_TIME ? lastTime : 7 * 256 + lastDistance);
7864 int jumps = [ce jumps] + 1;
7865
7866 if (cost < maxCost && (cheapest[n] == nil || [cheapest[n] cost] > cost)) {
7867 RouteElement* e = [RouteElement elementWithLocation:n parent:c cost:cost distance:distance time:time jumps:jumps];
7868 cheapest[n] = e;
7869 [next addObject:e];
7870
7871 if (n == goal && cost < maxCost)
7872 maxCost = cost;
7873 }
7874 }
7875 }
7876 [curr setArray:next];
7877 [next removeAllObjects];
7878 }
7879
7880 if (!cheapest[goal])
7881 return nil;
7882
7883 NSMutableArray* route = [NSMutableArray arrayWithCapacity:256];
7884 RouteElement* e = cheapest[goal];
7885 for (;;) {
7886 [route insertObject:[NSNumber numberWithInt:[e location]] atIndex:0];
7887 if ([e parent] == -1)
7888 break;
7889 e = cheapest[[e parent]];
7890 }
7891
7892#ifdef CACHE_ROUTE_FROM_SYSTEM_RESULTS
7893 c_start = start;
7894 c_goal = goal;
7895 c_optimizeBy = optimizeBy;
7896 [c_route release];
7897 c_route = [[NSDictionary alloc] initWithObjectsAndKeys:route, @"route", [NSNumber numberWithDouble:[cheapest[goal] distance]], @"distance", nil];
7898
7899 return c_route;
7900#else
7901 return [NSDictionary dictionaryWithObjectsAndKeys:
7902 route, @"route",
7903 [NSNumber numberWithDouble:[cheapest[goal] distance]], @"distance",
7904 [NSNumber numberWithDouble:[cheapest[goal] time]], @"time",
7905 [NSNumber numberWithInt:[cheapest[goal] jumps]], @"jumps",
7906 nil];
7907#endif
7908}
7909
7910- (NSArray*)neighboursToSystem:(OOSystemID)s
7911{
7912 if (s == systemID && closeSystems != nil) {
7913 return closeSystems;
7914 }
7915 NSArray* neighbours = [systemManager getNeighbourIDsForSystem:s inGalaxy:galaxyID];
7916
7917 if (s == systemID) {
7918 [closeSystems release];
7919 closeSystems = [neighbours copy];
7920 return closeSystems;
7921 }
7922 return neighbours;
7923}
7924
7925/*
7926 Planet texture preloading.
7927
7928 In order to hide the cost of synthesizing textures, we want to start
7929 rendering them asynchronously as soon as there's a hint they may be needed
7930 soon: when a system is selected on one of the charts, and when beginning a
7931 jump. However, it would be a Bad Ideaâ„¢ to allow an arbitrary number of
7932 planets to be queued, since you can click on lots of systems quite
7933 quickly on the long-range chart.
7934
7935 To rate-limit this, we track the materials that are being preloaded and
7936 only queue the ones for a new system if there are no more than two in the
7937 queue. (Currently, each system will have at most two materials, the main
7938 planet and the main planet's atmosphere, but it may be worth adding the
7939 ability to declare planets in planetinfo.plist instead of using scripts so
7940 that they can also benefit from preloading.)
7941
7942 The preloading materials list is pruned before preloading, and also once
7943 per frame so textures can fall out of the regular cache.
7944 -- Ahruman 2009-12-19
7945
7946 DISABLED due to crashes on some Windows systems. Textures generated here
7947 remain in the sRecentTextures cache when released, suggesting a retain
7948 imbalance somewhere. Cannot reproduce under Mac OS X. Needs further
7949 analysis before reenabling.
7950 http://www.aegidian.org/bb/viewtopic.php?f=3&t=12109
7951 -- Ahruman 2012-06-29
7952*/
7953- (void)preloadPlanetTexturesForSystem:(OOSystemID)s
7954{
7955// #if NEW_PLANETS
7956#if 0
7957 [self prunePreloadingPlanetMaterials];
7958
7959 if ([_preloadingPlanetMaterials count] < 3)
7960 {
7961 if (_preloadingPlanetMaterials == nil) _preloadingPlanetMaterials = [[NSMutableArray alloc] initWithCapacity:4];
7962
7963 OOPlanetEntity *planet = [[OOPlanetEntity alloc] initAsMainPlanetForSystem:s];
7964 OOMaterial *surface = [planet material];
7965 // can be nil if texture mis-defined
7966 if (surface != nil)
7967 {
7968 // if it's already loaded, no need to continue
7969 if (![surface isFinishedLoading])
7970 {
7971 [_preloadingPlanetMaterials addObject:surface];
7972
7973 // In some instances (retextured planets atm), the main planet might not have an atmosphere defined.
7974 // Trying to add nil to _preloadingPlanetMaterials will prematurely terminate the calling function.(!) --Kaks 20100107
7975 OOMaterial *atmo = [planet atmosphereMaterial];
7976 if (atmo != nil) [_preloadingPlanetMaterials addObject:atmo];
7977 }
7978 }
7979
7980 [planet release];
7981 }
7982#endif
7983}
7984
7985- (NSDictionary*)globalSettings
7986{
7987 return globalSettings;
7988}
7989
7990- (NSArray*)equipmentData
7991{
7992 return equipmentData;
7993}
7994
7996{
7998}
7999
8004
8005- (NSString*)timeDescription:(double)interval
8006{
8007 double r_time = interval;
8008 NSString* result = @"";
8009
8010 if (r_time > 86400) {
8011 int days = floor(r_time / 86400);
8012 r_time -= 86400 * days;
8013 result = [NSString stringWithFormat:@"%@ %d day%@", result, days, (days > 1) ? @"s" : @""];
8014 }
8015 if (r_time > 3600) {
8016 int hours = floor(r_time / 3600);
8017 r_time -= 3600 * hours;
8018 result = [NSString stringWithFormat:@"%@ %d hour%@", result, hours, (hours > 1) ? @"s" : @""];
8019 }
8020 if (r_time > 60) {
8021 int mins = floor(r_time / 60);
8022 r_time -= 60 * mins;
8023 result = [NSString stringWithFormat:@"%@ %d minute%@", result, mins, (mins > 1) ? @"s" : @""];
8024 }
8025 if (r_time > 0) {
8026 int secs = floor(r_time);
8027 result = [NSString stringWithFormat:@"%@ %d second%@", result, secs, (secs > 1) ? @"s" : @""];
8028 }
8029 return [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
8030}
8031
8032- (NSString*)shortTimeDescription:(double)interval
8033{
8034 double r_time = interval;
8035 NSString* result = @"";
8036 int parts = 0;
8037
8038 if (interval <= 0.0)
8039 return DESC(@"contracts-no-time");
8040
8041 if (r_time > 86400) {
8042 int days = floor(r_time / 86400);
8043 r_time -= 86400 * days;
8044 result = [NSString stringWithFormat:@"%@ %d %@", result, days, DESC_PLURAL(@"contracts-day-word", days)];
8045 parts++;
8046 }
8047 if (r_time > 3600) {
8048 int hours = floor(r_time / 3600);
8049 r_time -= 3600 * hours;
8050 result = [NSString stringWithFormat:@"%@ %d %@", result, hours, DESC_PLURAL(@"contracts-hour-word", hours)];
8051 parts++;
8052 }
8053 if (parts < 2 && r_time > 60) {
8054 int mins = floor(r_time / 60);
8055 r_time -= 60 * mins;
8056 result = [NSString stringWithFormat:@"%@ %d %@", result, mins, DESC_PLURAL(@"contracts-minute-word", mins)];
8057 parts++;
8058 }
8059 if (parts < 2 && r_time > 0) {
8060 int secs = floor(r_time);
8061 result = [NSString stringWithFormat:@"%@ %d %@", result, secs, DESC_PLURAL(@"contracts-second-word", secs)];
8062 }
8063 return [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
8064}
8065
8066- (void)makeSunSkimmer:(ShipEntity*)ship andSetAI:(BOOL)setAI
8067{
8068 if (setAI)
8069 [ship switchAITo:@"oolite-traderAI.js"]; // perfectly acceptable for both route 2 & 3
8070 [ship setFuel:(Ranrot() & 31)];
8071 // slow ships need extra insulation or they will burn up when sunskimming. (Tested at biggest sun in G3: Aenqute)
8072 float minInsulation = 1000 / [ship maxFlightSpeed] + 1;
8073 if ([ship heatInsulation] < minInsulation)
8074 [ship setHeatInsulation:minInsulation];
8075}
8076
8078{
8080
8081 // adjust basic seed by market random factor
8082 // which for (very bad) historical reasons is 0x80
8083
8084 ret.f ^= 0x80; // XOR back to front
8085 ret.e ^= ret.f; // XOR
8086 ret.d ^= ret.e; // XOR
8087 ret.c ^= ret.d; // XOR
8088 ret.b ^= ret.c; // XOR
8089 ret.a ^= ret.b; // XOR
8090
8091 return ret;
8092}
8093
8094- (void)loadStationMarkets:(NSArray*)marketData
8095{
8096 if (marketData == nil) {
8097 return;
8098 }
8099
8100 NSArray* stations = [self stations];
8102 NSDictionary* savedMarket = nil;
8103
8104 foreach (savedMarket, marketData) {
8105 HPVector pos = [savedMarket oo_hpvectorForKey:@"position"];
8106 foreach (station, stations) {
8107 // must be deterministic and secondary
8108 if ([station allowsSaving] && station != [UNIVERSE station]) {
8109 // allow a km of drift just in case
8110 if (HPdistance2(pos, [station position]) < 1000000) {
8111 [station setLocalMarket:[savedMarket oo_arrayForKey:@"market"]];
8112 break;
8113 }
8114 }
8115 }
8116 }
8117}
8118
8120{
8121 NSMutableArray* markets = [[NSMutableArray alloc] init];
8122 NSArray* stations = [self stations];
8123
8125 NSMutableDictionary* savedMarket = nil;
8126
8127 OOCommodityMarket* stationMarket = nil;
8128
8129 foreach (station, stations) {
8130 // must be deterministic and secondary
8131 if ([station allowsSaving] && station != [UNIVERSE station]) {
8132 stationMarket = [station localMarket];
8133 if (stationMarket != nil) {
8134 savedMarket = [NSMutableDictionary dictionaryWithCapacity:2];
8135 [savedMarket setObject:[stationMarket saveStationAmounts] forKey:@"market"];
8136 [savedMarket setObject:ArrayFromHPVector([station position]) forKey:@"position"];
8137 [markets addObject:savedMarket];
8138 }
8139 }
8140 }
8141
8142 return [markets autorelease];
8143}
8144
8145- (NSArray*)shipsForSaleForSystem:(OOSystemID)s withTL:(OOTechLevelID)specialTL atTime:(OOTimeAbsolute)current_time
8146{
8147 RANROTSeed saved_seed = RANROTGetFullSeed();
8148 Random_Seed ship_seed = [self marketSeed];
8149
8150 NSMutableDictionary* resultDictionary = [NSMutableDictionary dictionary];
8151
8152 float tech_price_boost = (ship_seed.a + ship_seed.b) / 256.0;
8153 unsigned i;
8154 PlayerEntity* player = PLAYER;
8156 RANROTSeed personalitySeed = RanrotSeedFromRandomSeed(ship_seed);
8157
8158 for (i = 0; i < 256; i++) {
8159 long long reference_time = 0x1000000 * floor(current_time / 0x1000000);
8160
8161 long long c_time = ship_seed.a * 0x10000 + ship_seed.b * 0x100 + ship_seed.c;
8162 double ship_sold_time = reference_time + c_time;
8163
8164 if (ship_sold_time < 0)
8165 ship_sold_time += 0x1000000; // wraparound
8166
8167 double days_until_sale = (ship_sold_time - current_time) / 86400.0;
8168
8169 NSMutableArray* keysForShips = [NSMutableArray arrayWithArray:[registry playerShipKeys]];
8170 unsigned si;
8171 for (si = 0; si < [keysForShips count]; si++) {
8172 // eliminate any ships that fail a 'conditions test'
8173 NSString* key = [keysForShips oo_stringAtIndex:si];
8174 NSDictionary* dict = [registry shipyardInfoForKey:key];
8175 NSArray* conditions = [dict oo_arrayForKey:@"conditions"];
8176
8177 if (![player scriptTestConditions:conditions]) {
8178 [keysForShips removeObjectAtIndex:si--];
8179 }
8180 NSString* condition_script = [dict oo_stringForKey:@"condition_script"];
8181 if (condition_script != nil) {
8182 OOJSScript* condScript = [self getConditionScript:condition_script];
8183 if (condScript != nil) // should always be non-nil, but just in case
8184 {
8185 JSContext* context = OOJSAcquireContext();
8186 BOOL OK;
8187 BOOL allow_purchase = NO;
8188 OOJSVal result = OOJSUndefinedValue();
8189 OOJSVal args[] = { OOJSValueFromNativeObject(context, key) };
8190
8191 OK = [condScript callMethod:OOJSID("allowOfferShip")
8192 inContext:context
8193 withArguments:args
8194 count:sizeof args / sizeof *args
8195 result:&result];
8196
8197 if (OK)
8198 allow_purchase = OOJSValueToBOOL(context, result);
8199
8200 OOJSFreeValue(context, result);
8201 OOJSFreeValue(context, args[0]);
8202 OOJSRelinquishContext(context);
8203
8204 if (OK && !allow_purchase) {
8205 /* if the script exists, the function exists, the function
8206 * returns a bool, and that bool is false, block
8207 * purchase. Otherwise allow it as default */
8208 [keysForShips removeObjectAtIndex:si--];
8209 }
8210 }
8211 }
8212 }
8213
8214 NSDictionary* systemInfo = [self generateSystemData:s];
8215 OOTechLevelID techlevel;
8216 if (specialTL != NSNotFound) {
8217 // if we are passed a tech level use that
8218 techlevel = specialTL;
8219 } else {
8220 // otherwise use default for system
8221 techlevel = [systemInfo oo_unsignedIntForKey:KEY_TECHLEVEL];
8222 }
8223 unsigned ship_index = (ship_seed.d * 0x100 + ship_seed.e) % [keysForShips count];
8224 NSString* ship_key = [keysForShips oo_stringAtIndex:ship_index];
8225 NSDictionary* ship_info = [registry shipyardInfoForKey:ship_key];
8226 OOTechLevelID ship_techlevel = [ship_info oo_intForKey:KEY_TECHLEVEL];
8227
8228 double chance = 1.0 - pow(1.0 - [ship_info oo_doubleForKey:KEY_CHANCE], MAX((OOTechLevelID)1, techlevel - ship_techlevel));
8229
8230 // seed random number generator
8231 int superRand1 = ship_seed.a * 0x10000 + ship_seed.c * 0x100 + ship_seed.e;
8232 uint32_t superRand2 = ship_seed.b * 0x10000 + ship_seed.d * 0x100 + ship_seed.f;
8233 ranrot_srand(superRand2);
8234
8235 NSDictionary* shipBaseDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:ship_key];
8236
8237 if ((days_until_sale > 0.0) && (days_until_sale < 30.0) && (ship_techlevel <= techlevel) && (randf() < chance) && (shipBaseDict != nil)) {
8238 NSMutableDictionary* shipDict = [NSMutableDictionary dictionaryWithDictionary:shipBaseDict];
8239 NSMutableString* shortShipDescription = [NSMutableString stringWithCapacity:256];
8240 NSString* shipName = [shipDict oo_stringForKey:@"display_name" defaultValue:[shipDict oo_stringForKey:KEY_NAME]];
8241 OOCreditsQuantity price = [ship_info oo_unsignedIntForKey:KEY_PRICE];
8242 OOCreditsQuantity base_price = price;
8243 NSMutableArray* extras = [NSMutableArray arrayWithArray:[[ship_info oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
8244 NSString* fwdWeaponString = [[ship_info oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_stringForKey:KEY_EQUIPMENT_FORWARD_WEAPON];
8245 NSString* aftWeaponString = [[ship_info oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_stringForKey:KEY_EQUIPMENT_AFT_WEAPON];
8246
8247 NSMutableArray* options = [NSMutableArray arrayWithArray:[ship_info oo_arrayForKey:KEY_OPTIONAL_EQUIPMENT]];
8248 OOCargoQuantity maxCargo = [shipDict oo_unsignedIntForKey:@"max_cargo"];
8249
8250 // more info for potential purchasers - how to reveal this I'm not yet sure...
8251 // NSString* brochure_desc = [self brochureDescriptionWithDictionary: ship_dict standardEquipment: extras optionalEquipment: options];
8252 // NSLog(@"%@ Brochure description : \"%@\"", [ship_dict objectForKey:KEY_NAME], brochure_desc);
8253
8254 [shortShipDescription appendFormat:@"%@:", shipName];
8255
8256 OOWeaponFacingSet availableFacings = [ship_info oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:VALID_WEAPON_FACINGS] & VALID_WEAPON_FACINGS;
8257
8258 OOWeaponType fwdWeapon = OOWeaponTypeFromEquipmentIdentifierSloppy(fwdWeaponString);
8259 OOWeaponType aftWeapon = OOWeaponTypeFromEquipmentIdentifierSloppy(aftWeaponString);
8260 // port and starboard weapons are not modified in the shipyard
8261 // apply fwd and aft weapons to the ship
8262 if (fwdWeapon && fwdWeaponString)
8263 [shipDict setObject:fwdWeaponString forKey:KEY_EQUIPMENT_FORWARD_WEAPON];
8264 if (aftWeapon && aftWeaponString)
8265 [shipDict setObject:aftWeaponString forKey:KEY_EQUIPMENT_AFT_WEAPON];
8266
8267 int passengerBerthCount = 0;
8268 BOOL customised = NO;
8269 BOOL weaponCustomized = NO;
8270
8271 NSString* fwdWeaponDesc = nil;
8272
8273 NSString* shortExtrasKey = @"shipyard-first-extra";
8274
8275 // for testing condition scripts
8276 ShipEntity* testship = [[ProxyPlayerEntity alloc] initWithKey:ship_key definition:shipDict];
8277 // customise the ship (if chance = 1, then ship will get all possible add ons)
8278 while ((randf() < chance) && ([options count])) {
8279 chance *= chance; // decrease the chance of a further customisation (unless it is 1, which might be a bug)
8280 int optionIndex = Ranrot() % [options count];
8281 NSString* equipmentKey = [options oo_stringAtIndex:optionIndex];
8283
8284 if (item != nil) {
8285 OOTechLevelID eqTechLevel = [item techLevel];
8286 OOCreditsQuantity eqPrice = [item price] / 10; // all amounts are x/10 due to being represented in tenths of credits.
8287 NSString* eqShortDesc = [item name];
8288
8289 if ([item techLevel] > techlevel) {
8290 // Cap maximum tech level.
8291 eqTechLevel = MIN(eqTechLevel, 15U);
8292
8293 // Higher tech items are rarer!
8294 if (randf() * (eqTechLevel - techlevel) < 1.0) {
8295 // All included equip has a 10% discount.
8296 eqPrice *= (tech_price_boost + eqTechLevel - techlevel) * 90 / 100;
8297 } else
8298 break; // Bar this upgrade.
8299 }
8300
8301 if ([item incompatibleEquipment] != nil && extras != nil) {
8302 id key = nil;
8303 BOOL incompatible = NO;
8304
8305 foreach (key, [item incompatibleEquipment]) {
8306 if ([extras containsObject:key]) {
8307 [options removeObject:equipmentKey];
8308 incompatible = YES;
8309 break;
8310 }
8311 }
8312 if (incompatible)
8313 break;
8314
8315 // make sure the incompatible equipment is not choosen later on.
8316 foreach (key, [item incompatibleEquipment]) {
8317 if ([options containsObject:key]) {
8318 [options removeObject:key];
8319 }
8320 }
8321 }
8322
8323 /* Check condition scripts */
8324 NSString* condition_script = [item conditionScript];
8325 if (condition_script != nil) {
8326 OOJSScript* condScript = [self getConditionScript:condition_script];
8327 if (condScript != nil) // should always be non-nil, but just in case
8328 {
8329 JSContext* JScontext = OOJSAcquireContext();
8330 BOOL OK;
8331 BOOL allow_addition = NO;
8332 OOJSVal result = OOJSUndefinedValue();
8333 OOJSVal args[] = { OOJSValueFromNativeObject(JScontext, equipmentKey), OOJSValueFromNativeObject(JScontext, testship), OOJSValueFromNativeObject(JScontext, @"newShip") };
8334
8335 OK = [condScript callMethod:OOJSID("allowAwardEquipment")
8336 inContext:JScontext
8337 withArguments:args
8338 count:sizeof args / sizeof *args
8339 result:&result];
8340
8341 if (OK)
8342 allow_addition = OOJSValueToBOOL(JScontext, result);
8343
8344 OOJSFreeValue(JScontext, result);
8345 OOJSFreeValue(JScontext, args[0]);
8346 OOJSFreeValue(JScontext, args[1]);
8347 OOJSFreeValue(JScontext, args[2]);
8348 OOJSRelinquishContext(JScontext);
8349
8350 if (OK && !allow_addition) {
8351 /* if the script exists, the function exists, the function
8352 * returns a bool, and that bool is false, block
8353 * addition. Otherwise allow it as default */
8354 break;
8355 }
8356 }
8357 }
8358
8359 if ([item requiresEquipment] != nil && extras != nil) {
8360 id key = nil;
8361 BOOL missing = NO;
8362
8363 foreach (key, [item requiresEquipment]) {
8364 if (![extras containsObject:key]) {
8365 missing = YES;
8366 }
8367 }
8368 if (missing)
8369 break;
8370 }
8371
8372 if ([item requiresAnyEquipment] != nil && extras != nil) {
8373 id key = nil;
8374 BOOL missing = YES;
8375
8376 foreach (key, [item requiresAnyEquipment]) {
8377 if ([extras containsObject:key]) {
8378 missing = NO;
8379 }
8380 }
8381 if (missing)
8382 break;
8383 }
8384
8385 // Special case, NEU has to be compatible with EEU inside equipment.plist
8386 // but we can only have either one or the other on board.
8387 if ([equipmentKey isEqualTo:@"EQ_NAVAL_ENERGY_UNIT"]) {
8388 if ([extras containsObject:@"EQ_ENERGY_UNIT"]) {
8389 [options removeObject:equipmentKey];
8390 break;
8391 }
8392 }
8393
8394 if ([equipmentKey hasPrefix:@"EQ_WEAPON"]) {
8396 // fit best weapon forward
8397 if (availableFacings & WEAPON_FACING_FORWARD && [new_weapon weaponThreatAssessment] > [fwdWeapon weaponThreatAssessment]) {
8398 // again remember to divide price by 10 to get credits from tenths of credit
8399 price -= [self getEquipmentPriceForKey:fwdWeaponString] * 90 / 1000; // 90% credits
8400 price += eqPrice;
8401 fwdWeaponString = equipmentKey;
8402 fwdWeapon = new_weapon;
8403 [shipDict setObject:fwdWeaponString forKey:KEY_EQUIPMENT_FORWARD_WEAPON];
8404 weaponCustomized = YES;
8405 fwdWeaponDesc = eqShortDesc;
8406 } else {
8407 // if less good than current forward, try fitting is to rear
8408 if (availableFacings & WEAPON_FACING_AFT && (isWeaponNone(aftWeapon) || [new_weapon weaponThreatAssessment] > [aftWeapon weaponThreatAssessment])) {
8409 price -= [self getEquipmentPriceForKey:aftWeaponString] * 90 / 1000; // 90% credits
8410 price += eqPrice;
8411 aftWeaponString = equipmentKey;
8412 aftWeapon = new_weapon;
8413 [shipDict setObject:aftWeaponString forKey:KEY_EQUIPMENT_AFT_WEAPON];
8414 } else {
8415 [options removeObject:equipmentKey]; // dont try again
8416 }
8417 }
8418
8419 } else {
8420 if ([equipmentKey isEqualToString:@"EQ_PASSENGER_BERTH"]) {
8421 if ((maxCargo >= PASSENGER_BERTH_SPACE) && (randf() < chance)) {
8422 maxCargo -= PASSENGER_BERTH_SPACE;
8423 price += eqPrice;
8424 [extras addObject:equipmentKey];
8425 passengerBerthCount++;
8426 customised = YES;
8427 } else {
8428 // remove the option if there's no space left
8429 [options removeObject:equipmentKey];
8430 }
8431 } else {
8432 price += eqPrice;
8433 [extras addObject:equipmentKey];
8434 if ([item isVisible]) {
8435 NSString* item = eqShortDesc;
8436 [shortShipDescription appendString:OOExpandKey(shortExtrasKey, item)];
8437 shortExtrasKey = @"shipyard-additional-extra";
8438 }
8439 customised = YES;
8440 [options removeObject:equipmentKey]; // dont add twice
8441 }
8442 }
8443 } else {
8444 [options removeObject:equipmentKey];
8445 }
8446 } // end adding optional equipment
8447 [testship release];
8448 // i18n: Some languages require that no conversion to lower case string takes place.
8449 BOOL lowercaseIgnore = [[self descriptions] oo_boolForKey:@"lowercase_ignore"];
8450
8451 if (passengerBerthCount) {
8452 NSString* npb = (passengerBerthCount > 1) ? [NSString stringWithFormat:@"%d ", passengerBerthCount] : (id) @"";
8453 NSString* ppb = DESC_PLURAL(@"passenger-berth", passengerBerthCount);
8454 NSString* extraPassengerBerthsDescription = [NSString stringWithFormat:DESC(@"extra-@-@-(passenger-berths)"), npb, ppb];
8455 NSString* item = extraPassengerBerthsDescription;
8456 [shortShipDescription appendString:OOExpandKey(shortExtrasKey, item)];
8457 shortExtrasKey = @"shipyard-additional-extra";
8458 }
8459
8460 if (!customised) {
8461 [shortShipDescription appendString:OOExpandKey(@"shipyard-standard-customer-model")];
8462 }
8463
8464 if (weaponCustomized) {
8465 NSString* weapon = (lowercaseIgnore ? fwdWeaponDesc : [fwdWeaponDesc lowercaseString]);
8466 [shortShipDescription appendString:OOExpandKey(@"shipyard-forward-weapon-upgraded", weapon)];
8467 }
8468 if (price > base_price) {
8469 price = base_price + cunningFee(price - base_price, 0.05);
8470 }
8471
8472 [shortShipDescription appendString:OOExpandKey(@"shipyard-price", price)];
8473
8474 NSString* shipID = [NSString stringWithFormat:@"%06x-%06x", superRand1, superRand2];
8475
8476 uint16_t personality = RanrotWithSeed(&personalitySeed) & ENTITY_PERSONALITY_MAX;
8477
8478 NSDictionary* ship_info_dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
8479 shipID, SHIPYARD_KEY_ID,
8480 ship_key, SHIPYARD_KEY_SHIPDATA_KEY,
8481 shipDict, SHIPYARD_KEY_SHIP,
8482 shortShipDescription, KEY_SHORT_DESCRIPTION,
8483 [NSNumber numberWithUnsignedLongLong:price], SHIPYARD_KEY_PRICE,
8484 extras, KEY_EQUIPMENT_EXTRAS,
8485 [NSNumber numberWithUnsignedShort:personality], SHIPYARD_KEY_PERSONALITY,
8486 NULL];
8487
8488 [resultDictionary setObject:ship_info_dictionary forKey:shipID]; // should order them fairly randomly
8489 }
8490
8491 // next contract
8492 rotate_seed(&ship_seed);
8493 rotate_seed(&ship_seed);
8494 rotate_seed(&ship_seed);
8495 rotate_seed(&ship_seed);
8496 }
8497
8498 NSMutableArray* resultArray = [[[resultDictionary allValues] mutableCopy] autorelease];
8499 [resultArray sortUsingFunction:compareName context:NULL];
8500
8501 // remove identically priced ships of the same name
8502 i = 1;
8503
8504 while (i < [resultArray count]) {
8505 if (compareName([resultArray objectAtIndex:i - 1], [resultArray objectAtIndex:i], nil) == NSOrderedSame) {
8506 [resultArray removeObjectAtIndex:i];
8507 } else {
8508 i++;
8509 }
8510 }
8511
8512 RANROTSetFullSeed(saved_seed);
8513
8514 return [NSArray arrayWithArray:resultArray];
8515}
8516
8517static OOComparisonResult compareName(id dict1, id dict2, void* context)
8518{
8519 NSDictionary* ship1 = [(NSDictionary*)dict1 oo_dictionaryForKey:SHIPYARD_KEY_SHIP];
8520 NSDictionary* ship2 = [(NSDictionary*)dict2 oo_dictionaryForKey:SHIPYARD_KEY_SHIP];
8521 NSString* name1 = [ship1 oo_stringForKey:KEY_NAME];
8522 NSString* name2 = [ship2 oo_stringForKey:KEY_NAME];
8523
8524 NSComparisonResult result = [[name1 lowercaseString] compare:[name2 lowercaseString]];
8525 if (result != NSOrderedSame)
8526 return result;
8527 else
8528 return comparePrice(dict1, dict2, context);
8529}
8530
8531static OOComparisonResult comparePrice(id dict1, id dict2, void* context)
8532{
8533 NSNumber* price1 = [(NSDictionary*)dict1 objectForKey:SHIPYARD_KEY_PRICE];
8534 NSNumber* price2 = [(NSDictionary*)dict2 objectForKey:SHIPYARD_KEY_PRICE];
8535
8536 return [price1 compare:price2];
8537}
8538
8539- (OOCreditsQuantity)tradeInValueForCommanderDictionary:(NSDictionary*)dict
8540{
8541 // get basic information about the craft
8542 OOCreditsQuantity base_price = 0ULL;
8543 NSString* ship_desc = [dict oo_stringForKey:@"ship_desc"];
8544 NSDictionary* shipyard_info = [[OOShipRegistry sharedRegistry] shipyardInfoForKey:ship_desc];
8545 // This checks a rare, but possible case. If the ship for which we are trying to calculate a trade in value
8546 // does not have a shipyard dictionary entry, report it and set its base price to 0 -- Nikos 20090613.
8547 if (shipyard_info == nil) {
8548 OOLogERR(@"universe.tradeInValueForCommanderDictionary.valueCalculationError",
8549 @"Shipyard dictionary entry for ship %@ required for trade in value calculation, but does not exist. Setting ship value to 0.", ship_desc);
8550 } else {
8551 base_price = [shipyard_info oo_unsignedLongLongForKey:SHIPYARD_KEY_PRICE defaultValue:0ULL];
8552 }
8553
8554 if (base_price == 0ULL)
8555 return base_price;
8556
8557 OOCreditsQuantity scrap_value = 351; // translates to 250 cr.
8558
8559 OOWeaponType ship_fwd_weapon = [OOEquipmentType equipmentTypeWithIdentifier:[dict oo_stringForKey:@"forward_weapon"]];
8560 OOWeaponType ship_aft_weapon = [OOEquipmentType equipmentTypeWithIdentifier:[dict oo_stringForKey:@"aft_weapon"]];
8561 OOWeaponType ship_port_weapon = [OOEquipmentType equipmentTypeWithIdentifier:[dict oo_stringForKey:@"port_weapon"]];
8562 OOWeaponType ship_starboard_weapon = [OOEquipmentType equipmentTypeWithIdentifier:[dict oo_stringForKey:@"starboard_weapon"]];
8563 unsigned ship_missiles = [dict oo_unsignedIntForKey:@"missiles"];
8564 unsigned ship_max_passengers = [dict oo_unsignedIntForKey:@"max_passengers"];
8565 NSMutableArray* ship_extra_equipment = [NSMutableArray arrayWithArray:[[dict oo_dictionaryForKey:@"extra_equipment"] allKeys]];
8566
8567 NSDictionary* basic_info = [shipyard_info oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT];
8568 unsigned base_missiles = [basic_info oo_unsignedIntForKey:KEY_EQUIPMENT_MISSILES];
8569 OOCreditsQuantity base_missiles_value = base_missiles * [UNIVERSE getEquipmentPriceForKey:@"EQ_MISSILE"] / 10;
8570 NSString* base_weapon_key = [basic_info oo_stringForKey:KEY_EQUIPMENT_FORWARD_WEAPON];
8571 OOCreditsQuantity base_weapons_value = [UNIVERSE getEquipmentPriceForKey:base_weapon_key] / 10;
8572 NSMutableArray* base_extra_equipment = [NSMutableArray arrayWithArray:[basic_info oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
8573 NSString* weapon_key = nil;
8574
8575 // was aft_weapon defined as standard equipment ?
8576 base_weapon_key = [basic_info oo_stringForKey:KEY_EQUIPMENT_AFT_WEAPON defaultValue:nil];
8577 if (base_weapon_key != nil)
8578 base_weapons_value += [UNIVERSE getEquipmentPriceForKey:base_weapon_key] / 10;
8579
8580 OOCreditsQuantity ship_main_weapons_value = 0;
8581 OOCreditsQuantity ship_other_weapons_value = 0;
8582 OOCreditsQuantity ship_missiles_value = 0;
8583
8584 // calculate the actual value for the missiles present on board.
8585 NSArray* missileRoles = [dict oo_arrayForKey:@"missile_roles"];
8586 if (missileRoles != nil) {
8587 unsigned i;
8588 for (i = 0; i < ship_missiles; i++) {
8589 NSString* missile_desc = [missileRoles oo_stringAtIndex:i];
8590 if (missile_desc != nil && ![missile_desc isEqualToString:@"NONE"]) {
8591 ship_missiles_value += [UNIVERSE getEquipmentPriceForKey:missile_desc] / 10;
8592 }
8593 }
8594 } else
8595 ship_missiles_value = ship_missiles * [UNIVERSE getEquipmentPriceForKey:@"EQ_MISSILE"] / 10;
8596
8597 // needs to be a signed value, we can then subtract from the base price, if less than standard equipment.
8598 long long extra_equipment_value = ship_max_passengers * [UNIVERSE getEquipmentPriceForKey:@"EQ_PASSENGER_BERTH"] / 10;
8599
8600 // add on missile values
8601 extra_equipment_value += ship_missiles_value - base_missiles_value;
8602
8603 // work out weapon values
8604 if (ship_fwd_weapon) {
8605 weapon_key = OOEquipmentIdentifierFromWeaponType(ship_fwd_weapon);
8606 ship_main_weapons_value = [UNIVERSE getEquipmentPriceForKey:weapon_key] / 10;
8607 }
8608 if (ship_aft_weapon) {
8609 weapon_key = OOEquipmentIdentifierFromWeaponType(ship_aft_weapon);
8610 if (base_weapon_key != nil) // aft weapon was defined as a base weapon
8611 {
8612 ship_main_weapons_value += [UNIVERSE getEquipmentPriceForKey:weapon_key] / 10; // take weapon downgrades into account
8613 } else {
8614 ship_other_weapons_value += [UNIVERSE getEquipmentPriceForKey:weapon_key] / 10;
8615 }
8616 }
8617 if (ship_port_weapon) {
8618 weapon_key = OOEquipmentIdentifierFromWeaponType(ship_port_weapon);
8619 ship_other_weapons_value += [UNIVERSE getEquipmentPriceForKey:weapon_key] / 10;
8620 }
8621 if (ship_starboard_weapon) {
8622 weapon_key = OOEquipmentIdentifierFromWeaponType(ship_starboard_weapon);
8623 ship_other_weapons_value += [UNIVERSE getEquipmentPriceForKey:weapon_key] / 10;
8624 }
8625
8626 // add on extra weapons, take away the value of the base weapons
8627 extra_equipment_value += ship_other_weapons_value;
8628 extra_equipment_value += ship_main_weapons_value - base_weapons_value;
8629
8630 NSInteger i;
8631 NSString* eq_key = nil;
8632
8633 // shipyard.plist settings might have duplicate keys.
8634 // cull possible duplicates from inside base equipment
8635 for (i = [base_extra_equipment count] - 1; i > 0; i--) {
8636 eq_key = [base_extra_equipment oo_stringAtIndex:i];
8637 if ([base_extra_equipment indexOfObject:eq_key inRange:NSMakeRange(0, i - 1)] != NSNotFound)
8638 [base_extra_equipment removeObjectAtIndex:i];
8639 }
8640
8641 // do we at least have the same equipment as a standard ship?
8642 for (i = [base_extra_equipment count] - 1; i >= 0; i--) {
8643 eq_key = [base_extra_equipment oo_stringAtIndex:i];
8644 if ([ship_extra_equipment containsObject:eq_key])
8645 [ship_extra_equipment removeObject:eq_key];
8646 else // if the ship has less equipment than standard, deduct the missing equipent's price
8647 extra_equipment_value -= ([UNIVERSE getEquipmentPriceForKey:eq_key] / 10);
8648 }
8649
8650 // remove portable equipment from the totals
8651 OOEquipmentType* item = nil;
8652
8653 for (i = [ship_extra_equipment count] - 1; i >= 0; i--) {
8654 eq_key = [ship_extra_equipment oo_stringAtIndex:i];
8656 if ([item isPortableBetweenShips])
8657 [ship_extra_equipment removeObjectAtIndex:i];
8658 }
8659
8660 // add up what we've got left.
8661 for (i = [ship_extra_equipment count] - 1; i >= 0; i--)
8662 extra_equipment_value += ([UNIVERSE getEquipmentPriceForKey:[ship_extra_equipment oo_stringAtIndex:i]] / 10);
8663
8664 // 10% discount for second hand value, steeper reduction if worse than standard.
8665 extra_equipment_value *= extra_equipment_value < 0 ? 1.4 : 0.9;
8666
8667 // we'll return at least the scrap value
8668 // TODO: calculate scrap value based on the size of the ship.
8669 if ((long long)scrap_value > (long long)base_price + extra_equipment_value)
8670 return scrap_value;
8671
8672 return base_price + extra_equipment_value;
8673}
8674
8675- (NSString*)brochureDescriptionWithDictionary:(NSDictionary*)dict standardEquipment:(NSArray*)extras optionalEquipment:(NSArray*)options
8676{
8677 NSMutableArray* mut_extras = [NSMutableArray arrayWithArray:extras];
8678 NSString* allOptions = [options componentsJoinedByString:@" "];
8679
8680 NSMutableString* desc = [NSMutableString stringWithFormat:@"The %@.", [dict oo_stringForKey:KEY_NAME]];
8681
8682 // cargo capacity and expansion
8683 OOCargoQuantity max_cargo = [dict oo_unsignedIntForKey:@"max_cargo"];
8684 if (max_cargo) {
8685 OOCargoQuantity extra_cargo = [dict oo_unsignedIntForKey:@"extra_cargo" defaultValue:15];
8686 [desc appendFormat:@" Cargo capacity %dt", max_cargo];
8687 BOOL canExpand = ([allOptions rangeOfString:@"EQ_CARGO_BAY"].location != NSNotFound);
8688 if (canExpand)
8689 [desc appendFormat:@" (expandable to %dt at most starports)", max_cargo + extra_cargo];
8690 [desc appendString:@"."];
8691 }
8692
8693 // speed
8694 float top_speed = [dict oo_intForKey:@"max_flight_speed"];
8695 [desc appendFormat:@" Top speed %.3fLS.", 0.001 * top_speed];
8696
8697 // passenger berths
8698 if ([mut_extras count]) {
8699 unsigned n_berths = 0;
8700 unsigned i;
8701 for (i = 0; i < [mut_extras count]; i++) {
8702 NSString* item_key = [mut_extras oo_stringAtIndex:i];
8703 if ([item_key isEqual:@"EQ_PASSENGER_BERTH"]) {
8704 n_berths++;
8705 [mut_extras removeObjectAtIndex:i--];
8706 }
8707 }
8708 if (n_berths) {
8709 if (n_berths == 1)
8710 [desc appendString:@" Includes luxury accomodation for a single passenger."];
8711 else
8712 [desc appendFormat:@" Includes luxury accomodation for %d passengers.", n_berths];
8713 }
8714 }
8715
8716 // standard fittings
8717 if ([mut_extras count]) {
8718 [desc appendString:@"\nComes with"];
8719 unsigned i, j;
8720 for (i = 0; i < [mut_extras count]; i++) {
8721 NSString* item_key = [mut_extras oo_stringAtIndex:i];
8722 NSString* item_desc = nil;
8723 for (j = 0; ((j < [equipmentData count]) && (!item_desc)); j++) {
8724 NSString* eq_type = [[equipmentData oo_arrayAtIndex:j] oo_stringAtIndex:EQUIPMENT_KEY_INDEX];
8725 if ([eq_type isEqual:item_key])
8726 item_desc = [[equipmentData oo_arrayAtIndex:j] oo_stringAtIndex:EQUIPMENT_SHORT_DESC_INDEX];
8727 }
8728 if (item_desc) {
8729 switch ([mut_extras count] - i) {
8730 case 1:
8731 [desc appendFormat:@" %@ fitted as standard.", item_desc];
8732 break;
8733 case 2:
8734 [desc appendFormat:@" %@ and", item_desc];
8735 break;
8736 default:
8737 [desc appendFormat:@" %@,", item_desc];
8738 break;
8739 }
8740 }
8741 }
8742 }
8743
8744 // optional fittings
8745 if ([options count]) {
8746 [desc appendString:@"\nCan additionally be outfitted with"];
8747 unsigned i, j;
8748 for (i = 0; i < [options count]; i++) {
8749 NSString* item_key = [options oo_stringAtIndex:i];
8750 NSString* item_desc = nil;
8751 for (j = 0; ((j < [equipmentData count]) && (!item_desc)); j++) {
8752 NSString* eq_type = [[equipmentData oo_arrayAtIndex:j] oo_stringAtIndex:EQUIPMENT_KEY_INDEX];
8753 if ([eq_type isEqual:item_key])
8754 item_desc = [[equipmentData oo_arrayAtIndex:j] oo_stringAtIndex:EQUIPMENT_SHORT_DESC_INDEX];
8755 }
8756 if (item_desc) {
8757 switch ([options count] - i) {
8758 case 1:
8759 [desc appendFormat:@" %@ at suitably equipped starports.", item_desc];
8760 break;
8761 case 2:
8762 [desc appendFormat:@" %@ and/or", item_desc];
8763 break;
8764 default:
8765 [desc appendFormat:@" %@,", item_desc];
8766 break;
8767 }
8768 }
8769 }
8770 }
8771
8772 return desc;
8773}
8774
8779
8781{
8782 // this should be fairly close to {0,0,0,1}
8783 Quaternion q_result;
8784
8785 // CIM: seems to be no reason why this should be a per-system constant
8786 // - trying it without resetting the RNG for now
8787 // seed_RNG_only_for_planet_description(system_seed);
8788
8789 q_result.x = (gen_rnd_number() - 128) / 1024.0;
8790 q_result.y = (gen_rnd_number() - 128) / 1024.0;
8791 q_result.z = (gen_rnd_number() - 128) / 1024.0;
8792 q_result.w = 1.0;
8793 quaternion_normalize(&q_result);
8794
8795 return q_result;
8796}
8797
8798// FIXME: should use vector functions
8799- (HPVector)getSunSkimStartPositionForShip:(ShipEntity*)ship
8800{
8801 if (!ship) {
8802 OOLog(kOOLogParameterError, @"%@", @"***** No ship set in Universe getSunSkimStartPositionForShip:");
8803 return kZeroHPVector;
8804 }
8805 OOSunEntity* the_sun = [self sun];
8806 // get vector from sun position to ship
8807 if (!the_sun) {
8808 OOLog(kOOLogInconsistentState, @"%@", @"***** No sun set in Universe getSunSkimStartPositionForShip:");
8809 return kZeroHPVector;
8810 }
8811 HPVector v0 = the_sun->position;
8812 HPVector v1 = ship->position;
8813 v1.x -= v0.x;
8814 v1.y -= v0.y;
8815 v1.z -= v0.z; // vector from sun to ship
8816 if (v1.x || v1.y || v1.z)
8817 v1 = HPvector_normal(v1);
8818 else
8819 v1.z = 1.0;
8820 double radius = SUN_SKIM_RADIUS_FACTOR * the_sun->collision_radius - 250.0; // 250 m inside the skim radius
8821 v1.x *= radius;
8822 v1.y *= radius;
8823 v1.z *= radius;
8824 v1.x += v0.x;
8825 v1.y += v0.y;
8826 v1.z += v0.z;
8827
8828 return v1;
8829}
8830
8831// FIXME: should use vector functions
8832- (HPVector)getSunSkimEndPositionForShip:(ShipEntity*)ship
8833{
8834 OOSunEntity* the_sun = [self sun];
8835 if (!ship) {
8836 OOLog(kOOLogParameterError, @"%@", @"***** No ship set in Universe getSunSkimEndPositionForShip:");
8837 return kZeroHPVector;
8838 }
8839 // get vector from sun position to ship
8840 if (!the_sun) {
8841 OOLog(kOOLogInconsistentState, @"%@", @"***** No sun set in Universe getSunSkimEndPositionForShip:");
8842 return kZeroHPVector;
8843 }
8844 HPVector v0 = the_sun->position;
8845 HPVector v1 = ship->position;
8846 v1.x -= v0.x;
8847 v1.y -= v0.y;
8848 v1.z -= v0.z;
8849 if (v1.x || v1.y || v1.z)
8850 v1 = HPvector_normal(v1);
8851 else
8852 v1.z = 1.0;
8853 HPVector v2 = make_HPvector(randf() - 0.5, randf() - 0.5, randf() - 0.5); // random vector
8854 if (v2.x || v2.y || v2.z)
8855 v2 = HPvector_normal(v2);
8856 else
8857 v2.x = 1.0;
8858 HPVector v3 = HPcross_product(v1, v2); // random vector at 90 degrees to v1 and v2 (random Vector)
8859 if (v3.x || v3.y || v3.z)
8860 v3 = HPvector_normal(v3);
8861 else
8862 v3.y = 1.0;
8863 double radius = SUN_SKIM_RADIUS_FACTOR * the_sun->collision_radius - 250.0; // 250 m inside the skim radius
8864 v1.x *= radius;
8865 v1.y *= radius;
8866 v1.z *= radius;
8867 v1.x += v0.x;
8868 v1.y += v0.y;
8869 v1.z += v0.z;
8870 v1.x += 15000 * v3.x;
8871 v1.y += 15000 * v3.y;
8872 v1.z += 15000 * v3.z; // point 15000m at a tangent to sun from v1
8873 v1.x -= v0.x;
8874 v1.y -= v0.y;
8875 v1.z -= v0.z;
8876 if (v1.x || v1.y || v1.z)
8877 v1 = HPvector_normal(v1);
8878 else
8879 v1.z = 1.0;
8880 v1.x *= radius;
8881 v1.y *= radius;
8882 v1.z *= radius;
8883 v1.x += v0.x;
8884 v1.y += v0.y;
8885 v1.z += v0.z;
8886
8887 return v1;
8888}
8889
8890- (NSArray*)listBeaconsWithCode:(NSString*)code
8891{
8892 NSMutableArray* result = [NSMutableArray array];
8893 Entity<OOBeaconEntity>* beacon = [self firstBeacon];
8894
8895 while (beacon != nil) {
8896 NSString* beaconCode = [beacon beaconCode];
8897 if ([beaconCode rangeOfString:code options:NSCaseInsensitiveSearch].location != NSNotFound) {
8898 [result addObject:beacon];
8899 }
8900 beacon = [beacon nextBeacon];
8901 }
8902
8903 return [result sortedArrayUsingSelector:@selector(compareBeaconCodeWith:)];
8904}
8905
8906- (void)allShipsDoScriptEvent:(OOJSPropID)event andReactToAIMessage:(NSString*)message
8907{
8908 int i;
8909 int ent_count = n_entities;
8910 int ship_count = 0;
8911 ShipEntity* my_ships[ent_count];
8912 for (i = 0; i < ent_count; i++) {
8913 if (sortedEntities[i]->isShip) {
8914 my_ships[ship_count++] = [(ShipEntity*)sortedEntities[i] retain]; // retained
8915 }
8916 }
8917
8918 for (i = 0; i < ship_count; i++) {
8919 ShipEntity* se = my_ships[i];
8920 [se doScriptEvent:event];
8921 if (message != nil)
8922 [[se getAI] reactToMessage:message context:@"global message"];
8923 [se release]; // released
8924 }
8925}
8926
8928
8930{
8931 return gui;
8932}
8933
8935{
8936 return comm_log_gui;
8937}
8938
8940{
8941 return message_gui;
8942}
8943
8945{
8946 [gui clear];
8949 [comm_log_gui printLongText:DESC(@"communications-log-string")
8950 align:GUI_ALIGN_CENTER
8952 fadeTime:0
8953 key:nil
8954 addToArray:nil];
8955}
8956
8961
8962- (void)setDisplayText:(BOOL)value
8963{
8964 displayGUI = !!value;
8965}
8966
8968{
8969 return displayGUI;
8970}
8971
8972- (void)setDisplayFPS:(BOOL)value
8973{
8974 displayFPS = !!value;
8975}
8976
8978{
8979 return displayFPS;
8980}
8981
8982- (void)setAutoSave:(BOOL)value
8983{
8984 autoSave = !!value;
8985 [[NSUserDefaults standardUserDefaults] setBool:autoSave forKey:@"autosave"];
8986}
8987
8989{
8990 return autoSave;
8991}
8992
8993- (void)setAutoSaveNow:(BOOL)value
8994{
8995 autoSaveNow = !!value;
8996}
8997
8999{
9000 return autoSaveNow;
9001}
9002
9003- (void)setWireframeGraphics:(BOOL)value
9004{
9005 wireframeGraphics = !!value;
9006 [[NSUserDefaults standardUserDefaults] setBool:wireframeGraphics forKey:@"wireframe-graphics"];
9007}
9008
9010{
9011 return wireframeGraphics;
9012}
9013
9015{
9017}
9018
9019/* Only to be called directly at initialisation */
9020- (void)setDetailLevelDirectly:(OOGraphicsDetail)value
9021{
9022 if (value >= DETAIL_LEVEL_MAXIMUM) {
9023 value = DETAIL_LEVEL_MAXIMUM;
9024 } else if (value <= DETAIL_LEVEL_MINIMUM) {
9025 value = DETAIL_LEVEL_MINIMUM;
9026 }
9027 if (![[OOOpenGLExtensionManager sharedManager] shadersSupported]) {
9028 value = DETAIL_LEVEL_MINIMUM;
9029 }
9030 detailLevel = value;
9031}
9032
9033- (void)setDetailLevel:(OOGraphicsDetail)value
9034{
9036 [self setDetailLevelDirectly:value];
9037 [[NSUserDefaults standardUserDefaults] setInteger:detailLevel forKey:@"detailLevel"];
9038 // if changed then reset graphics state
9039 // (some items now require this even if shader on/off mode unchanged)
9040 if (old != detailLevel) {
9041 OOLog(@"rendering.detail-level", @"Detail level set to %@.", OOStringFromGraphicsDetail(detailLevel));
9043 }
9044}
9045
9047{
9048 return detailLevel;
9049}
9050
9052{
9054}
9055
9056- (void)handleOoliteException:(NSException*)exception
9057{
9058 if (exception != nil) {
9059 if ([[exception name] isEqual:OOLITE_EXCEPTION_FATAL]) {
9060 PlayerEntity* player = PLAYER;
9061 [player setStatus:STATUS_HANDLING_ERROR];
9062
9063 OOLog(kOOLogException, @"***** Handling Fatal : %@ : %@ *****", [exception name], [exception reason]);
9064 NSString* exception_msg = [NSString stringWithFormat:@"Exception : %@ : %@ Please take a screenshot and/or press esc or Q to quit.", [exception name], [exception reason]];
9065 [self addMessage:exception_msg forCount:30.0];
9066 [[self gameController] setGamePaused:YES];
9067 } else {
9068 OOLog(kOOLogException, @"***** Handling Non-fatal : %@ : %@ *****", [exception name], [exception reason]);
9069 }
9070 }
9071}
9072
9074{
9075 return airResistanceFactor;
9076}
9077
9078- (void)setAirResistanceFactor:(GLfloat)newFactor
9079{
9081}
9082
9083// speech routines
9084#if OOLITE_MAC_COCOA_UI
9085
9086- (void)startSpeakingString:(NSString*)text
9087{
9088 [speechSynthesizer startSpeakingString:[NSString stringWithFormat:@"[[volm %.3f]]%@", 0.3333333f * [OOSound masterVolume], text]];
9089}
9090
9092{
9093 if ([speechSynthesizer respondsToSelector:@selector(stopSpeakingAtBoundary:)]) {
9094 [speechSynthesizer stopSpeakingAtBoundary:NSSpeechWordBoundary];
9095 } else {
9096 [speechSynthesizer stopSpeaking];
9097 }
9098}
9099
9101{
9102 return [speechSynthesizer isSpeaking];
9103}
9104
9105#elif OOLITE_ESPEAK
9106
9107- (void)startSpeakingString:(NSString*)text
9108{
9109 NSData* utf8 = [text dataUsingEncoding:NSUTF8StringEncoding];
9110
9111 if (utf8 != nil) // we have a valid UTF-8 string
9112 {
9113 const char* stringToSay = [text UTF8String];
9114 espeak_Synth(stringToSay, strlen(stringToSay) + 1 /* inc. NULL */, 0, POS_CHARACTER, 0, espeakCHARS_UTF8 | espeakPHONEMES | espeakENDPAUSE, NULL, NULL);
9115 }
9116}
9117
9118- (void)stopSpeaking
9119{
9120 espeak_Cancel();
9121}
9122
9123- (BOOL)isSpeaking
9124{
9125 return espeak_IsPlaying();
9126}
9127
9128- (NSString*)voiceName:(unsigned int)index
9129{
9130 if (index >= espeak_voice_count)
9131 return @"-";
9132 return [NSString stringWithCString:espeak_voices[index]->name];
9133}
9134
9135- (unsigned int)voiceNumber:(NSString*)name
9136{
9137 if (name == nil)
9138 return UINT_MAX;
9139
9140 const char* const label = [name UTF8String];
9141 if (!label)
9142 return UINT_MAX;
9143
9144 unsigned int index = -1;
9145 while (espeak_voices[++index] && strcmp(espeak_voices[index]->name, label))
9146 /**/;
9147 return (index < espeak_voice_count) ? index : UINT_MAX;
9148}
9149
9150- (unsigned int)nextVoice:(unsigned int)index
9151{
9152 if (++index >= espeak_voice_count)
9153 index = 0;
9154 return index;
9155}
9156
9157- (unsigned int)prevVoice:(unsigned int)index
9158{
9159 if (--index >= espeak_voice_count)
9160 index = espeak_voice_count - 1;
9161 return index;
9162}
9163
9164- (unsigned int)setVoice:(unsigned int)index withGenderM:(BOOL)isMale
9165{
9166 if (index == UINT_MAX)
9167 index = [self voiceNumber:DESC(@"espeak-default-voice")];
9168
9169 if (index < espeak_voice_count) {
9170 espeak_VOICE voice = { espeak_voices[index]->name, NULL, NULL, isMale ? 1 : 2 };
9171 espeak_SetVoiceByProperties(&voice);
9172 }
9173
9174 return index;
9175}
9176
9177#else
9178
9179- (void)startSpeakingString:(NSString*)text
9180{
9181}
9182
9183- (void)stopSpeaking
9184{
9185}
9186
9187- (BOOL)isSpeaking
9188{
9189 return NO;
9190}
9191#endif
9192
9194{
9195 return _pauseMessage;
9196}
9197
9198- (void)setPauseMessageVisible:(BOOL)value
9199{
9200 _pauseMessage = value;
9201}
9202
9204{
9205 return _permanentMessageLog;
9206}
9207
9208- (void)setPermanentMessageLog:(BOOL)value
9209{
9210 _permanentMessageLog = value;
9211}
9212
9214{
9215 return _autoMessageLogBg;
9216}
9217
9218- (void)setAutoMessageLogBg:(BOOL)value
9219{
9220 _autoMessageLogBg = !!value;
9221}
9222
9224{
9225 return _permanentCommLog;
9226}
9227
9228- (void)setPermanentCommLog:(BOOL)value
9229{
9230 _permanentCommLog = value;
9231}
9232
9233- (void)setAutoCommLog:(BOOL)value
9234{
9235 _autoCommLog = value;
9236}
9237
9239{
9240 return gOOJSPlayerIfStale != nil;
9241}
9242
9243- (void)setBlockJSPlayerShipProps:(BOOL)value
9244{
9245 if (value) {
9247 } else {
9249 }
9250}
9251
9253{
9254 [self resetBeacons];
9255
9256 next_universal_id = 100; // start arbitrarily above zero
9257 memset(entity_for_uid, 0, sizeof entity_for_uid);
9258
9259 [self setMainLightPosition:kZeroVector];
9260
9261 [gui autorelease];
9262 gui = [[GuiDisplayGen alloc] init];
9263 [gui setTextColor:[OOColor colorWithDescription:[[gui userSettings] objectForKey:kGuiDefaultTextColor]]];
9264
9265 // message_gui and comm_log_gui defaults are set up inside [hud resetGuis:] ( via [player deferredInit], called from the code that calls this method).
9266 [message_gui autorelease];
9267 message_gui = [[GuiDisplayGen alloc]
9268 initWithPixelSize:NSMakeSize(480, 160)
9269 columns:1
9270 rows:9
9271 rowHeight:19
9272 rowStart:20
9273 title:nil];
9274
9275 [comm_log_gui autorelease];
9276 comm_log_gui = [[GuiDisplayGen alloc]
9277 initWithPixelSize:NSMakeSize(360, 120)
9278 columns:1
9279 rows:10
9280 rowHeight:12
9281 rowStart:12
9282 title:nil];
9283
9284 //
9285
9286 time_delta = 0.0;
9287#ifdef OO_DEBUG_MONITOR_ENABLED
9288 [self setTimeAccelerationFactor:TIME_ACCELERATION_FACTOR_DEFAULT];
9289#endif
9290 universal_time = 0.0;
9291 messageRepeatTime = 0.0;
9293
9294#if OOLITE_SPEECH_SYNTH
9295 [speechArray autorelease];
9296 speechArray = [[ResourceManager arrayFromFilesNamed:@"speech_pronunciation_guide.plist" inFolder:@"Config" andMerge:YES] retain];
9297#endif
9298
9299 [commodities autorelease];
9300 commodities = [[OOCommodities alloc] init];
9301
9302 [self loadDescriptions];
9303
9304 [characters autorelease];
9305 characters = [[ResourceManager dictionaryFromFilesNamed:@"characters.plist" inFolder:@"Config" andMerge:YES] retain];
9306
9307 [customSounds autorelease];
9308 customSounds = [[ResourceManager dictionaryFromFilesNamed:@"customsounds.plist" inFolder:@"Config" andMerge:YES] retain];
9309
9310 [globalSettings autorelease];
9311 globalSettings = [[ResourceManager dictionaryFromFilesNamed:@"global-settings.plist" inFolder:@"Config" mergeMode:MERGE_SMART cache:YES] retain];
9312
9313 [systemManager autorelease];
9315
9316 [screenBackgrounds autorelease];
9317 screenBackgrounds = [[ResourceManager dictionaryFromFilesNamed:@"screenbackgrounds.plist" inFolder:@"Config" andMerge:YES] retain];
9318
9319 // role-categories.plist and pirate-victim-roles.plist
9320 [roleCategories autorelease];
9322
9323 [autoAIMap autorelease];
9324 autoAIMap = [[ResourceManager dictionaryFromFilesNamed:@"autoAImap.plist" inFolder:@"Config" andMerge:YES] retain];
9325
9326 [equipmentData autorelease];
9327 [equipmentDataOutfitting autorelease];
9328 NSArray* equipmentTemp = [ResourceManager arrayFromFilesNamed:@"equipment.plist" inFolder:@"Config" andMerge:YES];
9329 equipmentData = [[equipmentTemp sortedArrayUsingFunction:equipmentSort context:NULL] retain];
9330 equipmentDataOutfitting = [[equipmentTemp sortedArrayUsingFunction:equipmentSortOutfitting context:NULL] retain];
9331
9333
9334 [explosionSettings autorelease];
9335 explosionSettings = [[ResourceManager dictionaryFromFilesNamed:@"explosions.plist" inFolder:@"Config" andMerge:YES] retain];
9336}
9337
9339{
9340 NSMutableDictionary* tmp = [[NSMutableDictionary alloc] initWithCapacity:[commodities count]];
9341 OOCommodityType type = nil;
9342 foreach (type, [commodities goods]) {
9343 ShipEntity* container = [self newShipWithRole:@"oolite-template-cargopod"];
9344 [container setScanClass:CLASS_CARGO];
9346 [tmp setObject:container forKey:type];
9347 [container release];
9348 }
9349 [cargoPods release];
9350 cargoPods = [[NSDictionary alloc] initWithDictionary:tmp];
9351 [tmp release];
9352}
9353
9355{
9356#ifndef NDEBUG
9357 NSMutableArray* badEntities = nil;
9358 Entity* entity = nil;
9359
9360 unsigned i;
9361 for (i = 0; i < n_entities; i++) {
9362 entity = sortedEntities[i];
9363 if ([entity sessionID] != _sessionID) {
9364 OOLogERR(@"universe.sessionIDs.verify.failed", @"Invalid entity %@ (came from session %zu, current session is %zu).", [entity shortDescription], [entity sessionID], _sessionID);
9365 if (badEntities == nil)
9366 badEntities = [NSMutableArray array];
9367 [badEntities addObject:entity];
9368 }
9369 }
9370
9371 foreach (entity, badEntities) {
9372 [self removeEntity:entity];
9373 }
9374#endif
9375}
9376
9377// FIXME: needs less redundancy?
9378- (BOOL)reinitAndShowDemo:(BOOL)showDemo
9379{
9380 no_update = YES;
9381 PlayerEntity* player = PLAYER;
9382 assert(player != nil);
9383
9384 if (JSResetFlags != 0) // JS reset failed, remember previous settings
9385 {
9386 showDemo = (JSResetFlags & 2) > 0; // binary 10, a.k.a. 1 << 1
9387 } else {
9388 JSResetFlags = (showDemo << 1);
9389 }
9390
9393
9394 _sessionID++; // Must be after removing old entities and before adding new ones.
9395
9396 [ResourceManager setUseAddOns:useAddOns]; // also logs the paths
9397 //[ResourceManager loadScripts]; // initialised inside [player setUp]!
9398
9399 // NOTE: Anything in the sharedCache is now trashed and must be
9400 // reloaded. Ideally anything using the sharedCache should
9401 // be aware of cache flushes so it can automatically
9402 // reinitialize itself - mwerle 20081107.
9404 [[self gameController] setGamePaused:NO];
9406 [PLAYER setSpeed:0.0];
9407
9408 [self loadDescriptions];
9409 [self loadScenarios];
9410
9411 [missiontext autorelease];
9412 missiontext = [[ResourceManager dictionaryFromFilesNamed:@"missiontext.plist" inFolder:@"Config" andMerge:YES] retain];
9413
9414 if (showDemo) {
9415 [demo_ships release];
9417 demo_ship_index = 0;
9419 }
9420
9422
9423 cachedSun = nil;
9424 cachedPlanet = nil;
9426
9427 [self setUpSettings];
9428
9429 // reset these in case OXP set has changed
9430
9431 // set up cargopod templates
9432 [self setUpCargoPods];
9433
9434 if (![player setUpAndConfirmOK:YES]) {
9435 // reinitAndShowDemo rescheduled inside setUpAndConfirmOK...
9436 return NO; // Abort!
9437 }
9438
9439 // we can forget the previous settings now.
9440 JSResetFlags = 0;
9441
9442 [self addEntity:player];
9443 demo_ship = nil;
9444 [[self gameController] setPlayerFileToLoad:nil]; // reset Quicksave
9445
9446 [self setUpInitialUniverse];
9447 autoSaveNow = NO; // don't autosave immediately after restarting a game
9448
9450
9451 if (showDemo) {
9452 [player setStatus:STATUS_START_GAME];
9453 // re-read keyconfig.plist just in case we've loaded a keyboard
9454 // configuration expansion
9456 } else {
9458 }
9459
9461 if (showDemo) {
9463 } else {
9464 // no need to do these if showing the demo as the only way out
9465 // now is to load a game
9466 [self populateNormalSpace];
9467
9469 }
9470
9471 if (!showDemo) {
9473 [player doWorldEventUntilMissionScreen:OOJSID("missionScreenOpportunity")];
9474 }
9475
9477
9478 no_update = NO;
9479 return YES;
9480}
9481
9483{
9484 PlayerEntity* player = PLAYER;
9485
9486 OO_DEBUG_PUSH_PROGRESS(@"%@", @"Wormhole and character reset");
9487 if (activeWormholes)
9488 [activeWormholes autorelease];
9489 activeWormholes = [[NSMutableArray arrayWithCapacity:16] retain];
9490 if (characterPool)
9491 [characterPool autorelease];
9492 characterPool = [[NSMutableArray arrayWithCapacity:256] retain];
9494
9495 OO_DEBUG_PUSH_PROGRESS(@"%@", @"Galaxy reset");
9497 systemID = [player systemID];
9499
9500 OO_DEBUG_PUSH_PROGRESS(@"%@", @"Player init: setUpShipFromDictionary");
9502 [player baseMass]; // bootstrap the base mass used in all fuel charge calculations.
9504
9505 // Player init above finishes initialising all standard player ship properties. Now that the base mass is set, we can run setUpSpace!
9506 [self setUpSpace];
9507
9509 [[self currentSystemData] oo_boolForKey:@"stations_require_docking_clearance"
9510 defaultValue:YES]];
9511
9514 [player setOrientation:kIdentityQuaternion];
9515}
9516
9518{
9519 return SCANNER_MAX_RANGE * ((Ranrot() & 255) / 256.0 - 0.5);
9520}
9521
9522- (Vector)randomPlaceWithinScannerFrom:(Vector)pos alongRoute:(Vector)route withOffset:(double)offset
9523{
9524 pos.x += offset * route.x + [self randomDistanceWithinScanner];
9525 pos.y += offset * route.y + [self randomDistanceWithinScanner];
9526 pos.z += offset * route.z + [self randomDistanceWithinScanner];
9527
9528 return pos;
9529}
9530
9531- (HPVector)fractionalPositionFrom:(HPVector)point0 to:(HPVector)point1 withFraction:(double)routeFraction
9532{
9533 if (routeFraction == NSNotFound)
9534 routeFraction = randf();
9535
9536 point1 = OOHPVectorInterpolate(point0, point1, routeFraction);
9537
9538 point1.x += 2 * SCANNER_MAX_RANGE * (randf() - 0.5);
9539 point1.y += 2 * SCANNER_MAX_RANGE * (randf() - 0.5);
9540 point1.z += 2 * SCANNER_MAX_RANGE * (randf() - 0.5);
9541
9542 return point1;
9543}
9544
9545- (BOOL)doRemoveEntity:(Entity*)entity
9546{
9547 // remove reference to entity in linked lists
9548 if ([entity canCollide]) // filter only collidables disappearing
9549 {
9550 doLinkedListMaintenanceThisUpdate = YES;
9551 }
9552
9554
9555 // moved forward ^^
9556 // remove from the reference dictionary
9557 int old_id = [entity universalID];
9558 entity_for_uid[old_id] = nil;
9559 [entity setUniversalID:NO_TARGET];
9561
9562 // maintain sorted lists
9563 int index = entity->zero_index;
9564
9565 int n = 1;
9566 if (index >= 0) {
9567 if (sortedEntities[index] != entity) {
9568 OOLog(kOOLogInconsistentState, @"DEBUG: Universe removeEntity:%@ ENTITY IS NOT IN THE RIGHT PLACE IN THE ZERO_DISTANCE SORTED LIST -- FIXING...", entity);
9569 unsigned i;
9570 index = -1;
9571 for (i = 0; (i < n_entities) && (index == -1); i++)
9572 if (sortedEntities[i] == entity)
9573 index = i;
9574 if (index == -1)
9575 OOLog(kOOLogInconsistentState, @"DEBUG: Universe removeEntity:%@ ENTITY IS NOT IN THE ZERO_DISTANCE SORTED LIST -- CONTINUING...", entity);
9576 }
9577 if (index != -1) {
9578 while ((unsigned)index < n_entities) {
9579 while (((unsigned)index + n < n_entities) && (sortedEntities[index + n] == entity)) {
9580 n++; // ie there's a duplicate entry for this entity
9581 }
9582
9583 /*
9584 BUG: when n_entities == UNIVERSE_MAX_ENTITIES, this read
9585 off the end of the array and copied (Entity *)n_entities =
9586 0x800 into the list. The subsequent update of zero_index
9587 derferenced 0x800 and crashed.
9588 FIX: add an extra unused slot to sortedEntities, which is
9589 always nil.
9590 EFFICIENCY CONCERNS: this could have been an alignment
9591 issue since UNIVERSE_MAX_ENTITIES == 2048, but it isn't
9592 really. sortedEntities is part of the object, not malloced,
9593 it isn't aligned, and the end of it is only live in
9594 degenerate cases.
9595 -- Ahruman 2012-07-11
9596 */
9597 sortedEntities[index] = sortedEntities[index + n]; // copy entity[index + n] -> entity[index] (preserves sort order)
9598 if (sortedEntities[index]) {
9599 sortedEntities[index]->zero_index = index; // give it its correct position
9600 }
9601 index++;
9602 }
9603 if (n > 1)
9604 OOLog(kOOLogInconsistentState, @"DEBUG: Universe removeEntity: REMOVED %d EXTRA COPIES OF %@ FROM THE ZERO_DISTANCE SORTED LIST", n - 1, entity);
9605 while (n--) {
9606 n_entities--;
9607 sortedEntities[n_entities] = nil;
9608 }
9609 }
9610 entity->zero_index = -1; // it's GONE!
9611 }
9612
9613 // remove from the definitive list
9614 if ([entities containsObject:entity]) {
9615 // FIXME: better approach needed for core break patterns - CIM
9616 if ([entity isBreakPattern] && ![entity isVisualEffect]) {
9617 breakPatternCounter--;
9618 }
9619
9620 if ([entity isShip]) {
9621 ShipEntity* se = (ShipEntity*)entity;
9622 [self clearBeacon:se];
9623 }
9624 if ([entity isWaypoint]) {
9625 OOWaypointEntity* wp = (OOWaypointEntity*)entity;
9626 [self clearBeacon:wp];
9627 }
9628 if ([entity isVisualEffect]) {
9630 [self clearBeacon:ve];
9631 }
9632
9633 if ([entity isWormhole]) {
9634 [activeWormholes removeObject:entity];
9635 } else if ([entity isPlanet]) {
9636 [allPlanets removeObject:entity];
9637 }
9638
9639 [entities removeObject:entity];
9640 return YES;
9641 }
9642
9643 return NO;
9644}
9645
9646static void PreloadOneSound(NSString* soundName)
9647{
9648 if (![soundName hasPrefix:@"["] && ![soundName hasSuffix:@"]"]) {
9649 [ResourceManager ooSoundNamed:soundName inFolder:@"Sounds"];
9650 }
9651}
9652
9654{
9655 // Preload sounds to avoid loading stutter.
9656 NSString* key = nil;
9658 {
9659 id object = [customSounds objectForKey:key];
9660 if ([object isKindOfClass:[NSString class]]) {
9661 PreloadOneSound(object);
9662 } else if ([object isKindOfClass:[NSArray class]] && [object count] > 0) {
9663 NSString* soundName = nil;
9664 foreach (soundName, object) {
9665 if ([soundName isKindOfClass:[NSString class]]) {
9666 PreloadOneSound(soundName);
9667 }
9668 }
9669 }
9670 }
9671
9672 // Afterburner sound doesn't go through customsounds.plist.
9673 PreloadOneSound(@"afterburner1.ogg");
9674}
9675
9677{
9678 NSAutoreleasePool* pool = nil;
9679
9680 while ([activeWormholes count]) {
9681 pool = [[NSAutoreleasePool alloc] init];
9682 @try {
9683 WormholeEntity* whole = [activeWormholes objectAtIndex:0];
9684 // If the wormhole has been scanned by the player then the
9685 // PlayerEntity will take care of it
9686 if (![whole isScanned] && NSEqualPoints([PLAYER galaxy_coordinates], [whole destinationCoordinates])) {
9687 // this is a wormhole to this system
9689 }
9690 [activeWormholes removeObjectAtIndex:0]; // empty it out
9691 }
9692 @catch (NSException* exception) {
9693 OOLog(kOOLogException, @"Squashing exception during wormhole unpickling (%@: %@).", [exception name], [exception reason]);
9694 }
9695 [pool release];
9696 }
9697}
9698
9699- (NSString*)chooseStringForKey:(NSString*)key inDictionary:(NSDictionary*)dictionary
9700{
9701 id object = [dictionary objectForKey:key];
9702 if ([object isKindOfClass:[NSString class]])
9703 return object;
9704 else if ([object isKindOfClass:[NSArray class]] && [object count] > 0)
9705 return [object oo_stringAtIndex:Ranrot() % [object count]];
9706 return nil;
9707}
9708
9709#if OO_LOCALIZATION_TOOLS
9710
9711#if DEBUG_GRAPHVIZ
9712- (void)dumpDebugGraphViz
9713{
9714 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"universe-dump-debug-graphviz"]) {
9715 [self dumpSystemDescriptionGraphViz];
9716 }
9717}
9718
9719- (void)dumpSystemDescriptionGraphViz
9720{
9721 NSMutableString* graphViz = nil;
9722 NSArray* systemDescriptions = nil;
9723 NSArray* thisDesc = nil;
9724 NSUInteger i, count, j, subCount;
9725 NSString* descLine = nil;
9726 NSArray* curses = nil;
9727 NSString* label = nil;
9728 NSDictionary* keyMap = nil;
9729
9730 keyMap = [ResourceManager dictionaryFromFilesNamed:@"sysdesc_key_table.plist"
9731 inFolder:@"Config"
9732 andMerge:NO];
9733
9734 graphViz = [NSMutableString stringWithString:
9735 @"// System description grammar:\n\n"
9736 "digraph system_descriptions\n"
9737 "{\n"
9738 "\tgraph [charset=\"UTF-8\", label=\"System description grammar\", labelloc=t, labeljust=l rankdir=LR compound=true nodesep=0.02 ranksep=1.5 concentrate=true fontname=Helvetica]\n"
9739 "\tedge [arrowhead=dot]\n"
9740 "\tnode [shape=none height=0.2 width=3 fontname=Helvetica]\n\t\n"];
9741
9742 systemDescriptions = [[self descriptions] oo_arrayForKey:@"system_description"];
9743 count = [systemDescriptions count];
9744
9745 // Add system-description-string as special node (it's the one thing that ties [14] to everything else).
9746 descLine = DESC(@"system-description-string");
9747 label = OOStringifySystemDescriptionLine(descLine, keyMap, NO);
9748 [graphViz appendFormat:@"\tsystem_description_string [label=\"%@\" shape=ellipse]\n", EscapedGraphVizString(label)];
9749 [self addNumericRefsInString:descLine
9750 toGraphViz:graphViz
9751 fromNode:@"system_description_string"
9752 nodeCount:count];
9753 [graphViz appendString:@"\t\n"];
9754
9755 // Add special nodes for formatting codes
9756 [graphViz appendString:
9757 @"\tpercent_I [label=\"%I\\nInhabitants\" shape=diamond]\n"
9758 "\tpercent_H [label=\"%H\\nSystem name\" shape=diamond]\n"
9759 "\tpercent_RN [label=\"%R/%N\\nRandom name\" shape=diamond]\n"
9760 "\tpercent_J [label=\"%J\\nNumbered system name\" shape=diamond]\n"
9761 "\tpercent_G [label=\"%G\\nNumbered system name in chart number\" shape=diamond]\n\t\n"];
9762
9763 // Toss in the Thargoid curses, too
9764 [graphViz appendString:@"\tsubgraph cluster_thargoid_curses\n\t{\n\t\tlabel = \"Thargoid curses\"\n"];
9765 curses = [[self descriptions] oo_arrayForKey:@"thargoid_curses"];
9766 subCount = [curses count];
9767 for (j = 0; j < subCount; ++j) {
9768 label = OOStringifySystemDescriptionLine([curses oo_stringAtIndex:j], keyMap, NO);
9769 [graphViz appendFormat:@"\t\tthargoid_curse_%zu [label=\"%@\"]\n", j, EscapedGraphVizString(label)];
9770 }
9771 [graphViz appendString:@"\t}\n"];
9772 for (j = 0; j < subCount; ++j) {
9773 [self addNumericRefsInString:[curses oo_stringAtIndex:j]
9774 toGraphViz:graphViz
9775 fromNode:[NSString stringWithFormat:@"thargoid_curse_%zu", j]
9776 nodeCount:count];
9777 }
9778 [graphViz appendString:@"\t\n"];
9779
9780 // The main show: the bits of systemDescriptions itself.
9781 // Define the nodes
9782 for (i = 0; i < count; ++i) {
9783 // Build label, using sysdesc_key_table.plist if available
9784 label = [keyMap objectForKey:[NSString stringWithFormat:@"%zu", i]];
9785 if (label == nil)
9786 label = [NSString stringWithFormat:@"[%zu]", i];
9787 else
9788 label = [NSString stringWithFormat:@"[%zu] (%@)", i, label];
9789
9790 [graphViz appendFormat:@"\tsubgraph cluster_%zu\n\t{\n\t\tlabel=\"%@\"\n", i, EscapedGraphVizString(label)];
9791
9792 thisDesc = [systemDescriptions oo_arrayAtIndex:i];
9793 subCount = [thisDesc count];
9794 for (j = 0; j < subCount; ++j) {
9795 label = OOStringifySystemDescriptionLine([thisDesc oo_stringAtIndex:j], keyMap, NO);
9796 [graphViz appendFormat:@"\t\tn%zu_%zu [label=\"\\\"%@\\\"\"]\n", i, j, EscapedGraphVizString(label)];
9797 }
9798
9799 [graphViz appendString:@"\t}\n"];
9800 }
9801 [graphViz appendString:@"\t\n"];
9802
9803 // Define the edges
9804 for (i = 0; i != count; ++i) {
9805 thisDesc = [systemDescriptions oo_arrayAtIndex:i];
9806 subCount = [thisDesc count];
9807 for (j = 0; j != subCount; ++j) {
9808 descLine = [thisDesc oo_stringAtIndex:j];
9809 [self addNumericRefsInString:descLine
9810 toGraphViz:graphViz
9811 fromNode:[NSString stringWithFormat:@"n%zu_%zu", i, j]
9812 nodeCount:count];
9813 }
9814 }
9815
9816 // Write file
9817 [graphViz appendString:@"\t}\n"];
9818 [ResourceManager writeDiagnosticData:[graphViz dataUsingEncoding:NSUTF8StringEncoding] toFileNamed:@"SystemDescription.dot"];
9819}
9820#endif // DEBUG_GRAPHVIZ
9821
9822- (void)addNumericRefsInString:(NSString*)string toGraphViz:(NSMutableString*)graphViz fromNode:(NSString*)fromNode nodeCount:(NSUInteger)nodeCount
9823{
9824 NSString* index = nil;
9825 NSInteger start, end;
9826 NSRange remaining, subRange;
9827 unsigned i;
9828
9829 remaining = NSMakeRange(0, [string length]);
9830
9831 for (;;) {
9832 subRange = [string rangeOfString:@"[" options:NSLiteralSearch range:remaining];
9833 if (subRange.location == NSNotFound)
9834 break;
9835 start = subRange.location + subRange.length;
9836 remaining.length -= start - remaining.location;
9837 remaining.location = start;
9838
9839 subRange = [string rangeOfString:@"]" options:NSLiteralSearch range:remaining];
9840 if (subRange.location == NSNotFound)
9841 break;
9842 end = subRange.location;
9843 remaining.length -= end - remaining.location;
9844 remaining.location = end;
9845
9846 index = [string substringWithRange:NSMakeRange(start, end - start)];
9847 i = [index intValue];
9848
9849 // Each node gets a colour for its incoming edges. The multiplication and mod shuffle them to avoid adjacent nodes having similar colours.
9850 [graphViz appendFormat:@"\t%@ -> n%u_0 [color=\"%f,0.75,0.8\" lhead=cluster_%u]\n", fromNode, i, ((float)(i * 511 % nodeCount)) / ((float)nodeCount), i];
9851 }
9852
9853 if ([string rangeOfString:@"%I"].location != NSNotFound) {
9854 [graphViz appendFormat:@"\t%@ -> percent_I [color=\"0,0,0.25\"]\n", fromNode];
9855 }
9856 if ([string rangeOfString:@"%H"].location != NSNotFound) {
9857 [graphViz appendFormat:@"\t%@ -> percent_H [color=\"0,0,0.45\"]\n", fromNode];
9858 }
9859 if ([string rangeOfString:@"%R"].location != NSNotFound || [string rangeOfString:@"%N"].location != NSNotFound) {
9860 [graphViz appendFormat:@"\t%@ -> percent_RN [color=\"0,0,0.65\"]\n", fromNode];
9861 }
9862
9863 // TODO: test graphViz output for @"%Jxxx" and @"%Gxxxxxx"
9864 if ([string rangeOfString:@"%J"].location != NSNotFound) {
9865 [graphViz appendFormat:@"\t%@ -> percent_J [color=\"0,0,0.75\"]\n", fromNode];
9866 }
9867
9868 if ([string rangeOfString:@"%G"].location != NSNotFound) {
9869 [graphViz appendFormat:@"\t%@ -> percent_G [color=\"0,0,0.85\"]\n", fromNode];
9870 }
9871}
9872
9874{
9875 // Handle command line options to transform system_description array for easier localization
9876
9877 NSArray* arguments = nil;
9878 NSString* arg = nil;
9879 BOOL compileSysDesc = NO, exportSysDesc = NO, xml = NO;
9880
9881 arguments = [[NSProcessInfo processInfo] arguments];
9882
9883 foreach (arg, arguments) {
9884 if ([arg isEqual:@"--compile-sysdesc"])
9885 compileSysDesc = YES;
9886 else if ([arg isEqual:@"--export-sysdesc"])
9887 exportSysDesc = YES;
9888 else if ([arg isEqual:@"--xml"])
9889 xml = YES;
9890 else if ([arg isEqual:@"--openstep"])
9891 xml = NO;
9892 }
9893
9894 if (compileSysDesc)
9896 if (exportSysDesc)
9898}
9899#endif
9900
9901#if NEW_PLANETS
9902// See notes at preloadPlanetTexturesForSystem:.
9903- (void)prunePreloadingPlanetMaterials
9904{
9906
9907 NSUInteger i = [_preloadingPlanetMaterials count];
9908 while (i--) {
9909 if ([[_preloadingPlanetMaterials objectAtIndex:i] isFinishedLoading]) {
9910 [_preloadingPlanetMaterials removeObjectAtIndex:i];
9911 }
9912 }
9913}
9914#endif
9915
9917{
9918 [conditionScripts autorelease];
9919 conditionScripts = [[NSMutableDictionary alloc] init];
9920 // get list of names from cache manager
9921 [self addConditionScripts:[[[OOCacheManager sharedCache] objectForKey:@"equipment conditions" inCache:@"condition scripts"] objectEnumerator]];
9922
9923 [self addConditionScripts:[[[OOCacheManager sharedCache] objectForKey:@"ship conditions" inCache:@"condition scripts"] objectEnumerator]];
9924
9925 [self addConditionScripts:[[[OOCacheManager sharedCache] objectForKey:@"demoship conditions" inCache:@"condition scripts"] objectEnumerator]];
9926}
9927
9928- (void)addConditionScripts:(NSEnumerator*)scripts
9929{
9930 NSString* scriptname = nil;
9931 while ((scriptname = [scripts nextObject])) {
9932 if ([conditionScripts objectForKey:scriptname] == nil) {
9933 OOJSScript* script = [OOScript jsScriptFromFileNamed:scriptname properties:nil];
9934 if (script != nil) {
9935 [conditionScripts setObject:script forKey:scriptname];
9936 }
9937 }
9938 }
9939}
9940
9941- (OOJSScript*)getConditionScript:(NSString*)scriptname
9942{
9943 return [conditionScripts objectForKey:scriptname];
9944}
9945
9946@end
9947
9948@implementation OOSound (OOCustomSounds)
9949
9950+ (id)soundWithCustomSoundKey:(NSString*)key
9951{
9952 NSString* fileName = [UNIVERSE soundNameForCustomSoundKey:key];
9953 if (fileName == nil)
9954 return nil;
9955 return [ResourceManager ooSoundNamed:fileName inFolder:@"Sounds"];
9956}
9957
9958- (id)initWithCustomSoundKey:(NSString*)key
9959{
9960 [self release];
9961 return [[OOSound soundWithCustomSoundKey:key] retain];
9962}
9963
9964@end
9965
9966@implementation OOSoundSource (OOCustomSounds)
9967
9968+ (id)sourceWithCustomSoundKey:(NSString*)key
9969{
9970 return [[[self alloc] initWithCustomSoundKey:key] autorelease];
9971}
9972
9973- (id)initWithCustomSoundKey:(NSString*)key
9974{
9975 OOSound* theSound = [OOSound soundWithCustomSoundKey:key];
9976 if (theSound != nil) {
9977 self = [self initWithSound:theSound];
9978 } else {
9979 [self release];
9980 self = nil;
9981 }
9982 return self;
9983}
9984
9985- (void)playCustomSoundWithKey:(NSString*)key
9986{
9987 OOSound* theSound = [OOSound soundWithCustomSoundKey:key];
9988 if (theSound != nil)
9989 [self playSound:theSound];
9990}
9991
9992@end
9993
9994NSComparisonResult populatorPrioritySort(id a, id b, void* context)
9995{
9996 NSDictionary* one = (NSDictionary*)a;
9997 NSDictionary* two = (NSDictionary*)b;
9998 int pri_one = [one oo_intForKey:@"priority" defaultValue:100];
9999 int pri_two = [two oo_intForKey:@"priority" defaultValue:100];
10000 if (pri_one < pri_two)
10001 return NSOrderedAscending;
10002 if (pri_one > pri_two)
10003 return NSOrderedDescending;
10004 return NSOrderedSame;
10005}
10006
10007NSComparisonResult equipmentSort(id a, id b, void* context)
10008{
10009 NSArray* one = (NSArray*)a;
10010 NSArray* two = (NSArray*)b;
10011
10012 /* Sort by explicit sort_order, then tech level, then price */
10013
10014 OOCreditsQuantity comp1 = [[one oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"sort_order" defaultValue:1000];
10015 OOCreditsQuantity comp2 = [[two oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"sort_order" defaultValue:1000];
10016 if (comp1 < comp2)
10017 return NSOrderedAscending;
10018 if (comp1 > comp2)
10019 return NSOrderedDescending;
10020
10021 comp1 = [one oo_unsignedLongLongAtIndex:EQUIPMENT_TECH_LEVEL_INDEX];
10022 comp2 = [two oo_unsignedLongLongAtIndex:EQUIPMENT_TECH_LEVEL_INDEX];
10023 if (comp1 < comp2)
10024 return NSOrderedAscending;
10025 if (comp1 > comp2)
10026 return NSOrderedDescending;
10027
10028 comp1 = [one oo_unsignedLongLongAtIndex:EQUIPMENT_PRICE_INDEX];
10029 comp2 = [two oo_unsignedLongLongAtIndex:EQUIPMENT_PRICE_INDEX];
10030 if (comp1 < comp2)
10031 return NSOrderedAscending;
10032 if (comp1 > comp2)
10033 return NSOrderedDescending;
10034
10035 return NSOrderedSame;
10036}
10037
10038NSComparisonResult equipmentSortOutfitting(id a, id b, void* context)
10039{
10040 NSArray* one = (NSArray*)a;
10041 NSArray* two = (NSArray*)b;
10042
10043 /* Sort by explicit sort_order, then tech level, then price */
10044
10045 OOCreditsQuantity comp1 = [[one oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"purchase_sort_order" defaultValue:[[one oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"sort_order" defaultValue:1000]];
10046 OOCreditsQuantity comp2 = [[two oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"purchase_sort_order" defaultValue:[[two oo_dictionaryAtIndex:EQUIPMENT_EXTRA_INFO_INDEX] oo_unsignedLongLongForKey:@"sort_order" defaultValue:1000]];
10047 if (comp1 < comp2)
10048 return NSOrderedAscending;
10049 if (comp1 > comp2)
10050 return NSOrderedDescending;
10051
10052 comp1 = [one oo_unsignedLongLongAtIndex:EQUIPMENT_TECH_LEVEL_INDEX];
10053 comp2 = [two oo_unsignedLongLongAtIndex:EQUIPMENT_TECH_LEVEL_INDEX];
10054 if (comp1 < comp2)
10055 return NSOrderedAscending;
10056 if (comp1 > comp2)
10057 return NSOrderedDescending;
10058
10059 comp1 = [one oo_unsignedLongLongAtIndex:EQUIPMENT_PRICE_INDEX];
10060 comp2 = [two oo_unsignedLongLongAtIndex:EQUIPMENT_PRICE_INDEX];
10061 if (comp1 < comp2)
10062 return NSOrderedAscending;
10063 if (comp1 > comp2)
10064 return NSOrderedDescending;
10065
10066 return NSOrderedSame;
10067}
10068
10069NSString* OOLookUpDescriptionPRIV(NSString* key)
10070{
10071 NSString* result = [UNIVERSE descriptionForKey:key];
10072 if (result == nil)
10073 result = key;
10074 return result;
10075}
10076
10077// There's a hint of gettext about this...
10078NSString* OOLookUpPluralDescriptionPRIV(NSString* key, NSInteger count)
10079{
10080 NSArray* conditions = [[UNIVERSE descriptions] oo_arrayForKey:@"plural-rules"];
10081
10082 // are we using an older descriptions.plist (1.72.x) ?
10083 NSString* tmp = [UNIVERSE descriptionForKey:key];
10084 if (tmp != nil) {
10085 static NSMutableSet* warned = nil;
10086
10087 if (![warned containsObject:tmp]) {
10088 OOLogWARN(@"localization.plurals", @"'%@' found in descriptions.plist, should be '%@%%0'. Localization data needs updating.", key, key);
10089 if (warned == nil)
10090 warned = [[NSMutableSet alloc] init];
10091 [warned addObject:tmp];
10092 }
10093 }
10094
10095 if (conditions == nil) {
10096 if (tmp == nil) // this should mean that descriptions.plist is from 1.73 or above.
10097 return OOLookUpDescriptionPRIV([NSString stringWithFormat:@"%@%%%d", key, count != 1]);
10098 // still using an older descriptions.plist
10099 return tmp;
10100 }
10101 int unsigned i;
10102 long int index;
10103
10104 for (index = i = 0; i < [conditions count]; ++index, ++i) {
10105 const char* cond = [[conditions oo_stringAtIndex:i] UTF8String];
10106 if (!cond)
10107 break;
10108
10109 long int input = count;
10110 BOOL flag = NO; // we XOR test results with this
10111
10112 while (isspace(*cond))
10113 ++cond;
10114
10115 for (;;) {
10116 while (isspace(*cond))
10117 ++cond;
10118
10119 char command = *cond++;
10120
10121 switch (command) {
10122 case 0:
10123 goto passed; // end of string
10124
10125 case '~':
10126 flag = !flag;
10127 continue;
10128 }
10129
10130 long int param = strtol(cond, (char**)&cond, 10);
10131
10132 switch (command) {
10133 case '#':
10134 index = param;
10135 continue;
10136
10137 case '%':
10138 if (param < 2)
10139 break; // ouch - fail this!
10140 input %= param;
10141 continue;
10142
10143 case '=':
10144 if (flag ^ (input == param))
10145 continue;
10146 break;
10147 case '!':
10148 if (flag ^ (input != param))
10149 continue;
10150 break;
10151
10152 case '<':
10153 if (flag ^ (input < param))
10154 continue;
10155 break;
10156 case '>':
10157 if (flag ^ (input > param))
10158 continue;
10159 break;
10160 }
10161 // if we arrive here, we have an unknown test or a test has failed
10162 break;
10163 }
10164 }
10165
10166passed:
10167 return OOLookUpDescriptionPRIV([NSString stringWithFormat:@"%@%%%ld", key, index]);
10168}
OOEntityStatus
Definition Entity.h:60
OOScanClass
Definition Entity.h:69
#define SCANNER_MAX_RANGE
Definition Entity.h:53
#define SCANNER_MAX_RANGE2
Definition Entity.h:54
static NSString *const kOOLogEntityVerificationError
Definition Entity.m:54
#define OO_DEBUG_POP_PROGRESS()
#define OO_DEBUG_PROGRESS(...)
#define OO_DEBUG_PUSH_PROGRESS(...)
OOGUITabStop OOGUITabSettings[GUI_MAX_COLUMNS]
#define MAIN_GUI_PIXEL_WIDTH
#define MAIN_GUI_PIXEL_HEIGHT
NSInteger OOGUIRow
NSRect OORectFromString(NSString *text, GLfloat x, GLfloat y, NSSize siz)
void OODrawString(NSString *text, GLfloat x, GLfloat y, GLfloat z, NSSize siz)
#define MAX_CLEAR_DEPTH
#define INTERMEDIATE_CLEAR_DEPTH
#define MIN_FOV_DEG
OOINLINE void bounding_box_reset_to_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE void bounding_box_add_xyz(BoundingBox *box, GLfloat x, GLfloat y, GLfloat z) ALWAYS_INLINE_FUNC NONNULL_FUNC
#define BREAK_PATTERN_RING_SPEED
#define BREAK_PATTERN_RING_SPACING
@ kOOBreakPatternMaxSides
void OOCPUInfoInit(void)
Definition OOCPUInfo.m:60
double OODoubleFromObject(id object, double defaultValue)
OOINLINE jsval OOJSValueFromViewID(JSContext *context, OOViewID value)
NSString * OOStringFromGraphicsDetail(OOGraphicsDetail detail)
void CompileSystemDescriptions(BOOL asXML)
void ExportSystemDescriptions(BOOL asXML)
NSString * OOStringifySystemDescriptionLine(NSString *line, NSDictionary *indicesToKeys, BOOL useFallback)
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
#define OOInitDebugSupport()
BOOL IsShipPredicate(Entity *entity, void *parameter)
BOOL IsVisualEffectPredicate(Entity *entity, void *parameter)
BOOL YESPredicate(Entity *entity, void *parameter)
OOINLINE double OOClamp_0_max_d(double value, double max) INLINE_CONST_FUNC
OOINLINE float OOClamp_0_max_f(float value, float max) INLINE_CONST_FUNC
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
NSInteger OOComparisonResult
#define DESTROY(x)
#define foreachkey(VAR, DICT)
#define EXPECT_NOT(x)
#define OOINLINE
#define EXPECT(x)
HPVector OOHPVectorRandomRadial(OOHPScalar maxLength)
Definition OOHPVector.m:88
HPVector OOProjectHPVectorToPlane(HPVector point, HPVector plane, HPVector normal)
Definition OOHPVector.m:126
OOINLINE HPVector HPvector_flip(HPVector v) INLINE_CONST_FUNC
Definition OOHPVector.h:245
HPVector OORandomPositionInShell(HPVector centre, OOHPScalar inner, OOHPScalar outer)
Definition OOHPVector.m:116
OOINLINE HPVector vectorToHPVector(Vector v) INLINE_CONST_FUNC
Definition OOHPVector.h:166
OOINLINE OOHPScalar HPdot_product(HPVector first, HPVector second) INLINE_CONST_FUNC
Definition OOHPVector.h:317
OOINLINE HPVector HPvector_subtract(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:236
OOINLINE HPVector HPvector_multiply_scalar(HPVector v, OOHPScalar s) INLINE_CONST_FUNC
Definition OOHPVector.h:198
OOINLINE HPVector HPcross_product(HPVector first, HPVector second) INLINE_CONST_FUNC
Definition OOHPVector.h:312
const HPVector kZeroHPVector
Definition OOHPVector.m:27
OOINLINE bool HPvector_equal(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:250
OOINLINE OOHPScalar HPmagnitude(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:260
OOINLINE Vector HPVectorToVector(HPVector v) INLINE_CONST_FUNC
Definition OOHPVector.h:175
OOINLINE HPVector HPvector_normal_or_xbasis(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:273
OOINLINE HPVector make_HPvector(OOHPScalar vx, OOHPScalar vy, OOHPScalar vz) INLINE_CONST_FUNC
Definition OOHPVector.h:149
OOINLINE OOHPScalar HPdistance2(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:293
OOINLINE HPVector HPvector_normal(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:288
OOINLINE HPVector HPvector_normal_or_zbasis(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:283
OOINLINE HPVector HPvector_add(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:213
HPVector OOHPVectorRandomSpatial(OOHPScalar maxLength)
Definition OOHPVector.m:75
#define HPvector_between(a, b)
Definition OOHPVector.h:83
const HPVector kBasisZHPVector
Definition OOHPVector.h:51
OOINLINE OOHPScalar HPmagnitude2(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:255
OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:298
OOINLINE HPVector OOHPVectorInterpolate(HPVector a, HPVector b, OOHPScalar where) INLINE_CONST_FUNC
Definition OOHPVector.h:222
HPVector OORandomPositionInCylinder(HPVector centre1, OOHPScalar exclusion1, HPVector centre2, OOHPScalar exclusion2, OOHPScalar radius)
Definition OOHPVector.m:102
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_ENTER
jsid OOJSPropID
Definition OOJSPropID.h:31
void OOJSPauseTimeLimiter(void)
OOINLINE jsval OOJSValueFromDouble(JSContext *context, double value)
jsval OOJSVal
#define OOJSFreeValue(context, value)
#define OOJSUndefinedValue()
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
OOINLINE BOOL OOJSValueToBOOL(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSRelinquishContext(JSContext *context)
void OOJSResumeTimeLimiter(void)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
NSString *const kOOLogException
Definition OOLogging.m:600
NSString *const kOOLogInconsistentState
Definition OOLogging.m:599
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
#define OOLogOutdentIf(class)
Definition OOLogging.h:112
void OOLogOutdent(void)
Definition OOLogging.m:354
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OOExtraLog
Definition OOLogging.h:166
NSString *const kOOLogParameterError
Definition OOLogging.m:596
#define OOLogIndentIf(class)
Definition OOLogging.h:107
void OOLogIndent(void)
Definition OOLogging.m:345
#define ABS(A)
Definition OOMaths.h:97
double OOHPScalar
Definition OOMaths.h:51
#define M_SQRT1_2
Definition OOMaths.h:75
#define MAX(A, B)
Definition OOMaths.h:94
#define MIN(A, B)
Definition OOMaths.h:91
GLfloat OOScalar
Definition OOMaths.h:49
#define M_PI
Definition OOMaths.h:54
OOINLINE OOMatrix OOMatrixForScale(OOScalar sx, OOScalar sy, OOScalar sz) INLINE_CONST_FUNC
Definition OOMatrix.h:264
const OOMatrix kIdentityMatrix
Definition OOMatrix.m:28
OOINLINE OOMatrix OOMatrixFromBasisVectors(Vector i, Vector j, Vector k) INLINE_CONST_FUNC
Definition OOMatrix.h:185
Vector OOVectorMultiplyMatrix(Vector v, OOMatrix m) CONST_FUNC
Definition OOMatrix.m:121
OOMatrix OOMatrixMultiply(OOMatrix a, OOMatrix b) CONST_FUNC
Definition OOMatrix.m:105
@ MOUSE_MODE_UI_SCREEN_WITH_INTERACTION
@ kOOMusicOn
@ kOOMusicITunes
@ kOOMusicOff
void OOGLLoadModelView(OOMatrix matrix)
void OOGLLookAt(Vector eye, Vector center, Vector up)
OOMatrix OOGLGetModelView(void)
void OOGLPushModelView(void)
void OOGLResetModelView(void)
void OOGLTranslateModelView(Vector vector)
void OOGLFrustum(double left, double right, double bottom, double top, double near, double far)
void OOGLMultModelView(OOMatrix matrix)
OOMatrix OOGLGetModelViewProjection(void)
OOMatrix OOGLPopModelView(void)
void OOGLResetProjection(void)
OOShaderSetting
Definition OOOpenGL.h:33
@ OPENGL_STATE_OVERLAY
Definition OOOpenGL.h:124
@ OPENGL_STATE_OPAQUE
Definition OOOpenGL.h:121
#define OOGLProgramName(handle)
Definition OOOpenGL.h:44
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
BOOL OOCheckOpenGLErrors(NSString *format,...)
Definition OOOpenGL.m:38
void GLScaledLineWidth(GLfloat width)
Definition OOOpenGL.m:206
#define OOSetOpenGLState(STATE)
Definition OOOpenGL.h:132
#define OOGL(statement)
Definition OOOpenGL.h:262
unsigned count
return nil
Quaternion quaternion_rotation_between(Vector v0, Vector v1) CONST_FUNC
Vector vector_forward_from_quaternion(Quaternion quat) CONST_FUNC
void basis_vectors_from_quaternion(Quaternion quat, Vector *outRight, Vector *outUp, Vector *outForward)
OOINLINE Quaternion make_quaternion(OOScalar qw, OOScalar qx, OOScalar qy, OOScalar qz) INLINE_CONST_FUNC
void quaternion_rotate_about_axis(Quaternion *quat, Vector axis, OOScalar angle) NONNULL_FUNC
const Quaternion kIdentityQuaternion
OOINLINE void quaternion_normalize(Quaternion *quat) NONNULL_FUNC ALWAYS_INLINE_FUNC
void quaternion_rotate_about_y(Quaternion *quat, OOScalar angle) NONNULL_FUNC
void quaternion_set_random(Quaternion *quat) NONNULL_FUNC
NSString * OOShipLibraryCategorySingular(NSString *category)
NSString * OOShipLibraryWitchspace(ShipEntity *demo_ship)
NSString * OOShipLibraryTurrets(ShipEntity *demo_ship)
NSString * OOShipLibraryShields(ShipEntity *demo_ship)
NSString * OOShipLibraryCargo(ShipEntity *demo_ship)
NSString * OOShipLibraryCategoryPlural(NSString *category)
static NSString *const kOODemoShipClass
NSString * OOShipLibraryGenerator(ShipEntity *demo_ship)
static NSString *const kOODemoShipShipData
NSString * OOShipLibrarySize(ShipEntity *demo_ship)
NSString * OOShipLibrarySpeed(ShipEntity *demo_ship)
static NSString *const kOODemoShipKey
NSString * OOShipLibraryWeapons(ShipEntity *demo_ship)
NSString * OOShipLibraryTurnRate(ShipEntity *demo_ship)
#define OOExpandKey(key,...)
#define OOExpand(string,...)
NSMutableArray * ScanTokensFromString(NSString *values)
@ OO_SYSTEMCONCEALMENT_NOTHING
@ OO_SYSTEMCONCEALMENT_NONAME
#define GL_CLAMP_TO_EDGE
@ MIN_ENTITY_UID
Definition OOTypes.h:170
@ MAX_ENTITY_UID
Definition OOTypes.h:171
@ UNIVERSE_MAX_ENTITIES
Definition OOTypes.h:168
@ NO_TARGET
Definition OOTypes.h:169
@ kOOMinimumSystemID
Definition OOTypes.h:188
uint8_t OOWeaponFacingSet
Definition OOTypes.h:204
NSString * OOCommodityType
Definition OOTypes.h:97
OORouteType
Definition OOTypes.h:31
@ OPTIMIZED_BY_TIME
Definition OOTypes.h:34
OOGraphicsDetail
Definition OOTypes.h:208
@ DETAIL_LEVEL_EXTRAS
Definition OOTypes.h:212
@ DETAIL_LEVEL_SHADERS
Definition OOTypes.h:211
@ DETAIL_LEVEL_MAXIMUM
Definition OOTypes.h:214
@ DETAIL_LEVEL_MINIMUM
Definition OOTypes.h:209
OOViewID
Definition OOTypes.h:39
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
uint16_t OOUniversalID
Definition OOTypes.h:165
#define VALID_WEAPON_FACINGS
Definition OOTypes.h:206
NSUInteger OOTechLevelID
Definition OOTypes.h:177
int16_t OOSystemID
Definition OOTypes.h:183
@ CARGO_SCRIPTED_ITEM
Definition OOTypes.h:67
uint8_t OOGalaxyID
Definition OOTypes.h:182
uint32_t OOCargoQuantity
Definition OOTypes.h:155
OOMassUnit
Definition OOTypes.h:111
@ UNITS_TONS
Definition OOTypes.h:112
@ UNITS_GRAMS
Definition OOTypes.h:114
@ UNITS_KILOGRAMS
Definition OOTypes.h:113
double OOTimeDelta
Definition OOTypes.h:193
uint8_t OOGovernmentID
Definition OOTypes.h:179
double OOTimeAbsolute
Definition OOTypes.h:192
OOWeaponFacing
Definition OOTypes.h:195
@ WEAPON_FACING_FORWARD
Definition OOTypes.h:196
@ WEAPON_FACING_NONE
Definition OOTypes.h:201
@ WEAPON_FACING_AFT
Definition OOTypes.h:197
@ WEAPON_FACING_PORT
Definition OOTypes.h:198
@ WEAPON_FACING_STARBOARD
Definition OOTypes.h:199
uint8_t OOEconomyID
Definition OOTypes.h:180
OOINLINE Vector vector_flip(Vector v) INLINE_CONST_FUNC
Definition OOVector.h:227
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:242
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
OOINLINE OOScalar dot_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:299
const Vector kZeroVector
Definition OOVector.m:27
const Vector kBasisYVector
Definition OOVector.h:46
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 OOScalar distance(Vector v1, Vector v2) INLINE_CONST_FUNC
Definition OOVector.h:280
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
@ OOSPEECHSETTINGS_ALL
@ OOSPEECHSETTINGS_OFF
@ OOSPEECHSETTINGS_COMMS
#define PLAYER
OOEquipmentType * OOWeaponType
Definition ShipEntity.h:164
BOOL isWeaponNone(OOWeaponType weapon)
#define MAX_JUMP_RANGE
Definition ShipEntity.h:109
#define ENTITY_PERSONALITY_MAX
Definition ShipEntity.h:112
NSString * OOEquipmentIdentifierFromWeaponType(OOWeaponType weapon) CONST_FUNC
OOWeaponType OOWeaponTypeFromEquipmentIdentifierSloppy(NSString *string) PURE_FUNC
#define ShipScriptEvent(context, ship, event,...)
#define SUN_SKIM_RADIUS_FACTOR
Definition Universe.h:104
@ OO_POSTFX_ENDOFLIST
Definition Universe.h:92
@ OO_POSTFX_COLORBLINDNESS_TRITAN
Definition Universe.h:86
@ OO_POSTFX_NONE
Definition Universe.h:83
@ OO_POSTFX_CRTBADSIGNAL
Definition Universe.h:91
@ OO_POSTFX_CLOAK
Definition Universe.h:87
#define TIME_ACCELERATION_FACTOR_DEFAULT
Definition Universe.h:157
#define UNIVERSE
Definition Universe.h:827
#define PASSENGER_BERTH_SPACE
Definition Universe.h:143
#define BILLBOARD_DEPTH
Definition Universe.h:154
#define KEY_CHANCE
Definition Universe.h:124
#define MIN_DISTANCE_TO_BUOY
Definition Universe.h:162
#define DESC(key)
Definition Universe.h:832
#define DEMO_LIGHT_POSITION
Definition Universe.h:160
#define DESC_PLURAL(key, count)
Definition Universe.h:833
#define OOLITE_EXCEPTION_FATAL
Definition Universe.h:150
#define TIME_ACCELERATION_FACTOR_MAX
Definition Universe.h:158
NSString * OOLookUpDescriptionPRIV(NSString *key)
Definition Universe.m:10069
#define SAFE_ADDITION_FACTOR2
Definition Universe.h:102
NSString * OOLookUpPluralDescriptionPRIV(NSString *key, NSInteger count)
Definition Universe.m:10078
NSComparisonResult populatorPrioritySort(id a, id b, void *context)
Definition Universe.m:9994
NSComparisonResult equipmentSortOutfitting(id a, id b, void *context)
Definition Universe.m:10038
#define KEY_TECHLEVEL
Definition Universe.h:107
NSComparisonResult equipmentSort(id a, id b, void *context)
Definition Universe.m:10007
#define KEY_RADIUS
Definition Universe.h:115
#define KEY_NAME
Definition Universe.h:116
#define SYSTEM_REPOPULATION_INTERVAL
Definition Universe.h:167
#define OOLITE_EXCEPTION_DATA_NOT_FOUND
Definition Universe.h:149
BOOL(* EntityFilterPredicate)(Entity *entity, void *parameter)
Definition Universe.h:51
#define DOCKED_ILLUM_LEVEL
Definition Universe.m:273
const GLfloat framebufferQuadVertices[]
Definition Universe.m:119
static const OOMatrix fwd_matrix
Definition Universe.m:4181
#define SKY_AMBIENT_ADJUSTMENT
Definition Universe.m:282
static GLfloat docked_light_specular[4]
Definition Universe.m:276
static NSString *const kOOLogUniversePopulateWitchspace
Definition Universe.m:115
static const OOMatrix port_matrix
Definition Universe.m:4189
Universe * gSharedUniverse
Definition Universe.m:131
static const OOMatrix starboard_matrix
Definition Universe.m:4193
#define SUN_AMBIENT_INFLUENCE
Definition Universe.m:280
static int JSResetFlags
Definition Universe.m:264
static BOOL MaintainLinkedLists(Universe *uni)
static OOComparisonResult compareName(id dict1, id dict2, void *context)
static BOOL demo_light_on
Definition Universe.m:268
static const OOMatrix aft_matrix
Definition Universe.m:4185
static NSString *const kOOLogEntityVerificationRebuild
Definition Universe.m:117
static BOOL object_light_on
Definition Universe.m:267
Entity * gOOJSPlayerIfStale
Definition Universe.m:134
static GLfloat docked_light_ambient[4]
Definition Universe.m:274
#define DEMO2_FLY_IN_STAGE_TIME
Definition Universe.m:107
static GLfloat sun_off[4]
Definition Universe.m:269
#define LANE_WIDTH
Definition Universe.m:112
@ DEMO_FLY_IN
Definition Universe.m:101
@ DEMO_FLY_OUT
Definition Universe.m:103
@ DEMO_SHOW_THING
Definition Universe.m:102
static NSString *const kOOLogUniversePopulateError
Definition Universe.m:114
#define DEMO2_VANISHING_DISTANCE
Definition Universe.m:106
const GLuint framebufferQuadIndices[]
Definition Universe.m:126
static GLfloat docked_light_diffuse[4]
Definition Universe.m:275
static GLfloat demo_light_position[4]
Definition Universe.m:270
#define DOCKED_AMBIENT_LEVEL
Definition Universe.m:272
OOINLINE BOOL EntityInRange(HPVector p1, Entity *e2, float range)
static OOComparisonResult comparePrice(id dict1, id dict2, void *context)
NSDictionary * demoShipData()
Definition Universe.m:3057
void drawTargetTextureIntoDefaultFramebuffer()
Definition Universe.m:598
void verifyEntitySessionIDs()
Definition Universe.m:9354
void setLibraryTextForDemoShip()
Definition Universe.m:3062
void prepareToRenderIntoDefaultFramebuffer()
Definition Universe.m:4782
float randomDistanceWithinScanner()
Definition Universe.m:9517
void populateSpaceFromActiveWormholes()
Definition Universe.m:9676
void setGuiToIntroFirstGo:(BOOL justCobra)
Definition AI.h:35
void setNextThinkTime:(OOTimeAbsolute ntt)
Definition AI.m:581
void setOwner:(ShipEntity *ship)
Definition AI.m:175
OOTimeDelta thinkTimeInterval
Definition AI.m:599
void setState:(NSString *stateName)
Definition AI.m:303
OOTimeAbsolute nextThinkTime
Definition AI.m:586
void think()
Definition AI.m:514
void reactToMessage:context:(NSString *message,[context] NSString *debugContext)
Definition AI.m:363
NSString * collisionDescription()
BOOL checkEntity:(Entity *ent)
void setDustColor:(OOColor *color)
Definition DustEntity.m:127
unsigned isImmuneToBreakPatternHide
Definition Entity.m:1050
void setAtmosphereFogging:(OOColor *fogging)
Definition Entity.m:990
void removeFromLinkedLists()
Definition Entity.m:269
GLfloat collision_radius
Definition Entity.h:107
void drawImmediate:translucent:(bool immediate,[translucent] bool translucent)
Definition Entity.m:894
void setUniversalID:(OOUniversalID uid)
Definition Entity.m:517
OOUniversalID universalID
Definition Entity.m:522
Entity * z_next
Definition Entity.h:118
void setThrowSparks:(BOOL value)
Definition Entity.m:532
void setVelocity:(Vector vel)
Definition Entity.m:703
Entity * z_previous
Definition Entity.h:118
Quaternion orientation
Definition Entity.m:682
void updateCameraRelativePosition()
Definition Entity.m:622
int zero_index
Definition Entity.h:113
void setOrientation:(Quaternion quat)
Definition Entity.m:676
void update:(OOTimeDelta delta_t)
Definition Entity.m:850
GLfloat zero_distance
Definition Entity.h:104
unsigned collisionTestFilter
Definition Entity.h:96
GLfloat collisionRadius()
Definition Entity.m:830
Entity * x_previous
Definition Entity.h:116
void wasRemovedFromUniverse()
Definition Entity.m:494
void setLastDrawCounter:(NSUInteger drawCounter)
Definition Entity.m:968
void setScanClass:(OOScanClass sClass)
Definition Entity.m:738
Vector cameraRelativePosition
Definition Entity.m:581
OOEntityStatus status()
Definition Entity.m:733
void setPositionX:y:z:(OOHPScalar x,[y] OOHPScalar y,[z] OOHPScalar z)
Definition Entity.m:614
void updateLinkedLists()
Definition Entity.m:393
BoundingBox boundingBox
Definition Entity.m:666
unsigned isStation
Definition Entity.m:135
HPVector position
Definition Entity.m:576
BOOL canCollide()
Definition Entity.m:825
HPVector absolutePositionForSubentityOffset:(HPVector offset)
Definition Entity.m:632
GLfloat cameraRangeBack()
Definition Entity.m:591
void setEnergy:(GLfloat amount)
Definition Entity.m:748
Entity * x_next
Definition Entity.h:116
Quaternion normalOrientation()
Definition Entity.m:687
BOOL isStellarObject()
Definition Entity.m:165
ShipEntity * parentEntity()
Definition Entity.m:553
unsigned isExplicitlyNotMainStation
Definition Entity.h:99
void addToLinkedLists()
Definition Entity.m:207
Entity * collision_chain
Definition Entity.h:120
void setStatus:(OOEntityStatus stat)
Definition Entity.m:728
Entity * y_next
Definition Entity.h:117
Entity * y_previous
Definition Entity.h:117
GLfloat mass
Definition Entity.m:671
void setPosition:(HPVector posn)
Definition Entity.m:608
void setMouseInteractionModeForUIWithMouseInteraction:(BOOL interaction)
GameController * sharedController()
void setGamePaused:(BOOL value)
void logProgress:(NSString *message)
void exitAppWithContext:(NSString *context)
void setMouseInteractionModeForFlight()
void setPlayerFileToLoad:(NSString *filename)
BOOL inFullScreenMode()
void setTextColor:(OOColor *color)
void printLineNoScroll:align:color:fadeTime:key:addToArray:(NSString *str,[align] OOGUIAlignment alignment,[color] OOColor *text_color,[fadeTime] float text_fade,[key] NSString *text_key,[addToArray] NSMutableArray *text_array)
OOColor * textColor
NSDictionary * userSettings()
void setBackgroundColor:(OOColor *color)
void printLongText:align:color:fadeTime:key:addToArray:(NSString *str,[align] OOGUIAlignment alignment,[color] OOColor *text_color,[fadeTime] float text_fade,[key] NSString *text_key,[addToArray] NSMutableArray *text_array)
int drawGUI:drawCursor:(GLfloat alpha,[drawCursor] BOOL drawCursor)
void setAlpha:(GLfloat an_alpha)
OOColor * textCommsColor
void fadeOutFromTime:overDuration:(OOTimeAbsolute now_time,[overDuration] OOTimeDelta duration)
void setLineWidth:(GLfloat value)
NSString * deferredHudName
void setOverallAlpha:(GLfloat newAlphaValue)
GLfloat overallAlpha
void setFov:fromFraction:(float value,[fromFraction] BOOL fromFraction)
NSSize backingViewSize()
float fov:(BOOL inFraction)
void setMsaa:(BOOL newMsaa)
OOSDRToneMapper sdrToneMapper()
GameController * gameController
OOAsyncWorkManager * sharedAsyncWorkManager()
void setInnerColor:outerColor:(OOColor *color1,[outerColor] OOColor *color2)
void setLifetime:(double lifetime)
instancetype breakPatternWithPolygonSides:startAngle:aspectRatio:(NSUInteger sides,[startAngle] float startAngleDegrees,[aspectRatio] float aspectRatio)
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
OOCacheManager * sharedCache()
OOCharacter * randomCharacterWithRole:andOriginalSystem:(NSString *c_role,[andOriginalSystem] OOSystemID s)
Definition OOCharacter.m:94
OOColor * colorWithRed:green:blue:alpha:(float red,[green] float green,[blue] float blue,[alpha] float alpha)
Definition OOColor.m:107
OOColor * brightColorWithDescription:(id description)
Definition OOColor.m:202
OOColor * colorWithDescription:(id description)
Definition OOColor.m:135
OOColor * greenColor()
Definition OOColor.m:264
void getRed:green:blue:alpha:(float *red,[green] float *green,[blue] float *blue,[alpha] float *alpha)
Definition OOColor.m:344
OOColor * whiteColor()
Definition OOColor.m:249
OOColor * colorWithHue:saturation:brightness:alpha:(float hue,[saturation] float saturation,[brightness] float brightness,[alpha] float alpha)
Definition OOColor.m:100
OOColor * yellowColor()
Definition OOColor.m:279
OOColor * blendedColorWithFraction:ofColor:(float fraction,[ofColor] OOColor *color)
Definition OOColor.m:309
NSString * getRandomCommodity()
OOCommodityMarket * generateMarketForSystemWithEconomy:andScript:(OOEconomyID economy,[andScript] NSString *scriptName)
OOMassUnit massUnitForGood:(NSString *good)
OOMassUnit massUnitForGood:(OOCommodityType good)
OOCargoQuantity quantityForGood:(OOCommodityType good)
NSDictionary * definitionForGood:(OOCommodityType good)
NSString * nameForGood:(OOCommodityType good)
NSString * conditionScript()
OOTechLevelID techLevel()
OOEquipmentType * equipmentTypeWithIdentifier:(NSString *identifier)
OOCreditsQuantity price()
instancetype explosionCloudFromEntity:withSettings:(Entity *entity,[withSettings] NSDictionary *settings)
instancetype laserFlashWithPosition:velocity:color:(HPVector position,[velocity] Vector vel,[color] OOColor *color)
OOGraphicsResetManager * sharedManager()
void runCallback:(HPVector location)
BOOL callMethod:inContext:withArguments:count:result:(jsid methodID,[inContext] JSContext *context,[withArguments] jsval *argv,[count] intN argc,[result] jsval *outResult)
Definition OOJSScript.m:328
OOJavaScriptEngine * sharedEngine()
void garbageCollectionOpportunity:(BOOL force)
void setUp()
Definition OOMaterial.m:36
OOOpenGLExtensionManager * sharedManager()
instancetype shrinkingRingFromEntity:(Entity *sourceEntity)
instancetype ringFromEntity:(Entity *sourceEntity)
id jsScriptFromFileNamed:properties:(NSString *fileName,[properties] NSDictionary *properties)
Definition OOScript.m:177
instancetype groupWithName:(NSString *name)
Definition OOShipGroup.m:94
NSDictionary * shipyardInfoForKey:(NSString *key)
NSArray * playerShipKeys()
OOProbabilitySet * probabilitySetForRole:(NSString *role)
NSString * randomShipKeyForRole:(NSString *role)
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
NSArray * demoShipKeys()
NSDictionary * effectInfoForKey:(NSString *key)
id initWithSound:(OOSound *inSound)
void playSound:(OOSound *inSound)
float masterVolume()
Definition OOALSound.m:75
id soundWithCustomSoundKey:(NSString *key)
Definition Universe.m:9950
void setRadius:andCorona:(GLfloat rad,[andCorona] GLfloat corona)
void drawDirectVisionSunGlare()
double radius()
BOOL changeSunProperty:withDictionary:(NSString *key,[withDictionary] NSDictionary *dict)
void setPosition:(HPVector posn)
void getSpecularComponents:(GLfloat[4] components)
void getDiffuseComponents:(GLfloat[4] components)
void drawStarGlare()
BOOL setSunColor:(OOColor *sun_color)
Definition OOSunEntity.m:59
NSDictionary * getPropertiesForSystemKey:(NSString *key)
NSPoint getCoordinatesForSystem:inGalaxy:(OOSystemID s,[inGalaxy] OOGalaxyID g)
id getProperty:forSystem:inGalaxy:(NSString *property,[forSystem] OOSystemID s,[inGalaxy] OOGalaxyID g)
void setProperty:forSystemKey:andLayer:toValue:fromManifest:(NSString *property,[forSystemKey] NSString *key,[andLayer] OOSystemLayer layer,[toValue] id value,[fromManifest] NSString *manifest)
NSArray * getNeighbourIDsForSystem:inGalaxy:(OOSystemID s,[inGalaxy] OOGalaxyID g)
NSDictionary * getPropertiesForSystem:inGalaxy:(OOSystemID s,[inGalaxy] OOGalaxyID g)
void clearCache()
Definition OOTexture.m:335
instancetype waypointWithDictionary:(NSDictionary *info)
void setBounty:withReason:(OOCreditsQuantity amount, [withReason] OOLegalStatusReason reason)
void setSystemID:(OOSystemID sid)
void setGuiToStatusScreen()
void setRandom_factor:(int rf)
Vector weaponViewOffset()
OOGalaxyID galaxyNumber()
void setWormhole:(WormholeEntity *newWormhole)
BOOL setUpShipFromDictionary:(NSDictionary *shipDict)
StationEntity * dockedStation()
void setShowDemoShips:(BOOL value)
Quaternion normalOrientation()
BOOL switchHudTo:(NSString *hudFileName)
BOOL doWorldEventUntilMissionScreen:(OOJSPropID message)
void addScannedWormhole:(WormholeEntity *wormhole)
void addToAdjustTime:(double seconds)
NSPoint galaxy_coordinates
NSMutableArray * commLog
unsigned showDemoShips
void setGalaxyCoordinates:(NSPoint newPosition)
HeadUpDisplay * hud
void runUnsanitizedScriptActions:allowingAIMethods:withContextName:forTarget:(NSArray *unsanitizedActions,[allowingAIMethods] BOOL allowAIMethods,[withContextName] NSString *contextName,[forTarget] ShipEntity *target)
void setJumpCause:(NSString *value)
void setDockedAtMainStation()
void setPreviousSystemID:(OOSystemID sid)
OOMatrix customViewMatrix
Vector customViewUpVector
Vector customViewForwardVector
Vector viewpointOffset()
OOSystemID systemID()
GLfloat baseMass()
NSString * jumpCause()
NSString * dial_clock_adjusted()
PlayerEntity * sharedPlayer()
OOSystemID targetSystemID()
NSString * builtInPath()
OOSound * ooSoundNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
NSDictionary * dictionaryFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)
NSArray * arrayFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)
BOOL writeDiagnosticData:toFileNamed:(NSData *data,[toFileNamed] NSString *name)
OOSystemDescriptionManager * systemDescriptionManager()
void setUseAddOns:(NSString *useAddOns)
NSDictionary * roleCategoriesDictionary()
NSDictionary * dictionaryFromFilesNamed:inFolder:mergeMode:cache:(NSString *fileName,[inFolder] NSString *folderName,[mergeMode] OOResourceMergeMode mergeMode,[cache] BOOL useCache)
OOSystemID parent()
Definition Universe.m:178
OOSystemID _location
Definition Universe.m:147
double distance()
Definition Universe.m:190
OOSystemID _parent
Definition Universe.m:147
double _time
Definition Universe.m:148
double _cost
Definition Universe.m:148
OOSystemID location()
Definition Universe.m:182
instancetype elementWithLocation:parent:cost:distance:time:jumps:(OOSystemID location,[parent] OOSystemID parent,[cost] double cost,[distance] double distance,[time] double time,[jumps] int jumps)
Definition Universe.m:164
double cost()
Definition Universe.m:186
double _distance
Definition Universe.m:148
double time()
Definition Universe.m:194
void setDemoStartTime:(OOTimeAbsolute time)
void doScriptEvent:(OOJSPropID message)
void setIsWreckage:(BOOL isw)
void setBounty:withReason:(OOCreditsQuantity amount,[withReason] OOLegalStatusReason reason)
NSDictionary * shipInfoDictionary()
void removeEquipmentItem:(NSString *equipmentKey)
void setFuel:(OOFuelQuantity amount)
void rescaleBy:writeToCache:(GLfloat factor, [writeToCache] BOOL writeToCache)
void setStatus:(OOEntityStatus stat)
GLfloat weaponRange
void setCargoFlag:(OOCargoFlag flag)
BOOL witchspaceLeavingEffects()
void setRoll:(double amount)
void performTumble()
void setDestination:(HPVector dest)
NSString * shipDataKey()
void setGroup:(OOShipGroup *group)
NSString * primaryRole
void setSubEntityTakingDamage:(ShipEntity *sub)
NSArray * portWeaponOffset
GLfloat doesHitLine:v1:hitEntity:(HPVector v0,[v1] HPVector v1,[hitEntity] ShipEntity **hitEntity)
void setPrimaryRole:(NSString *role)
NSArray * starboardWeaponOffset
void setHeatInsulation:(GLfloat value)
OOScanClass scanClass()
void leaveWitchspace()
void setPitch:(double amount)
BOOL isHostileTo:(Entity *entity)
void setAITo:(NSString *aiString)
void enterTargetWormhole()
NSArray * aftWeaponOffset
NSArray * forwardWeaponOffset
void setPendingEscortCount:(uint8_t count)
HPVector destination()
Vector velocity()
uint8_t pendingEscortCount()
void setTemperature:(GLfloat value)
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
void setCrew:(NSArray *crewArray)
void setDemoShip:(OOScalar demoRate)
void switchAITo:(NSString *aiString)
void setCommodity:andAmount:(OOCommodityType co_type,[andAmount] OOCargoQuantity co_amount)
GLfloat maxFlightSpeed
OOCommodityType commodityType()
BOOL changeProperty:withDictionary:(NSString *key,[withDictionary] NSDictionary *dict)
Definition SkyEntity.m:150
OOColor * skyColor
Definition SkyEntity.m:145
OOCommodityMarket * localMarket
void setAllowsFastDocking:(BOOL newValue)
OOCommodityMarket * initialiseLocalMarket()
void setRequiresDockingClearance:(BOOL newValue)
void setEquivalentTechLevel:(OOTechLevelID value)
void setLocalMarket:(NSArray *market)
unsigned interstellarUndockingAllowed
void setPlanet:(OOPlanetEntity *planet)
void setLocalShipyard:(NSArray *market)
void setAllegiance:(NSString *newAllegiance)
BOOL role:isInCategory:(NSString *role,[isInCategory] NSString *category)
Definition Universe.m:2808
OOSystemID findSystemNumberAtCoords:withGalaxy:includingHidden:(NSPoint coords,[withGalaxy] OOGalaxyID gal,[includingHidden] BOOL hidden)
Definition Universe.m:7697
OOGraphicsDetail detailLevel
Definition Universe.m:9046
Random_Seed marketSeed()
Definition Universe.m:8077
HPVector legacyPositionFrom:asCoordinateSystem:(HPVector pos,[asCoordinateSystem] NSString *system)
Definition Universe.m:2169
unsigned n_entities
Definition Universe.h:181
void setTimeAccelerationFactor:(double newTimeAccelerationFactor)
Definition Universe.m:6702
NSDictionary * commodityDataForType:(OOCommodityType type)
Definition Universe.m:3998
void populateNormalSpace()
Definition Universe.m:1622
OOWeakReference * _firstBeacon
Definition Universe.h:210
Entity< OOBeaconEntity > * lastBeacon()
Definition Universe.m:3419
void setDetailLevelDirectly:(OOGraphicsDetail value)
Definition Universe.m:9020
NSMutableDictionary * conditionScripts
Definition Universe.h:338
Entity * firstEntityTargetedByPlayerPrecisely()
Definition Universe.m:5723
BOOL useShaders()
Definition Universe.m:9051
OOGalaxyID galaxyID
Definition Universe.h:272
OOSunEntity * sun()
Definition Universe.m:3345
NSArray * demo_ships
Definition Universe.h:246
static BOOL MaintainLinkedLists(Universe *uni)
Definition Universe.m:4867
void pauseGame()
Definition Universe.m:997
OOTimeDelta getTimeDelta()
Definition Universe.m:6033
static OOComparisonResult compareName(id dict1, id dict2, void *context)
Definition Universe.m:8517
BOOL _autoMessageLogBg
Definition Universe.h:343
unsigned countShipsMatchingPredicate:parameter:inRange:ofEntity:(EntityFilterPredicate predicate,[parameter] void *parameter,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5839
OOSystemID systemID
Definition Universe.h:273
ShipEntity * newShipWithName:usePlayerProxy:isSubentity:(NSString *shipKey,[usePlayerProxy] BOOL usePlayerProxy,[isSubentity] BOOL OO_RETURNS_RETAINED)
Definition Universe.m:3704
void deleteOpenGLObjects()
Definition Universe.m:529
void setUpUniverseFromWitchspace()
Definition Universe.m:1162
void resetCommsLogColor()
Definition Universe.m:8957
BOOL * systemsFound()
Definition Universe.m:7777
BOOL reducedDetail()
Definition Universe.m:9014
NSString * collisionDescription()
Definition Universe.m:6056
BOOL autoSaveNow
Definition Universe.m:8998
BOOL _doingStartUp
Definition Universe.h:347
OOINLINE BOOL EntityInRange(HPVector p1, Entity *e2, float range)
Definition Universe.m:5862
BOOL autoMessageLogBg()
Definition Universe.m:9213
void setDockingClearanceProtocolActive:(BOOL newValue)
Definition Universe.m:2941
NSString * system_repopulator
Definition Universe.h:293
OOTimeAbsolute demo_start_time
Definition Universe.h:241
OOSystemID targetSystemID
Definition Universe.h:274
void setLighting()
Definition Universe.m:1879
BOOL ECMVisualFXEnabled
Definition Universe.m:6707
NSString * system_names[256]
Definition Universe.h:276
void setUpSpace()
Definition Universe.m:1334
NSString * useAddOns
Definition Universe.m:943
unsigned countShipsWithRole:inRange:ofEntity:(NSString *role,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5770
NSString * defaultAIForRole:(NSString *role)
Definition Universe.m:3822
GLfloat sun_diffuse[4]
Definition Universe.h:194
id nearestEntityMatchingPredicate:parameter:relativeToEntity:(EntityFilterPredicate predicate,[parameter] void *parameter,[relativeToEntity] Entity *entity)
Definition Universe.m:5978
void selectIntro2Previous()
Definition Universe.m:3261
GuiDisplayGen * messageGUI()
Definition Universe.m:8939
void forceWitchspaceEntries()
Definition Universe.m:2818
NSUInteger demo_ship_index
Definition Universe.h:244
BOOL dockingClearanceProtocolActive()
Definition Universe.m:2936
Entity * y_list_start
Definition Universe.h:186
NSDictionary * customSounds
Definition Universe.h:256
BOOL doProcedurallyTexturedPlanets
Definition Universe.m:932
void setPauseMessageVisible:(BOOL value)
Definition Universe.m:9198
OOCreditsQuantity getEquipmentPriceForKey:(NSString *eq_key)
Definition Universe.m:3835
static void VerifyDescArray(NSString *key, NSArray *desc)
Definition Universe.m:7226
NSDictionary * currentSystemData()
Definition Universe.m:7357
NSDictionary * descriptions()
Definition Universe.m:7202
OOCommodities * commodities
Definition Universe.m:3848
void getActiveViewMatrix:forwardVector:upVector:(OOMatrix *outMatrix, [forwardVector] Vector *outForward, [upVector] Vector *outUp)
Definition Universe.m:4198
void showCommsLog:(OOTimeDelta how_long)
Definition Universe.m:6393
NSArray * stations()
Definition Universe.m:3358
NSMutableSet * allStations
Definition Universe.h:287
NSDictionary * roleCategories
Definition Universe.h:265
GuiDisplayGen * comm_log_gui
Definition Universe.h:222
void setAirResistanceFactor:(GLfloat newFactor)
Definition Universe.m:9078
GLfloat sun_specular[4]
Definition Universe.h:195
void removeAllEntitiesExceptPlayer()
Definition Universe.m:5155
void setWitchspaceBreakPattern:(BOOL newValue)
Definition Universe.m:2931
OOTimeAbsolute getTime()
Definition Universe.m:6028
NSUInteger demo_ship_subindex
Definition Universe.h:245
NSDictionary * gameSettings()
Definition Universe.m:4069
BOOL doRemoveEntity:(Entity *entity)
Definition Universe.m:9545
void handleOoliteException:(NSException *ooliteException)
Definition Universe.m:9056
BOOL breakPatternHide()
Definition Universe.m:3516
GLuint targetFramebufferID
Definition Universe.h:356
NSDictionary * _descriptions
Definition Universe.h:255
void drawWatermarkString:(NSString *watermarkString)
Definition Universe.m:4831
void speakWithSubstitutions:(NSString *text)
Definition Universe.m:6295
ShipEntity * addShipAt:withRole:withinRadius:(HPVector pos,[withRole] NSString *role,[withinRadius] GLfloat radius)
Definition Universe.m:2608
void enterGUIViewModeWithMouseInteraction:(BOOL mouseInteraction)
Definition Universe.m:6138
ShipEntity * addShipWithRole:launchPos:rfactor:(NSString *desc, [launchPos] HPVector launchPos, [rfactor] GLfloat rfactor)
Definition Universe.m:1973
ShipEntity * newShipWithName:(NSString *OO_RETURNS_RETAINED)
Definition Universe.m:3793
NSArray * equipmentData
Definition Universe.m:7990
ShipEntity * newShipWithRole:(NSString *OO_RETURNS_RETAINED)
Definition Universe.m:3623
void drawTargetTextureIntoDefaultFramebuffer()
Definition Universe.m:598
int cursor_row
Definition Universe.h:183
void resetFramesDoneThisUpdate()
Definition Universe.m:4800
void setGalaxyTo:andReinit:(OOGalaxyID g,[andReinit] BOOL forced)
Definition Universe.m:7156
HPVector coordinatesFromCoordinateSystemString:(NSString *system_x_y_z)
Definition Universe.m:2273
int demo_stage
Definition Universe.h:243
static void VerifyDescString(NSString *key, NSString *desc)
Definition Universe.m:7218
BOOL doLinkedListMaintenanceThisUpdate
Definition Universe.h:315
NSArray * getStationMarkets()
Definition Universe.m:8119
NSDictionary * characters
Definition Universe.m:7294
void setMainLightPosition:(Vector sunPos)
Definition Universe.m:1965
void setUpSettings()
Definition Universe.m:9252
void setDisplayText:(BOOL value)
Definition Universe.m:8962
void quitGame()
Definition Universe.m:1024
NSMutableDictionary * waypoints
Definition Universe.h:212
void setECMVisualFXEnabled:(BOOL isEnabled)
Definition Universe.m:6712
int next_universal_id
Definition Universe.h:205
BOOL wasDisplayGUI
Definition Universe.h:225
OOTimeAbsolute demo_stage_time
Definition Universe.h:240
BOOL _pauseMessage
Definition Universe.h:340
BOOL no_update
Definition Universe.h:300
OOViewID viewDirection
Definition Universe.m:6069
void addMessage:forCount:forceDisplay:(NSString *text,[forCount] OOTimeDelta count,[forceDisplay] BOOL forceDisplay)
Definition Universe.m:6340
void populateSystemFromDictionariesWithSun:andPlanet:(OOSunEntity *sun,[andPlanet] OOPlanetEntity *planet)
Definition Universe.m:1707
NSUInteger sessionID()
Definition Universe.m:922
void addMessage:forCount:(NSString *text,[forCount] OOTimeDelta count)
Definition Universe.m:6290
BOOL deterministic_population
Definition Universe.h:294
BOOL _autoCommLog
Definition Universe.h:341
OOMatrix viewMatrix
Definition Universe.m:4805
void setUpUniverseFromStation()
Definition Universe.m:1088
void selectIntro2Next()
Definition Universe.m:3285
void verifyEntitySessionIDs()
Definition Universe.m:9354
NSMutableDictionary * populatorSettings
Definition Universe.h:291
NSDictionary * screenBackgrounds
Definition Universe.h:267
void unMagicMainStation()
Definition Universe.m:3368
unsigned countEntitiesMatchingPredicate:parameter:inRange:ofEntity:(EntityFilterPredicate predicate,[parameter] void *parameter,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5804
void setUpWitchspaceBetweenSystem:andSystem:(OOSystemID s1,[andSystem] OOSystemID s2)
Definition Universe.m:1234
NSDictionary * globalSettings
Definition Universe.m:7985
GuiDisplayGen * message_gui
Definition Universe.h:221
BOOL addShips:withRole:intoBoundingBox:(int howMany,[withRole] NSString *desc,[intoBoundingBox] BoundingBox bbox)
Definition Universe.m:2405
OOJSScript * getConditionScript:(NSString *scriptname)
Definition Universe.m:9941
OOSunEntity * cachedSun
Definition Universe.h:285
static BOOL IsCandidateMainStationPredicate(Entity *entity, void *parameter)
Definition Universe.m:3291
void lightForEntity:(BOOL isLit)
Definition Universe.m:4149
void dumpCollisions()
Definition Universe.m:6064
void allShipsDoScriptEvent:andReactToAIMessage:(OOJSPropID event,[andReactToAIMessage] NSString *message)
Definition Universe.m:8906
HPVector getWitchspaceExitPosition()
Definition Universe.m:8775
NSUInteger _sessionID
Definition Universe.h:191
BOOL system_found[256]
Definition Universe.h:277
NSMutableArray * findEntitiesMatchingPredicate:parameter:inRange:ofEntity:(EntityFilterPredicate predicate,[parameter] void *parameter,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5872
NSString * currentMessage
Definition Universe.h:216
CollisionRegion * universeRegion
Definition Universe.h:312
NSDictionary * generateSystemData:useCache:(OOSystemID s,[useCache] BOOL useCache)
Definition Universe.m:7343
NSArray * wormholes()
Definition Universe.m:3363
void setUpUniverseFromMisjump()
Definition Universe.m:1198
void drawMessage()
Definition Universe.m:4810
NSUInteger drawCounter
Definition Universe.h:319
NSDictionary * explosionSettings
Definition Universe.h:268
void clearSystemPopulator()
Definition Universe.m:1682
OOPlanetEntity * cachedPlanet
Definition Universe.h:284
OOMatrix activeViewMatrix()
Definition Universe.m:4241
NSSize targetFramebufferSize
Definition Universe.h:352
NSDictionary * getPopulatorSettings()
Definition Universe.m:1688
NSUInteger entityCount()
Definition Universe.m:964
NSMutableArray * activeWormholes
Definition Universe.h:308
void setGalaxyTo:(OOGalaxyID g)
Definition Universe.m:7151
ShipEntity * demo_ship
Definition Universe.h:281
void clearPreviousMessage()
Definition Universe.m:6235
NSMutableArray * entities
Definition Universe.h:208
NSMutableArray * findShipsMatchingPredicate:parameter:inRange:ofEntity:(EntityFilterPredicate predicate,[parameter] void *parameter,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5932
void setSystemTo:(OOSystemID s)
Definition Universe.m:7177
void setUpInitialUniverse()
Definition Universe.m:9482
void populateSpaceFromActiveWormholes()
Definition Universe.m:9676
void defineFrustum()
Definition Universe.m:4255
BOOL deterministicPopulation()
Definition Universe.m:1702
void prepareToRenderIntoDefaultFramebuffer()
Definition Universe.m:4782
void loadDescriptions()
Definition Universe.m:7271
BOOL reinitAndShowDemo:(BOOL showDemo)
Definition Universe.m:9378
OOPlanetEntity * setUpPlanet()
Definition Universe.m:1298
Entity * firstEntityTargetedByPlayer()
Definition Universe.m:5649
GLfloat skyClearColor[4]
Definition Universe.m:3497
NSString * getSystemName:(OOSystemID sys)
Definition Universe.m:7528
OOCommodityMarket * commodityMarket
Definition Universe.m:8000
OOPlanetEntity * planet()
Definition Universe.m:3337
void loadScenarios()
Definition Universe.m:7288
OOSystemDescriptionManager * systemManager
Definition Universe.m:7322
NSPoint findSystemCoordinatesWithPrefix:exactMatch:(NSString *p_fix,[exactMatch] BOOL exactMatch)
Definition Universe.m:7749
BOOL _permanentMessageLog
Definition Universe.h:344
BOOL inInterstellarSpace()
Definition Universe.m:7389
BOOL _witchspaceBreakPattern
Definition Universe.h:345
NSArray * closeSystems
Definition Universe.h:296
void loadConditionScripts()
Definition Universe.m:9916
static void PreloadOneSound(NSString *soundName)
Definition Universe.m:9646
NSArray * _scenarios
Definition Universe.h:258
void setViewDirection:(OOViewID vd)
Definition Universe.m:6074
ShipEntity * newShipWithName:usePlayerProxy:(NSString *shipKey,[usePlayerProxy] BOOL OO_RETURNS_RETAINED)
Definition Universe.m:3699
OOTimeDelta next_repopulation
Definition Universe.h:292
void setSystemDataForGalaxy:planet:key:value:fromManifest:forLayer:(OOGalaxyID gnum,[planet] OOSystemID pnum,[key] NSString *key,[value] id object,[fromManifest] NSString *manifest,[forLayer] OOSystemLayer layer)
Definition Universe.m:7401
ShipEntity * addWreckageFrom:withRole:at:scale:lifetime:(ShipEntity *ship,[withRole] NSString *wreckRole,[at] HPVector rpos,[scale] GLfloat scale,[lifetime] GLfloat lifetime)
Definition Universe.m:5497
GLuint msaaFramebufferID
Definition Universe.h:353
BOOL _bloom
Definition Universe.h:365
BOOL removeEntity:(Entity *entity)
Definition Universe.m:5128
OOTimeDelta time_delta
Definition Universe.h:238
void setCurrentPostFX:(int newCurrentPostFX)
Definition Universe.m:299
void removeDemoShips()
Definition Universe.m:5201
NSString * getSystemInhabitants:plural:(OOSystemID sys,[plural] BOOL plural)
Definition Universe.m:7548
BOOL dumpCollisionInfo
Definition Universe.h:250
Entity * sortedEntities[UNIVERSE_MAX_ENTITIES+1]
Definition Universe.h:180
GLfloat main_light_position[4]
Definition Universe.h:248
NSArray * addShipsAt:withRole:quantity:withinRadius:asGroup:(HPVector pos,[withRole] NSString *role,[quantity] unsigned count,[withinRadius] GLfloat radius,[asGroup] BOOL isGroup)
Definition Universe.m:2698
void setSkyColorRed:green:blue:alpha:(GLfloat red,[green] GLfloat green,[blue] GLfloat blue,[alpha] GLfloat alpha)
Definition Universe.m:3502
void showGUIMessage:withScroll:andColor:overDuration:(NSString *text,[withScroll] BOOL scroll,[andColor] OOColor *selectedColor,[overDuration] OOTimeDelta how_long)
Definition Universe.m:6400
BOOL _dockingClearanceProtocolActive
Definition Universe.h:346
void handleGameOver()
Definition Universe.m:2961
BOOL displayFPS
Definition Universe.m:8977
BOOL setUseAddOns:fromSaveGame:forceReinit:(NSString *newUse,[fromSaveGame] BOOL saveGame,[forceReinit] BOOL force)
Definition Universe.m:953
BOOL autoSave
Definition Universe.m:8988
static BOOL IsFriendlyStationPredicate(Entity *entity, void *parameter)
Definition Universe.m:3296
ShipEntity * firstShipHitByLaserFromShip:inDirection:offset:gettingRangeFound:(ShipEntity *srcEntity,[inDirection] OOWeaponFacing direction,[offset] Vector offset,[gettingRangeFound] GLfloat *range_ptr)
Definition Universe.m:5549
int breakPatternCounter
Definition Universe.h:279
ShipEntity * newShipWithName:usePlayerProxy:isSubentity:andScaleFactor:(NSString *shipKey,[usePlayerProxy] BOOL usePlayerProxy,[isSubentity] BOOL isSubentity,[andScaleFactor] float OO_RETURNS_RETAINED)
Definition Universe.m:3709
NSPoint coordinatesForSystem:(OOSystemID s)
Definition Universe.m:7562
void initTargetFramebufferWithViewSize:(NSSize viewSize)
Definition Universe.m:340
NSArray * neighboursToSystem:(OOSystemID system_number)
Definition Universe.m:7910
OOTimeAbsolute countdown_messageRepeatTime
Definition Universe.h:218
void setUpCargoPods()
Definition Universe.m:9338
void setGameView:(MyOpenGLView *view)
Definition Universe.m:4053
BOOL _permanentCommLog
Definition Universe.h:342
NSMutableSet * entitiesDeadThisUpdate
Definition Universe.h:317
NSArray * shipsForSaleForSystem:withTL:atTime:(OOSystemID s,[withTL] OOTechLevelID specialTL,[atTime] OOTimeAbsolute current_time)
Definition Universe.m:8145
HPVector locationByCode:withSun:andPlanet:(NSString *code,[withSun] OOSunEntity *sun,[andPlanet] OOPlanetEntity *planet)
Definition Universe.m:1783
int currentPostFX()
Definition Universe.m:294
NSString * getRandomCommodity()
Definition Universe.m:3972
GLfloat stars_ambient[4]
Definition Universe.h:188
void fillCargopodWithRandomCargo:(ShipEntity *cargopod)
Definition Universe.m:3960
void verifyDescriptions()
Definition Universe.m:7248
MyOpenGLView * gameView
Definition Universe.m:4059
BOOL doingStartUp()
Definition Universe.m:927
void startSpeakingString:(NSString *text)
Definition Universe.m:9086
GLfloat airResistanceFactor
Definition Universe.m:9073
NSString * randomShipKeyForRoleRespectingConditions:(NSString *role)
Definition Universe.m:3572
void repopulateSystem()
Definition Universe.m:6410
void addConditionScripts:(NSEnumerator *scripts)
Definition Universe.m:9928
double timeAccelerationFactor()
Definition Universe.m:6697
NSDictionary * autoAIMap
Definition Universe.h:266
BOOL addEntity:(Entity *entity)
Definition Universe.m:4990
id findOneEntityMatchingPredicate:parameter:(EntityFilterPredicate predicate,[parameter] void *parameter)
Definition Universe.m:5910
NSDictionary * currentWaypoints()
Definition Universe.m:3467
NSString * keyForPlanetOverridesForSystem:inGalaxy:(OOSystemID s,[inGalaxy] OOGalaxyID g)
Definition Universe.m:7327
OOTimeAbsolute messageRepeatTime
Definition Universe.h:217
NSMutableArray * allPlanets
Definition Universe.h:286
void stopSpeaking()
Definition Universe.m:9091
GLfloat demo_start_z
Definition Universe.h:242
Class shipClassForShipDictionary:(NSDictionary *dict)
Definition Universe.m:3798
NSString * chooseStringForKey:inDictionary:(NSString *key, [inDictionary] NSDictionary *dictionary)
Definition Universe.m:9699
GameController * gameController()
Definition Universe.m:4064
NSDictionary * generateSystemData:(OOSystemID s)
Definition Universe.m:7337
void setUpWitchspace()
Definition Universe.m:1229
void dealloc()
Definition Universe.m:858
NSString * keyForInterstellarOverridesForSystems:s2:inGalaxy:(OOSystemID s1,[s2] OOSystemID s2,[inGalaxy] OOGalaxyID g)
Definition Universe.m:7332
GLint defaultDrawFBO
Definition Universe.h:362
NSArray * scenarios()
Definition Universe.m:7283
void setLastBeacon:(Entity< OOBeaconEntity > *beacon)
Definition Universe.m:3424
StationEntity * station()
Definition Universe.m:3301
Entity * z_list_start
Definition Universe.h:186
Entity< OOBeaconEntity > * firstBeacon()
Definition Universe.m:3403
GLfloat safeWitchspaceExitDistance()
Definition Universe.m:2843
void addCommsMessage:forCount:andShowComms:logOnly:(NSString *text,[forCount] OOTimeDelta count,[andShowComms] BOOL showComms,[logOnly] BOOL logOnly)
Definition Universe.m:6362
void forceLightSwitch()
Definition Universe.m:1960
Quaternion getWitchspaceExitRotation()
Definition Universe.m:8780
void selectIntro2NextCategory()
Definition Universe.m:3277
void drawUniverse()
Definition Universe.m:4353
BOOL displayGUI
Definition Universe.m:8967
GLfloat frustum[6][4]
Definition Universe.h:336
int framesDoneThisUpdate
Definition Universe.m:4795
void filterSortedLists()
Definition Universe.m:6717
void clearGUIs()
Definition Universe.m:8944
BOOL blockJSPlayerShipProps()
Definition Universe.m:9238
BOOL permanentMessageLog()
Definition Universe.m:9203
void findCollisionsAndShadows()
Definition Universe.m:6038
Entity * entity_for_uid[MAX_ENTITY_UID]
Definition Universe.h:206
BOOL wireframeGraphics
Definition Universe.m:9009
BOOL pauseMessageVisible()
Definition Universe.m:9193
static void VerifyDesc(NSString *key, id desc)
Definition Universe.m:7234
BOOL breakPatternOver()
Definition Universe.m:3511
float randomDistanceWithinScanner()
Definition Universe.m:9517
OOTimeAbsolute universal_time
Definition Universe.h:237
GuiDisplayGen * commLogGUI()
Definition Universe.m:8934
void setLibraryTextForDemoShip()
Definition Universe.m:3062
void setFirstBeacon:(Entity< OOBeaconEntity > *beacon)
Definition Universe.m:3408
StationEntity * cachedStation
Definition Universe.h:283
void clearBeacon:(Entity< OOBeaconEntity > *beaconShip)
Definition Universe.m:3446
NSString * getSystemName:forGalaxy:(OOSystemID sys,[forGalaxy] OOGalaxyID gnum)
Definition Universe.m:7533
OOWeakReference * _lastBeacon
Definition Universe.h:211
NSDictionary * generateSystemDataForGalaxy:planet:(OOGalaxyID gnum, [planet] OOSystemID pnum)
Definition Universe.m:7511
void resetBeacons()
Definition Universe.m:3389
Entity * x_list_start
Definition Universe.h:186
int _currentPostFX
Definition Universe.h:366
OOSystemID currentSystemID()
Definition Universe.m:7197
OOVisualEffectEntity * newVisualEffectWithName:(NSString *OO_RETURNS_RETAINED)
Definition Universe.m:3668
HPVector fractionalPositionFrom:to:withFraction:(HPVector point0, [to] HPVector point1, [withFraction] double routeFraction)
Definition Universe.m:9531
BOOL isSpeaking()
Definition Universe.m:9100
HPVector coordinatesForPosition:withCoordinateSystem:returningScalar:(HPVector pos,[withCoordinateSystem] NSString *system,[returningScalar] GLfloat *my_scalar)
Definition Universe.m:2021
void resizeTargetFramebufferWithViewSize:(NSSize viewSize)
Definition Universe.m:553
void preloadSounds()
Definition Universe.m:9653
BOOL witchspaceBreakPattern()
Definition Universe.m:2926
void makeSunSkimmer:andSetAI:(ShipEntity *ship,[andSetAI] BOOL setAI)
Definition Universe.m:8066
void selectIntro2PreviousCategory()
Definition Universe.m:3269
BOOL permanentCommLog()
Definition Universe.m:9223
NSDictionary * missiontext
Definition Universe.m:7299
float ambientLightLevel
Definition Universe.m:1874
BOOL bloom()
Definition Universe.m:284
int _colorblindMode
Definition Universe.h:367
static OOComparisonResult comparePrice(id dict1, id dict2, void *context)
Definition Universe.m:8531
NSDictionary * demoShipData()
Definition Universe.m:3057
unsigned countShipsWithPrimaryRole:inRange:ofEntity:(NSString *role,[inRange] double range,[ofEntity] Entity *entity)
Definition Universe.m:5783
NSArray * planets()
Definition Universe.m:3353
void setNextBeacon:(Entity< OOBeaconEntity > *beaconShip)
Definition Universe.m:3435
int colorblindMode()
Definition Universe.m:335
NSArray * equipmentDataOutfitting
Definition Universe.m:7995
OOCargoQuantity getRandomAmountOfCommodity:(OOCommodityType co_type)
Definition Universe.m:3977
GuiDisplayGen * gui
Definition Universe.m:8929
OOSystemID destination
NSPoint destinationCoordinates()
OOSystemID origin
voidpf uLong offset
Definition ioapi.h:132
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
const char int mode
Definition ioapi.h:125
RANROTSeed RanrotSeedFromRandomSeed(Random_Seed seed)
float randf(void)
RANROTSeed RANROTGetFullSeed(void)
void ranrot_srand(uint32_t seed)
void OOInitReallyRandom(uint64_t seed)
void RANROTSetFullSeed(RANROTSeed seed)
unsigned RanrotWithSeed(RANROTSeed *ioSeed)
int gen_rnd_number(void)
double cunningFee(double value, double precision)
void seed_for_planet_description(Random_Seed s_seed)
RANROTSeed MakeRanrotSeed(uint32_t seed)
unsigned Ranrot(void)
void rotate_seed(Random_Seed *seed_ptr)
OOINLINE double distanceBetweenPlanetPositions(int x1, int y1, int x2, int y2) INLINE_CONST_FUNC
OOHPScalar x
Definition OOHPVector.h:36
OOHPScalar y
Definition OOHPVector.h:37
OOHPScalar z
Definition OOHPVector.h:38
OOScalar m[4][4]
Definition OOMatrix.h:31
OOScalar w
OOScalar x
OOScalar y
OOScalar z
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34