Oolite
Loading...
Searching...
No Matches
ShipEntityLoadRestore.m
Go to the documentation of this file.
1/*
2
3ShipEntityLoadRestore.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
27#import "Universe.h"
28
29#import "AI.h"
31#import "OOConstToString.h"
32#import "OOEquipmentType.h"
33#import "OORoleSet.h"
34#import "OOShipGroup.h"
35#import "OOShipRegistry.h"
36#import "ShipEntityAI.h"
37
38#define KEY_SHIP_KEY @"ship_key"
39#define KEY_SHIPDATA_OVERRIDES @"shipdata_overrides"
40#define KEY_SHIPDATA_DELETES @"shipdata_deletes"
41#define KEY_PRIMARY_ROLE @"primary_role"
42#define KEY_POSITION @"position"
43#define KEY_ORIENTATION @"orientation"
44#define KEY_ROLES @"roles"
45#define KEY_FUEL @"fuel"
46#define KEY_BOUNTY @"bounty"
47#define KEY_ENERGY_LEVEL @"energy_level"
48#define KEY_EQUIPMENT @"equipment"
49#define KEY_MISSILES @"missiles"
50#define KEY_FORWARD_WEAPON @"forward_weapon_type"
51#define KEY_AFT_WEAPON @"aft_weapon_type"
52#define KEY_SCAN_CLASS @"scan_class"
53
54// AI is a complete pickled AI state.
55#define KEY_AI @"AI"
56
57// Group IDs are numbers synchronised through the context object.
58#define KEY_GROUP_ID @"group"
59#define KEY_GROUP_NAME @"group_name"
60#define KEY_IS_GROUP_LEADER @"is_group_leader"
61#define KEY_ESCORT_GROUP_ID @"escort_group"
62
63static void StripIgnoredKeys(NSMutableDictionary* dict);
64static NSUInteger GroupIDForGroup(OOShipGroup* group, NSMutableDictionary* context);
65static OOShipGroup* GroupForGroupID(NSUInteger groupID, NSMutableDictionary* context);
66
67@interface ShipEntity (LoadRestoreInternal)
68
69- (void)simplifyShipdata:(NSMutableDictionary*)data andGetDeletes:(NSArray**)deletes;
70
71@end
72
73@implementation ShipEntity (LoadRestore)
74
75- (NSDictionary*)savedShipDictionaryWithContext:(NSMutableDictionary*)context
76{
77 NSMutableDictionary* result = [NSMutableDictionary dictionary];
78 if (context == nil)
79 context = [NSMutableDictionary dictionary];
80
81 [result setObject:_shipKey forKey:KEY_SHIP_KEY];
82
83 NSMutableDictionary* updatedShipInfo = [NSMutableDictionary dictionaryWithDictionary:shipinfoDictionary];
84
85 [updatedShipInfo setObject:[[self roleSet] roleString] forKey:KEY_ROLES];
86 [updatedShipInfo oo_setUnsignedInteger:fuel forKey:KEY_FUEL];
87 [updatedShipInfo oo_setUnsignedLongLong:bounty forKey:KEY_BOUNTY];
88 [updatedShipInfo setObject:OOStringFromWeaponType(forward_weapon_type) forKey:KEY_FORWARD_WEAPON];
89 [updatedShipInfo setObject:OOStringFromWeaponType(aft_weapon_type) forKey:KEY_AFT_WEAPON];
90 [updatedShipInfo setObject:OOStringFromScanClass(scanClass) forKey:KEY_SCAN_CLASS];
91
92 NSArray* deletes = nil;
93 [self simplifyShipdata:updatedShipInfo andGetDeletes:&deletes];
94
95 [result setObject:updatedShipInfo forKey:KEY_SHIPDATA_OVERRIDES];
96 if (deletes != nil)
97 [result setObject:deletes forKey:KEY_SHIPDATA_DELETES];
98
99 if (!HPvector_equal([self position], kZeroHPVector)) {
100 [result oo_setHPVector:[self position] forKey:KEY_POSITION];
101 }
102 if (!quaternion_equal([self normalOrientation], kIdentityQuaternion)) {
103 [result oo_setQuaternion:[self normalOrientation] forKey:KEY_ORIENTATION];
104 }
105
106 if (energy != maxEnergy)
107 [result oo_setFloat:energy / maxEnergy forKey:KEY_ENERGY_LEVEL];
108
109 [result setObject:[self primaryRole] forKey:KEY_PRIMARY_ROLE];
110
111 // Add equipment.
112 NSArray* equipment = [[self equipmentEnumerator] allObjects];
113 if ([equipment count] != 0)
114 [result setObject:equipment forKey:KEY_EQUIPMENT];
115
116 // Add missiles.
117 if (missiles > 0) {
118 NSMutableArray* missileArray = [NSMutableArray array];
119 unsigned i;
120 for (i = 0; i < missiles; i++) {
121 NSString* missileType = [missile_list[i] identifier];
122 if (missileType != nil)
123 [missileArray addObject:missileType];
124 }
125 [result setObject:missileArray forKey:KEY_MISSILES];
126 }
127
128 // Add groups.
129 if (_group != nil) {
130 [result oo_setUnsignedInteger:GroupIDForGroup(_group, context) forKey:KEY_GROUP_ID];
131 if ([_group leader] == self)
132 [result oo_setBool:YES forKey:KEY_IS_GROUP_LEADER];
133 NSString* groupName = [_group name];
134 if (groupName != nil) {
135 [result setObject:groupName forKey:KEY_GROUP_NAME];
136 }
137 }
138 if (_escortGroup != nil) {
139 [result oo_setUnsignedInteger:GroupIDForGroup(_escortGroup, context) forKey:KEY_ESCORT_GROUP_ID];
140 }
141 /* Eric:
142 The escortGroup property is removed from the lead ship, on entering witchspace.
143 But it is needed in the save file to correctly restore an escorted group.
144 */
145 else if (_group != nil && [_group leader] == self) {
146 [result oo_setUnsignedInteger:GroupIDForGroup(_group, context) forKey:KEY_ESCORT_GROUP_ID];
147 }
148
149 // FIXME: AI.
150 // Eric: I think storing the AI name should be enough. On entering a wormhole, the stack is cleared so there are no preserved AI states.
151 // Also the AI restarts itself with the GLOBAL state, so no need to store any old state.
152 if ([[[self getAI] name] isEqualToString:@"nullAI.plist"]) {
153 // might be a JS version
154 [result setObject:[[self getAI] associatedJS] forKey:KEY_AI];
155 // if there isn't, loading nullAI.js will load nullAI.plist anyway
156 } else {
157 [result setObject:[[self getAI] name] forKey:KEY_AI];
158 }
159
160 return result;
161}
162
163+ (id)shipRestoredFromDictionary:(NSDictionary*)dict
164 useFallback:(BOOL)fallback
165 context:(NSMutableDictionary*)context
166{
167 if (dict == nil)
168 return nil;
169 if (context == nil)
170 context = [NSMutableDictionary dictionary];
171
172 ShipEntity* ship = nil;
173
174 NSString* shipKey = [dict oo_stringForKey:KEY_SHIP_KEY];
175 NSDictionary* shipData = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
176
177 if (shipData != nil) {
178 NSMutableDictionary* mergedData = [NSMutableDictionary dictionaryWithDictionary:shipData];
179
180 StripIgnoredKeys(mergedData);
181 NSArray* deletes = [dict oo_arrayForKey:KEY_SHIPDATA_DELETES];
182 if (deletes != nil)
183 [mergedData removeObjectsForKeys:deletes];
184 [mergedData addEntriesFromDictionary:[dict oo_dictionaryForKey:KEY_SHIPDATA_OVERRIDES]];
185 [mergedData oo_setBool:NO forKey:@"auto_ai"];
186 [mergedData oo_setUnsignedInteger:0 forKey:@"escorts"];
187
188 Class shipClass = [UNIVERSE shipClassForShipDictionary:mergedData];
189 ship = [[[shipClass alloc] initWithKey:shipKey definition:mergedData] autorelease];
190
191 // FIXME: restore AI.
192 [ship setAITo:[dict oo_stringForKey:KEY_AI defaultValue:@"nullAI.plist"]];
193
194 [ship setPrimaryRole:[dict oo_stringForKey:KEY_PRIMARY_ROLE]];
195
196 } else {
197 // Unknown ship; fall back on role if desired and possible.
198 NSString* shipPrimaryRole = [dict oo_stringForKey:KEY_PRIMARY_ROLE];
199 if (!fallback || shipPrimaryRole == nil)
200 return nil;
201
202 ship = [[UNIVERSE newShipWithRole:shipPrimaryRole] autorelease];
203 if (ship == nil)
204 return nil;
205 }
206
207 // The following stuff is deliberately set up the same way even if using role fallback.
208 [ship setPosition:[dict oo_hpvectorForKey:KEY_POSITION]];
209 [ship setNormalOrientation:[dict oo_quaternionForKey:KEY_ORIENTATION]];
210
211 float energyLevel = [dict oo_floatForKey:KEY_ENERGY_LEVEL defaultValue:1.0f];
212 [ship setEnergy:energyLevel * [ship maxEnergy]];
213
215 NSString* eqKey = nil;
216 foreach (eqKey, [dict oo_arrayForKey:KEY_EQUIPMENT]) {
217 [ship addEquipmentItem:eqKey withValidation:NO inContext:@"loading"];
218 }
219
221 foreach (eqKey, [dict oo_arrayForKey:KEY_MISSILES]) {
222 [ship addEquipmentItem:eqKey withValidation:NO inContext:@"loading"];
223 }
224
225 // Groups.
226 NSUInteger groupID = [dict oo_integerForKey:KEY_GROUP_ID defaultValue:NSNotFound];
227 if (groupID != NSNotFound) {
228 OOShipGroup* group = GroupForGroupID(groupID, context);
229 [ship setGroup:group]; // Handles adding to group
230 if ([dict oo_boolForKey:KEY_IS_GROUP_LEADER])
231 [group setLeader:ship];
232 NSString* groupName = [dict oo_stringForKey:KEY_GROUP_NAME];
233 if (groupName != nil)
234 [group setName:groupName];
235 if ([ship hasPrimaryRole:@"escort"] && ship != [group leader]) {
237 }
238 }
239
240 groupID = [dict oo_integerForKey:KEY_ESCORT_GROUP_ID defaultValue:NSNotFound];
241 if (groupID != NSNotFound) {
242 OOShipGroup* group = GroupForGroupID(groupID, context);
243 [group setLeader:ship];
244 [group setName:@"escort group"];
245 [ship setEscortGroup:group];
246 }
247
248 return ship;
249}
250
251- (void)simplifyShipdata:(NSMutableDictionary*)data andGetDeletes:(NSArray**)deletes
252{
253 NSParameterAssert(data != nil && deletes != NULL);
254 *deletes = nil;
255
256 // Get original ship data.
257 NSMutableDictionary* referenceData = [NSMutableDictionary dictionaryWithDictionary:[[OOShipRegistry sharedRegistry] shipInfoForKey:[self shipDataKey]]];
258
259 // Discard stuff that we handle separately.
260 StripIgnoredKeys(referenceData);
261 StripIgnoredKeys(data);
262
263 // Note items that are in referenceData, but not data.
264 NSMutableArray* foundDeletes = [NSMutableArray array];
265 NSString* key = nil;
266 foreachkey(key, referenceData)
267 {
268 if ([data objectForKey:key] == nil) {
269 [foundDeletes addObject:key];
270 }
271 }
272 if ([foundDeletes count] != 0)
273 *deletes = foundDeletes;
274
275 // after rev3010 this loop was using cycles without doing anything - commenting this whole loop out for now. -- kaks 20100207
276 /*
277 // Discard anything that hasn't changed.
278 for (enumerator = [data keyEnumerator]; (key = [enumerator nextObject]); )
279 {
280 id referenceVal = [referenceData objectForKey:key];
281 id myVal = [data objectForKey:key];
282 if ([referenceVal isEqual:myVal])
283 {
284 // [data removeObjectForKey:key];
285 }
286 }
287 */
288}
289
290@end
291
292static void StripIgnoredKeys(NSMutableDictionary* dict)
293{
294 static NSArray* ignoredKeys = nil;
295 if (ignoredKeys == nil)
296 ignoredKeys = [[NSArray alloc] initWithObjects:@"ai_type", @"has_ecm", @"has_scoop", @"has_escape_pod", @"has_energy_bomb", @"has_fuel_injection", @"has_cloaking_device", @"has_military_jammer", @"has_military_scanner_filter", @"has_shield_booster", @"has_shield_enhancer", @"escorts", @"escort_role", @"escort-ship", @"conditions", @"missiles", @"auto_ai", nil];
297
298 NSString* key = nil;
299 foreach (key, ignoredKeys) {
300 [dict removeObjectForKey:key];
301 }
302}
303
304static NSUInteger GroupIDForGroup(OOShipGroup* group, NSMutableDictionary* context)
305{
306 NSMutableDictionary* groupIDs = [context objectForKey:@"groupIDs"];
307 if (groupIDs == nil) {
308 groupIDs = [NSMutableDictionary dictionary];
309 [context setObject:groupIDs forKey:@"groupIDs"];
310 }
311
312 NSValue* key = [NSValue valueWithNonretainedObject:group];
313 NSNumber* groupIDObj = [groupIDs objectForKey:key];
314 unsigned groupID;
315 if (groupIDObj == nil) {
316 // Assign a new group ID.
317 groupID = [context oo_unsignedIntForKey:@"nextGroupID"];
318 groupIDObj = [NSNumber numberWithUnsignedInt:groupID];
319 [context oo_setUnsignedInteger:groupID + 1 forKey:@"nextGroupID"];
320 [groupIDs setObject:groupIDObj forKey:key];
321
322 /* Also keep references to the groups. This isn't necessary at the
323 time of writing, but would be if we e.g. switched to pickling
324 ships in wormholes all the time (each wormhole would then need a
325 persistent context). We can't simply use the groups instead of
326 NSValues as keys, becuase dictionary keys must be copyable.
327 */
328 NSMutableSet* groups = [context objectForKey:@"groups"];
329 if (groups == nil) {
330 groups = [NSMutableSet set];
331 [context setObject:groups forKey:@"groups"];
332 }
333 [groups addObject:group];
334 } else {
335 groupID = [groupIDObj unsignedIntValue];
336 }
337
338 return groupID;
339}
340
341static OOShipGroup* GroupForGroupID(NSUInteger groupID, NSMutableDictionary* context)
342{
343 NSNumber* key = [NSNumber numberWithUnsignedInteger:groupID];
344
345 NSMutableDictionary* groups = [context objectForKey:@"groupsByID"];
346 if (groups == nil) {
347 groups = [NSMutableDictionary dictionary];
348 [context setObject:groups forKey:@"groupsByID"];
349 }
350
351 OOShipGroup* group = [groups objectForKey:key];
352 if (group == nil) {
353 group = [[[OOShipGroup alloc] init] autorelease];
354 [groups setObject:group forKey:key];
355 }
356
357 return group;
358}
#define foreachkey(VAR, DICT)
const HPVector kZeroHPVector
Definition OOHPVector.m:27
OOINLINE bool HPvector_equal(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:250
unsigned count
return nil
OOINLINE bool quaternion_equal(Quaternion a, Quaternion b) INLINE_CONST_FUNC
const Quaternion kIdentityQuaternion
#define KEY_EQUIPMENT
#define KEY_MISSILES
static NSUInteger GroupIDForGroup(OOShipGroup *group, NSMutableDictionary *context)
static void StripIgnoredKeys(NSMutableDictionary *dict)
#define KEY_IS_GROUP_LEADER
static OOShipGroup * GroupForGroupID(NSUInteger groupID, NSMutableDictionary *context)
NSString * name()
Definition AI.m:329
NSString * associatedJS()
Definition AI.m:334
GLfloat maxEnergy
Definition Entity.m:763
void setNormalOrientation:(Quaternion quat)
Definition Entity.m:692
HPVector position
Definition Entity.m:576
void setEnergy:(GLfloat amount)
Definition Entity.m:748
Quaternion normalOrientation()
Definition Entity.m:687
void setPosition:(HPVector posn)
Definition Entity.m:608
NSString * roleString()
Definition OORoleSet.m:103
void setName:(NSString *name)
void setLeader:(ShipEntity *leader)
ShipEntity * leader()
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
BOOL addEquipmentItem:withValidation:inContext:(NSString *equipmentKey,[withValidation] BOOL validateAddition,[inContext] NSString *context)
NSString * shipDataKey()
OORoleSet * roleSet
void setGroup:(OOShipGroup *group)
NSString * primaryRole
void setPrimaryRole:(NSString *role)
OOCreditsQuantity removeMissiles()
NSEnumerator * equipmentEnumerator()
void removeAllEquipment()
void setAITo:(NSString *aiString)
void simplifyShipdata:andGetDeletes:(NSMutableDictionary *data, [andGetDeletes] NSArray **deletes)
void setEscortGroup:(OOShipGroup *group)
void setOwner:(Entity *who_owns_entity)