/
fileio.cpp
645 lines (523 loc) · 17.8 KB
/
fileio.cpp
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/* fileio.cpp
*
* Micropolis, Unix Version. This game was released for the Unix platform
* in or about 1990 and has been modified for inclusion in the One Laptop
* Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If
* you need assistance with this program, you may contact:
* http://wiki.laptop.org/go/Micropolis or email micropolis@laptop.org.
*
* 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, either version 3 of the License, or (at
* your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* ADDITIONAL TERMS per GNU GPL Section 7
*
* No trademark or publicity rights are granted. This license does NOT
* give you any right, title or interest in the trademark SimCity or any
* other Electronic Arts trademark. You may not distribute any
* modification of this program using the trademark SimCity or claim any
* affliation or association with Electronic Arts Inc. or its employees.
*
* Any propagation or conveyance of this program must include this
* copyright notice and these terms.
*
* If you convey this program (or any modifications of it) and assume
* contractual liability for the program to recipients of it, you agree
* to indemnify Electronic Arts for any liability that those contractual
* assumptions impose on Electronic Arts.
*
* You may not misrepresent the origins of this program; modified
* versions of the program must be marked as such and not identified as
* the original program.
*
* This disclaimer supplements the one included in the General Public
* License. TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, THIS
* PROGRAM IS PROVIDED TO YOU "AS IS," WITH ALL FAULTS, WITHOUT WARRANTY
* OF ANY KIND, AND YOUR USE IS AT YOUR SOLE RISK. THE ENTIRE RISK OF
* SATISFACTORY QUALITY AND PERFORMANCE RESIDES WITH YOU. ELECTRONIC ARTS
* DISCLAIMS ANY AND ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES,
* INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT OF THIRD PARTY
* RIGHTS, AND WARRANTIES (IF ANY) ARISING FROM A COURSE OF DEALING,
* USAGE, OR TRADE PRACTICE. ELECTRONIC ARTS DOES NOT WARRANT AGAINST
* INTERFERENCE WITH YOUR ENJOYMENT OF THE PROGRAM; THAT THE PROGRAM WILL
* MEET YOUR REQUIREMENTS; THAT OPERATION OF THE PROGRAM WILL BE
* UNINTERRUPTED OR ERROR-FREE, OR THAT THE PROGRAM WILL BE COMPATIBLE
* WITH THIRD PARTY SOFTWARE OR THAT ANY ERRORS IN THE PROGRAM WILL BE
* CORRECTED. NO ORAL OR WRITTEN ADVICE PROVIDED BY ELECTRONIC ARTS OR
* ANY AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SOME
* JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF OR LIMITATIONS ON IMPLIED
* WARRANTIES OR THE LIMITATIONS ON THE APPLICABLE STATUTORY RIGHTS OF A
* CONSUMER, SO SOME OR ALL OF THE ABOVE EXCLUSIONS AND LIMITATIONS MAY
* NOT APPLY TO YOU.
*/
/** @file fileio.cpp */
////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "micropolis.h"
////////////////////////////////////////////////////////////////////////
#ifdef IS_INTEL
/**
* Convert an array of short values between MAC and Intel endian formats.
* @param buf Array with shorts.
* @param len Number of short values in the array.
*/
#define SWAP_SHORTS(buf, len) swap_shorts(buf, len)
/**
* Convert an array of long values between MAC and Intel endian formats.
* @param buf Array with longs.
* @param len Number of long values in the array.
*/
#define HALF_SWAP_LONGS(buf, len) half_swap_longs(buf, len)
/**
* Swap upper and lower byte of all shorts in the array.
* @param buf Array with shorts.
* @param len Number of short values in the array.
*/
static void swap_shorts(short *buf, int len)
{
int i;
/* Flip bytes in each short! */
for (i = 0; i < len; i++) {
*buf = ((*buf & 0xFF) <<8) | ((*buf &0xFF00) >>8);
buf++;
}
}
/**
* Swap upper and lower words of all longs in the array.
* @param buf Array with longs.
* @param len Number of long values in the array.
*/
static void half_swap_longs(long *buf, int len)
{
int i;
/* Flip bytes in each long! */
for (i = 0; i < len; i++) {
long l = *buf;
*buf =
((l & 0x0000ffff) << 16) |
((l & 0xffff0000) >> 16);
buf++;
}
}
#else
/**
* Convert an array of short values between MAC and MAC endian formats.
* @param buf Array with shorts.
* @param len Number of short values in the array.
* @note This version does not change anything since the data is already in the
* correct format.
*/
#define SWAP_SHORTS(buf, len)
/**
* Convert an array of long values between MAC and MAC endian formats.
* @param buf Array with longs.
* @param len Number of long values in the array.
* @note This version does not change anything since the data is already in the
* correct format.
*/
#define HALF_SWAP_LONGS(buf, len)
#endif
/**
* Load an array of short values from file to memory.
*
* Convert to the correct processor architecture, if necessary.
* @param buf Buffer to put the loaded short values in.
* @param len Number of short values to load.
* @param f File handle of the file to load from.
* @return Load was succesfull.
*/
static bool load_short(short *buf, int len, FILE *f)
{
size_t result = fread(buf, sizeof(short), len, f);
if ((int)result != len) {
return false;
}
SWAP_SHORTS(buf, len); /* to intel */
return true;
}
/**
* Save an array of short values from memory to file.
*
* Convert to the correct endianness first, if necessary.
* @param buf Buffer containing the short values to save.
* @param len Number of short values to save.
* @param f File handle of the file to save to.
* @return Save was succesfull.
*/
static bool save_short(short *buf, int len, FILE *f)
{
SWAP_SHORTS(buf, len); /* to MAC */
if ((int)fwrite(buf, sizeof(short), len, f) != len) {
return false;
}
SWAP_SHORTS(buf, len); /* back to intel */
return true;
}
/**
* Load a city file from a given filename and (optionally) directory.
* @param filename Name of the file to load.
* @param dir If not \c NULL, name of the directory containing the file.
* @return Load was succesfull.
*/
bool Micropolis::loadFileDir(const char *filename, const char *dir)
{
char *path = NULL;
FILE *f;
Quad size;
// If needed, construct a path to the file.
if (dir != NULL) {
path = (char *)malloc(strlen(dir) + 1 + strlen(filename) + 1);
sprintf(path, "%s/%s", dir, filename);
filename = path;
}
// Open the file.
f = fopen(filename, "rb");
// Before checking whether open() succeeded, first drop the path.
if (path != NULL) {
free(path);
}
// open() failed; report failure.
if (f == NULL) {
return false;
}
fseek(f, 0L, SEEK_END);
size = ftell(f);
fseek(f, 0L, SEEK_SET);
bool result =
(size == 27120) &&
load_short(resHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(comHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(indHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(crimeHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(pollutionHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(moneyHist, HISTORY_LENGTH / sizeof(short), f) &&
load_short(miscHist, MISC_HISTORY_LENGTH / sizeof(short), f) &&
load_short(((short *)&map[0][0]), WORLD_W * WORLD_H, f);
fclose(f);
return result;
}
/**
* Load a file, and initialize the game variables.
* @param filename Name of the file to load.
* @return Load was succesfull.
*/
bool Micropolis::loadFile(const char *filename)
{
long n;
if (!loadFileDir(filename, NULL)) {
return false;
}
/* total funds is a long..... miscHist is array of shorts */
/* total funds is being put in the 50th & 51th word of miscHist */
/* find the address, cast the ptr to a longPtr, take contents */
n = *(Quad *)(miscHist + 50);
HALF_SWAP_LONGS(&n, 1);
setFunds(n);
n = *(Quad *)(miscHist + 8);
HALF_SWAP_LONGS(&n, 1);
cityTime = n;
setAutoBulldoze(miscHist[52] != 0); // flag for autoBulldoze
setAutoBudget(miscHist[53] != 0); // flag for autoBudget
setAutoGoto(miscHist[54] != 0); // flag for auto-goto
setEnableSound(miscHist[55] != 0); // flag for the sound on/off
setCityTax(miscHist[56]);
setSpeed(miscHist[57]);
changeCensus();
mustUpdateOptions = true;
/* yayaya */
n = *(Quad *)(miscHist + 58);
HALF_SWAP_LONGS(&n, 1);
policePercent = ((float)n) / ((float)65536);
n = *(Quad *)(miscHist + 60);
HALF_SWAP_LONGS(&n, 1);
firePercent = (float)n / (float)65536.0;
n = *(Quad *)(miscHist + 62);
HALF_SWAP_LONGS(&n, 1);
roadPercent = (float)n / (float)65536.0;
policePercent =
(float)(*(Quad*)(miscHist + 58)) /
(float)65536.0; /* and 59 */
firePercent =
(float)(*(Quad*)(miscHist + 60)) /
(float)65536.0; /* and 61 */
roadPercent =
(float)(*(Quad*)(miscHist + 62)) /
(float)65536.0; /* and 63 */
cityTime = max((Quad)0, cityTime);
// If the tax is nonsensical, set it to a reasonable value.
if (cityTax > 20 || cityTax < 0) {
setCityTax(7);
}
// If the speed is nonsensical, set it to a reasonable value.
if (simSpeed < 0 || simSpeed > 3) {
setSpeed(3);
}
setSpeed(simSpeed);
setPasses(1);
initFundingLevel();
// Set the scenario id to 0.
initWillStuff();
scenario = SC_NONE;
initSimLoad = 1;
doInitialEval = false;
doSimInit();
invalidateMaps();
return true;
}
/**
* Save a game to disk.
* @param filename Name of the file to use for storing the game.
* @return The game was saved successfully.
*/
bool Micropolis::saveFile(const char *filename)
{
long n;
FILE *f;
if ((f = fopen(filename, "wb")) == NULL) {
/// @todo Report error saving file.
return false;
}
/* total funds is a long..... miscHist is array of ints */
/* total funds is bien put in the 50th & 51th word of miscHist */
/* find the address, cast the ptr to a longPtr, take contents */
n = totalFunds;
HALF_SWAP_LONGS(&n, 1);
(*(Quad *)(miscHist + 50)) = n;
n = cityTime;
HALF_SWAP_LONGS(&n, 1);
(*(Quad *)(miscHist + 8)) = n;
miscHist[52] = autoBulldoze; // flag for autoBulldoze
miscHist[53] = autoBudget; // flag for autoBudget
miscHist[54] = autoGoto; // flag for auto-goto
miscHist[55] = enableSound; // flag for the sound on/off
miscHist[57] = simSpeed;
miscHist[56] = cityTax; /* post release */
/* yayaya */
n = (int)(policePercent * 65536);
HALF_SWAP_LONGS(&n, 1);
(*(Quad *)(miscHist + 58)) = n;
n = (int)(firePercent * 65536);
HALF_SWAP_LONGS(&n, 1);
(*(Quad *)(miscHist + 60)) = n;
n = (int)(roadPercent * 65536);
HALF_SWAP_LONGS(&n, 1);
(*(Quad *)(miscHist + 62)) = n;
bool result =
save_short(resHist, HISTORY_LENGTH / 2, f) &&
save_short(comHist, HISTORY_LENGTH / 2, f) &&
save_short(indHist, HISTORY_LENGTH / 2, f) &&
save_short(crimeHist, HISTORY_LENGTH / 2, f) &&
save_short(pollutionHist, HISTORY_LENGTH / 2, f) &&
save_short(moneyHist, HISTORY_LENGTH / 2, f) &&
save_short(miscHist, MISC_HISTORY_LENGTH / 2, f) &&
save_short(((short *)&map[0][0]), WORLD_W * WORLD_H, f);
fclose(f);
return result;
}
/**
* Load a scenario.
* @param s Scenario to load.
* @note \a s cannot be \c SC_NONE.
*/
void Micropolis::loadScenario(Scenario s)
{
const char *name = NULL;
const char *fname = NULL;
cityFileName = "";
setGameLevel(LEVEL_EASY);
if (s < SC_DULLSVILLE || s > SC_RIO) {
s = SC_DULLSVILLE;
}
switch (s) {
case SC_DULLSVILLE:
name = "Dullsville";
fname = "snro.111";
scenario = SC_DULLSVILLE;
cityTime = ((1900 - 1900) * 48) + 2;
setFunds(5000);
break;
case SC_SAN_FRANCISCO:
name = "San Francisco";
fname = "snro.222";
scenario = SC_SAN_FRANCISCO;
cityTime = ((1906 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_HAMBURG:
name = "Hamburg";
fname = "snro.333";
scenario = SC_HAMBURG;
cityTime = ((1944 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_BERN:
name = "Bern";
fname = "snro.444";
scenario = SC_BERN;
cityTime = ((1965 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_TOKYO:
name = "Tokyo";
fname = "snro.555";
scenario = SC_TOKYO;
cityTime = ((1957 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_DETROIT:
name = "Detroit";
fname = "snro.666";
scenario = SC_DETROIT;
cityTime = ((1972 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_BOSTON:
name = "Boston";
fname = "snro.777";
scenario = SC_BOSTON;
cityTime = ((2010 - 1900) * 48) + 2;
setFunds(20000);
break;
case SC_RIO:
name = "Rio de Janeiro";
fname = "snro.888";
scenario = SC_RIO;
cityTime = ((2047 - 1900) * 48) + 2;
setFunds(20000);
break;
default:
NOT_REACHED();
break;
}
setCleanCityName(name);
setSpeed(3);
setCityTax(7);
loadFileDir(
fname,
resourceDir.c_str());
initWillStuff();
initFundingLevel();
updateFunds();
invalidateMaps();
initSimLoad = 1;
doInitialEval = false;
doSimInit();
didLoadScenario();
}
/** Report to the front-end that the scenario was loaded. */
void Micropolis::didLoadScenario()
{
callback("didLoadScenario", "");
}
/**
* Try to load a new game from disk.
* @param filename Name of the file to load.
* @return Game was loaded successfully.
* @todo In what state is the game left when loading fails?
* @todo String normalization code is duplicated in Micropolis::saveCityAs().
* Extract to a sub-function.
* @bug Function fails if \c lastDot<lastSlash (ie with \c "x.y/bla" )
*/
bool Micropolis::loadCity(const char *filename)
{
if (loadFile(filename)) {
cityFileName = filename;
unsigned int lastSlash = cityFileName.find_last_of('/');
unsigned int pos = (lastSlash == std::string::npos) ? 0 : lastSlash + 1;
unsigned int lastDot = cityFileName.find_last_of('.');
unsigned int last =
(lastDot == std::string::npos) ? cityFileName.length() : lastDot;
std::string newCityName = cityFileName.substr(pos, last - pos);
setCityName(newCityName);
didLoadCity();
return true;
} else {
didntLoadCity((filename && *filename) ? filename : "(null)");
return false;
}
}
/** Report to the frontend that the game was successfully loaded. */
void Micropolis::didLoadCity()
{
callback("didLoadCity", "");
}
/**
* Report to the frontend that the game failed to load.
* @param msg File that attempted to load
*/
void Micropolis::didntLoadCity(const char *msg)
{
callback("didntLoadCity", "s", msg);
}
/**
* Try to save the game.
* @todo This is a no-op if the Micropolis::cityFileName is empty.
* In that case, we should probably warn the user about the failure.
*/
void Micropolis::saveCity()
{
if (cityFileName.length() > 0) {
doSaveCityAs();
} else {
if (saveFile(cityFileName.c_str())) {
didSaveCity();
} else {
didntSaveCity(cityFileName.c_str());
}
}
}
/** Report to the frontend that the city is being saved. */
void Micropolis::doSaveCityAs()
{
callback("saveCityAs", "");
}
/** Report to the frontend that the city was saved successfully. */
void Micropolis::didSaveCity()
{
callback("didSaveCity", "");
}
/**
* Report to the frontend that the city could not be saved.
* @param msg Name of the file used
*/
void Micropolis::didntSaveCity(const char *msg)
{
callback("didntSaveCity", "s", msg);
}
/**
* Save the city under a new name (?)
* @param filename Name of the file to use for storing the game.
* @todo String normalization code is duplicated in Micropolis::loadCity().
* Extract to a sub-function.
* @bug Function fails if \c lastDot<lastSlash (ie with \c "x.y/bla" )
*/
void Micropolis::saveCityAs(const char *filename)
{
cityFileName = filename;
if (saveFile(cityFileName.c_str())) {
unsigned int lastDot = cityFileName.find_last_of('.');
unsigned int lastSlash = cityFileName.find_last_of('/');
unsigned int pos =
(lastSlash == std::string::npos) ? 0 : lastSlash + 1;
unsigned int last =
(lastDot == std::string::npos) ? cityFileName.length() : lastDot;
unsigned int len =
last - pos;
std::string newCityName =
cityFileName.substr(pos, len);
setCityName(newCityName);
didSaveCity();
} else {
didntSaveCity(cityFileName.c_str());
}
}
////////////////////////////////////////////////////////////////////////