]> icculus.org git repositories - btb/d2x.git/blob - main/state.c
new PLAYER_DIR macro, use it for secret files
[btb/d2x.git] / main / state.c
1 /* $Id: state.c,v 1.27 2006-07-24 08:20:39 chris Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * Functions to save/restore game state.
18  *
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <conf.h>
23 #endif
24
25 #ifdef WINDOWS
26 #include "desw.h"
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <math.h>
32 #include <string.h>
33 #if !defined(_MSC_VER) && !defined(macintosh)
34 #include <unistd.h>
35 #endif
36 #ifndef _WIN32_WCE
37 #include <errno.h>
38 #endif
39 #ifdef MACINTOSH
40 #include <Files.h>
41 #endif
42
43 #ifdef OGL
44 # ifdef _MSC_VER
45 #  include <windows.h>
46 # endif
47 #if defined(__APPLE__) && defined(__MACH__)
48 #include <OpenGL/gl.h>
49 #else
50 #include <GL/gl.h>
51 #endif
52 #endif
53
54 #include "pstypes.h"
55 #include "mono.h"
56 #include "inferno.h"
57 #include "segment.h"
58 #include "textures.h"
59 #include "wall.h"
60 #include "object.h"
61 #include "digi.h"
62 #include "gamemine.h"
63 #include "error.h"
64 #include "gameseg.h"
65 #include "menu.h"
66 #include "switch.h"
67 #include "game.h"
68 #include "screens.h"
69 #include "newmenu.h"
70 #include "cfile.h"
71 #include "fuelcen.h"
72 #include "hash.h"
73 #include "key.h"
74 #include "piggy.h"
75 #include "player.h"
76 #include "cntrlcen.h"
77 #include "morph.h"
78 #include "weapon.h"
79 #include "render.h"
80 #include "gameseq.h"
81 #include "gauges.h"
82 #include "newdemo.h"
83 #include "automap.h"
84 #include "piggy.h"
85 #include "paging.h"
86 #include "titles.h"
87 #include "text.h"
88 #include "mission.h"
89 #include "pcx.h"
90 #include "u_mem.h"
91 #ifdef NETWORK
92 #include "network.h"
93 #endif
94 #include "args.h"
95 #include "ai.h"
96 #include "fireball.h"
97 #include "controls.h"
98 #include "laser.h"
99 #include "multibot.h"
100 #include "state.h"
101 #include "playsave.h"
102 #ifdef OGL
103 #include "gr.h"
104 #endif
105 #include "physfsx.h"
106
107 #define STATE_VERSION 22
108 #define STATE_COMPATIBLE_VERSION 20
109 // 0 - Put DGSS (Descent Game State Save) id at tof.
110 // 1 - Added Difficulty level save
111 // 2 - Added Cheats_enabled flag
112 // 3 - Added between levels save.
113 // 4 - Added mission support
114 // 5 - Mike changed ai and object structure.
115 // 6 - Added buggin' cheat save
116 // 7 - Added other cheat saves and game_id.
117 // 8 - Added AI stuff for escort and thief.
118 // 9 - Save palette with screen shot
119 // 12- Saved last_was_super array
120 // 13- Saved palette flash stuff
121 // 14- Save cloaking wall stuff
122 // 15- Save additional ai info
123 // 16- Save Light_subtracted
124 // 17- New marker save
125 // 18- Took out saving of old cheat status
126 // 19- Saved cheats_enabled flag
127 // 20- First_secret_visit
128 // 22- Omega_charge
129
130 #define NUM_SAVES 9
131 #define THUMBNAIL_W 100
132 #define THUMBNAIL_H 50
133 #define DESC_LENGTH 20
134
135 extern void multi_initiate_save_game();
136 extern void multi_initiate_restore_game();
137 extern void apply_all_changed_light(void);
138
139 extern int Do_appearance_effect;
140 extern fix Fusion_next_sound_time;
141
142 extern int Laser_rapid_fire;
143 extern int Physics_cheat_flag;
144 extern int Lunacy;
145 extern void do_lunacy_on(void);
146 extern void do_lunacy_off(void);
147 extern int First_secret_visit;
148
149 int sc_last_item= 0;
150 grs_bitmap *sc_bmp[NUM_SAVES+1];
151
152 char dgss_id[4] = "DGSS";
153
154 int state_default_item = 0;
155
156 uint state_game_id;
157
158 extern int robot_controlled[MAX_ROBOTS_CONTROLLED];
159 extern int robot_agitation[MAX_ROBOTS_CONTROLLED];
160 extern fix robot_controlled_time[MAX_ROBOTS_CONTROLLED];
161 extern fix robot_last_send_time[MAX_ROBOTS_CONTROLLED];
162 extern fix robot_last_message_time[MAX_ROBOTS_CONTROLLED];
163 extern int robot_send_pending[MAX_ROBOTS_CONTROLLED];
164 extern int robot_fired[MAX_ROBOTS_CONTROLLED];
165 extern sbyte robot_fire_buf[MAX_ROBOTS_CONTROLLED][18+3];
166
167
168 #if defined(WINDOWS) || defined(MACINTOSH)
169 extern ubyte Hack_DblClick_MenuMode;
170 #endif
171
172 //-------------------------------------------------------------------
173 void state_callback(int nitems,newmenu_item * items, int * last_key, int citem)
174 {
175 //      if ( sc_last_item != citem )    {
176 //              sc_last_item = citem;
177                 if ( citem > 0 )        {
178                         if ( sc_bmp[citem-1] )  {
179                                 if (MenuHires) {
180                                         grs_canvas *save_canv = grd_curcanv;
181                                         grs_canvas *temp_canv = gr_create_canvas(THUMBNAIL_W*2,(THUMBNAIL_H*24/10));
182                                         grs_point vertbuf[3] = {{0,0}, {0,0}, {i2f(THUMBNAIL_W*2),i2f(THUMBNAIL_H*24/10)} };
183                                         gr_set_current_canvas(temp_canv);
184                                         scale_bitmap(sc_bmp[citem-1], vertbuf, 0 );
185                                         gr_set_current_canvas( save_canv );
186                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W*2)/2,items[0].y-10, &temp_canv->cv_bitmap);
187                                         gr_free_canvas(temp_canv);
188                                 }
189                                 else    {
190                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W)/2,items[0].y-5, sc_bmp[citem-1] );
191                                 }
192                         }
193                 }
194 //      }       
195 }
196
197 void rpad_string( char * string, int max_chars )
198 {
199         int i, end_found;
200
201         end_found = 0;
202         for( i=0; i<max_chars; i++ )    {
203                 if ( *string == 0 )
204                         end_found = 1;
205                 if ( end_found )
206                         *string = ' ';
207                 string++;
208         }
209         *string = 0;            // NULL terminate
210 }
211
212 int state_get_save_file(char * fname, char * dsc, int multi, int blind_save)
213 {
214         PHYSFS_file *fp;
215         int i, choice, version;
216         newmenu_item m[NUM_SAVES+2];
217         char filename[NUM_SAVES+1][30];
218         char desc[NUM_SAVES+1][DESC_LENGTH+16];
219         char id[5];
220         int valid=0;
221         
222         for (i=0;i<NUM_SAVES; i++ )     {
223                 sc_bmp[i] = NULL;
224                 if ( !multi )
225                         #ifndef MACINTOSH
226                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
227                         #else
228                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
229                         #endif
230                 else
231                         #ifndef MACINTOSH
232                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
233                         #else
234                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
235                         #endif
236                 valid = 0;
237                 fp = PHYSFSX_openReadBuffered(filename[i]);
238                 if ( fp ) {
239                         //Read id
240                         //FIXME: check for swapped file, react accordingly...
241                         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
242                         if ( !memcmp( id, dgss_id, 4 )) {
243                                 //Read version
244                                 PHYSFS_read(fp, &version, sizeof(int), 1);
245                                 if (version >= STATE_COMPATIBLE_VERSION)        {
246                                         // Read description
247                                         PHYSFS_read(fp, desc[i], sizeof(char) * DESC_LENGTH, 1);
248                                         //rpad_string( desc[i], DESC_LENGTH-1 );
249                                         // Read thumbnail
250                                         //sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
251                                         //PHYSFS_read(fp, sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1);
252                                         valid = 1;
253                                 }
254                         } 
255                         PHYSFS_close(fp);
256                 }
257                 if (!valid) {
258                         strcpy( desc[i], TXT_EMPTY );
259                         //rpad_string( desc[i], DESC_LENGTH-1 );
260                 }
261                 m[i].type = NM_TYPE_INPUT_MENU; m[i].text = desc[i]; m[i].text_len = DESC_LENGTH-1;
262         }
263
264         sc_last_item = -1;
265         if (blind_save && state_default_item >= 0)
266                 choice = state_default_item;
267         else
268                 choice = newmenu_do1(NULL, "Save Game", NUM_SAVES, m, NULL, state_default_item);
269
270         for (i=0; i<NUM_SAVES; i++ )    {
271                 if ( sc_bmp[i] )
272                         gr_free_bitmap( sc_bmp[i] );
273         }
274
275         if (choice > -1) {
276                 strcpy( fname, filename[choice] );
277                 strcpy( dsc, desc[choice] );
278                 state_default_item = choice;
279                 return choice+1;
280         }
281         return 0;
282 }
283
284 int RestoringMenu=0;
285
286 int state_get_restore_file(char * fname, int multi)
287 {
288         PHYSFS_file *fp;
289         int i, choice, version, nsaves;
290         newmenu_item m[NUM_SAVES+2];
291         char filename[NUM_SAVES+1][30];
292         char desc[NUM_SAVES+1][DESC_LENGTH + 16];
293         char id[5];
294         int valid;
295
296         nsaves=0;
297         m[0].type = NM_TYPE_TEXT; m[0].text = "\n\n\n\n";       
298         for (i=0;i<NUM_SAVES+1; i++ )   {
299                 sc_bmp[i] = NULL;
300                 if (!multi)
301                         #ifndef MACINTOSH
302                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
303                         #else
304                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
305                         #endif
306                 else
307                         #ifndef MACINTOSH
308                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
309                         #else
310                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
311                         #endif
312                 valid = 0;
313                 fp = PHYSFSX_openReadBuffered(filename[i]);
314                 if ( fp ) {
315                         //Read id
316                         //FIXME: check for swapped file, react accordingly...
317                         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
318                         if ( !memcmp( id, dgss_id, 4 )) {
319                                 //Read version
320                                 PHYSFS_read(fp, &version, sizeof(int), 1);
321                                 if (version >= STATE_COMPATIBLE_VERSION)        {
322                                         // Read description
323                                         PHYSFS_read(fp, desc[i], sizeof(char) * DESC_LENGTH, 1);
324                                         //rpad_string( desc[i], DESC_LENGTH-1 );
325                                         m[i+1].type = NM_TYPE_MENU; m[i+1].text = desc[i];
326                                         // Read thumbnail
327                                         sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
328                                         PHYSFS_read(fp, sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1);
329                                         if (version >= 9) {
330                                                 ubyte pal[256*3];
331                                                 PHYSFS_read(fp, pal, 3, 256);
332                                                 gr_remap_bitmap_good( sc_bmp[i], pal, -1, -1 );
333                                         }
334                                         nsaves++;
335                                         valid = 1;
336                                 }
337                         }
338                         PHYSFS_close(fp);
339                 }
340                 if (!valid) {
341                         strcpy( desc[i], TXT_EMPTY );
342                         //rpad_string( desc[i], DESC_LENGTH-1 );
343                         m[i+1].type = NM_TYPE_TEXT; m[i+1].text = desc[i];
344                 }
345         }
346
347         if ( nsaves < 1 )       {
348                 nm_messagebox( NULL, 1, "Ok", "No saved games were found!" );
349                 return 0;
350         }
351
352         if (Current_display_mode == SM(640,400)) //restore menu won't fit on 640x400
353                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
354
355         sc_last_item = -1;
356
357 #if defined(WINDOWS) || defined(MACINTOSH)
358         Hack_DblClick_MenuMode = 1;
359 #endif
360
361    RestoringMenu=1;
362         choice = newmenu_do3( NULL, "Select Game to Restore", NUM_SAVES+2, m, state_callback, state_default_item+1, NULL, 190, -1 );
363    RestoringMenu=0;
364
365 #if defined(WINDOWS) || defined(MACINTOSH)
366         Hack_DblClick_MenuMode = 0;
367 #endif
368
369         if (Current_display_mode == SM(640,400)) //set flag back
370                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
371
372
373         for (i=0; i<NUM_SAVES+1; i++ )  {
374                 if ( sc_bmp[i] )
375                         gr_free_bitmap( sc_bmp[i] );
376         }
377
378         if (choice > 0) {
379                 strcpy( fname, filename[choice-1] );
380                 if (choice != NUM_SAVES+1)              //no new default when restore from autosave
381                         state_default_item = choice - 1;
382                 return choice;
383         }
384         return 0;
385 }
386
387 #define DESC_OFFSET     8
388
389 //      -----------------------------------------------------------------------------------
390 //      Imagine if C had a function to copy a file...
391 int copy_file(char *old_file, char *new_file)
392 {
393         sbyte   *buf;
394         int             buf_size;
395         PHYSFS_file *in_file, *out_file;
396
397         out_file = PHYSFS_openWrite(new_file);
398
399         if (out_file == NULL)
400                 return -1;
401
402         in_file = PHYSFS_openRead(old_file);
403
404         if (in_file == NULL)
405                 return -2;
406
407         buf_size = PHYSFS_fileLength(in_file);
408         while (buf_size && !(buf = d_malloc(buf_size)))
409                 buf_size /= 2;
410         if (buf_size == 0)
411                 return -5;      // likely to be an empty file
412
413         while (!PHYSFS_eof(in_file))
414         {
415                 int bytes_read;
416
417                 bytes_read = PHYSFS_read(in_file, buf, 1, buf_size);
418                 if (bytes_read < 0)
419                         Error("Cannot read from file <%s>: %s", old_file, PHYSFS_getLastError());
420
421                 Assert(bytes_read == buf_size || PHYSFS_eof(in_file));
422
423                 if (PHYSFS_write(out_file, buf, 1, bytes_read) < bytes_read)
424                         Error("Cannot write to file <%s>: %s", new_file, PHYSFS_getLastError());
425         }
426
427         d_free(buf);
428
429         if (!PHYSFS_close(in_file))
430         {
431                 PHYSFS_close(out_file);
432                 return -3;
433         }
434
435         if (!PHYSFS_close(out_file))
436                 return -4;
437
438         return 0;
439 }
440
441
442 extern int Final_boss_is_dead;
443
444 //      -----------------------------------------------------------------------------------
445 //      blind_save means don't prompt user for any info.
446 int state_save_all(int between_levels, int secret_save, char *filename_override, int blind_save)
447 {
448         int     rval, filenum = -1;
449
450         char    filename[128], desc[DESC_LENGTH+1];
451
452         Assert(between_levels == 0);    //between levels save ripped out
453
454 #ifdef NETWORK
455         if ( Game_mode & GM_MULTI )     {
456                         multi_initiate_save_game();
457                 return 0;
458         }
459 #endif
460
461         if ((Current_level_num < 0) && (secret_save == 0)) {
462                 HUD_init_message( "Can't save in secret level!" );
463                 return 0;
464         }
465
466         if (Final_boss_is_dead)         //don't allow save while final boss is dying
467                 return 0;
468
469         mprintf(( 0, "CL=%d, NL=%d\n", Current_level_num, Next_level_num ));
470         
471         //      If this is a secret save and the control center has been destroyed, don't allow
472         //      return to the base level.
473         if (secret_save && (Control_center_destroyed)) {
474                 mprintf((0, "Deleting secret.sgb so player can't return to base level.\n"));
475                 PHYSFS_delete(PLAYER_DIR "secret.sgb");
476                 return 0;
477         }
478
479         stop_time();
480
481         if (secret_save == 1) {
482                 filename_override = filename;
483                 sprintf(filename_override, PLAYER_DIR "secret.sgb");
484         } else if (secret_save == 2) {
485                 filename_override = filename;
486                 sprintf(filename_override, PLAYER_DIR "secret.sgc");
487         } else {
488                 if (filename_override) {
489                         strcpy( filename, filename_override);
490                         sprintf(desc, "[autosave backup]");
491                 }
492                 else if (!(filenum = state_get_save_file(filename, desc, 0, blind_save)))
493                 {
494                         start_time();
495                         return 0;
496                 }
497         }
498                 
499         //      MK, 1/1/96
500         //      If not in multiplayer, do special secret level stuff.
501         //      If secret.sgc exists, then copy it to Nsecret.sgc (where N = filenum).
502         //      If it doesn't exist, then delete Nsecret.sgc
503         if (!secret_save && !(Game_mode & GM_MULTI)) {
504                 int     rval;
505                 char    temp_fname[32], fc;
506
507                 if (filenum != -1) {
508
509                         if (filenum >= 10)
510                                 fc = (filenum-10) + 'a';
511                         else
512                                 fc = '0' + filenum;
513
514                         sprintf(temp_fname, PLAYER_DIR "%csecret.sgc", fc);
515
516                         mprintf((0, "Trying to copy secret.sgc to %s.\n", temp_fname));
517
518                         if (PHYSFS_exists(temp_fname))
519                         {
520                                 mprintf((0, "Deleting file %s\n", temp_fname));
521                                 if (!PHYSFS_delete(temp_fname))
522                                         Error("Cannot delete file <%s>: %s", temp_fname, PHYSFS_getLastError());
523                         }
524
525                         if (PHYSFS_exists(PLAYER_DIR "secret.sgc"))
526                         {
527                                 mprintf((0, "Copying secret.sgc to %s.\n", temp_fname));
528                                 rval = copy_file(PLAYER_DIR "secret.sgc", temp_fname);
529                                 Assert(rval == 0);      //      Oops, error copying secret.sgc to temp_fname!
530                         }
531                 }
532         }
533
534         //      Save file we're going to save over in last slot and call "[autosave backup]"
535         if (!filename_override) {
536                 PHYSFS_file *tfp;
537
538                 tfp = PHYSFSX_openWriteBuffered(filename);
539
540                 if ( tfp ) {
541                         char    newname[128];
542
543                         #ifndef MACINTOSH
544                         sprintf( newname, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
545                         #else
546                         sprintf(newname, "Players/%s.sg%x", Players[Player_num].callsign, NUM_SAVES);
547                         #endif
548
549                         PHYSFS_seek(tfp, DESC_OFFSET);
550                         PHYSFS_write(tfp, "[autosave backup]", sizeof(char) * DESC_LENGTH, 1);
551                         PHYSFS_close(tfp);
552                         PHYSFS_delete(newname);
553                         PHYSFSX_rename(filename, newname);
554                 }
555         }
556         
557         rval = state_save_all_sub(filename, desc, between_levels);
558         if (rval && !secret_save)
559                 HUD_init_message("Game saved.");
560
561         return rval;
562 }
563
564 extern  fix     Flash_effect, Time_flash_last_played;
565
566
567 int state_save_all_sub(char *filename, char *desc, int between_levels)
568 {
569         int i,j;
570         PHYSFS_file *fp;
571         grs_canvas * cnv;
572         ubyte *pal;
573
574         Assert(between_levels == 0);    //between levels save ripped out
575
576 /*      if ( Game_mode & GM_MULTI )     {
577                 {
578                 start_time();
579                 return 0;
580                 }
581         }*/
582
583         #if defined(MACINTOSH) && !defined(NDEBUG)
584         if ( strncmp(filename, ":Players:", 9) )
585                 Int3();
586         #endif
587
588         fp = PHYSFSX_openWriteBuffered(filename);
589         if ( !fp ) {
590                 if ( !(Game_mode & GM_MULTI) )
591                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
592                 start_time();
593                 return 0;
594         }
595
596 //Save id
597         PHYSFS_write(fp, dgss_id, sizeof(char) * 4, 1);
598
599 //Save version
600         i = STATE_VERSION;
601         PHYSFS_write(fp, &i, sizeof(int), 1);
602
603 //Save description
604         PHYSFS_write(fp, desc, sizeof(char) * DESC_LENGTH, 1);
605         
606 // Save the current screen shot...
607
608         cnv = gr_create_canvas( THUMBNAIL_W, THUMBNAIL_H );
609         if ( cnv )
610         {
611 #ifdef OGL
612                 ubyte *buf;
613                 int k;
614                 GLint gl_draw_buffer;
615 #endif
616                 grs_canvas * cnv_save;
617                 cnv_save = grd_curcanv;
618
619                 gr_set_current_canvas( cnv );
620
621                 render_frame(0, 0);
622
623 #if defined(OGL)
624 # if 1
625                 buf = d_malloc(THUMBNAIL_W * THUMBNAIL_H * 3);
626                 glGetIntegerv(GL_DRAW_BUFFER, &gl_draw_buffer);
627                 glReadBuffer(gl_draw_buffer);
628                 glReadPixels(0, SHEIGHT - THUMBNAIL_H, THUMBNAIL_W, THUMBNAIL_H, GL_RGB, GL_UNSIGNED_BYTE, buf);
629                 k = THUMBNAIL_H;
630                 for (i = 0; i < THUMBNAIL_W * THUMBNAIL_H; i++) {
631                         if (!(j = i % THUMBNAIL_W))
632                                 k--;
633                         cnv->cv_bitmap.bm_data[THUMBNAIL_W * k + j] =
634                                 gr_find_closest_color(buf[3*i]/4, buf[3*i+1]/4, buf[3*i+2]/4);
635                 }
636                 d_free(buf);
637 # else // simpler d1x method, not tested yet
638                 ogl_ubitblt_tolinear(grd_curcanv->cv_bitmap.bm_w, grd_curcanv->cv_bitmap.bm_h, 0, 0, 0, 0, &grd_curscreen->sc_canvas.cv_bitmap, &grd_curcanv->cv_bitmap);
639 # endif
640 #endif
641
642                 pal = gr_palette;
643
644                 PHYSFS_write(fp, cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H, 1);
645
646                 gr_set_current_canvas(cnv_save);
647                 gr_free_canvas( cnv );
648                 PHYSFS_write(fp, pal, 3, 256);
649         }
650         else
651         {
652                 ubyte color = 0;
653                 for ( i=0; i<THUMBNAIL_W*THUMBNAIL_H; i++ )
654                         PHYSFS_write(fp, &color, sizeof(ubyte), 1);             
655         } 
656
657 // Save the Between levels flag...
658         PHYSFS_write(fp, &between_levels, sizeof(int), 1);
659
660 // Save the mission info...
661         mprintf ((0, "HEY! Mission name is %s\n", Current_mission_filename));
662         PHYSFS_write(fp, Current_mission_filename, 9 * sizeof(char), 1);
663
664 //Save level info
665         PHYSFS_write(fp, &Current_level_num, sizeof(int), 1);
666         PHYSFS_write(fp, &Next_level_num, sizeof(int), 1);
667
668 //Save GameTime
669         PHYSFS_write(fp, &GameTime, sizeof(fix), 1);
670
671 // If coop save, save all
672 #ifdef NETWORK
673    if (Game_mode & GM_MULTI_COOP)
674          {
675                 PHYSFS_write(fp, &state_game_id,sizeof(int), 1);
676                 PHYSFS_write(fp, &Netgame,sizeof(netgame_info), 1);
677                 PHYSFS_write(fp, &NetPlayers,sizeof(AllNetPlayers_info), 1);
678                 PHYSFS_write(fp, &N_players,sizeof(int), 1);
679                 PHYSFS_write(fp, &Player_num,sizeof(int), 1);
680                 for (i=0;i<N_players;i++)
681                         PHYSFS_write(fp, &Players[i], sizeof(player), 1);
682
683 #ifdef RISKY_PROPOSITION
684                 PHYSFS_write(fp, &robot_controlled[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
685                 PHYSFS_write(fp, &robot_agitation[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
686                 PHYSFS_write(fp, &robot_controlled_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
687                 PHYSFS_write(fp, &robot_last_send_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
688                 PHYSFS_write(fp, &robot_last_message_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
689                 PHYSFS_write(fp, &robot_send_pending[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
690                 PHYSFS_write(fp, &robot_fired[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
691  
692       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
693                         PHYSFS_write(fp, robot_fire_buf[i][0], 18 + 3, 1);
694 #endif
695
696          }
697 #endif
698
699 //Save player info
700         PHYSFS_write(fp, &Players[Player_num], sizeof(player), 1);
701
702 // Save the current weapon info
703         PHYSFS_write(fp, &Primary_weapon, sizeof(sbyte), 1);
704         PHYSFS_write(fp, &Secondary_weapon, sizeof(sbyte), 1);
705
706 // Save the difficulty level
707         PHYSFS_write(fp, &Difficulty_level, sizeof(int), 1);
708 // Save cheats enabled
709         PHYSFS_write(fp, &Cheats_enabled,sizeof(int), 1);
710
711         if ( !between_levels )  {
712
713         //Finish all morph objects
714                 for (i=0; i<=Highest_object_index; i++ )        {
715                         if ( (Objects[i].type != OBJ_NONE) && (Objects[i].render_type==RT_MORPH))       {
716                                 morph_data *md;
717                                 md = find_morph_data(&Objects[i]);
718                                 if (md) {                                       
719                                         md->obj->control_type = md->morph_save_control_type;
720                                         md->obj->movement_type = md->morph_save_movement_type;
721                                         md->obj->render_type = RT_POLYOBJ;
722                                         md->obj->mtype.phys_info = md->morph_save_phys_info;
723                                         md->obj = NULL;
724                                 } else {                                                //maybe loaded half-morphed from disk
725                                         Objects[i].flags |= OF_SHOULD_BE_DEAD;
726                                         Objects[i].render_type = RT_POLYOBJ;
727                                         Objects[i].control_type = CT_NONE;
728                                         Objects[i].movement_type = MT_NONE;
729                                 }
730                         }
731                 }
732         
733         //Save object info
734                 i = Highest_object_index+1;
735                 PHYSFS_write(fp, &i, sizeof(int), 1);
736                 PHYSFS_write(fp, Objects, sizeof(object), i);
737                 
738         //Save wall info
739                 i = Num_walls;
740                 PHYSFS_write(fp, &i, sizeof(int), 1);
741                 PHYSFS_write(fp, Walls, sizeof(wall), i);
742
743         //Save exploding wall info
744                 i = MAX_EXPLODING_WALLS;
745                 PHYSFS_write(fp, &i, sizeof(int), 1);
746                 PHYSFS_write(fp, expl_wall_list, sizeof(*expl_wall_list), i);
747         
748         //Save door info
749                 i = Num_open_doors;
750                 PHYSFS_write(fp, &i, sizeof(int), 1);
751                 PHYSFS_write(fp, ActiveDoors, sizeof(active_door), i);
752         
753         //Save cloaking wall info
754                 i = Num_cloaking_walls;
755                 PHYSFS_write(fp, &i, sizeof(int), 1);
756                 PHYSFS_write(fp, CloakingWalls, sizeof(cloaking_wall), i);
757         
758         //Save trigger info
759                 PHYSFS_write(fp, &Num_triggers, sizeof(int), 1);
760                 PHYSFS_write(fp, Triggers, sizeof(trigger), Num_triggers);
761         
762         //Save tmap info
763                 for (i = 0; i <= Highest_segment_index; i++)
764                 {
765                         for (j = 0; j < 6; j++)
766                         {
767                                 PHYSFS_write(fp, &Segments[i].sides[j].wall_num, sizeof(short), 1);
768                                 PHYSFS_write(fp, &Segments[i].sides[j].tmap_num, sizeof(short), 1);
769                                 PHYSFS_write(fp, &Segments[i].sides[j].tmap_num2, sizeof(short), 1);
770                         }
771                 }
772         
773         // Save the fuelcen info
774                 PHYSFS_write(fp, &Control_center_destroyed, sizeof(int), 1);
775                 PHYSFS_write(fp, &Countdown_timer, sizeof(int), 1);
776                 PHYSFS_write(fp, &Num_robot_centers, sizeof(int), 1);
777                 PHYSFS_write(fp, RobotCenters, sizeof(matcen_info), Num_robot_centers);
778                 PHYSFS_write(fp, &ControlCenterTriggers, sizeof(control_center_triggers), 1);
779                 PHYSFS_write(fp, &Num_fuelcenters, sizeof(int), 1);
780                 PHYSFS_write(fp, Station, sizeof(FuelCenter), Num_fuelcenters);
781         
782         // Save the control cen info
783                 PHYSFS_write(fp, &Control_center_been_hit, sizeof(int), 1);
784                 PHYSFS_write(fp, &Control_center_player_been_seen, sizeof(int), 1);
785                 PHYSFS_write(fp, &Control_center_next_fire_time, sizeof(int), 1);
786                 PHYSFS_write(fp, &Control_center_present, sizeof(int), 1);
787                 PHYSFS_write(fp, &Dead_controlcen_object_num, sizeof(int), 1);
788         
789         // Save the AI state
790                 ai_save_state( fp );
791         
792         // Save the automap visited info
793                 PHYSFS_write(fp, Automap_visited, sizeof(ubyte), MAX_SEGMENTS);
794
795         }
796         PHYSFS_write(fp, &state_game_id, sizeof(uint), 1);
797         PHYSFS_write(fp, &Laser_rapid_fire, sizeof(int), 1);
798         PHYSFS_write(fp, &Lunacy, sizeof(int), 1);  //  Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
799         PHYSFS_write(fp, &Lunacy, sizeof(int), 1);
800
801         // Save automap marker info
802
803         PHYSFS_write(fp, MarkerObject, sizeof(MarkerObject) ,1);
804         PHYSFS_write(fp, MarkerOwner, sizeof(MarkerOwner), 1);
805         PHYSFS_write(fp, MarkerMessage, sizeof(MarkerMessage), 1);
806
807         PHYSFS_write(fp, &Afterburner_charge, sizeof(fix), 1);
808
809         //save last was super information
810         PHYSFS_write(fp, &Primary_last_was_super, sizeof(Primary_last_was_super), 1);
811         PHYSFS_write(fp, &Secondary_last_was_super, sizeof(Secondary_last_was_super), 1);
812
813         //      Save flash effect stuff
814         PHYSFS_write(fp, &Flash_effect, sizeof(int), 1);
815         PHYSFS_write(fp, &Time_flash_last_played, sizeof(int), 1);
816         PHYSFS_write(fp, &PaletteRedAdd, sizeof(int), 1);
817         PHYSFS_write(fp, &PaletteGreenAdd, sizeof(int), 1);
818         PHYSFS_write(fp, &PaletteBlueAdd, sizeof(int), 1);
819
820         PHYSFS_write(fp, Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS);
821
822         PHYSFS_write(fp, &First_secret_visit, sizeof(First_secret_visit), 1);
823
824         if (PHYSFS_write(fp, &Omega_charge, sizeof(Omega_charge), 1) < 1)
825         {
826                 if ( !(Game_mode & GM_MULTI) ) {
827                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
828                         PHYSFS_close(fp);
829                         PHYSFS_delete(filename);
830                 }
831         } else  {
832                 PHYSFS_close(fp);
833
834                 #ifdef MACINTOSH                // set the type and creator of the saved game file
835                 {
836                         FInfo finfo;
837                         OSErr err;
838                         Str255 pfilename;
839         
840                         strcpy(pfilename, filename);
841                         c2pstr(pfilename);
842                         err = HGetFInfo(0, 0, pfilename, &finfo);
843                         finfo.fdType = 'SVGM';
844                         finfo.fdCreator = 'DCT2';
845                         err = HSetFInfo(0, 0, pfilename, &finfo);
846                 }
847                 #endif
848         }
849         
850         start_time();
851
852         return 1;
853 }
854
855 //      -----------------------------------------------------------------------------------
856 //      Set the player's position from the globals Secret_return_segment and Secret_return_orient.
857 void set_pos_from_return_segment(void)
858 {
859         int     plobjnum = Players[Player_num].objnum;
860
861         compute_segment_center(&Objects[plobjnum].pos, &Segments[Secret_return_segment]);
862         obj_relink(plobjnum, Secret_return_segment);
863         reset_player_object();
864         Objects[plobjnum].orient = Secret_return_orient;
865 }
866
867 //      -----------------------------------------------------------------------------------
868 int state_restore_all(int in_game, int secret_restore, char *filename_override)
869 {
870         char filename[128];
871         int     filenum = -1;
872
873 #ifdef NETWORK
874         if ( Game_mode & GM_MULTI )     {
875 #ifdef MULTI_SAVE
876                         multi_initiate_restore_game();
877 #endif
878                 return 0;
879         }
880 #endif
881
882         if (in_game && (Current_level_num < 0) && (secret_restore == 0)) {
883                 HUD_init_message( "Can't restore in secret level!" );
884                 return 0;
885         }
886
887         if ( Newdemo_state == ND_STATE_RECORDING )
888                 newdemo_stop_recording();
889
890         if ( Newdemo_state != ND_STATE_NORMAL )
891                 return 0;
892
893         stop_time();
894
895         if (filename_override) {
896                 strcpy(filename, filename_override);
897                 filenum = NUM_SAVES+1;          //      So we don't trigger autosave
898         } else if (!(filenum = state_get_restore_file(filename, 0)))    {
899                 start_time();
900                 return 0;
901         }
902         
903         //      MK, 1/1/96
904         //      If not in multiplayer, do special secret level stuff.
905         //      If Nsecret.sgc (where N = filenum) exists, then copy it to secret.sgc.
906         //      If it doesn't exist, then delete secret.sgc
907         if (!secret_restore && !(Game_mode & GM_MULTI)) {
908                 int     rval;
909                 char    temp_fname[32], fc;
910
911                 if (filenum != -1) {
912                         if (filenum >= 10)
913                                 fc = (filenum-10) + 'a';
914                         else
915                                 fc = '0' + filenum;
916                         
917                         sprintf(temp_fname, PLAYER_DIR "%csecret.sgc", fc);
918
919                         mprintf((0, "Trying to copy %s to secret.sgc.\n", temp_fname));
920
921                         if (PHYSFS_exists(temp_fname))
922                         {
923                                 mprintf((0, "Copying %s to secret.sgc\n", temp_fname));
924                                 rval = copy_file(temp_fname, PLAYER_DIR "secret.sgc");
925                                 Assert(rval == 0);      //      Oops, error copying temp_fname to secret.sgc!
926                         } else
927                                 PHYSFS_delete(PLAYER_DIR "secret.sgc");
928                 }
929         }
930
931         //      Changed, 11/15/95, MK, don't to autosave if restoring from main menu.
932         if ((filenum != (NUM_SAVES+1)) && in_game) {
933                 char    temp_filename[128];
934                 mprintf((0, "Doing autosave, filenum = %i, != %i!\n", filenum, NUM_SAVES+1));
935                 #ifndef MACINTOSH
936                 sprintf( temp_filename, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
937                 #else
938                 sprintf(temp_filename, "Players/%s.sg%x", Players[Player_num].callsign, NUM_SAVES);
939                 #endif
940                 state_save_all(!in_game, secret_restore, temp_filename, 0);
941         }
942
943         if ( !secret_restore && in_game ) {
944                 int choice;
945                 choice =  nm_messagebox( NULL, 2, "Yes", "No", "Restore Game?" );
946                 if ( choice != 0 )      {
947                         start_time();
948                         return 0;
949                 }
950         }
951
952         start_time();
953
954         return state_restore_all_sub(filename, 0, secret_restore);
955 }
956
957 extern void init_player_stats_new_ship(void);
958
959 void ShowLevelIntro(int level_num);
960
961 extern void do_cloak_invul_secret_stuff(fix old_gametime);
962 extern void copy_defaults_to_robot(object *objp);
963
964 int state_restore_all_sub(char *filename, int multi, int secret_restore)
965 {
966         int ObjectStartLocation;
967         int version,i, j, segnum;
968         object * obj;
969         PHYSFS_file *fp;
970         int current_level, next_level;
971         int between_levels;
972         char mission[16];
973         char desc[DESC_LENGTH+1];
974         char id[5];
975         char org_callsign[CALLSIGN_LEN+16];
976 #ifdef NETWORK
977         int found;
978         int nplayers;   //,playid[12],mynum;
979         player restore_players[MAX_PLAYERS];
980 #endif
981         fix     old_gametime = GameTime;
982         short TempTmapNum[MAX_SEGMENTS][MAX_SIDES_PER_SEGMENT];
983         short TempTmapNum2[MAX_SEGMENTS][MAX_SIDES_PER_SEGMENT];
984
985         #if defined(MACINTOSH) && !defined(NDEBUG)
986         if (strncmp(filename, "Players/", 9))
987                 Int3();
988         #endif
989
990         fp = PHYSFSX_openReadBuffered(filename);
991         if ( !fp ) return 0;
992
993 //Read id
994         //FIXME: check for swapped file, react accordingly...
995         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
996         if ( memcmp( id, dgss_id, 4 )) {
997                 PHYSFS_close(fp);
998                 return 0;
999         }
1000
1001 //Read version
1002         PHYSFS_read(fp, &version, sizeof(int), 1);
1003         if (version < STATE_COMPATIBLE_VERSION) {
1004                 PHYSFS_close(fp);
1005                 return 0;
1006         }
1007
1008 // Read description
1009         PHYSFS_read(fp, desc, sizeof(char) * DESC_LENGTH, 1);
1010
1011 // Skip the current screen shot...
1012         PHYSFS_seek(fp, PHYSFS_tell(fp) + THUMBNAIL_W * THUMBNAIL_H);
1013
1014 // And now...skip the goddamn palette stuff that somebody forgot to add
1015         PHYSFS_seek(fp, PHYSFS_tell(fp) + 768);
1016
1017 // Read the Between levels flag...
1018         PHYSFS_read(fp, &between_levels, sizeof(int), 1);
1019
1020         Assert(between_levels == 0);    //between levels save ripped out
1021
1022 // Read the mission info...
1023         PHYSFS_read(fp, mission, sizeof(char) * 9, 1);
1024         mprintf ((0,"Missionname to load = %s\n",mission));
1025
1026         if (!load_mission_by_name( mission ))   {
1027                 nm_messagebox( NULL, 1, "Ok", "Error!\nUnable to load mission\n'%s'\n", mission );
1028                 PHYSFS_close(fp);
1029                 return 0;
1030         }
1031
1032 //Read level info
1033         PHYSFS_read(fp, &current_level, sizeof(int), 1);
1034         PHYSFS_read(fp, &next_level, sizeof(int), 1);
1035
1036 //Restore GameTime
1037         PHYSFS_read(fp, &GameTime, sizeof(fix), 1);
1038
1039 // Start new game....
1040         if (!multi)     {
1041                 Game_mode = GM_NORMAL;
1042                 Function_mode = FMODE_GAME;
1043 #ifdef NETWORK
1044                 change_playernum_to(0);
1045 #endif
1046                 strcpy( org_callsign, Players[0].callsign );
1047                 N_players = 1;
1048                 if (!secret_restore) {
1049                         InitPlayerObject();                             //make sure player's object set up
1050                         init_player_stats_game();               //clear all stats
1051                 }
1052         } else {
1053                 strcpy( org_callsign, Players[Player_num].callsign );
1054         }
1055
1056 #ifdef NETWORK
1057    if (Game_mode & GM_MULTI)
1058          {
1059                 PHYSFS_read(fp, &state_game_id, sizeof(int), 1);
1060                 PHYSFS_read(fp, &Netgame, sizeof(netgame_info), 1);
1061                 PHYSFS_read(fp, &NetPlayers, sizeof(AllNetPlayers_info), 1);
1062                 PHYSFS_read(fp, &nplayers, sizeof(N_players), 1);
1063                 PHYSFS_read(fp, &Player_num, sizeof(Player_num), 1);
1064                 for (i=0;i<nplayers;i++)
1065                         PHYSFS_read(fp, &restore_players[i], sizeof(player), 1);
1066 #ifdef RISKY_PROPOSITION
1067                 PHYSFS_read(fp, &robot_controlled[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1068                 PHYSFS_read(fp, &robot_agitation[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1069                 PHYSFS_read(fp, &robot_controlled_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1070                 PHYSFS_read(fp, &robot_last_send_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1071                 PHYSFS_read(fp, &robot_last_message_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1072                 PHYSFS_read(fp, &robot_send_pending[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1073                 PHYSFS_read(fp, &robot_fired[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1074
1075       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
1076                         PHYSFS_read(fp, &robot_fire_buf[i][0],21,1);
1077 #endif
1078
1079            for (i=0;i<nplayers;i++)
1080                  {
1081                   found=0;
1082                   for (j=0;j<nplayers;j++)
1083                          {
1084            if ((!strcmp (restore_players[i].callsign,Players[j].callsign)) && Players[j].connected==1)
1085                                  found=1;
1086                          }
1087                   restore_players[i].connected=found;
1088             }
1089                 memcpy (&Players,&restore_players,sizeof(player)*nplayers);
1090                 N_players=nplayers;
1091
1092       if (network_i_am_master())
1093                  {
1094                   for (i=0;i<N_players;i++)
1095                         {
1096                          if (i==Player_num)
1097                                 continue;
1098                  Players[i].connected=0;
1099                         }
1100                  }
1101
1102                 //Viewer = ConsoleObject = &Objects[Players[Player_num].objnum];
1103          }
1104
1105 #endif
1106
1107 //Read player info
1108
1109         {
1110                 StartNewLevelSub(current_level, 1, secret_restore);
1111
1112                 if (secret_restore) {
1113                         player  dummy_player;
1114
1115                         PHYSFS_read(fp, &dummy_player, sizeof(player), 1);
1116                         if (secret_restore == 1) {              //      This means he didn't die, so he keeps what he got in the secret level.
1117                                 Players[Player_num].level = dummy_player.level;
1118                                 Players[Player_num].last_score = dummy_player.last_score;
1119                                 Players[Player_num].time_level = dummy_player.time_level;
1120
1121                                 Players[Player_num].num_robots_level = dummy_player.num_robots_level;
1122                                 Players[Player_num].num_robots_total = dummy_player.num_robots_total;
1123                                 Players[Player_num].hostages_rescued_total = dummy_player.hostages_rescued_total;
1124                                 Players[Player_num].hostages_total = dummy_player.hostages_total;
1125                                 Players[Player_num].hostages_on_board = dummy_player.hostages_on_board;
1126                                 Players[Player_num].hostages_level = dummy_player.hostages_level;
1127                                 Players[Player_num].homing_object_dist = dummy_player.homing_object_dist;
1128                                 Players[Player_num].hours_level = dummy_player.hours_level;
1129                                 Players[Player_num].hours_total = dummy_player.hours_total;
1130                                 do_cloak_invul_secret_stuff(old_gametime);
1131                         } else {
1132                                 Players[Player_num] = dummy_player;
1133                         }
1134                 } else {
1135                         PHYSFS_read(fp, &Players[Player_num], sizeof(player), 1);
1136                 }
1137         }
1138         strcpy( Players[Player_num].callsign, org_callsign );
1139
1140 // Set the right level
1141         if ( between_levels )
1142                 Players[Player_num].level = next_level;
1143
1144 // Restore the weapon states
1145         PHYSFS_read(fp, &Primary_weapon, sizeof(sbyte), 1);
1146         PHYSFS_read(fp, &Secondary_weapon, sizeof(sbyte), 1);
1147
1148         select_weapon(Primary_weapon, 0, 0, 0);
1149         select_weapon(Secondary_weapon, 1, 0, 0);
1150
1151 // Restore the difficulty level
1152         PHYSFS_read(fp, &Difficulty_level, sizeof(int), 1);
1153
1154 // Restore the cheats enabled flag
1155
1156         PHYSFS_read(fp, &Cheats_enabled, sizeof(int),1);
1157
1158         if ( !between_levels )  {
1159                 Do_appearance_effect = 0;                       // Don't do this for middle o' game stuff.
1160
1161                 ObjectStartLocation = PHYSFS_tell(fp);
1162                 //Clear out all the objects from the lvl file
1163                 for (segnum=0; segnum <= Highest_segment_index; segnum++)
1164                         Segments[segnum].objects = -1;
1165                 reset_objects(1);
1166         
1167                 //Read objects, and pop 'em into their respective segments.
1168                 PHYSFS_read(fp, &i, sizeof(int), 1);
1169                 Highest_object_index = i-1;
1170                 PHYSFS_read(fp, Objects, sizeof(object) * i, 1);
1171         
1172                 Object_next_signature = 0;
1173                 for (i=0; i<=Highest_object_index; i++ )        {
1174                         obj = &Objects[i];
1175                         obj->rtype.pobj_info.alt_textures = -1;
1176                         segnum = obj->segnum;
1177                         obj->next = obj->prev = obj->segnum = -1;
1178                         if ( obj->type != OBJ_NONE )    {
1179                                 obj_link(i,segnum);
1180                                 if ( obj->signature > Object_next_signature )
1181                                         Object_next_signature = obj->signature;
1182                         }
1183
1184                         //look for, and fix, boss with bogus shields
1185                         if (obj->type == OBJ_ROBOT && Robot_info[obj->id].boss_flag) {
1186                                 fix save_shields = obj->shields;
1187
1188                                 copy_defaults_to_robot(obj);            //calculate starting shields
1189
1190                                 //if in valid range, use loaded shield value
1191                                 if (save_shields > 0 && save_shields <= obj->shields)
1192                                         obj->shields = save_shields;
1193                                 else
1194                                         obj->shields /= 2;  //give player a break
1195                         }
1196
1197                 }       
1198                 special_reset_objects();
1199                 Object_next_signature++;
1200         
1201                 //      1 = Didn't die on secret level.
1202                 //      2 = Died on secret level.
1203                 if (secret_restore && (Current_level_num >= 0)) {
1204                         set_pos_from_return_segment();
1205                         if (secret_restore == 2)
1206                                 init_player_stats_new_ship();
1207                 }
1208
1209                 //Restore wall info
1210                 PHYSFS_read(fp, &i, sizeof(int), 1);
1211                 Num_walls = i;
1212                 PHYSFS_read(fp, Walls, sizeof(wall), Num_walls);
1213
1214                 //now that we have the walls, check if any sounds are linked to
1215                 //walls that are now open
1216                 for (i=0;i<Num_walls;i++) {
1217                         if (Walls[i].type == WALL_OPEN)
1218                                 digi_kill_sound_linked_to_segment(Walls[i].segnum,Walls[i].sidenum,-1); //-1 means kill any sound
1219                 }
1220
1221                 //Restore exploding wall info
1222                 if (version >= 10) {
1223                         PHYSFS_read(fp, &i, sizeof(int), 1);
1224                         PHYSFS_read(fp, expl_wall_list, sizeof(*expl_wall_list), i);
1225                 }
1226
1227                 //Restore door info
1228                 PHYSFS_read(fp, &i, sizeof(int), 1);
1229                 Num_open_doors = i;
1230                 PHYSFS_read(fp, ActiveDoors, sizeof(active_door), Num_open_doors);
1231         
1232                 if (version >= 14) {            //Restore cloaking wall info
1233                         PHYSFS_read(fp, &i, sizeof(int), 1);
1234                         Num_cloaking_walls = i;
1235                         PHYSFS_read(fp, CloakingWalls, sizeof(cloaking_wall), Num_cloaking_walls);
1236                 }
1237         
1238                 //Restore trigger info
1239                 PHYSFS_read(fp, &Num_triggers, sizeof(int), 1);
1240                 PHYSFS_read(fp, Triggers, sizeof(trigger), Num_triggers);
1241         
1242                 //Restore tmap info (to temp values so we can use compiled-in tmap info to compute static_light)
1243                 for (i=0; i<=Highest_segment_index; i++ )       {
1244                         for (j=0; j<6; j++ )    {
1245                                 PHYSFS_read(fp, &Segments[i].sides[j].wall_num, sizeof(short), 1);
1246                                 PHYSFS_read(fp, &TempTmapNum[i][j], sizeof(short), 1);
1247                                 PHYSFS_read(fp, &TempTmapNum2[i][j], sizeof(short), 1);
1248                         }
1249                 }
1250         
1251                 //Restore the fuelcen info
1252                 PHYSFS_read(fp, &Control_center_destroyed, sizeof(int), 1);
1253                 PHYSFS_read(fp, &Countdown_timer, sizeof(int), 1);
1254                 PHYSFS_read(fp, &Num_robot_centers, sizeof(int), 1);
1255                 PHYSFS_read(fp, RobotCenters, sizeof(matcen_info), Num_robot_centers);
1256                 PHYSFS_read(fp, &ControlCenterTriggers, sizeof(control_center_triggers), 1);
1257                 PHYSFS_read(fp, &Num_fuelcenters, sizeof(int), 1);
1258                 PHYSFS_read(fp, Station, sizeof(FuelCenter), Num_fuelcenters);
1259         
1260                 // Restore the control cen info
1261                 PHYSFS_read(fp, &Control_center_been_hit, sizeof(int), 1);
1262                 PHYSFS_read(fp, &Control_center_player_been_seen, sizeof(int), 1);
1263                 PHYSFS_read(fp, &Control_center_next_fire_time, sizeof(int), 1);
1264                 PHYSFS_read(fp, &Control_center_present, sizeof(int), 1);
1265                 PHYSFS_read(fp, &Dead_controlcen_object_num, sizeof(int), 1);
1266         
1267                 // Restore the AI state
1268                 ai_restore_state( fp, version );
1269         
1270                 // Restore the automap visited info
1271                 PHYSFS_read(fp, Automap_visited, sizeof(ubyte), MAX_SEGMENTS);
1272
1273                 //      Restore hacked up weapon system stuff.
1274                 Fusion_next_sound_time = GameTime;
1275                 Auto_fire_fusion_cannon_time = 0;
1276                 Next_laser_fire_time = GameTime;
1277                 Next_missile_fire_time = GameTime;
1278                 Last_laser_fired_time = GameTime;
1279
1280         }
1281         state_game_id = 0;
1282
1283         if ( version >= 7 )     {
1284                 PHYSFS_read(fp, &state_game_id, sizeof(uint), 1);
1285                 PHYSFS_read(fp, &Laser_rapid_fire, sizeof(int), 1);
1286                 PHYSFS_read(fp, &Lunacy, sizeof(int), 1);               //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
1287                 PHYSFS_read(fp, &Lunacy, sizeof(int), 1);
1288                 if ( Lunacy )
1289                         do_lunacy_on();
1290         }
1291
1292         if (version >= 17) {
1293                 PHYSFS_read(fp, MarkerObject, sizeof(MarkerObject), 1);
1294                 PHYSFS_read(fp, MarkerOwner, sizeof(MarkerOwner), 1);
1295                 PHYSFS_read(fp, MarkerMessage, sizeof(MarkerMessage), 1);
1296         }
1297         else {
1298                 int num,dummy;
1299
1300                 // skip dummy info
1301
1302                 PHYSFS_read(fp, &num,sizeof(int), 1);           // was NumOfMarkers
1303                 PHYSFS_read(fp, &dummy,sizeof(int), 1);         // was CurMarker
1304
1305                 PHYSFS_seek(fp, PHYSFS_tell(fp) + num * (sizeof(vms_vector) + 40));
1306
1307                 for (num=0;num<NUM_MARKERS;num++)
1308                         MarkerObject[num] = -1;
1309         }
1310
1311         if (version>=11) {
1312                 if (secret_restore != 1)
1313                         PHYSFS_read(fp, &Afterburner_charge, sizeof(fix), 1);
1314                 else {
1315                         fix     dummy_fix;
1316                         PHYSFS_read(fp, &dummy_fix, sizeof(fix), 1);
1317                 }
1318         }
1319         if (version>=12) {
1320                 //read last was super information
1321                 PHYSFS_read(fp, &Primary_last_was_super, sizeof(Primary_last_was_super), 1);
1322                 PHYSFS_read(fp, &Secondary_last_was_super, sizeof(Secondary_last_was_super), 1);
1323         }
1324
1325         if (version >= 12) {
1326                 PHYSFS_read(fp, &Flash_effect, sizeof(int), 1);
1327                 PHYSFS_read(fp, &Time_flash_last_played, sizeof(int), 1);
1328                 PHYSFS_read(fp, &PaletteRedAdd, sizeof(int), 1);
1329                 PHYSFS_read(fp, &PaletteGreenAdd, sizeof(int), 1);
1330                 PHYSFS_read(fp, &PaletteBlueAdd, sizeof(int), 1);
1331         } else {
1332                 Flash_effect = 0;
1333                 Time_flash_last_played = 0;
1334                 PaletteRedAdd = 0;
1335                 PaletteGreenAdd = 0;
1336                 PaletteBlueAdd = 0;
1337         }
1338
1339         //      Load Light_subtracted
1340         if (version >= 16) {
1341                 PHYSFS_read(fp, Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS);
1342                 apply_all_changed_light();
1343         } else {
1344                 int     i;
1345                 for (i=0; i<=Highest_segment_index; i++)
1346                         Light_subtracted[i] = 0;
1347         }
1348
1349         // static_light should now be computed - now actually set tmap info
1350         for (i=0; i<=Highest_segment_index; i++ )       {
1351                 for (j=0; j<6; j++ )    {
1352                         Segments[i].sides[j].tmap_num=TempTmapNum[i][j];
1353                         Segments[i].sides[j].tmap_num2=TempTmapNum2[i][j];
1354                 }
1355         }
1356
1357         if (!secret_restore) {
1358                 if (version >= 20) {
1359                         PHYSFS_read(fp, &First_secret_visit, sizeof(First_secret_visit), 1);
1360                         mprintf((0, "File: [%s] Read First_secret_visit: New value = %i\n", filename, First_secret_visit));
1361                 } else
1362                         First_secret_visit = 1;
1363         } else
1364                 First_secret_visit = 0;
1365
1366         if (version >= 22)
1367         {
1368                 if (secret_restore != 1)
1369                         PHYSFS_read(fp, &Omega_charge, sizeof(fix), 1);
1370                 else {
1371                         fix     dummy_fix;
1372                         PHYSFS_read(fp, &dummy_fix, sizeof(fix), 1);
1373                 }
1374         }
1375
1376         PHYSFS_close(fp);
1377
1378 #ifdef NETWORK
1379    if (Game_mode & GM_MULTI)   // Get rid of ships that aren't
1380          {                                                                       // connected in the restored game
1381                 for (i=0;i<nplayers;i++)
1382                  {
1383                   mprintf ((0,"Testing %s = %d\n",Players[i].callsign,Players[i].connected));
1384                   if (Players[i].connected!=1)
1385                    {
1386                     network_disconnect_player (i);
1387                create_player_appearance_effect(&Objects[Players[i].objnum]);
1388                          mprintf ((0,"Killing player ship %s!\n",Players[i].callsign));
1389               }
1390                  }
1391                         
1392          }
1393 #endif
1394
1395 // Load in bitmaps, etc..
1396 //!!    piggy_load_level_data();        //already done by StartNewLevelSub()
1397
1398         return 1;
1399 }
1400
1401
1402 int state_get_game_id(char *filename)
1403 {
1404         int version;
1405         PHYSFS_file *fp;
1406         int between_levels;
1407         char mission[16];
1408         char desc[DESC_LENGTH+1];
1409         char id[5];
1410         int dumbint;
1411
1412 mprintf((0, "Restoring multigame from [%s]\n", filename));
1413
1414         fp = PHYSFS_openRead(filename);
1415         if (!fp) return 0;
1416
1417 //Read id
1418         //FIXME: check for swapped file, react accordingly...
1419         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
1420         if ( memcmp( id, dgss_id, 4 )) {
1421                 PHYSFS_close(fp);
1422                 return 0;
1423         }
1424
1425 //Read version
1426         PHYSFS_read(fp, &version, sizeof(int), 1);
1427         if (version < STATE_COMPATIBLE_VERSION) {
1428                 PHYSFS_close(fp);
1429                 return 0;
1430         }
1431
1432 // Read description
1433         PHYSFS_read(fp, desc, sizeof(char) * DESC_LENGTH, 1);
1434
1435 // Skip the current screen shot...
1436         PHYSFS_seek(fp, PHYSFS_tell(fp) + THUMBNAIL_W * THUMBNAIL_H);
1437
1438 // And now...skip the palette stuff that somebody forgot to add
1439         PHYSFS_seek(fp, PHYSFS_tell(fp) + 768);
1440
1441 // Read the Between levels flag...
1442         PHYSFS_read(fp, &between_levels, sizeof(int), 1);
1443
1444         Assert(between_levels == 0);    //between levels save ripped out
1445
1446 // Read the mission info...
1447         PHYSFS_read(fp, mission, sizeof(char) * 9, 1);
1448 //Read level info
1449         PHYSFS_read(fp, &dumbint, sizeof(int), 1);
1450         PHYSFS_read(fp, &dumbint, sizeof(int), 1);
1451
1452 //Restore GameTime
1453         PHYSFS_read(fp, &dumbint, sizeof(fix), 1);
1454
1455         PHYSFS_read(fp, &state_game_id, sizeof(int), 1);
1456
1457         return (state_game_id);
1458  }