Oolite
Loading...
Searching...
No Matches
PlayerEntityLoadSave.m
Go to the documentation of this file.
1/*
2
3 PlayerEntityLoadSave.m
4
5 Oolite
6 Copyright (C) 2004-2013 Giles C Williams and contributors
7
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License
10 as published by the Free Software Foundation; either version 2
11 of the License, or (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 MA 02110-1301, USA.
22
23 */
24
28#import "PlayerEntitySound.h"
29
30#import "GameController.h"
35#import "OOColor.h"
36#import "OOConstToString.h"
37#import "OOJavaScriptEngine.h"
38#import "OOJoystickManager.h"
39#import "OOPListParsing.h"
40#import "OOShipRegistry.h"
41#import "OOSound.h"
42#import "OOStringExpander.h"
43#import "OOStringParsing.h"
44#import "OOTexture.h"
45#import "OOXMLExtensions.h"
47#import "ProxyPlayerEntity.h"
48#import "ResourceManager.h"
49#import "ShipEntityAI.h"
50#import "StationEntity.h"
51
52// Name of modifier key used to issue commands. See also -isCommandModifierKeyDown.
53#define COMMAND_MODIFIER_KEY "Ctrl"
54
55static uint16_t PersonalityForCommanderDict(NSDictionary* dict);
56
57@interface MyOpenGLView (OOLoadSaveExtensions)
58
60
61@end
62
63@interface PlayerEntity (OOLoadSavePrivate)
64
66- (void)setGuiToSaveCommanderScreen:(NSString*)cdrName;
67- (void)setGuiToOverwriteScreen:(NSString*)cdrName;
68- (void)lsCommanders:(GuiDisplayGen*)gui directory:(NSString*)directory pageNumber:(int)page highlightName:(NSString*)highlightName;
69- (void)showCommanderShip:(int)cdrArrayIndex;
70- (int)findIndexOfCommander:(NSString*)cdrName;
71- (void)nativeSavePlayer:(NSString*)cdrName;
72- (BOOL)existingNativeSave:(NSString*)cdrName;
73
74- (void)writePlayerToPath:(NSString*)path;
75
76@end
77
78@implementation PlayerEntity (LoadSave)
79
81{
82 BOOL OK = YES;
83
85 return OK;
86}
87
89{
91}
92
94{
95 NSString* tmp_path = nil;
96 NSString* tmp_name = nil;
97 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
98
99 tmp_name = [self lastsaveName];
100 tmp_path = save_path;
101
102 [self doScriptEvent:OOJSID("playerWillSaveGame") withArgument:@"AUTO_SAVE"];
103
104 NSString* saveName = [self lastsaveName];
105 NSString* autosaveSuffix = DESC(@"autosave-commander-suffix");
106
107 if (![saveName hasSuffix:autosaveSuffix]) {
108 saveName = [saveName stringByAppendingString:autosaveSuffix];
109 }
110 NSString* savePath = [dir stringByAppendingPathComponent:[saveName stringByAppendingString:@".oolite-save"]];
111
112 [self setLastsaveName:saveName];
113
114 @try {
115 [self writePlayerToPath:savePath];
116 }
117 @catch (id exception) {
118 // Suppress exceptions silently. Warning the user about failed autosaves would be pretty unhelpful.
119 }
120
121 if (tmp_path != nil) {
122 [save_path autorelease];
123 save_path = [tmp_path copy];
124 }
125 [self setLastsaveName:tmp_name];
126}
127
129{
130 MyOpenGLView* gameView = [UNIVERSE gameView];
131 NSString* path = nil;
132
133 path = save_path;
134 if (!path)
136 if (!path) {
137 OOLog(@"quickSave.failed.noName", @"%@", @"ERROR no file name returned by [[gameView gameController] playerFileToLoad]");
138 [NSException raise:@"OoliteGameNotSavedException"
139 format:@"ERROR no file name returned by [[gameView gameController] playerFileToLoad]"];
140 }
141
142 [self doScriptEvent:OOJSID("playerWillSaveGame") withArgument:@"QUICK_SAVE"];
143
144 [self writePlayerToPath:path];
145 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
147}
148
149- (void)setGuiToScenarioScreen:(int)page
150{
151 NSArray* scenarios = [UNIVERSE scenarios];
152 [UNIVERSE removeDemoShips];
153 // GUI stuff
154 {
155 GuiDisplayGen* gui = [UNIVERSE gui];
157 OOGUIRow row = start_row;
158 BOOL guiChanged = (gui_screen != GUI_SCREEN_NEWGAME);
159
160 [gui clearAndKeepBackground:!guiChanged];
161 [gui setTitle:DESC(@"oolite-newgame-title")];
162
163 OOGUITabSettings tab_stops;
164 tab_stops[0] = 0;
165 tab_stops[1] = -480;
166 [gui setTabStops:tab_stops];
167
168 unsigned n_rows = GUI_MAX_ROWS_SCENARIOS;
169 NSUInteger i, count = [scenarios count];
170
171 NSDictionary* scenario = nil;
172
173 [gui setArray:[NSArray arrayWithObjects:DESC(@"oolite-scenario-exit"), @" <----- ", nil] forRow:start_row - 2];
174 [gui setColor:[OOColor redColor] forRow:start_row - 2];
175 [gui setKey:@"exit" forRow:start_row - 2];
176
177 if (page > 0) {
178 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @" <-- ", nil] forRow:start_row - 1];
179 [gui setColor:[OOColor greenColor] forRow:start_row - 1];
180 [gui setKey:[NSString stringWithFormat:@"__page:%i", page - 1] forRow:start_row - 1];
181 }
182
183 [self setShowDemoShips:NO];
184
185 for (i = page * n_rows; i < count && row < start_row + n_rows; i++) {
186 scenario = [[UNIVERSE scenarios] objectAtIndex:i];
187 NSString* scenarioName = [NSString stringWithFormat:@" %@ ", [scenario oo_stringForKey:@"name"]];
188 [gui setText:OOExpand(scenarioName) forRow:row];
189 [gui setKey:[NSString stringWithFormat:@"Scenario:%zu", i] forRow:row];
190 ++row;
191 }
192
193 if ((page + 1) * n_rows < count) {
194 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @" --> ", nil] forRow:row];
195 [gui setColor:[OOColor greenColor] forRow:row];
196 [gui setKey:[NSString stringWithFormat:@"__page:%i", page + 1] forRow:row];
197 ++row;
198 }
199
200 gui_screen = GUI_SCREEN_NEWGAME;
201
202 [gui setSelectableRange:NSMakeRange(start_row - 2, 3 + row - start_row)];
203 [gui setSelectedRow:start_row];
204 [self showScenarioDetails];
205
206 if (guiChanged) {
207 [gui setBackgroundTextureKey:@"newgame"];
208 [gui setForegroundTextureKey:@"newgame_overlay"];
209 }
210 }
211
212 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
213}
214
215- (void)addScenarioModel:(NSString*)shipKey
216{
217 [self showShipModelWithKey:shipKey shipData:nil personality:0 factorX:1.2 factorY:0.8 factorZ:6.4 inContext:@"scenario"];
218}
219
221{
222 GuiDisplayGen* gui = [UNIVERSE gui];
223 NSString* key = [gui selectedRowKey];
224 [UNIVERSE removeDemoShips];
225
226 if ([key hasPrefix:@"Scenario"]) {
227 int item = [[key componentsSeparatedByString:@":"] oo_intAtIndex:1];
228 NSDictionary* scenario = [[UNIVERSE scenarios] objectAtIndex:item];
229 [self setShowDemoShips:NO];
230 for (NSUInteger i = GUI_ROW_SCENARIOS_DETAIL; i <= 27; i++) {
231 [gui setText:@"" forRow:i];
232 }
233 if (scenario) {
234 [gui addLongText:OOExpand([scenario oo_stringForKey:@"description"]) startingAtRow:GUI_ROW_SCENARIOS_DETAIL align:GUI_ALIGN_LEFT];
235 NSString* shipKey = [scenario oo_stringForKey:@"model"];
236 if (shipKey != nil) {
237 [self addScenarioModel:shipKey];
238 [self setShowDemoShips:YES];
239 }
240 }
241 }
242}
243
245{
246 GuiDisplayGen* gui = [UNIVERSE gui];
247 NSString* key = [gui selectedRowKey];
248
249 if ([key isEqualToString:@"exit"]) {
250 // intended to return to main menu
251 return NO;
252 }
253 if ([key hasPrefix:@"__page"]) {
254 int page = [[key componentsSeparatedByString:@":"] oo_intAtIndex:1];
255 [self setGuiToScenarioScreen:page];
256 return YES;
257 }
258 int selection = [[key componentsSeparatedByString:@":"] oo_intAtIndex:1];
259
260 NSDictionary* scenario = [[UNIVERSE scenarios] objectAtIndex:selection];
261 NSString* file = [scenario oo_stringForKey:@"file" defaultValue:nil];
262 if (file == nil) {
263 OOLog(@"scenario.init.error", @"%@", @"No file entry found for scenario");
264 return NO;
265 }
266 NSString* path = [ResourceManager pathForFileNamed:file inFolder:@"Scenarios"];
267 if (path == nil) {
268 OOLog(@"scenario.init.error", @"Game file not found for scenario %@", file);
269 return NO;
270 }
271 BOOL result = [self loadPlayerFromFile:path asNew:YES];
272 if (!result) {
273 return NO;
274 }
275 [scenarioKey release];
276 scenarioKey = [[scenario oo_stringForKey:@"scenario" defaultValue:nil] retain];
277
278 // don't drop the save game directory in
279 return YES;
280}
281
283{
284 MyOpenGLView* gameView = [UNIVERSE gameView];
285 GuiDisplayGen* gui = [UNIVERSE gui];
286 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
287 const BOOL* joyButtonState = [[OOJoystickManager sharedStickHandler] getAllButtonStates];
288
289 int idx;
290 if ([self handleGUIUpDownArrowKeys]) {
291 int guiSelectedRow = [gui selectedRow];
292 idx = (guiSelectedRow - STARTROW) + (currentPage * NUMROWS);
293 if (guiSelectedRow != MOREROW && guiSelectedRow != BACKROW && guiSelectedRow != EXITROW) {
294 [self showCommanderShip:idx];
295 } else {
296 [UNIVERSE removeDemoShips];
297 [gui setText:@"" forRow:CDRDESCROW align:GUI_ALIGN_LEFT];
298 [gui setText:@"" forRow:CDRDESCROW + 1 align:GUI_ALIGN_LEFT];
299 [gui setText:@"" forRow:CDRDESCROW + 2 align:GUI_ALIGN_LEFT];
300 }
301
302 } else {
303 idx = ([gui selectedRow] - STARTROW) + (currentPage * NUMROWS);
304 }
305
306 // handle page <-- and page --> keys
307 if (([self checkKeyPress:n_key_gui_arrow_left] || [self checkKeyPress:n_key_gui_page_up] || joyButtonState[BUTTON_GUILEFT] || joyButtonState[BUTTON_GUIPAGEUP]) && [[gui keyForRow:BACKROW] isEqual:GUI_KEY_OK]) {
308 currentPage--;
310 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
312 }
313 if (([self checkKeyPress:n_key_gui_arrow_right] || [self checkKeyPress:n_key_gui_page_down] || joyButtonState[BUTTON_GUIRIGHT] || joyButtonState[BUTTON_GUIPAGEDOWN]) && [[gui keyForRow:MOREROW] isEqual:GUI_KEY_OK]) {
314 currentPage++;
315 [self playMenuPageNext];
316 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
318 }
319
320 // Enter pressed - find the commander name underneath.
321 // ignore Ctrl for the moment - we check for it explicitly later
322 if ([self checkKeyPress:n_key_gui_select ignore_ctrl:YES] || [gameView isDown:gvMouseDoubleClick] || joyButtonState[BUTTON_GUISELECT]) {
323 NSDictionary* cdr;
324 switch ([gui selectedRow]) {
325 case EXITROW:
326 if ([self status] == STATUS_START_GAME) {
327 [self setGuiToIntroFirstGo:YES];
328 return nil;
329 }
330 break;
331 case BACKROW:
332 currentPage--;
333 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
335 break;
336 case MOREROW:
337 currentPage++;
338 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
340 break;
341 default:
342 cdr = [cdrDetailArray objectAtIndex:idx];
343 if ([cdr oo_boolForKey:@"isSavedGame"])
344 return [cdr oo_stringForKey:@"saved_game_path"];
345 else {
346 if ([gameView isCommandModifierKeyDown] || [gameView isDown:gvMouseDoubleClick]) {
347 // change directory to the selected path
348 NSString* newDir = [cdr oo_stringForKey:@"saved_game_path"];
349 [[UNIVERSE gameController] setPlayerFileDirectory:newDir];
350 dir = newDir;
351 currentPage = 0;
352 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
354 }
355 }
356 }
357 }
358
359 if ([gameView isDown:27]) // escape key
360 {
362 }
363 return nil;
364}
365
367{
368 MyOpenGLView* gameView = [UNIVERSE gameView];
369 GuiDisplayGen* gui = [UNIVERSE gui];
370 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
371 const BOOL* joyButtonState = [[OOJoystickManager sharedStickHandler] getAllButtonStates];
372
373 if ([self handleGUIUpDownArrowKeys]) {
374 int guiSelectedRow = [gui selectedRow];
375 int idx = (guiSelectedRow - STARTROW) + (currentPage * NUMROWS);
376 if (guiSelectedRow != MOREROW && guiSelectedRow != BACKROW) {
377 [self showCommanderShip:idx];
378 if ([(NSDictionary*)[cdrDetailArray objectAtIndex:idx] oo_boolForKey:@"isSavedGame"]) // don't show things that aren't saved games
379 commanderNameString = [[cdrDetailArray oo_dictionaryAtIndex:idx] oo_stringForKey:@"player_save_name" defaultValue:[[cdrDetailArray oo_dictionaryAtIndex:idx] oo_stringForKey:@"player_name"]];
380 else
381 commanderNameString = [gameView typedString];
382 } else {
383 [UNIVERSE removeDemoShips];
384 [gui setText:@"" forRow:CDRDESCROW align:GUI_ALIGN_LEFT];
385 [gui setText:@"" forRow:CDRDESCROW + 1 align:GUI_ALIGN_LEFT];
386 [gui setText:@"" forRow:CDRDESCROW + 2 align:GUI_ALIGN_LEFT];
387 }
388 } else {
389 commanderNameString = [gameView typedString];
390 }
391
392 [gameView setTypedString:commanderNameString];
393
394 [gui setText:
395 [NSString stringWithFormat:DESC(@"savescreen-commander-name-@"), commanderNameString]
396 forRow:INPUTROW];
397 [gui setColor:[OOColor cyanColor] forRow:INPUTROW];
398
399 // handle page <-- and page --> keys, and on-screen buttons
400 if (((([gameView isDown:gvMouseDoubleClick] || [self checkKeyPress:n_key_gui_select] || joyButtonState[BUTTON_GUISELECT]) && [gui selectedRow] == BACKROW) || ([self checkKeyPress:n_key_gui_arrow_left] || [self checkKeyPress:n_key_gui_page_up]))
401 && [[gui keyForRow:BACKROW] isEqual:GUI_KEY_OK]) {
402 currentPage--;
403 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
405 }
406 //
407 if (((([gameView isDown:gvMouseDoubleClick] || [self checkKeyPress:n_key_gui_select] || joyButtonState[BUTTON_GUISELECT]) && [gui selectedRow] == MOREROW) || ([self checkKeyPress:n_key_gui_arrow_right] || [self checkKeyPress:n_key_gui_page_down]))
408 && [[gui keyForRow:MOREROW] isEqual:GUI_KEY_OK]) {
409 currentPage++;
410 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
412 }
413
414 // ignore Ctrl if pressed together with Enter for the moment - we check for it explicitly immediately after
415 if (([self checkKeyPress:n_key_gui_select ignore_ctrl:YES] || [gameView isDown:gvMouseDoubleClick] || joyButtonState[BUTTON_GUISELECT]) && [commanderNameString length]) {
416 if ([gameView isCommandModifierKeyDown] || [gameView isDown:gvMouseDoubleClick]) {
417 int guiSelectedRow = [gui selectedRow];
418 int idx = (guiSelectedRow - STARTROW) + (currentPage * NUMROWS);
419 NSDictionary* cdr = [cdrDetailArray objectAtIndex:idx];
420
421 if (![cdr oo_boolForKey:@"isSavedGame"]) // don't open saved games
422 {
423 // change directory to the selected path
424 NSString* newDir = [cdr oo_stringForKey:@"saved_game_path"];
425 [[UNIVERSE gameController] setPlayerFileDirectory:newDir];
426 dir = newDir;
427 currentPage = 0;
428 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
430 }
431 } else {
432 pollControls = YES;
433 if ([self existingNativeSave:commanderNameString]) {
435 [self setGuiToOverwriteScreen:commanderNameString];
436 } else {
437 [self nativeSavePlayer:commanderNameString];
438 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
440 }
441 }
442 }
443
444 if ([gameView isDown:27]) // escape key
445 {
446 // get out of here
447 pollControls = YES;
448 [[UNIVERSE gameView] resetTypedString];
450 }
451}
452
454{
455 MyOpenGLView* gameView = [UNIVERSE gameView];
456 GuiDisplayGen* gui = [UNIVERSE gui];
457 const BOOL* joyButtonState = [[OOJoystickManager sharedStickHandler] getAllButtonStates];
458
460
461 // Translation issue: we can't confidently use raw Y and N ascii as shortcuts. It's better to use the load-previous-commander keys.
462 id valueYes = [[[UNIVERSE descriptions] oo_stringForKey:@"load-previous-commander-yes" defaultValue:@"y"] lowercaseString];
463 id valueNo = [[[UNIVERSE descriptions] oo_stringForKey:@"load-previous-commander-no" defaultValue:@"n"] lowercaseString];
464 unsigned char cYes, cNo;
465
466 cYes = [valueYes characterAtIndex:0] & 0x00ff; // Use lower byte of unichar.
467 cNo = [valueNo characterAtIndex:0] & 0x00ff; // Use lower byte of unichar.
468
469 if ((([self checkKeyPress:n_key_gui_select] || joyButtonState[BUTTON_GUISELECT]) && ([gui selectedRow] == SAVE_OVERWRITE_YES_ROW)) || [gameView isDown:cYes] || [gameView isDown:cYes - 32]) {
470 pollControls = YES;
471 [self nativeSavePlayer:commanderNameString];
473 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
475 }
476
477 if ((([self checkKeyPress:n_key_gui_select] || joyButtonState[BUTTON_GUISELECT]) && ([gui selectedRow] == SAVE_OVERWRITE_NO_ROW)) || [gameView isDown:27] || [gameView isDown:cNo] || [gameView isDown:cNo - 32]) {
478 // esc or NO was pressed - get out of here
479 pollControls = YES;
480 [self playSaveOverwriteNo];
482 }
483}
484
485- (BOOL)loadPlayerFromFile:(NSString*)fileToOpen asNew:(BOOL)asNew
486{
487 /* TODO: it would probably be better to load by creating a new
488 PlayerEntity, verifying that's OK, then replacing the global player.
489
490 Actually, it'd be better to separate PlayerEntity into OOPlayer and
491 OOPlayerShipEntity. And then move most of OOPlayerShipEntity into
492 ShipEntity, and make NPC ships behave more like player ships.
493 -- Ahruman
494 */
495
496 BOOL loadedOK = YES;
497 NSDictionary* fileDic = nil;
498 NSString* fail_reason = nil;
499
500 if (fileToOpen == nil) {
501 fail_reason = DESC(@"loadfailed-no-file-specified");
502 loadedOK = NO;
503 }
504
505 if (loadedOK) {
506 OOLog(@"load.progress", @"%@", @"Reading file");
507 fileDic = OODictionaryFromFile(fileToOpen);
508 if (fileDic == nil) {
509 fail_reason = DESC(@"loadfailed-could-not-load-file");
510 loadedOK = NO;
511 }
512 }
513
514 if (loadedOK) {
515 OOLog(@"load.progress", @"%@", @"Restricting scenario");
516 NSString* scenarioRestrict = [fileDic oo_stringForKey:@"scenario_restriction" defaultValue:nil];
517 if (scenarioRestrict == nil) {
518 // older save game - use the 'strict' key instead
519 BOOL strict = [fileDic oo_boolForKey:@"strict" defaultValue:NO];
520 if (strict) {
521 scenarioRestrict = SCENARIO_OXP_DEFINITION_NONE;
522 } else {
523 scenarioRestrict = SCENARIO_OXP_DEFINITION_ALL;
524 }
525 }
526
527 if (![UNIVERSE setUseAddOns:scenarioRestrict fromSaveGame:YES forceReinit:YES]) {
528 fail_reason = DESC(@"loadfailed-saved-game-failed-to-load");
529 loadedOK = NO;
530 }
531 }
532
533 if (loadedOK) {
534 OOLog(@"load.progress", @"%@", @"Creating player ship");
535 // Check that player ship exists
536 NSString* shipKey = nil;
537 NSDictionary* shipDict = nil;
538
539 shipKey = [fileDic oo_stringForKey:@"ship_desc"];
540 shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
541
542 if (shipDict == nil) {
543 loadedOK = NO;
544 if (shipKey != nil)
545 fail_reason = [NSString stringWithFormat:DESC(@"loadfailed-could-not-find-ship-type-@-please-reinstall-the-appropriate-OXP"), shipKey];
546 else
547 fail_reason = DESC(@"loadfailed-invalid-saved-game-no-ship-specified");
548 }
549 }
550
551 if (loadedOK) {
552 OOLog(@"load.progress", @"%@", @"Initialising player entity");
553 if (![self setUpAndConfirmOK:YES saveGame:YES]) {
554 fail_reason = DESC(@"loadfailed-could-not-reset-javascript");
555 loadedOK = NO;
556 }
557 }
558
559 if (loadedOK) {
560 OOLog(@"load.progress", @"%@", @"Loading commander data");
561 if (![self setCommanderDataFromDictionary:fileDic]) {
562 // this could still be a reset js issue, if switching from strict / unrestricted
563 // TODO: use "could not reset js message" if that's the case.
564 fail_reason = DESC(@"loadfailed-could-not-set-up-player-ship");
565 loadedOK = NO;
566 }
567 }
568
569 if (loadedOK) {
570 OOLog(@"load.progress", @"%@", @"Recording save path");
571 if (!asNew) {
572 [save_path autorelease];
573 save_path = [fileToOpen retain];
574
575 [[[UNIVERSE gameView] gameController] setPlayerFileToLoad:fileToOpen];
576 [[[UNIVERSE gameView] gameController] setPlayerFileDirectory:fileToOpen];
577 }
578 } else {
579 OOLog(@"load.failed", @"***** Failed to load saved game \"%@\": %@", [fileToOpen lastPathComponent], fail_reason ? fail_reason : (NSString*)@"unknown error");
580 [[UNIVERSE gameController] setPlayerFileToLoad:nil];
581 [UNIVERSE handleGameOver];
582 [UNIVERSE clearPreviousMessage];
583 [UNIVERSE addMessage:DESC(@"loadfailed-saved-game-failed-to-load") forCount:9.0];
584 if (fail_reason != nil)
585 [UNIVERSE addMessage:fail_reason forCount:9.0];
586 return NO;
587 }
588
589 OOLog(@"load.progress", @"%@", @"Creating system");
590 [UNIVERSE setTimeAccelerationFactor:TIME_ACCELERATION_FACTOR_DEFAULT];
591 [UNIVERSE setSystemTo:system_id];
592 [UNIVERSE removeAllEntitiesExceptPlayer];
593 [UNIVERSE setGalaxyTo:galaxy_number andReinit:YES]; // set overridden planet names on long range map
594 [UNIVERSE setUpSpace];
595 [UNIVERSE setAutoSaveNow:NO];
596
597 OOLog(@"load.progress", @"%@", @"Resetting player flight variables");
599 StationEntity* dockedStation = [self dockedStation];
600
601 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
602
603 if (dockedStation) {
604 position = [dockedStation position];
605 [self setOrientation:kIdentityQuaternion];
606 v_forward = vector_forward_from_quaternion(orientation);
607 v_right = vector_right_from_quaternion(orientation);
608 v_up = vector_up_from_quaternion(orientation);
609 }
610
611 flightRoll = 0.0;
612 flightPitch = 0.0;
613 flightYaw = 0.0;
614 flightSpeed = 0.0;
615
616 [self setEntityPersonalityInt:PersonalityForCommanderDict(fileDic)];
617
618 OOLog(@"load.progress", @"%@", @"Loading system market");
619 // dockedStation is always the main station at this point;
620 // "localMarket" save key always refers to the main station (system) market
621 NSArray* market = [fileDic oo_arrayForKey:@"localMarket"];
622 if (market != nil) {
624 } else {
626 }
627
629
630 OOLog(@"load.progress", @"%@", @"Setting scenario key");
631 // set scenario key if the scenario allows saving and has one
632 NSString* scenario = [fileDic oo_stringForKey:@"scenario_key" defaultValue:nil];
633 DESTROY(scenarioKey);
634 if (scenario != nil) {
635 scenarioKey = [scenario retain];
636 }
637
638 OOLog(@"load.progress", @"%@", @"Starting JS engine");
639 // Remember the savegame target, run js startUp.
641 // run initial system population
642 OOLog(@"load.progress", @"%@", @"Populating initial system");
643 [UNIVERSE populateNormalSpace];
644
645 // might as well start off with a collected JS environment
647
648 // read saved position vector and primary role, check for an
649 // appropriate station at those coordinates, if found, switch
650 // docked station to that one.
651 HPVector dockedPos = [fileDic oo_hpvectorForKey:@"docked_station_position"];
652 NSString* dockedRole = [fileDic oo_stringForKey:@"docked_station_role" defaultValue:@""];
653 StationEntity* saveStation = [UNIVERSE stationWithRole:dockedRole andPosition:dockedPos];
654 if (saveStation != nil && [saveStation allowsSaving]) {
655 [self setDockedStation:saveStation];
656 position = [saveStation position];
657 }
658 // and initialise markets for the secondary stations
659 [UNIVERSE loadStationMarkets:[fileDic oo_arrayForKey:@"station_markets"]];
660
661 OOLog(@"load.progress", @"%@", @"Completing JS startup");
662 [self startUpComplete];
663
664 // if the file was specified in the command line at startup, DO NOT suppress the keys!
665 if ([[UNIVERSE gameController] finishedLaunching])
666 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
667 if (asNew) {
668 gui_screen = GUI_SCREEN_NEWGAME;
669 } else {
670 gui_screen = GUI_SCREEN_LOAD; // force evaluation of new gui screen on startup
671 }
673 if (loadedOK)
674 [self doWorldEventUntilMissionScreen:OOJSID("missionScreenOpportunity")]; // trigger missionScreenOpportunity immediately after loading
675 OOLog(@"load.progress", @"%@", @"Loading complete");
676 return loadedOK;
677}
678
679@end
680
681@implementation PlayerEntity (OOLoadSavePrivate)
682
683- (void)writePlayerToPath:(NSString*)path
684{
685 NSString* errDesc = nil;
686 NSDictionary* dict = nil;
687 BOOL didSave = NO;
688 [[UNIVERSE gameView] resetTypedString];
689
690 if (!path) {
691 OOLog(@"save.failed", @"***** SAVE ERROR: %s called with nil path.", __PRETTY_FUNCTION__);
692 return;
693 }
694
695 dict = [self commanderDataDictionary];
696 if (dict == nil)
697 errDesc = @"could not construct commander data dictionary.";
698 else
699 didSave = [dict writeOOXMLToFile:path atomically:YES errorDescription:&errDesc];
700 if (didSave) {
701 [UNIVERSE clearPreviousMessage]; // allow this to be given time and again
702 [UNIVERSE addMessage:DESC(@"game-saved") forCount:2];
703 [save_path autorelease];
704 save_path = [path copy];
705 [[UNIVERSE gameController] setPlayerFileToLoad:save_path];
706 [[UNIVERSE gameController] setPlayerFileDirectory:save_path];
707 // no duplicated autosave immediately after a save.
708 [UNIVERSE setAutoSaveNow:NO];
709 } else {
710 OOLog(@"save.failed", @"***** SAVE ERROR: %@", errDesc);
711 [NSException raise:@"OoliteException"
712 format:@"Attempt to save game to file '%@' failed: %@", path, errDesc];
713 }
714 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
716}
717
718- (void)nativeSavePlayer:(NSString*)cdrName
719{
720 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
721 NSString* savePath = [dir stringByAppendingPathComponent:[cdrName stringByAppendingPathExtension:@"oolite-save"]];
722
723 [self doScriptEvent:OOJSID("playerWillSaveGame") withArgument:@"STANDARD_SAVE"];
724
725 [self setLastsaveName:cdrName];
726
727 [self writePlayerToPath:savePath];
728}
729
731{
732 GuiDisplayGen* gui = [UNIVERSE gui];
733 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
734
735 gui_screen = GUI_SCREEN_LOAD;
736
737 [gui clear];
738 [gui setTitle:DESC(@"loadscreen-title")];
739
740 currentPage = 0;
741 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
742
743 [gui setForegroundTextureKey:@"docked_overlay"];
744 [gui setBackgroundTextureKey:@"load_save"];
745
746 [[UNIVERSE gameView] suppressKeysUntilKeyUp];
747
748 [self setShowDemoShips:YES];
749 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
750}
751
752- (void)setGuiToSaveCommanderScreen:(NSString*)cdrName
753{
754 GuiDisplayGen* gui = [UNIVERSE gui];
755 MyOpenGLView* gameView = [UNIVERSE gameView];
756 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
757
758 pollControls = NO;
759 gui_screen = GUI_SCREEN_SAVE;
760
761 [gui clear];
762 [gui setTitle:DESC(@"savescreen-title")];
763
764 currentPage = 0;
765 [self lsCommanders:gui directory:dir pageNumber:currentPage highlightName:nil];
766
767 [gui setText:DESC(@"savescreen-commander-name") forRow:INPUTROW];
768 [gui setColor:[OOColor cyanColor] forRow:INPUTROW];
770 [gui setCurrentRow:INPUTROW];
771
772 [gui setForegroundTextureKey:@"docked_overlay"];
773 [gui setBackgroundTextureKey:@"load_save"];
774
775 [gameView setTypedString:cdrName];
777
778 [self setShowDemoShips:YES];
779 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
780}
781
782- (void)setGuiToOverwriteScreen:(NSString*)cdrName
783{
784 GuiDisplayGen* gui = [UNIVERSE gui];
785 MyOpenGLView* gameView = [UNIVERSE gameView];
786
787 // Don't poll controls
788 pollControls = NO;
789
790 gui_screen = GUI_SCREEN_SAVE_OVERWRITE;
791
792 [gui clear];
793 [gui setTitle:[NSString stringWithFormat:DESC(@"overwrite-save-commander-@"), cdrName]];
794
795 [gui setText:[NSString stringWithFormat:DESC(@"overwritescreen-commander-@-already-exists-overwrite-query"), cdrName]
796 forRow:SAVE_OVERWRITE_WARN_ROW
797 align:GUI_ALIGN_CENTER];
798
799 [gui setText:DESC(@"overwritescreen-yes") forRow:SAVE_OVERWRITE_YES_ROW align:GUI_ALIGN_CENTER];
800 [gui setKey:GUI_KEY_OK forRow:SAVE_OVERWRITE_YES_ROW];
801
802 [gui setText:DESC(@"overwritescreen-no") forRow:SAVE_OVERWRITE_NO_ROW align:GUI_ALIGN_CENTER];
803 [gui setKey:GUI_KEY_OK forRow:SAVE_OVERWRITE_NO_ROW];
804
805 [gui setSelectableRange:NSMakeRange(SAVE_OVERWRITE_YES_ROW, 2)];
806 [gui setSelectedRow:SAVE_OVERWRITE_NO_ROW];
807
808 // We can only leave this screen by answering yes or no, or esc. Therefore
809 // use a specific overlay, to allow visual reminders of the available options.
810 [gui setForegroundTextureKey:@"overwrite_overlay"];
811 [gui setBackgroundTextureKey:@"load_save"];
812
813 [self setShowDemoShips:NO];
814 [gameView setStringInput:gvStringInputNo];
815 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO]; // FIXME: should be YES, but was NO before introducing new mouse mode stuff. If set to YES, choices can be selected but not activated.
816}
817
818NSComparisonResult sortCommanders(id cdr1, id cdr2, void* context)
819{
820 return [[cdr1 objectForKey:@"saved_game_path"] localizedCompare:[cdr2 objectForKey:@"saved_game_path"]];
821}
822
823- (void)lsCommanders:(GuiDisplayGen*)gui
824 directory:(NSString*)directory
825 pageNumber:(int)page
826 highlightName:(NSString*)highlightName
827{
828 NSFileManager* cdrFileManager = [NSFileManager defaultManager];
829 int rangeStart = STARTROW;
830 unsigned lastIndex;
831 unsigned i;
832 int row = STARTROW;
833
834 // cdrArray defined in PlayerEntity.h
835 NSArray* cdrArray = [cdrFileManager commanderContentsOfPath:directory];
836
837 // get commander details so a brief rundown of the commander's details may
838 // be displayed.
839 if (!cdrDetailArray)
840 cdrDetailArray = [[NSMutableArray alloc] init]; // alloc retains this so the retain further on in the code was unnecessary
841 else
842 [cdrDetailArray removeAllObjects];
843
844 [cdrDetailArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
845 @"YES", @"isParentFolder",
846 [directory stringByDeletingLastPathComponent], @"saved_game_path", nil]];
847
848 for (i = 0; i < [cdrArray count]; i++) {
849 NSString* path = [cdrArray objectAtIndex:i];
850 BOOL exists, isDirectory = NO;
851
852 exists = [cdrFileManager fileExistsAtPath:path isDirectory:&isDirectory];
853
854 if (exists) {
855 if (!isDirectory && [[[path pathExtension] lowercaseString] isEqualToString:@"oolite-save"]) {
856 NSDictionary* cdr = OODictionaryFromFile(path);
857 if (cdr) {
858 // okay use the same dictionary but add a 'saved_game_path' attribute
859 NSMutableDictionary* cdr1 = [NSMutableDictionary dictionaryWithDictionary:cdr];
860 [cdr1 setObject:@"YES" forKey:@"isSavedGame"];
861 [cdr1 setObject:path forKey:@"saved_game_path"];
862 [cdrDetailArray addObject:cdr1];
863 }
864 }
865 if (isDirectory && ![[path lastPathComponent] hasPrefix:@"."]) {
866 [cdrDetailArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"YES", @"isFolder", path, @"saved_game_path", nil]];
867 }
868 }
869 }
870
871 if (![cdrDetailArray count]) {
872 // Empty directory; tell the user and exit immediately.
873 [gui setText:DESC(@"loadsavescreen-no-commanders-found") forRow:STARTROW align:GUI_ALIGN_CENTER];
874 return;
875 }
876
877 [cdrDetailArray sortUsingFunction:sortCommanders context:NULL];
878
879 // Do we need to highlight a name?
880 int highlightRowOnPage = STARTROW;
881 int highlightIdx = 0;
882 if (highlightName) {
883 highlightIdx = [self findIndexOfCommander:highlightName];
884 if (highlightIdx < 0) {
885 OOLog(@"save.list.commanders.commanderNotFound", @"Commander %@ doesn't exist, very bad", highlightName);
886 highlightIdx = 0;
887 }
888
889 // figure out what page we need to be on
890 page = highlightIdx / NUMROWS;
891 highlightRowOnPage = highlightIdx % NUMROWS + STARTROW;
892 }
893
894 // We now know for certain what page we're on -
895 // set the first index of the first commander on this page.
896 unsigned firstIndex = page * NUMROWS;
897
898 // Set up the GUI.
899 OOGUITabSettings tabStop;
900 tabStop[0] = 0;
901 tabStop[1] = 160;
902 tabStop[2] = 270;
903 [gui setTabStops:tabStop];
904
905 // clear text lines here
906 for (i = EXITROW; i < ENDROW + 1; i++) {
907 [gui setText:@"" forRow:i align:GUI_ALIGN_LEFT];
908 [gui setColor:[OOColor yellowColor] forRow:i];
909 [gui setKey:GUI_KEY_SKIP forRow:i];
910 }
911
912 [gui setColor:[OOColor greenColor] forRow:LABELROW];
913 [gui setArray:[NSArray arrayWithObjects:DESC(@"loadsavescreen-commander-name"), DESC(@"loadsavescreen-rating"), nil]
914 forRow:LABELROW];
915
916 if (page) {
917 [gui setColor:[OOColor greenColor] forRow:STARTROW - 1];
918 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @" <-- ", nil]
919 forRow:STARTROW - 1];
920 [gui setKey:GUI_KEY_OK forRow:STARTROW - 1];
921 rangeStart = STARTROW - 1;
922 }
923
924 if ([self status] == STATUS_START_GAME) {
925 [gui setArray:[NSArray arrayWithObjects:DESC(@"oolite-loadsave-exit"), @" <----- ", nil] forRow:EXITROW];
926 [gui setColor:[OOColor redColor] forRow:EXITROW];
927 [gui setKey:GUI_KEY_OK forRow:EXITROW];
928 rangeStart = EXITROW;
929 }
930
931 if (firstIndex + NUMROWS >= [cdrDetailArray count]) {
932 lastIndex = [cdrDetailArray count];
933 [gui setSelectableRange:NSMakeRange(rangeStart, rangeStart + NUMROWS + 2)];
934 } else {
935 lastIndex = (page * NUMROWS) + NUMROWS;
936 [gui setColor:[OOColor greenColor] forRow:ENDROW];
937 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @" --> ", nil]
938 forRow:ENDROW];
939 [gui setKey:GUI_KEY_OK forRow:ENDROW];
940 [gui setSelectableRange:NSMakeRange(rangeStart, MOREROW)];
941 }
942
943 for (i = firstIndex; i < lastIndex; i++) {
944 NSDictionary* cdr = [cdrDetailArray objectAtIndex:i];
945 if ([cdr oo_boolForKey:@"isSavedGame"]) {
946 NSString* ratingDesc = OODisplayRatingStringFromKillCount([cdr oo_unsignedIntForKey:@"ship_kills"]);
947 [gui setArray:[NSArray arrayWithObjects:
948 [NSString stringWithFormat:@" %@ ", [cdr oo_stringForKey:@"player_save_name" defaultValue:[cdr oo_stringForKey:@"player_name"]]],
949 [NSString stringWithFormat:@" %@ ", ratingDesc],
950 nil]
951 forRow:row];
952 if ([[self lastsaveName] isEqualToString:[cdr oo_stringForKey:@"player_save_name" defaultValue:[cdr oo_stringForKey:@"player_name"]]]) {
953 highlightRowOnPage = row;
954 }
955
956 [gui setKey:GUI_KEY_OK forRow:row];
957 row++;
958 }
959 if ([cdr oo_boolForKey:@"isParentFolder"]) {
960 [gui setArray:[NSArray arrayWithObjects:
961 [NSString stringWithFormat:@" (..) %@ ", [[cdr oo_stringForKey:@"saved_game_path"] lastPathComponent]],
962 @"",
963 nil]
964 forRow:row];
965 [gui setColor:[OOColor orangeColor] forRow:row];
966 [gui setKey:GUI_KEY_OK forRow:row];
967 row++;
968 }
969 if ([cdr oo_boolForKey:@"isFolder"]) {
970 [gui setArray:[NSArray arrayWithObjects:
971 [NSString stringWithFormat:@" >> %@ ", [[cdr oo_stringForKey:@"saved_game_path"] lastPathComponent]],
972 @"",
973 nil]
974 forRow:row];
975 [gui setColor:[OOColor orangeColor] forRow:row];
976 [gui setKey:GUI_KEY_OK forRow:row];
977 row++;
978 }
979 }
980 [gui setSelectedRow:highlightRowOnPage];
981 highlightIdx = (highlightRowOnPage - STARTROW) + (currentPage * NUMROWS);
982 // show the first ship, this will be the selected row
983 [self showCommanderShip:highlightIdx];
984}
985
986// check for an existing saved game...
987- (BOOL)existingNativeSave:(NSString*)cdrName
988{
989 NSString* dir = [[UNIVERSE gameController] playerFileDirectory];
990
991 NSString* savePath = [dir stringByAppendingPathComponent:[cdrName stringByAppendingPathExtension:@"oolite-save"]];
992 return [[NSFileManager defaultManager] fileExistsAtPath:savePath];
993}
994
995// Get some brief details about the commander file.
996- (void)showCommanderShip:(int)cdrArrayIndex
997{
998 GuiDisplayGen* gui = [UNIVERSE gui];
999 [UNIVERSE removeDemoShips];
1000 NSDictionary* cdr = [cdrDetailArray objectAtIndex:cdrArrayIndex];
1001
1002 [gui setText:@"" forRow:CDRDESCROW align:GUI_ALIGN_LEFT];
1003 [gui setText:@"" forRow:CDRDESCROW + 1 align:GUI_ALIGN_LEFT];
1004 [gui setText:@"" forRow:CDRDESCROW + 2 align:GUI_ALIGN_LEFT];
1005
1006 if ([cdr oo_boolForKey:@"isFolder"]) {
1007 NSString* folderDesc = [NSString stringWithFormat:DESC(@"loadsavescreen-hold-@-and-press-return-to-open-folder-@"), @COMMAND_MODIFIER_KEY, [[cdr oo_stringForKey:@"saved_game_path"] lastPathComponent]];
1008 [gui setColor:[OOColor orangeColor] forRow:CDRDESCROW];
1009 [gui addLongText:folderDesc startingAtRow:CDRDESCROW align:GUI_ALIGN_LEFT];
1010 return;
1011 }
1012
1013 if ([cdr oo_boolForKey:@"isParentFolder"]) {
1014 NSString* folderDesc = [NSString stringWithFormat:DESC(@"loadsavescreen-hold-@-and-press-return-to-open-parent-folder-@"), @COMMAND_MODIFIER_KEY, [[cdr oo_stringForKey:@"saved_game_path"] lastPathComponent]];
1015 [gui setColor:[OOColor orangeColor] forRow:CDRDESCROW];
1016 [gui addLongText:folderDesc startingAtRow:CDRDESCROW align:GUI_ALIGN_LEFT];
1017 return;
1018 }
1019 [gui setColor:[gui colorFromSetting:nil defaultValue:nil] forRow:CDRDESCROW];
1020
1021 if (![cdr oo_boolForKey:@"isSavedGame"])
1022 return; // don't show things that aren't saved games
1023
1024 if ([self dockedStation] == nil)
1026
1027 // Display the commander's ship.
1028 NSString* shipDesc = [cdr oo_stringForKey:@"ship_desc"];
1029 NSString* shipName = nil;
1030 NSDictionary* shipDict = nil;
1031 NSString* rating = nil;
1032 uint16_t personality = PersonalityForCommanderDict(cdr);
1033
1034 shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipDesc];
1035 if (shipDict != nil) {
1036 NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithCapacity:[shipDict count] + 1];
1037 [dict setDictionary:shipDict];
1038 id subEntStatus = [cdr objectForKey:@"subentities_status"];
1039 // don't add it to the dictionary if there's no subentities_status key
1040 if (subEntStatus != nil)
1041 [dict setObject:subEntStatus forKey:@"subentities_status"];
1042 [self showShipyardModel:shipDesc shipData:dict personality:personality];
1043 [dict release];
1044 shipName = [shipDict oo_stringForKey:@"display_name"];
1045 if (shipName == nil)
1046 shipName = [shipDict oo_stringForKey:KEY_NAME];
1047 } else {
1048 [self showShipyardModel:@"oolite-unknown-ship" shipData:nil personality:personality];
1049 shipName = [cdr oo_stringForKey:@"ship_name" defaultValue:@"unknown"];
1050 if (![[UNIVERSE useAddOns] isEqualToString:SCENARIO_OXP_DEFINITION_ALL]) {
1051 shipName = [shipName stringByAppendingString:@" - OXPs disabled or not installed"];
1052 } else {
1053 shipName = [shipName stringByAppendingString:@" - OXP not installed"];
1054 }
1055 }
1056
1057 // Make a short description of the commander
1058 NSString* legalDesc = OODisplayStringFromLegalStatus([cdr oo_intForKey:@"legal_status"]);
1059
1060 rating = KillCountToRatingAndKillString([cdr oo_unsignedIntForKey:@"ship_kills"]);
1061 OOCreditsQuantity money = OODeciCreditsFromObject([cdr objectForKey:@"credits"]);
1062
1063 // Nikos - Add some more information in the load game screen (current location, galaxy number and timestamp).
1064 //-------------------------------------------------------------------------------------------------------------------------
1065
1066 int galNumber;
1067 NSString* timeStamp = nil;
1068 NSString* locationName = [cdr oo_stringForKey:@"current_system_name"];
1069
1070 // If there is no key containing the name of the current system in
1071 // the savefile, calculating what it should have been is going to
1072 // be tricky now that system generation isn't seed based - but
1073 // this implies a save game well over 5 years old.
1074 if (locationName == nil) {
1075 // Leaving the location blank in this case is probably okay
1076 locationName = @"";
1077 }
1078
1079 galNumber = [cdr oo_intForKey:@"galaxy_number"] + 1; // Galaxy numbering starts at 0.
1080
1081 NSString* locationGov = @"";
1082 NSString* locationEco = @"";
1083 NSString* locationTL = [cdr objectForKey:@"current_system_techlevel"] ? [NSString stringWithFormat:@"%u", [cdr oo_unsignedIntForKey:@"current_system_techlevel"] + 1] : nil;
1084 if (locationTL) {
1085 locationGov = [NSString stringWithFormat:@"%c", [cdr oo_unsignedCharForKey:@"current_system_government"]];
1086 locationEco = [NSString stringWithFormat:@" %c", (7 - [cdr oo_unsignedCharForKey:@"current_system_economy"]) + 16];
1087 } else
1088 locationTL = @"";
1089
1090 timeStamp = ClockToString([cdr oo_doubleForKey:@"ship_clock" defaultValue:PLAYER_SHIP_CLOCK_START], NO);
1091
1092 //-------------------------------------------------------------------------------------------------------------------------
1093
1094 NSString* cdrDesc = nil;
1095
1096 cdrDesc = [NSString stringWithFormat:DESC(@"loadsavescreen-commander-@-rated-@-has-@-legal-status-@-ship-@-location-@-g-@-eco-@-gov-@-tl-@-timestamp-@"),
1097 [cdr oo_stringForKey:@"player_name"],
1098 rating,
1099 OOCredits(money),
1100 legalDesc,
1101 shipName,
1102 locationName,
1103 galNumber,
1104 locationEco,
1105 locationGov,
1106 locationTL,
1107 timeStamp];
1108
1109 //-------------------------------------------------------------------------------------------------------------------------
1110
1111 [gui addLongText:cdrDesc startingAtRow:CDRDESCROW align:GUI_ALIGN_LEFT];
1112}
1113
1114- (int)findIndexOfCommander:(NSString*)cdrName
1115{
1116 unsigned i;
1117 for (i = 0; i < [cdrDetailArray count]; i++) {
1118 NSString* currentName = [[cdrDetailArray oo_dictionaryAtIndex:i] oo_stringForKey:@"player_save_name" defaultValue:[[cdrDetailArray oo_dictionaryAtIndex:i] oo_stringForKey:@"player_name"]];
1119 if ([cdrName compare:currentName] == NSOrderedSame) {
1120 return i;
1121 }
1122 }
1123
1124 // not found!
1125 return -1;
1126}
1127
1128@end
1129
1130@implementation MyOpenGLView (OOLoadSaveExtensions)
1131
1133{
1134 return [self isCtrlDown];
1135}
1136
1137@end
1138
1139static uint16_t PersonalityForCommanderDict(NSDictionary* dict)
1140{
1141 uint16_t personality = [dict oo_unsignedShortForKey:@"entity_personality" defaultValue:ENTITY_PERSONALITY_INVALID];
1142
1143 if (personality == ENTITY_PERSONALITY_INVALID) {
1144 // For pre-1.74 saved games, generate a default personality based on some hashes.
1145 personality = [[dict oo_stringForKey:@"ship_desc"] oo_hash] * [[dict oo_stringForKey:@"player_name"] oo_hash];
1146 }
1147
1148 return personality & ENTITY_PERSONALITY_MAX;
1149}
1150
1152{
1153 /* Clamp value to 0..kOOMaxCredits.
1154 The important bit here is that kOOMaxCredits can't be represented
1155 exactly as a double, and casting it rounds it up; casting this value
1156 back to an OOCreditsQuantity truncates it. Comparing value directly to
1157 kOOMaxCredits promotes kOOMaxCredits to a double, giving us this
1158 problem.
1159 nextafter(kOOMaxCredits, -1) gives us the highest non-truncated
1160 credits value that's representable as a double (namely,
1161 18 446 744 073 709 549 568 decicredits, or 2047 less than kOOMaxCredits).
1162 -- Ahruman 2011-02-27
1163 */
1164 if (doubleDeciCredits > 0) {
1165 doubleDeciCredits = round(doubleDeciCredits);
1166 double threshold = nextafter(kOOMaxCredits, -1);
1167
1168 if (doubleDeciCredits <= threshold) {
1169 return doubleDeciCredits;
1170 } else {
1171 return kOOMaxCredits;
1172 }
1173 } else {
1174 return 0;
1175 }
1176}
1177
1179{
1180 if ([object isKindOfClass:[NSNumber class]] && [object oo_isFloatingPointNumber]) {
1181 return OODeciCreditsFromDouble([object doubleValue]);
1182 } else {
1183 return OOUnsignedLongLongFromObject(object, 0);
1184 }
1185}
#define GUI_KEY_OK
OOGUITabStop OOGUITabSettings[GUI_MAX_COLUMNS]
NSInteger OOGUIRow
@ gvMouseDoubleClick
unsigned long long OOUnsignedLongLongFromObject(id object, unsigned long long defaultValue)
#define DESTROY(x)
@ BUTTON_GUILEFT
@ BUTTON_GUISELECT
@ BUTTON_GUIRIGHT
@ BUTTON_GUIPAGEDOWN
@ BUTTON_GUIPAGEUP
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSDictionary * OODictionaryFromFile(NSString *path)
unsigned count
return nil
Vector vector_forward_from_quaternion(Quaternion quat) CONST_FUNC
Vector vector_up_from_quaternion(Quaternion quat) CONST_FUNC
Vector vector_right_from_quaternion(Quaternion quat) CONST_FUNC
NSString * ClockToString(double clock, BOOL adjusting)
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
#define kOOMaxCredits
Definition OOTypes.h:161
#define ENDROW
#define SAVE_OVERWRITE_NO_ROW
#define EXITROW
#define MOREROW
#define NUMROWS
#define STARTROW
#define SAVE_OVERWRITE_YES_ROW
#define BACKROW
OOCreditsQuantity OODeciCreditsFromObject(id object)
OOCreditsQuantity OODeciCreditsFromObject(id object)
OOCreditsQuantity OODeciCreditsFromDouble(double doubleDeciCredits)
static uint16_t PersonalityForCommanderDict(NSDictionary *dict)
@ GUI_ROW_SCENARIOS_START
@ GUI_ROW_SCENARIOS_DETAIL
@ GUI_MAX_ROWS_SCENARIOS
NSString * OODisplayRatingStringFromKillCount(unsigned kills)
NSString * OODisplayStringFromLegalStatus(int legalStatus)
NSString * KillCountToRatingAndKillString(unsigned kills)
#define PLAYER_SHIP_CLOCK_START
#define SCENARIO_OXP_DEFINITION_NONE
#define SCENARIO_OXP_DEFINITION_ALL
#define ENTITY_PERSONALITY_INVALID
Definition ShipEntity.h:113
#define ENTITY_PERSONALITY_MAX
Definition ShipEntity.h:112
#define UNIVERSE
Definition Universe.h:827
#define DESC(key)
Definition Universe.h:832
NSComparisonResult sortCommanders(id cdr1, id cdr2, void *context)
void setGuiToIntroFirstGo:(BOOL justCobra)
void setOrientation:(Quaternion quat)
Definition Entity.m:676
HPVector position
Definition Entity.m:576
NSString * playerFileToLoad
BOOL setBackgroundTextureKey:(NSString *key)
OOColor * colorFromSetting:defaultValue:(NSString *setting,[defaultValue] OOColor *def)
BOOL setSelectedRow:(OOGUIRow row)
OOGUIRow addLongText:startingAtRow:align:(NSString *str,[startingAtRow] OOGUIRow row,[align] OOGUIAlignment alignment)
BOOL setForegroundTextureKey:(NSString *key)
void setText:forRow:(NSString *str,[forRow] OOGUIRow row)
void setText:forRow:align:(NSString *str,[forRow] OOGUIRow row,[align] OOGUIAlignment alignment)
void clearAndKeepBackground:(BOOL keepBackground)
OOGUIRow selectedRow
void setSelectableRange:(NSRange range)
void setColor:forRow:(OOColor *color,[forRow] OOGUIRow row)
NSString * selectedRowKey()
void setTitle:(NSString *str)
void setTabStops:(OOGUITabSettings stops)
void setShowTextCursor:(BOOL yesno)
void setCurrentRow:(OOGUIRow value)
void setArray:forRow:(NSArray *arr,[forRow] OOGUIRow row)
void setKey:forRow:(NSString *str,[forRow] OOGUIRow row)
void setTypedString:(NSString *value)
NSMutableString * typedString
void setStringInput:(enum StringInput value)
GameController * gameController
OOColor * cyanColor()
Definition OOColor.m:274
OOColor * orangeColor()
Definition OOColor.m:289
OOColor * redColor()
Definition OOColor.m:259
OOColor * greenColor()
Definition OOColor.m:264
OOColor * yellowColor()
Definition OOColor.m:279
OOJavaScriptEngine * sharedEngine()
void garbageCollectionOpportunity:(BOOL force)
const BOOL * getAllButtonStates()
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
void showShipyardModel:shipData:personality:(NSString *shipKey,[shipData] NSDictionary *shipDict,[personality] uint16_t personality)
void showShipModelWithKey:shipData:personality:factorX:factorY:factorZ:inContext:(NSString *shipKey,[shipData] NSDictionary *shipData,[personality] uint16_t personality,[factorX] GLfloat factorX,[factorY] GLfloat factorY,[factorZ] GLfloat factorZ,[inContext] NSString *context)
void setGuiToScenarioScreen:(int page)
void writePlayerToPath:(NSString *path)
void setGuiToStatusScreen()
BOOL loadPlayerFromFile:asNew:(NSString *fileToOpen,[asNew] BOOL asNew)
StationEntity * dockedStation()
void setShowDemoShips:(BOOL value)
BOOL doWorldEventUntilMissionScreen:(OOJSPropID message)
NSDictionary * commanderDataDictionary()
void nativeSavePlayer:(NSString *cdrName)
void setLastsaveName:(NSString *value)
void completeSetUpAndSetTarget:(BOOL setTarget)
void calculateCurrentCargo()
void lsCommanders:directory:pageNumber:highlightName:(GuiDisplayGen *gui,[directory] NSString *directory,[pageNumber] int page,[highlightName] NSString *highlightName)
void addScenarioModel:(NSString *shipKey)
void setDockedAtMainStation()
void showCommanderShip:(int cdrArrayIndex)
void setDockedStation:(StationEntity *station)
NSString * lastsaveName()
int findIndexOfCommander:(NSString *cdrName)
void setGuiToOverwriteScreen:(NSString *cdrName)
void setGuiToSaveCommanderScreen:(NSString *cdrName)
NSString * pathForFileNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
void setEntityPersonalityInt:(uint16_t value)
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
OOCommodityMarket * initialiseLocalMarket()
void setLocalMarket:(NSArray *market)
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque