File: unit_save.cpp

package info (click to toggle)
boswars 2.7%2Bsvn160110-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 96,880 kB
  • sloc: cpp: 57,441; python: 1,759; makefile: 34; sh: 26
file content (495 lines) | stat: -rw-r--r-- 14,512 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//     ____                _       __               
//    / __ )____  _____   | |     / /___ ___________
//   / __  / __ \/ ___/   | | /| / / __ `/ ___/ ___/
//  / /_/ / /_/ (__  )    | |/ |/ / /_/ / /  (__  ) 
// /_____/\____/____/     |__/|__/\__,_/_/  /____/  
//                                              
//       A futuristic real-time strategy game.
//          This file is part of Bos Wars.
//
/**@name unit_save.cpp - Save unit. */
//
//      (c) Copyright 1998-2008 by Lutz Sammer and Jimmy Salmon
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; only version 2 of the License.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//      02111-1307, USA.
//

//@{

/*----------------------------------------------------------------------------
--  Includes
----------------------------------------------------------------------------*/

#include <sstream>
#include <iomanip>

#include "stratagus.h"
#include "unit.h"
#include "unittype.h"
#include "unit_manager.h"
#include "player.h"
#include "animation.h"
#include "spells.h"
#include "construct.h"
#include "iolib.h"

/*----------------------------------------------------------------------------
--  Functions
----------------------------------------------------------------------------*/

/**
**  Generate a unit reference, a printable unique string for unit.
*/
std::string UnitReference(const CUnit *unit)
{
	std::ostringstream ss;
	ss << "U" << std::setfill('0') << std::setw(4) << std::uppercase <<
		std::hex << UnitNumber(unit);
	return ss.str();
}

/**
**  Save an order.
**
**  @param order  Order who should be saved.
**  @param file   Output file.
*/
void SaveOrder(const COrder *order, CFile *file)
{
	file->printf("{");
	switch (order->Action) {
		case UnitActionNone:
			file->printf("\"action-none\",");
			break;

		case UnitActionStill:
			file->printf("\"action-still\",");
			break;
		case UnitActionStandGround:
			file->printf("\"action-stand-ground\",");
			break;
		case UnitActionFollow:
			file->printf("\"action-follow\",");
			break;
		case UnitActionMove:
			file->printf("\"action-move\",");
			break;
		case UnitActionAttack:
			file->printf("\"action-attack\",");
			break;
		case UnitActionAttackGround:
			file->printf("\"action-attack-ground\",");
			break;
		case UnitActionDie:
			file->printf("\"action-die\",");
			break;

		case UnitActionSpellCast:
			file->printf("\"action-spell-cast\",");
			break;

		case UnitActionTrain:
			file->printf("\"action-train\",");
			break;
		case UnitActionBuilt:
			file->printf("\"action-built\",");
			break;

		case UnitActionBoard:
			file->printf("\"action-board\",");
			break;
		case UnitActionUnload:
			file->printf("\"action-unload\",");
			break;
		case UnitActionPatrol:
			file->printf("\"action-patrol\",");
			break;
		case UnitActionBuild:
			file->printf("\"action-build\",");
			break;

		case UnitActionRepair:
			file->printf("\"action-repair\",");
			break;
		case UnitActionResource:
			file->printf("\"action-resource\",");
			break;
		default:
			DebugPrint("Unknown action in order\n");
	}

	file->printf(" \"range\", %d,", order->Range);
	file->printf(" \"width\", %d,", order->Width);
	file->printf(" \"height\", %d,", order->Height);
	file->printf(" \"min-range\", %d,", order->MinRange);
	if (order->Goal) {
		if (order->Goal->Destroyed) {
			/* this unit is destroyed so it's not in the global unit
			 * array - this means it won't be saved!!! */
			printf ("FIXME: storing destroyed Goal - loading will fail.\n");
		}
		file->printf(" \"goal\", \"%s\",", UnitReference(order->Goal).c_str());
	}
	file->printf(" \"tile\", {%d, %d},", order->X, order->Y);
	if (order->Type) {
		file->printf(" \"type\", \"%s\",", order->Type->Ident.c_str());
	}

	// Extra arg.
	switch (order->Action) {
		case UnitActionPatrol:
			file->printf(" \"patrol\", {%d, %d},",
				order->Arg1.Patrol.X, order->Arg1.Patrol.Y);
			break;
		case UnitActionSpellCast:
			if (order->Arg1.Spell) {
				file->printf(" \"spell\", \"%s\",", order->Arg1.Spell->Ident.c_str());
			}
			break;
		default:
			break;
	}

	file->printf("}");
}

/** Save the progress of the current order to a file.
**
**  @param unit  Unit pointer to be saved.
**  @param file  Output file.
**
**  Each unit must always have a current order, which is kept in
**  unit->Orders[0], and then possibly some other orders that it will
**  execute after the current order completes.  When the unit begins
**  executing an order, it can save additional order-specific data to
**  some member of the unit->Data union.  For example, the various
**  movement orders save a precalculated path in unit->Data.Move.
**  While the unit is executing the order, it can then read and update
**  this data.
**
**  This function saves the appropriate member of unit->Data to the
**  specified file.  unit->Orders[0]->Action controls which member that
**  is.
*/
static void SaveOrderData(const CUnit *unit, CFile *file)
{
	int i;

	// If the unit has not yet begun executing this order, then
	// unit->Data can still contain data from the previous order.
	// Do not attempt to save the data in that case, because
	// integers in it may be out of range, and pointers in it can
	// point to invalid addresses.
	//
	// HOWEVER... UnitActionBuilt apparently keeps SubAction == 0
	// at all times, and StartBuilding which sets UnitActionBuilt
	// also initializes unit->Data.  So there we must allow 0 too.
	if (unit->SubAction == 0 && unit->Orders[0]->Action != UnitActionBuilt)
		return;
	
	switch (unit->Orders[0]->Action) {
		case UnitActionNone:
		case UnitActionStill:
		case UnitActionStandGround:
		case UnitActionDie:
			break;
		case UnitActionBuilt:
			{
				CConstructionFrame *cframe;
				int frame;

				cframe = unit->Type->Construction->Frames;
				frame = 0;
				while (cframe != unit->Data.Built.Frame) {
					cframe = cframe->Next;
					++frame;
				}
				file->printf(",\n  \"data-built\", {");

				file->printf("\"progress\", %d, \"frame\", %d,",
					unit->Data.Built.Progress, frame);
				if (unit->Data.Built.Cancel) {
					file->printf(" \"cancel\",");
				}
				file->printf("}");
				break;
			}
		case UnitActionTrain:
			file->printf(",\n  \"data-train\", {");
			file->printf("\"ticks\", %d, ", unit->Data.Train.Ticks);
			file->printf("}");
			break;
		case UnitActionResource:
			/// @bug Should save unit->Data.Move instead,
			/// if unit->SubAction == SUB_MOVE_TO_RESOURCE.
			/// However, that macro is not visible here.
			file->printf(",\n  \"data-harvest\", {");
			file->printf("\"current-production\", {");
			for (i = 0; i < MaxCosts; ++i) {
				file->printf("%s%d", (i ? ", " : ""), unit->Data.Harvest.CurrentProduction[i]);
			}
			file->printf("}}");
			break;
		case UnitActionFollow:
		case UnitActionMove:
		case UnitActionAttack:
		case UnitActionAttackGround:
		case UnitActionSpellCast:
		case UnitActionBoard:
		case UnitActionUnload:
		case UnitActionPatrol:
		case UnitActionBuild:
		case UnitActionRepair:
			file->printf(",\n  \"data-move\", {");
			if (unit->Data.Move.Fast) {
				file->printf("\"fast\", ");
			}
			if (unit->Data.Move.Length > 0) {
				Assert(unit->Data.Move.Length <= MAX_PATH_LENGTH);

				file->printf("\"path\", {");
				for (i = 0; i < unit->Data.Move.Length; ++i) {
					file->printf("%d, ", unit->Data.Move.Path[i]);
				}
				file->printf("},");
			}
			file->printf("}");
			break;
		default:
			DebugPrint("Unknown action in order\n");
	}
}

/**
**  Save the state of a unit to file.
**
**  @param unit  Unit pointer to be saved.
**  @param file  Output file.
*/
void SaveUnit(const CUnit *unit, CFile *file)
{
	CUnit *uins;
	int i;

	file->printf("\nUnit(%d, ", UnitNumber(unit));

	// 'type and 'player must be first, needed to create the unit slot
	file->printf("\"type\", \"%s\", ", unit->Type->Ident.c_str());
	if (unit->Seen.Type) {
		file->printf("\"seen-type\", \"%s\", ", unit->Seen.Type->Ident.c_str());
	}

	file->printf("\"player\", %d,\n  ", unit->Player->Index);

	if (unit->Next) {
		file->printf("\"next\", %d, ", UnitNumber(unit->Next));
	}

	file->printf("\"tile\", {%d, %d}, ", unit->X, unit->Y);
	file->printf("\"seen-tile\", {%d, %d}, ", unit->Seen.X, unit->Seen.Y);
	file->printf("\"refs\", %lu, ", unit->Refs);
#if 0
	// latimerius: why is this so complex?
	// JOHNS: An unit can be owned by a new player and have still the old stats
	for (i = 0; i < PlayerMax; ++i) {
		if (&unit->Type->Stats[i] == unit->Stats) {
			file->printf("\"stats\", %d,\n  ", i);
			break;
		}
	}
	// latimerius: what's the point of storing a pointer value anyway?
	if (i == PlayerMax) {
		file->printf("\"stats\", \"S%08X\",\n  ", (int)unit->Stats);
	}
#else
	file->printf("\"stats\", %d,\n  ", unit->Player->Index);
#endif
	file->printf("\"pixel\", {%d, %d}, ", unit->IX, unit->IY);
	file->printf("\"seen-pixel\", {%d, %d}, ", unit->Seen.IX, unit->Seen.IY);
	file->printf("\"frame\", %d, ", unit->Frame);
	if (unit->Seen.Frame != UnitNotSeen) {
		file->printf("\"seen\", %d, ", unit->Seen.Frame);
	} else {
		file->printf("\"not-seen\", ");
	}
	file->printf("\"direction\", %d,\n  ", unit->Direction);
	file->printf("\"attacked\", %lu,\n ", unit->Attacked);
	file->printf(" \"current-sight-range\", %d,", unit->CurrentSightRange);
	if (unit->Burning) {
		file->printf(" \"burning\",");
	}
	if (unit->Destroyed) {
		file->printf(" \"destroyed\",");
	}
	if (unit->Removed) {
		file->printf(" \"removed\",");
	}
	if (unit->Selected) {
		file->printf(" \"selected\",");
	}
	if (unit->RescuedFrom) {
		file->printf(" \"rescued-from\", %d,", unit->RescuedFrom->Index);
	}
	// n0b0dy: How is this useful?
	// mr-russ: You can't always load units in order, it saved the information
	// so you can load a unit whose Container hasn't been loaded yet.
	// SEE unit loading code.
	if (unit->Container && unit->Removed) {
		file->printf(" \"host-info\", {%d, %d, %d, %d}, ",
			unit->Container->X, unit->Container->Y,
			unit->Container->Type->TileWidth,
			unit->Container->Type->TileHeight);
	}
	file->printf(" \"seen-by-player\", \"");
	for (i = 0; i < PlayerMax; ++i) {
		file->printf("%c", (unit->Seen.ByPlayer & (1 << i)) ? 'X' : '_');
	}
	file->printf("\",\n ");
	file->printf(" \"seen-destroyed\", \"");
	for (i = 0; i < PlayerMax; ++i) {
		file->printf("%c", (unit->Seen.Destroyed & (1 << i)) ? 'X' : '_');
	}
	file->printf("\",\n ");
	if (unit->Constructed) {
		file->printf(" \"constructed\",");
	}
	if (unit->Seen.Constructed) {
		file->printf(" \"seen-constructed\",");
	}

	if (unit->Seen.CFrame) {
		CConstructionFrame *cframe = unit->Seen.Type->Construction->Frames;
		int frame = 0;
		while (cframe != unit->Seen.CFrame) {
			cframe = cframe->Next;
			++frame;
		}
		file->printf(" \"seen-cframe\", %d,", frame);
	}

	file->printf(" \"seen-state\", %d, ", unit->Seen.State);
	file->printf("\"ttl\", %lu, ", unit->TTL);

	for (i = 0; i < UnitTypeVar.NumberVariable; i++) {
		file->printf("\"%s\", {Value = %d, Max = %d, Increase = %d, Enable = %s},\n  ",
			UnitTypeVar.VariableName[i], unit->Variable[i].Value, unit->Variable[i].Max,
			unit->Variable[i].Increase, unit->Variable[i].Enable ? "true" : "false");
	}

	file->printf("\"group-id\", %d,\n  ", unit->GroupId);
	file->printf("\"last-group\", %d,\n  ", unit->LastGroup);

	file->printf("\"resources-held\", {");
	for (i = 0; i < MaxCosts; ++i) {
		file->printf("%s%d", (i ? ", " : ""), unit->ResourcesHeld[i]);
	}
	file->printf("},\n  ");

	file->printf("\"production-efficiency\", %d, ", unit->ProductionEfficiency);

	file->printf("\"sub-action\", %d, ", unit->SubAction);
	file->printf("\"wait\", %d, ", unit->Wait);
	file->printf("\"state\", %d,", unit->State);
	file->printf("\"anim-wait\", %d,", unit->Anim.Wait);
	for (i = 0; i < NumAnimations; ++i) {
		if (AnimationsArray[i] == unit->Anim.CurrAnim) {
			file->printf("\"curr-anim\", %d,", i);
			// The cast from ptrdiff_t to int will not
			// overflow because the array of animation
			// frames was converted from a Lua list
			// and lua_objlen returns int.
			file->printf("\"anim\", %d,",
				     static_cast<int>(unit->Anim.Anim - unit->Anim.CurrAnim));
			break;
		}
	}
	if (unit->Anim.Unbreakable) {
		file->printf(" \"unbreakable\",");
	}
	file->printf("\n  \"blink\", %d,", unit->Blink);
	if (unit->Moving) {
		file->printf(" \"moving\",");
	}
	if (unit->ReCast) {
		file->printf(" \"re-cast\",");
	}
	if (unit->Boarded) {
		file->printf(" \"boarded\",");
	}
	if (unit->AutoRepair) {
		file->printf(" \"auto-repair\",");
	}

	file->printf(" \"units-boarded-count\", %d,", unit->BoardCount);

	if (unit->UnitInside) {
		file->printf("\n  \"units-contained\", {");
		uins = unit->UnitInside->PrevContained;
		for (i = unit->InsideCount; i; --i, uins = uins->PrevContained) {
			file->printf("\"%s\"", UnitReference(uins).c_str());
			if (i > 1) {
				file->printf(", ");
			}
		}
		file->printf("},\n  ");
	}
	Assert((unsigned int)unit->OrderCount == unit->Orders.size());
	file->printf("\"order-count\", %d,\n  ", unit->OrderCount);
	file->printf("\"order-flush\", %d,\n  ", unit->OrderFlush);
	file->printf("\"orders\", {");
	for (i = 0; i < unit->OrderCount; ++i) {
		file->printf("\n ");
		SaveOrder(unit->Orders[i], file);
		file->printf(",");
	}
	file->printf("},\n  \"saved-order\", ");
	SaveOrder(&unit->SavedOrder, file);
	file->printf(",\n  \"new-order\", ");
	SaveOrder(&unit->NewOrder, file);

	//
	//  Order data part
	//
	SaveOrderData(unit, file);

	if (unit->Goal) {
		file->printf(",\n  \"goal\", %d", UnitNumber(unit->Goal));
	}
	if (unit->AutoCastSpell) {
		for (i = 0; (unsigned int) i < SpellTypeTable.size(); ++i) {
			if (unit->AutoCastSpell[i]) {
				file->printf(",\n  \"auto-cast\", \"%s\"", SpellTypeTable[i]->Ident.c_str());
			}
		}
	}

	file->printf(")\n");
}

/**
**  Save state of units to file.
**
**  @param file  Output file.
*/
void SaveUnits(CFile *file)
{
	UnitManager.Save(file);

	for (CUnit **table = Units; table < &Units[NumUnits]; ++table) {
		SaveUnit(*table, file);
	}
}

//@}