Visual C, PocketPC fixes
[btb/d2x.git] / main / state.c
1 /* $Id: state.c,v 1.11 2003-11-26 12:26:33 btb 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  * Old Log:
20  * Revision 1.7  1995/10/31  10:18:25  allender
21  * shareware stuff
22  *
23  * Revision 1.6  1995/10/21  22:25:45  allender
24  * put in creator code and file type for saved games.
25  * put save games in players folder
26  *
27  * Revision 1.5  1995/10/20  00:51:21  allender
28  * close boxes and proper mouse support on save game stuff
29  *
30  * Revision 1.4  1995/10/17  13:19:02  allender
31  * close boxes for load and save game
32  *
33  * Revision 1.3  1995/09/18  08:09:15  allender
34  * made larger thumbnail and handled NULL gr_bitmap pointers
35  * better
36  *
37  * Revision 1.2  1995/08/14  14:36:12  allender
38  * change transparency to 0
39  *
40  * Revision 1.1  1995/05/16  15:31:12  allender
41  * Initial revision
42  *
43  * Revision 2.14  1995/05/26  16:16:10  john
44  * Split SATURN into define's for requiring cd, using cd, etc.
45  * Also started adding all the Rockwell stuff.
46  *
47  * Revision 2.13  1995/04/06  15:12:20  john
48  * Fixed bug with lunacy not working.
49  *
50  * Revision 2.12  1995/04/04  13:33:05  john
51  * Removed multiplayer save.
52  *
53  * Revision 2.11  1995/03/31  13:42:10  john
54  * Made saved games from the bogus saturn version read in
55  * correctly.
56  *
57  * Revision 2.10  1995/03/31  12:45:28  john
58  * Fixed bug with previous.
59  *
60  * Revision 2.9  1995/03/31  12:24:40  john
61  * I had changed alt_textures from a pointer to a byte. This hosed old
62  * saved games, so I restored it to an int.
63  *
64  * Revision 2.8  1995/03/28  11:22:47  john
65  * Added cheats to save file. Changed lunacy text.
66  *
67  * Revision 2.7  1995/03/27  21:41:03  john
68  * Added code to verify that the proper multi save file
69  * is used when restoring a network game.
70  *
71  * Revision 2.6  1995/03/27  18:04:18  john
72  * Made multi save/restore require the -multisave command line arg.
73  *
74  * Revision 2.5  1995/03/27  17:01:52  john
75  * Made deafult choice work better.
76  *
77  * Revision 2.4  1995/03/27  15:49:44  john
78  * Added slots to save games.
79  *
80  * Revision 2.3  1995/03/27  12:59:19  john
81  * Initial version of multiplayer save games.
82  *
83  * Revision 2.2  1995/03/24  13:11:35  john
84  * Added save game during briefing screens.
85  *
86  * Revision 2.1  1995/03/21  14:38:36  john
87  * Ifdef'd out the NETWORK code.
88  *
89  * Revision 2.0  1995/02/27  11:27:00  john
90  * New version 2.0, which has no anonymous unions, builds with
91  * Watcom 10.0, and doesn't require parsing BITMAPS.TBL.
92  *
93  * Revision 1.43  1995/02/22  14:32:41  allender
94  * remove anonymous unions from object structure
95  *
96  * Revision 1.42  1995/02/13  20:34:33  john
97  * Lintized
98  *
99  * Revision 1.41  1995/02/13  10:37:30  john
100  * Saved Buggin' cheat mode to save file.
101  *
102  * Revision 1.40  1995/02/09  10:24:25  john
103  * *** empty log message ***
104  *
105  * Revision 1.39  1995/02/09  10:22:20  john
106  * Fixed bug with callsign getting trashed if you copy somebody else
107  * 's save game file into your directory.
108  *
109  * Revision 1.38  1995/02/08  21:01:27  john
110  * Closed state file around the code that shows briefing screens so that the
111  * code works on machines with clean boot with only 5 file handles.
112  *
113  * Revision 1.37  1995/02/07  14:02:33  john
114  * Added code to verify game restore.
115  *
116  * Revision 1.36  1995/02/07  11:07:43  john
117  * Added hooks for confirm on game state restore.
118  *
119  * Revision 1.35  1995/02/03  11:27:36  john
120  * Made inbetween level save's thumbnail's have correct aspect.
121  *
122  * Revision 1.34  1995/02/03  10:58:43  john
123  * Added code to save shareware style saved games into new format...
124  * Also, made new player file format not have the saved game array in it.
125  *
126  * Revision 1.33  1995/02/02  19:40:52  john
127  * Added 10 save game slots.
128  *
129  * Revision 1.32  1995/02/02  12:23:20  john
130  * Made between level saves have picture.
131  *
132  * Revision 1.31  1995/01/31  11:21:43  john
133  * Added code for fixed with menus.
134  *
135  * Revision 1.30  1995/01/29  21:37:29  mike
136  * initialize variables on game load so you don't drain your energy when you fire.
137  *
138  * Revision 1.29  1995/01/29  13:47:58  mike
139  * Restore some variables on game load (in game).
140  *
141  * Revision 1.28  1995/01/26  10:46:57  john
142  * Fixed bug with state names getting hosed.
143  *
144  * Revision 1.27  1995/01/26  09:51:23  john
145  * Fixed bug with game descriptions getting hosed.
146  *
147  * Revision 1.26  1995/01/25  16:35:49  john
148  * Made so that when you hit enter during
149  * game save, -empty- goes away.
150  *
151  * Revision 1.25  1995/01/25  15:01:39  john
152  * Upped the save file version.
153  *
154  * Revision 1.24  1995/01/24  20:35:35  john
155  * *** empty log message ***
156  *
157  * Revision 1.23  1995/01/24  20:34:24  john
158  * Fixed bug with player stats not being set right for in
159  * between level saves.
160  *
161  * Revision 1.22  1995/01/23  10:39:03  john
162  * Added mission stuff to game saves.
163  *
164  * Revision 1.21  1995/01/22  16:07:12  mike
165  * localization.
166  *
167  * Revision 1.20  1995/01/22  15:58:32  mike
168  * localization
169  *
170  * Revision 1.19  1995/01/20  11:04:40  john
171  * Upped state save version.
172  *
173  * Revision 1.18  1995/01/19  17:00:44  john
174  * Made save game work between levels.
175  *
176  * Revision 1.17  1995/01/17  14:27:33  john
177  * *** empty log message ***
178  *
179  * Revision 1.16  1995/01/17  13:36:37  john
180  * Moved pig loading into StartNewLevelSub.
181  *
182  * Revision 1.15  1995/01/16  16:53:38  john
183  * Added code to save cheat state during save game.
184  *
185  * Revision 1.14  1995/01/15  16:55:22  john
186  * Improved mine texture parsing.
187  *
188  * Revision 1.13  1995/01/12  10:45:15  john
189  * Added difficulty level to save/restore game.
190  *
191  * Revision 1.12  1995/01/05  15:46:55  john
192  * Made weapons not rearm when starting a saved game.
193  *
194  * Revision 1.11  1995/01/05  11:51:45  john
195  * Added better Abort game menu.
196  * Made save state return success or nopt.
197  *
198  * Revision 1.10  1995/01/05  11:34:51  john
199  * Took out endlevel save stuff for registered.
200  *
201  * Revision 1.9  1995/01/04  18:19:52  john
202  * Added automap visited list saving.
203  *
204  * Revision 1.8  1995/01/04  17:29:56  john
205  * Made save/restore ALT+F?. Also made them not work
206  * in network mode, and if recording a demo, will
207  * quit recording.
208  *
209  * Revision 1.7  1995/01/04  13:18:31  john
210  * Added cool 6 game save.
211  *
212  * Revision 1.6  1995/01/03  20:38:46  john
213  * Saved morph objects.
214  *
215  * Revision 1.5  1995/01/03  20:19:29  john
216  * Pretty good working version of game save.
217  *
218  * Revision 1.4  1995/01/03  14:18:18  matt
219  * ifdefs added to compile code add.  Added by Mike, I think.
220  *
221  * Revision 1.3  1994/12/29  18:40:19  john
222  * Initial version.
223  *
224  * Revision 1.2  1994/12/29  15:26:40  john
225  * Put in hooks for saving/restoring game state.
226  *
227  * Revision 1.1  1994/12/29  15:16:02  john
228  * Initial revision
229  *
230  *
231  */
232
233 #ifdef HAVE_CONFIG_H
234 #include <conf.h>
235 #endif
236
237 #ifdef WINDOWS
238 #include "desw.h"
239 #endif
240
241 #include <stdio.h>
242 #include <stdlib.h>
243 #include <math.h>
244 #include <string.h>
245 #ifndef _MSC_VER
246 #include <unistd.h>
247 #endif
248 #ifndef _WIN32_WCE
249 #include <errno.h>
250 #endif
251 #ifdef MACINTOSH
252 #include <Files.h>
253 #endif
254
255 #ifdef OGL
256 #if defined(__APPLE__) && defined(__MACH__)
257 #include <OpenGL/gl.h>
258 #else
259 #include <GL/gl.h>
260 #endif
261 #endif
262
263 #include "pstypes.h"
264 #include "pa_enabl.h"                   //$$POLY_ACC
265 #include "mono.h"
266 #include "inferno.h"
267 #include "segment.h"
268 #include "textures.h"
269 #include "wall.h"
270 #include "object.h"
271 #include "digi.h"
272 #include "gamemine.h"
273 #include "error.h"
274 #include "gameseg.h"
275 #include "menu.h"
276 #include "switch.h"
277 #include "game.h"
278 #include "screens.h"
279 #include "newmenu.h"
280 #include "cfile.h"
281 #include "fuelcen.h"
282 #include "hash.h"
283 #include "key.h"
284 #include "piggy.h"
285 #include "player.h"
286 #include "cntrlcen.h"
287 #include "morph.h"
288 #include "weapon.h"
289 #include "render.h"
290 #include "gameseq.h"
291 #include "gauges.h"
292 #include "newdemo.h"
293 #include "automap.h"
294 #include "piggy.h"
295 #include "paging.h"
296 #include "titles.h"
297 #include "text.h"
298 #include "mission.h"
299 #include "pcx.h"
300 #include "u_mem.h"
301 #ifdef NETWORK
302 #include "network.h"
303 #endif
304 #include "args.h"
305 #include "ai.h"
306 #include "fireball.h"
307 #include "controls.h"
308 #include "laser.h"
309 #include "multibot.h"
310 #include "state.h"
311
312 #if defined(POLY_ACC)
313 #include "poly_acc.h"
314 #endif
315
316 #ifdef OGL
317 #include "gr.h"
318 #endif
319
320 #define STATE_VERSION 22
321 #define STATE_COMPATIBLE_VERSION 20
322 // 0 - Put DGSS (Descent Game State Save) id at tof.
323 // 1 - Added Difficulty level save
324 // 2 - Added Cheats_enabled flag
325 // 3 - Added between levels save.
326 // 4 - Added mission support
327 // 5 - Mike changed ai and object structure.
328 // 6 - Added buggin' cheat save
329 // 7 - Added other cheat saves and game_id.
330 // 8 - Added AI stuff for escort and thief.
331 // 9 - Save palette with screen shot
332 // 12- Saved last_was_super array
333 // 13- Saved palette flash stuff
334 // 14- Save cloaking wall stuff
335 // 15- Save additional ai info
336 // 16- Save Light_subtracted
337 // 17- New marker save
338 // 18- Took out saving of old cheat status
339 // 19- Saved cheats_enabled flag
340 // 20- First_secret_visit
341 // 22- Omega_charge
342
343 #define NUM_SAVES 9
344 #define THUMBNAIL_W 100
345 #define THUMBNAIL_H 50
346 #define DESC_LENGTH 20
347
348 extern void multi_initiate_save_game();
349 extern void multi_initiate_restore_game();
350 extern void apply_all_changed_light(void);
351
352 extern int Do_appearance_effect;
353 extern fix Fusion_next_sound_time;
354
355 extern int Laser_rapid_fire;
356 extern int Physics_cheat_flag;
357 extern int Lunacy;
358 extern void do_lunacy_on(void);
359 extern void do_lunacy_off(void);
360 extern int First_secret_visit;
361
362 int sc_last_item= 0;
363 grs_bitmap *sc_bmp[NUM_SAVES+1];
364
365 char dgss_id[4] = "DGSS";
366
367 int state_default_item = 0;
368
369 uint state_game_id;
370
371 extern int robot_controlled[MAX_ROBOTS_CONTROLLED];
372 extern int robot_agitation[MAX_ROBOTS_CONTROLLED];
373 extern fix robot_controlled_time[MAX_ROBOTS_CONTROLLED];
374 extern fix robot_last_send_time[MAX_ROBOTS_CONTROLLED];
375 extern fix robot_last_message_time[MAX_ROBOTS_CONTROLLED];
376 extern int robot_send_pending[MAX_ROBOTS_CONTROLLED];
377 extern int robot_fired[MAX_ROBOTS_CONTROLLED];
378 extern sbyte robot_fire_buf[MAX_ROBOTS_CONTROLLED][18+3];
379
380
381 #if defined(WINDOWS) || defined(MACINTOSH)
382 extern ubyte Hack_DblClick_MenuMode;
383 #endif
384
385 void compute_all_static_light(void);
386
387 //-------------------------------------------------------------------
388 void state_callback(int nitems,newmenu_item * items, int * last_key, int citem)
389 {
390         nitems = nitems;
391         last_key = last_key;
392         
393 //      if ( sc_last_item != citem )    {
394 //              sc_last_item = citem;
395                 if ( citem > 0 )        {
396                         if ( sc_bmp[citem-1] )  {
397                                 if (MenuHires) {
398                                 WINDOS(
399                                         dd_grs_canvas *save_canv = dd_grd_curcanv,
400                                         grs_canvas *save_canv = grd_curcanv
401                                 );
402                                         grs_canvas *temp_canv = gr_create_canvas(THUMBNAIL_W*2,(THUMBNAIL_H*24/10));
403                                         grs_point vertbuf[3] = {{0,0}, {0,0}, {i2f(THUMBNAIL_W*2),i2f(THUMBNAIL_H*24/10)} };
404                                         gr_set_current_canvas(temp_canv);
405                                         scale_bitmap(sc_bmp[citem-1], vertbuf, 0 );
406                                 WINDOS(
407                                         dd_gr_set_current_canvas(save_canv),
408                                         gr_set_current_canvas( save_canv )
409                                 );
410                                 WIN(DDGRLOCK(dd_grd_curcanv));
411                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W*2)/2,items[0].y-10, &temp_canv->cv_bitmap);
412                                 WIN(DDGRUNLOCK(dd_grd_curcanv));
413                                         gr_free_canvas(temp_canv);
414                                 }
415                                 else    {
416                                 #ifdef WINDOWS
417                                         Int3();
418                                 #else
419                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W)/2,items[0].y-5, sc_bmp[citem-1] );
420                                 #endif
421                                 }
422                         }
423                 }
424 //      }       
425 }
426
427 void rpad_string( char * string, int max_chars )
428 {
429         int i, end_found;
430
431         end_found = 0;
432         for( i=0; i<max_chars; i++ )    {
433                 if ( *string == 0 )
434                         end_found = 1;
435                 if ( end_found )
436                         *string = ' ';
437                 string++;
438         }
439         *string = 0;            // NULL terminate
440 }
441
442 int state_get_save_file(char * fname, char * dsc, int multi )
443 {
444         CFILE *fp;
445         int i, choice, version;
446         newmenu_item m[NUM_SAVES+2];
447         char filename[NUM_SAVES+1][30];
448         char desc[NUM_SAVES+1][DESC_LENGTH+16];
449         char id[5];
450         int valid=0;
451         
452         for (i=0;i<NUM_SAVES; i++ )     {
453                 sc_bmp[i] = NULL;
454                 if ( !multi )
455                         #ifndef MACINTOSH
456                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
457                         #else
458                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
459                         #endif
460                 else
461                         #ifndef MACINTOSH
462                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
463                         #else
464                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
465                         #endif
466                 valid = 0;
467                 fp = cfopen(filename[i], "rb");
468                 if ( fp ) {
469                         //Read id
470                         cfread(id, sizeof(char)*4, 1, fp);
471                         if ( !memcmp( id, dgss_id, 4 )) {
472                                 //Read version
473                                 cfread(&version, sizeof(int), 1, fp);
474                                 if (version >= STATE_COMPATIBLE_VERSION)        {
475                                         // Read description
476                                         cfread(desc[i], sizeof(char)*DESC_LENGTH, 1, fp);
477                                         //rpad_string( desc[i], DESC_LENGTH-1 );
478                                         // Read thumbnail
479                                         //sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
480                                         //cfread(sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
481                                         valid = 1;
482                                 }
483                         }
484                         cfclose(fp);
485                 }
486                 if (!valid) {
487                         strcpy( desc[i], TXT_EMPTY );
488                         //rpad_string( desc[i], DESC_LENGTH-1 );
489                 }
490                 m[i].type = NM_TYPE_INPUT_MENU; m[i].text = desc[i]; m[i].text_len = DESC_LENGTH-1;
491         }
492
493         sc_last_item = -1;
494         choice = newmenu_do1( NULL, "Save Game", NUM_SAVES, m, NULL, state_default_item );
495
496         for (i=0; i<NUM_SAVES; i++ )    {
497                 if ( sc_bmp[i] )
498                         gr_free_bitmap( sc_bmp[i] );
499         }
500
501         if (choice > -1) {
502                 strcpy( fname, filename[choice] );
503                 strcpy( dsc, desc[choice] );
504                 state_default_item = choice;
505                 return choice+1;
506         }
507         return 0;
508 }
509
510 int RestoringMenu=0;
511 extern int Current_display_mode;
512
513 int state_get_restore_file(char * fname, int multi)
514 {
515         CFILE *fp;
516         int i, choice, version, nsaves;
517         newmenu_item m[NUM_SAVES+2];
518         char filename[NUM_SAVES+1][30];
519         char desc[NUM_SAVES+1][DESC_LENGTH + 16];
520         char id[5];
521         int valid;
522
523         nsaves=0;
524         m[0].type = NM_TYPE_TEXT; m[0].text = "\n\n\n\n";       
525         for (i=0;i<NUM_SAVES+1; i++ )   {
526                 sc_bmp[i] = NULL;
527                 if (!multi)
528                         #ifndef MACINTOSH
529                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
530                         #else
531                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
532                         #endif
533                 else
534                         #ifndef MACINTOSH
535                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
536                         #else
537                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
538                         #endif
539                 valid = 0;
540                 fp = cfopen(filename[i], "rb");
541                 if ( fp ) {
542                         //Read id
543                         cfread(id, sizeof(char)*4, 1, fp);
544                         if ( !memcmp( id, dgss_id, 4 )) {
545                                 //Read version
546                                 cfread(&version, sizeof(int), 1, fp);
547                                 if (version >= STATE_COMPATIBLE_VERSION)        {
548                                         // Read description
549                                         cfread(desc[i], sizeof(char)*DESC_LENGTH, 1, fp);
550                                         //rpad_string( desc[i], DESC_LENGTH-1 );
551                                         m[i+1].type = NM_TYPE_MENU; m[i+1].text = desc[i];
552                                         // Read thumbnail
553                                         sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
554                                         cfread(sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
555                                         if (version >= 9) {
556                                                 ubyte pal[256*3];
557                                                 cfread(pal, 3, 256, fp);
558                                                 gr_remap_bitmap_good( sc_bmp[i], pal, -1, -1 );
559                                         }
560                                         nsaves++;
561                                         valid = 1;
562                                 }
563                         }
564                         cfclose(fp);
565                 }
566                 if (!valid) {
567                         strcpy( desc[i], TXT_EMPTY );
568                         //rpad_string( desc[i], DESC_LENGTH-1 );
569                         m[i+1].type = NM_TYPE_TEXT; m[i+1].text = desc[i];
570                 }
571         }
572
573         if ( nsaves < 1 )       {
574                 nm_messagebox( NULL, 1, "Ok", "No saved games were found!" );
575                 return 0;
576         }
577
578         if (Current_display_mode == 3)  //restore menu won't fit on 640x400
579                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
580
581         sc_last_item = -1;
582
583 #if defined(WINDOWS) || defined(MACINTOSH)
584         Hack_DblClick_MenuMode = 1;
585 #endif
586
587    RestoringMenu=1;
588         choice = newmenu_do3( NULL, "Select Game to Restore", NUM_SAVES+2, m, state_callback, state_default_item+1, NULL, 190, -1 );
589    RestoringMenu=0;
590
591 #if defined(WINDOWS) || defined(MACINTOSH)
592         Hack_DblClick_MenuMode = 0;
593 #endif
594
595         if (Current_display_mode == 3)  //set flag back
596                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
597
598
599         for (i=0; i<NUM_SAVES+1; i++ )  {
600                 if ( sc_bmp[i] )
601                         gr_free_bitmap( sc_bmp[i] );
602         }
603
604         if (choice > 0) {
605                 strcpy( fname, filename[choice-1] );
606                 if (choice != NUM_SAVES+1)              //no new default when restore from autosave
607                         state_default_item = choice - 1;
608                 return choice;
609         }
610         return 0;
611 }
612
613 #define DESC_OFFSET     8
614
615 #define CF_BUF_SIZE     1024
616
617 #ifdef _WIN32_WCE
618 # define errno -1
619 # define strerror(x) "Unknown Error"
620 #endif
621
622
623 //      -----------------------------------------------------------------------------------
624 //      Imagine if C had a function to copy a file...
625 int copy_file(char *old_file, char *new_file)
626 {
627         sbyte   buf[CF_BUF_SIZE];
628         CFILE   *in_file, *out_file;
629
630         out_file = cfopen(new_file, "wb");
631
632         if (out_file == NULL)
633                 return -1;
634
635         in_file = cfopen(old_file, "rb");
636
637         if (in_file == NULL)
638                 return -2;
639
640         while (!cfeof(in_file))
641         {
642                 int bytes_read;
643
644                 bytes_read = cfread(buf, 1, CF_BUF_SIZE, in_file);
645                 if (cferror(in_file))
646                         Error("Cannot read from file <%s>: %s", old_file, strerror(errno));
647
648                 Assert(bytes_read == CF_BUF_SIZE || cfeof(in_file));
649
650                 cfwrite(buf, 1, bytes_read, out_file);
651
652                 if (cferror(out_file))
653                         Error("Cannot write to file <%s>: %s", new_file, strerror(errno));
654         }
655
656         if (cfclose(in_file)) {
657                 cfclose(out_file);
658                 return -3;
659         }
660
661         if (cfclose(out_file))
662                 return -4;
663
664         return 0;
665 }
666
667 #ifndef MACINTOSH
668 #define SECRETB_FILENAME        "secret.sgb"
669 #define SECRETC_FILENAME        "secret.sgc"
670 #else
671 #define SECRETB_FILENAME        ":Players:secret.sgb"
672 #define SECRETC_FILENAME        ":Players:secret.sgc"
673 #endif
674
675 extern int Final_boss_is_dead;
676
677 //      -----------------------------------------------------------------------------------
678 //      blind_save means don't prompt user for any info.
679 int state_save_all(int between_levels, int secret_save, char *filename_override)
680 {
681         int     rval, filenum = -1;
682
683         char    filename[128], desc[DESC_LENGTH+1];
684
685         Assert(between_levels == 0);    //between levels save ripped out
686
687 #ifdef NETWORK
688         if ( Game_mode & GM_MULTI )     {
689                         multi_initiate_save_game();
690                 return 0;
691         }
692 #endif
693
694         if ((Current_level_num < 0) && (secret_save == 0)) {
695                 HUD_init_message( "Can't save in secret level!" );
696                 return 0;
697         }
698
699         if (Final_boss_is_dead)         //don't allow save while final boss is dying
700                 return 0;
701
702         mprintf(( 0, "CL=%d, NL=%d\n", Current_level_num, Next_level_num ));
703         
704         //      If this is a secret save and the control center has been destroyed, don't allow
705         //      return to the base level.
706         if (secret_save && (Control_center_destroyed)) {
707                 mprintf((0, "Deleting secret.sgb so player can't return to base level.\n"));
708                 cfile_delete(SECRETB_FILENAME);
709                 return 0;
710         }
711
712         stop_time();
713
714         if (secret_save == 1) {
715                 filename_override = filename;
716                 sprintf(filename_override, SECRETB_FILENAME);
717         } else if (secret_save == 2) {
718                 filename_override = filename;
719                 sprintf(filename_override, SECRETC_FILENAME);
720         } else {
721                 if (filename_override) {
722                         strcpy( filename, filename_override);
723                         sprintf(desc, "[autosave backup]");
724                 } else if (!(filenum = state_get_save_file(filename,desc,0))) {
725                         start_time();
726                         return 0;
727                 }
728         }
729                 
730         //      MK, 1/1/96
731         //      If not in multiplayer, do special secret level stuff.
732         //      If secret.sgc exists, then copy it to Nsecret.sgc (where N = filenum).
733         //      If it doesn't exist, then delete Nsecret.sgc
734         if (!secret_save && !(Game_mode & GM_MULTI)) {
735                 int     rval;
736                 char    temp_fname[32], fc;
737
738                 if (filenum != -1) {
739
740                         if (filenum >= 10)
741                                 fc = (filenum-10) + 'a';
742                         else
743                                 fc = '0' + filenum;
744
745                         #ifndef MACINTOSH
746                         sprintf(temp_fname, "%csecret.sgc", fc);
747                         #else
748                         sprintf(temp_fname, ":Players:%csecret.sgc", fc);
749                         #endif
750
751                         mprintf((0, "Trying to copy secret.sgc to %s.\n", temp_fname));
752
753                         if (cfexist(temp_fname))
754                         {
755                                 mprintf((0, "Deleting file %s\n", temp_fname));
756                                 rval = cfile_delete(temp_fname);
757                                 Assert(rval == 0);      //      Oops, error deleting file in temp_fname.
758                         }
759
760                         if (cfexist(SECRETC_FILENAME))
761                         {
762                                 mprintf((0, "Copying secret.sgc to %s.\n", temp_fname));
763                                 rval = copy_file(SECRETC_FILENAME, temp_fname);
764                                 Assert(rval == 0);      //      Oops, error copying temp_fname to secret.sgc!
765                         }
766                 }
767         }
768
769         //      Save file we're going to save over in last slot and call "[autosave backup]"
770         if (!filename_override) {
771                 CFILE *tfp;
772         
773                 tfp = cfopen(filename, "rb");
774
775                 if ( tfp ) {
776                         char    newname[128];
777
778                         #ifndef MACINTOSH
779                         sprintf( newname, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
780                         #else
781                         sprintf( newname, ":Players:%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
782                         #endif
783                         
784                         cfseek(tfp, DESC_OFFSET, SEEK_SET);
785                         cfwrite("[autosave backup]", sizeof(char)*DESC_LENGTH, 1, tfp);
786                         cfclose(tfp);
787                         cfile_delete(newname);
788                         cfile_rename(filename, newname);
789                 }
790         }
791         
792         rval = state_save_all_sub(filename, desc, between_levels);
793
794         return rval;
795 }
796
797 extern  fix     Flash_effect, Time_flash_last_played;
798
799
800 int state_save_all_sub(char *filename, char *desc, int between_levels)
801 {
802         int i,j;
803         CFILE *fp;
804         grs_canvas * cnv;
805         #ifdef POLY_ACC
806         grs_canvas cnv2,*save_cnv2;
807         #endif
808         ubyte *pal;
809
810         Assert(between_levels == 0);    //between levels save ripped out
811
812 /*      if ( Game_mode & GM_MULTI )     {
813                 {
814                 start_time();
815                 return 0;
816                 }
817         }*/
818
819         #if defined(MACINTOSH) && !defined(NDEBUG)
820         if ( strncmp(filename, ":Players:", 9) )
821                 Int3();
822         #endif
823
824         fp = cfopen(filename, "wb");
825         if ( !fp ) {
826                 if ( !(Game_mode & GM_MULTI) )
827                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
828                 start_time();
829                 return 0;
830         }
831
832 //Save id
833         cfwrite(dgss_id, sizeof(char)*4, 1, fp);
834
835 //Save version
836         i = STATE_VERSION;
837         cfwrite(&i, sizeof(int), 1, fp);
838
839 //Save description
840         cfwrite(desc, sizeof(char) * DESC_LENGTH, 1, fp);
841         
842 // Save the current screen shot...
843
844         cnv = gr_create_canvas( THUMBNAIL_W, THUMBNAIL_H );
845         if ( cnv )
846         {
847 #ifdef OGL
848                 ubyte *buf;
849                 int k;
850 #endif
851                 #ifdef WINDOWS
852                         dd_grs_canvas *cnv_save;
853                         cnv_save = dd_grd_curcanv;
854                 #else
855                         grs_canvas * cnv_save;
856                         cnv_save = grd_curcanv;
857                 #endif
858
859                 #ifndef MACINTOSH
860                 
861                         #if defined(POLY_ACC)
862                         
863                                         PA_DFX (pa_fool_to_backbuffer());
864                         
865                                         //for poly_acc, we render the frame to the normal render buffer
866                                         //so that this doesn't show, we create yet another canvas to save
867                                         //and restore what's on the render buffer
868                                         PA_DFX (pa_alpha_always());     
869                                         PA_DFX (pa_set_front_to_read());
870                                         gr_init_sub_canvas( &cnv2, &VR_render_buffer[0], 0, 0, THUMBNAIL_W, THUMBNAIL_H );
871                                         save_cnv2 = gr_create_canvas2(THUMBNAIL_W, THUMBNAIL_H, cnv2.cv_bitmap.bm_type);
872                                         gr_set_current_canvas( save_cnv2 );
873                                         PA_DFX (pa_set_front_to_read());
874                                         gr_bitmap(0,0,&cnv2.cv_bitmap);
875                                         gr_set_current_canvas( &cnv2 );
876                         #else
877                                         gr_set_current_canvas( cnv );
878                         #endif
879                         
880                                         PA_DFX (pa_set_backbuffer_current());
881                                         render_frame(0, 0);
882                                         PA_DFX (pa_alpha_always());
883                         
884 #if defined(POLY_ACC)
885                                         #ifndef MACINTOSH
886                                         screen_shot_pa(cnv,&cnv2);
887                                         #else
888                                         if ( PAEnabled )
889                                                 screen_shot_pa(cnv,&cnv2);
890                                         #endif
891 #elif defined(OGL)
892                 buf = d_malloc(THUMBNAIL_W * THUMBNAIL_H * 3);
893                 glReadBuffer(GL_FRONT);
894                 glReadPixels(0, SHEIGHT - THUMBNAIL_H, THUMBNAIL_W, THUMBNAIL_H, GL_RGB, GL_UNSIGNED_BYTE, buf);
895                 k = THUMBNAIL_H;
896                 for (i = 0; i < THUMBNAIL_W * THUMBNAIL_H; i++) {
897                         if (!(j = i % THUMBNAIL_W))
898                                 k--;
899                         cnv->cv_bitmap.bm_data[THUMBNAIL_W * k + j] =
900                                 gr_find_closest_color(buf[3*i]/4, buf[3*i+1]/4, buf[3*i+2]/4);
901                 }
902                 d_free(buf);
903 #endif
904
905                                         pal = gr_palette;
906
907                                         cfwrite(cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
908
909                         #if defined(POLY_ACC)
910                                         PA_DFX (pa_alpha_always());     
911                                         PA_DFX (pa_set_frontbuffer_current());
912                                         PA_DFX(gr_bitmap(0,0,&save_cnv2->cv_bitmap));
913                                         PA_DFX (pa_set_backbuffer_current());
914                                         gr_bitmap(0,0,&save_cnv2->cv_bitmap);
915                                         gr_free_canvas(save_cnv2);
916                                         PA_DFX (pa_fool_to_offscreen());
917                         
918                         #endif
919                 
920                 #else   // macintosh stuff below
921                 {
922                         #if defined(POLY_ACC)
923                                 int     savePAEnabled = PAEnabled;
924                                 PAEnabled = false;
925                         #endif
926
927                         gr_set_current_canvas( cnv );
928                         render_frame(0, 0);
929                         pal = gr_palette;
930                         cfwrite(cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
931                         
932                         #if defined(POLY_ACC)
933                                 PAEnabled = savePAEnabled;
934                         #endif
935                 }       
936                 #endif  // end of ifndef macintosh
937                 
938                 
939                 WINDOS(
940                         dd_gr_set_current_canvas(cnv_save),
941                         gr_set_current_canvas(cnv_save)
942                 );
943                 gr_free_canvas( cnv );
944                 cfwrite(pal, 3, 256, fp);
945         }
946         else
947         {
948                 ubyte color = 0;
949                 for ( i=0; i<THUMBNAIL_W*THUMBNAIL_H; i++ )
950                         cfwrite(&color, sizeof(ubyte), 1, fp);
951         }
952
953 // Save the Between levels flag...
954         cfwrite(&between_levels, sizeof(int), 1, fp);
955
956 // Save the mission info...
957         mprintf ((0,"HEY! Mission name is %s\n",Mission_list[Current_mission_num].filename));
958         cfwrite(&Mission_list[Current_mission_num], sizeof(char), 9, fp);
959
960 //Save level info
961         cfwrite(&Current_level_num, sizeof(int), 1, fp);
962         cfwrite(&Next_level_num, sizeof(int), 1, fp);
963
964 //Save GameTime
965         cfwrite(&GameTime, sizeof(fix), 1, fp);
966
967 // If coop save, save all
968 #ifdef NETWORK
969    if (Game_mode & GM_MULTI_COOP)
970          {
971                 cfwrite(&state_game_id, sizeof(int), 1, fp);
972                 cfwrite(&Netgame, sizeof(netgame_info), 1, fp);
973                 cfwrite(&NetPlayers, sizeof(AllNetPlayers_info), 1, fp);
974                 cfwrite(&N_players, sizeof(int), 1, fp);
975                 cfwrite(&Player_num, sizeof(int), 1, fp);
976                 for (i=0;i<N_players;i++)
977                         cfwrite(&Players[i], sizeof(player), 1, fp);
978
979 #ifdef RISKY_PROPOSITION
980                 cfwrite(&robot_controlled[0], 4, MAX_ROBOTS_CONTROLLED, fp);
981                 cfwrite(&robot_agitation[0], 4, MAX_ROBOTS_CONTROLLED, fp);
982                 cfwrite(&robot_controlled_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
983                 cfwrite(&robot_last_send_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
984                 cfwrite(&robot_last_message_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
985                 cfwrite(&robot_send_pending[0], 4, MAX_ROBOTS_CONTROLLED, fp);
986                 cfwrite(&robot_fired[0], 4, MAX_ROBOTS_CONTROLLED, fp);
987
988       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
989                         cfwrite(robot_fire_buf[i][0], 18 + 3, 1, fp);
990 #endif
991
992          }
993 #endif
994
995 //Save player info
996         cfwrite(&Players[Player_num], sizeof(player), 1, fp);
997
998 // Save the current weapon info
999         cfwrite(&Primary_weapon, sizeof(sbyte), 1, fp);
1000         cfwrite(&Secondary_weapon, sizeof(sbyte), 1, fp);
1001
1002 // Save the difficulty level
1003         cfwrite(&Difficulty_level, sizeof(int), 1, fp);
1004 // Save cheats enabled
1005         cfwrite(&Cheats_enabled, sizeof(int), 1, fp);
1006
1007         if ( !between_levels )  {
1008
1009         //Finish all morph objects
1010                 for (i=0; i<=Highest_object_index; i++ )        {
1011                         if ( (Objects[i].type != OBJ_NONE) && (Objects[i].render_type==RT_MORPH))       {
1012                                 morph_data *md;
1013                                 md = find_morph_data(&Objects[i]);
1014                                 if (md) {                                       
1015                                         md->obj->control_type = md->morph_save_control_type;
1016                                         md->obj->movement_type = md->morph_save_movement_type;
1017                                         md->obj->render_type = RT_POLYOBJ;
1018                                         md->obj->mtype.phys_info = md->morph_save_phys_info;
1019                                         md->obj = NULL;
1020                                 } else {                                                //maybe loaded half-morphed from disk
1021                                         Objects[i].flags |= OF_SHOULD_BE_DEAD;
1022                                         Objects[i].render_type = RT_POLYOBJ;
1023                                         Objects[i].control_type = CT_NONE;
1024                                         Objects[i].movement_type = MT_NONE;
1025                                 }
1026                         }
1027                 }
1028         
1029         //Save object info
1030                 i = Highest_object_index+1;
1031                 cfwrite(&i, sizeof(int), 1, fp);
1032                 cfwrite(Objects, sizeof(object), i, fp);
1033                 
1034         //Save wall info
1035                 i = Num_walls;
1036                 cfwrite(&i, sizeof(int), 1, fp);
1037                 cfwrite(Walls, sizeof(wall), i, fp);
1038
1039         //Save exploding wall info
1040                 i = MAX_EXPLODING_WALLS;
1041                 cfwrite(&i, sizeof(int), 1, fp);
1042                 cfwrite(expl_wall_list, sizeof(*expl_wall_list), i, fp);
1043         
1044         //Save door info
1045                 i = Num_open_doors;
1046                 cfwrite(&i, sizeof(int), 1, fp );
1047                 cfwrite(ActiveDoors, sizeof(active_door), i, fp);
1048         
1049         //Save cloaking wall info
1050                 i = Num_cloaking_walls;
1051                 cfwrite(&i, sizeof(int), 1, fp );
1052                 cfwrite(CloakingWalls, sizeof(cloaking_wall), i, fp);
1053         
1054         //Save trigger info
1055                 cfwrite(&Num_triggers, sizeof(int), 1, fp);
1056                 cfwrite(Triggers, sizeof(trigger), Num_triggers, fp);
1057         
1058         //Save tmap info
1059                 for (i=0; i<=Highest_segment_index; i++ )       {
1060                         for (j=0; j<6; j++ )    {
1061                                 cfwrite(&Segments[i].sides[j].wall_num, sizeof(short), 1, fp);
1062                                 cfwrite(&Segments[i].sides[j].tmap_num, sizeof(short), 1, fp);
1063                                 cfwrite(&Segments[i].sides[j].tmap_num2, sizeof(short), 1, fp);
1064                         }
1065                 }
1066         
1067         // Save the fuelcen info
1068                 cfwrite(&Control_center_destroyed, sizeof(int), 1, fp);
1069                 cfwrite(&Countdown_timer, sizeof(int), 1, fp);
1070                 cfwrite(&Num_robot_centers, sizeof(int), 1, fp);
1071                 cfwrite(RobotCenters, sizeof(matcen_info), Num_robot_centers, fp);
1072                 cfwrite(&ControlCenterTriggers, sizeof(control_center_triggers), 1, fp);
1073                 cfwrite(&Num_fuelcenters, sizeof(int), 1, fp);
1074                 cfwrite(Station, sizeof(FuelCenter), Num_fuelcenters, fp);
1075         
1076         // Save the control cen info
1077                 cfwrite(&Control_center_been_hit, sizeof(int), 1, fp);
1078                 cfwrite(&Control_center_player_been_seen, sizeof(int), 1, fp);
1079                 cfwrite(&Control_center_next_fire_time, sizeof(int), 1, fp);
1080                 cfwrite(&Control_center_present, sizeof(int), 1, fp);
1081                 cfwrite(&Dead_controlcen_object_num, sizeof(int), 1, fp);
1082         
1083         // Save the AI state
1084                 ai_save_state( fp );
1085         
1086         // Save the automap visited info
1087                 cfwrite(Automap_visited, sizeof(ubyte) * MAX_SEGMENTS, 1, fp);
1088
1089         }
1090         cfwrite(&state_game_id, sizeof(uint), 1, fp);
1091         cfwrite(&Laser_rapid_fire, sizeof(int), 1, fp);
1092         cfwrite(&Lunacy, sizeof(int), 1, fp);           //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
1093         cfwrite(&Lunacy, sizeof(int), 1, fp);
1094
1095         // Save automap marker info
1096
1097         cfwrite(MarkerObject, sizeof(MarkerObject), 1, fp);
1098         cfwrite(MarkerOwner, sizeof(MarkerOwner), 1, fp);
1099         cfwrite(MarkerMessage, sizeof(MarkerMessage), 1, fp);
1100
1101         cfwrite(&Afterburner_charge, sizeof(fix), 1, fp);
1102
1103         //save last was super information
1104         cfwrite(&Primary_last_was_super, sizeof(Primary_last_was_super), 1, fp);
1105         cfwrite(&Secondary_last_was_super, sizeof(Secondary_last_was_super), 1, fp);
1106
1107         //      Save flash effect stuff
1108         cfwrite(&Flash_effect, sizeof(int), 1, fp);
1109         cfwrite(&Time_flash_last_played, sizeof(int), 1, fp);
1110         cfwrite(&PaletteRedAdd, sizeof(int), 1, fp);
1111         cfwrite(&PaletteGreenAdd, sizeof(int), 1, fp);
1112         cfwrite(&PaletteBlueAdd, sizeof(int), 1, fp);
1113
1114         cfwrite(Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS, fp);
1115
1116         cfwrite(&First_secret_visit, sizeof(First_secret_visit), 1, fp);
1117
1118         cfwrite(&Omega_charge, sizeof(Omega_charge), 1, fp);
1119         
1120         if (cferror(fp))
1121         {
1122                 if ( !(Game_mode & GM_MULTI) ) {
1123                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
1124                         cfclose(fp);
1125                         cfile_delete(filename);
1126                 }
1127         } else  {
1128                 cfclose(fp);
1129
1130                 #ifdef MACINTOSH                // set the type and creator of the saved game file
1131                 {
1132                         FInfo finfo;
1133                         OSErr err;
1134                         Str255 pfilename;
1135         
1136                         strcpy(pfilename, filename);
1137                         c2pstr(pfilename);
1138                         err = HGetFInfo(0, 0, pfilename, &finfo);
1139                         finfo.fdType = 'SVGM';
1140                         finfo.fdCreator = 'DCT2';
1141                         err = HSetFInfo(0, 0, pfilename, &finfo);
1142                 }
1143                 #endif
1144         }
1145         
1146         start_time();
1147
1148         return 1;
1149 }
1150
1151 //      -----------------------------------------------------------------------------------
1152 //      Set the player's position from the globals Secret_return_segment and Secret_return_orient.
1153 void set_pos_from_return_segment(void)
1154 {
1155         int     plobjnum = Players[Player_num].objnum;
1156
1157         compute_segment_center(&Objects[plobjnum].pos, &Segments[Secret_return_segment]);
1158         obj_relink(plobjnum, Secret_return_segment);
1159         reset_player_object();
1160         Objects[plobjnum].orient = Secret_return_orient;
1161 }
1162
1163 //      -----------------------------------------------------------------------------------
1164 int state_restore_all(int in_game, int secret_restore, char *filename_override)
1165 {
1166         char filename[128];
1167         int     filenum = -1;
1168
1169 #ifdef NETWORK
1170         if ( Game_mode & GM_MULTI )     {
1171 #ifdef MULTI_SAVE
1172                         multi_initiate_restore_game();
1173 #endif
1174                 return 0;
1175         }
1176 #endif
1177
1178         if (in_game && (Current_level_num < 0) && (secret_restore == 0)) {
1179                 HUD_init_message( "Can't restore in secret level!" );
1180                 return 0;
1181         }
1182
1183         if ( Newdemo_state == ND_STATE_RECORDING )
1184                 newdemo_stop_recording();
1185
1186         if ( Newdemo_state != ND_STATE_NORMAL )
1187                 return 0;
1188
1189         stop_time();
1190
1191         if (filename_override) {
1192                 strcpy(filename, filename_override);
1193                 filenum = NUM_SAVES+1;          //      So we don't trigger autosave
1194         } else if (!(filenum = state_get_restore_file(filename, 0)))    {
1195                 start_time();
1196                 return 0;
1197         }
1198         
1199         //      MK, 1/1/96
1200         //      If not in multiplayer, do special secret level stuff.
1201         //      If Nsecret.sgc (where N = filenum) exists, then copy it to secret.sgc.
1202         //      If it doesn't exist, then delete secret.sgc
1203         if (!secret_restore && !(Game_mode & GM_MULTI)) {
1204                 int     rval;
1205                 char    temp_fname[32], fc;
1206
1207                 if (filenum != -1) {
1208                         if (filenum >= 10)
1209                                 fc = (filenum-10) + 'a';
1210                         else
1211                                 fc = '0' + filenum;
1212                         
1213                         #ifndef MACINTOSH
1214                         sprintf(temp_fname, "%csecret.sgc", fc);
1215                         #else
1216                         sprintf(temp_fname, ":Players:%csecret.sgc", fc);
1217                         #endif
1218
1219                         mprintf((0, "Trying to copy %s to secret.sgc.\n", temp_fname));
1220
1221                         if (cfexist(temp_fname))
1222                         {
1223                                 mprintf((0, "Copying %s to secret.sgc\n", temp_fname));
1224                                 rval = copy_file(temp_fname, SECRETC_FILENAME);
1225                                 Assert(rval == 0);      //      Oops, error copying temp_fname to secret.sgc!
1226                         } else
1227                                 cfile_delete(SECRETC_FILENAME);
1228                 }
1229         }
1230
1231         //      Changed, 11/15/95, MK, don't to autosave if restoring from main menu.
1232         if ((filenum != (NUM_SAVES+1)) && in_game) {
1233                 char    temp_filename[128];
1234                 mprintf((0, "Doing autosave, filenum = %i, != %i!\n", filenum, NUM_SAVES+1));
1235                 #ifndef MACINTOSH
1236                 sprintf( temp_filename, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
1237                 #else
1238                 sprintf( temp_filename, ":Players:%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
1239                 #endif          
1240                 state_save_all(!in_game, secret_restore, temp_filename);
1241         }
1242
1243         if ( !secret_restore && in_game ) {
1244                 int choice;
1245                 choice =  nm_messagebox( NULL, 2, "Yes", "No", "Restore Game?" );
1246                 if ( choice != 0 )      {
1247                         start_time();
1248                         return 0;
1249                 }
1250         }
1251
1252         start_time();
1253
1254         return state_restore_all_sub(filename, 0, secret_restore);
1255 }
1256
1257 extern void init_player_stats_new_ship(void);
1258
1259 void ShowLevelIntro(int level_num);
1260
1261 extern void do_cloak_invul_secret_stuff(fix old_gametime);
1262 extern void copy_defaults_to_robot(object *objp);
1263
1264 int state_restore_all_sub(char *filename, int multi, int secret_restore)
1265 {
1266         int ObjectStartLocation;
1267         int version,i, j, segnum;
1268         object * obj;
1269         CFILE *fp;
1270         int current_level, next_level;
1271         int between_levels;
1272         char mission[16];
1273         char desc[DESC_LENGTH+1];
1274         char id[5];
1275         char org_callsign[CALLSIGN_LEN+16];
1276 #ifdef NETWORK
1277         int found;
1278         int nplayers;   //,playid[12],mynum;
1279         player restore_players[MAX_PLAYERS];
1280 #endif
1281         fix     old_gametime = GameTime;
1282
1283         #if defined(MACINTOSH) && !defined(NDEBUG)
1284         if ( strncmp(filename, ":Players:", 9) )
1285                 Int3();
1286         #endif
1287
1288         fp = cfopen(filename, "rb");
1289         if ( !fp ) return 0;
1290
1291 //Read id
1292         cfread(id, sizeof(char)*4, 1, fp);
1293         if ( memcmp( id, dgss_id, 4 )) {
1294                 cfclose(fp);
1295                 return 0;
1296         }
1297
1298 //Read version
1299         cfread(&version, sizeof(int), 1, fp);
1300         if (version < STATE_COMPATIBLE_VERSION) {
1301                 cfclose(fp);
1302                 return 0;
1303         }
1304
1305 // Read description
1306         cfread(desc, sizeof(char) * DESC_LENGTH, 1, fp);
1307
1308 // Skip the current screen shot...
1309         cfseek(fp, THUMBNAIL_W*THUMBNAIL_H, SEEK_CUR);
1310
1311 // And now...skip the goddamn palette stuff that somebody forgot to add
1312         cfseek(fp, 768, SEEK_CUR);
1313
1314 // Read the Between levels flag...
1315         cfread(&between_levels, sizeof(int), 1, fp);
1316
1317         Assert(between_levels == 0);    //between levels save ripped out
1318
1319 // Read the mission info...
1320         cfread(mission, sizeof(char), 9, fp);
1321         mprintf ((0,"Missionname to load = %s\n",mission));
1322
1323         if (!load_mission_by_name( mission ))   {
1324                 nm_messagebox( NULL, 1, "Ok", "Error!\nUnable to load mission\n'%s'\n", mission );
1325                 cfclose(fp);
1326                 return 0;
1327         }
1328
1329 //Read level info
1330         cfread(&current_level, sizeof(int), 1, fp);
1331         cfread(&next_level, sizeof(int), 1, fp);
1332
1333 //Restore GameTime
1334         cfread(&GameTime, sizeof(fix), 1, fp);
1335
1336 // Start new game....
1337         if (!multi)     {
1338                 Game_mode = GM_NORMAL;
1339                 Function_mode = FMODE_GAME;
1340 #ifdef NETWORK
1341                 change_playernum_to(0);
1342 #endif
1343                 strcpy( org_callsign, Players[0].callsign );
1344                 N_players = 1;
1345                 if (!secret_restore) {
1346                         InitPlayerObject();                             //make sure player's object set up
1347                         init_player_stats_game();               //clear all stats
1348                 }
1349         } else {
1350                 strcpy( org_callsign, Players[Player_num].callsign );
1351         }
1352
1353 #ifdef NETWORK
1354    if (Game_mode & GM_MULTI)
1355          {
1356                 cfread(&state_game_id,sizeof(int), 1, fp);
1357                 cfread(&Netgame,sizeof(netgame_info), 1, fp);
1358                 cfread(&NetPlayers,sizeof(AllNetPlayers_info), 1, fp);
1359                 cfread(&nplayers,sizeof(N_players), 1, fp);
1360                 cfread(&Player_num,sizeof(Player_num), 1, fp);
1361                 for (i=0;i<nplayers;i++)
1362                         cfread(&restore_players[i], sizeof(player), 1, fp);
1363 #ifdef RISKY_PROPOSITION
1364                 cfread(&robot_controlled[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1365                 cfread(&robot_agitation[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1366                 cfread(&robot_controlled_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1367                 cfread(&robot_last_send_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1368                 cfread(&robot_last_message_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1369                 cfread(&robot_send_pending[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1370                 cfread(&robot_fired[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1371
1372       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
1373                         cfread(&robot_fire_buf[i][0], 21, 1, fp);
1374 #endif
1375
1376            for (i=0;i<nplayers;i++)
1377                  {
1378                   found=0;
1379                   for (j=0;j<nplayers;j++)
1380                          {
1381            if ((!strcmp (restore_players[i].callsign,Players[j].callsign)) && Players[j].connected==1)
1382                                  found=1;
1383                          }
1384                   restore_players[i].connected=found;
1385             }
1386                 memcpy (&Players,&restore_players,sizeof(player)*nplayers);
1387                 N_players=nplayers;
1388
1389       if (network_i_am_master())
1390                  {
1391                   for (i=0;i<N_players;i++)
1392                         {
1393                          if (i==Player_num)
1394                                 continue;
1395                  Players[i].connected=0;
1396                         }
1397                  }
1398
1399                 //Viewer = ConsoleObject = &Objects[Players[Player_num].objnum];
1400          }
1401
1402 #endif
1403
1404 //Read player info
1405
1406         {
1407                 StartNewLevelSub(current_level, 1, secret_restore);
1408
1409                 if (secret_restore) {
1410                         player  dummy_player;
1411
1412                         cfread(&dummy_player, sizeof(player), 1, fp);
1413                         if (secret_restore == 1) {              //      This means he didn't die, so he keeps what he got in the secret level.
1414                                 Players[Player_num].level = dummy_player.level;
1415                                 Players[Player_num].last_score = dummy_player.last_score;
1416                                 Players[Player_num].time_level = dummy_player.time_level;
1417
1418                                 Players[Player_num].num_robots_level = dummy_player.num_robots_level;
1419                                 Players[Player_num].num_robots_total = dummy_player.num_robots_total;
1420                                 Players[Player_num].hostages_rescued_total = dummy_player.hostages_rescued_total;
1421                                 Players[Player_num].hostages_total = dummy_player.hostages_total;
1422                                 Players[Player_num].hostages_on_board = dummy_player.hostages_on_board;
1423                                 Players[Player_num].hostages_level = dummy_player.hostages_level;
1424                                 Players[Player_num].homing_object_dist = dummy_player.homing_object_dist;
1425                                 Players[Player_num].hours_level = dummy_player.hours_level;
1426                                 Players[Player_num].hours_total = dummy_player.hours_total;
1427                                 do_cloak_invul_secret_stuff(old_gametime);
1428                         } else {
1429                                 Players[Player_num] = dummy_player;
1430                         }
1431                 } else {
1432                         cfread(&Players[Player_num], sizeof(player), 1, fp);
1433                 }
1434         }
1435         strcpy( Players[Player_num].callsign, org_callsign );
1436
1437 // Set the right level
1438         if ( between_levels )
1439                 Players[Player_num].level = next_level;
1440
1441 // Restore the weapon states
1442         cfread(&Primary_weapon, sizeof(sbyte), 1, fp);
1443         cfread(&Secondary_weapon, sizeof(sbyte), 1, fp);
1444
1445         select_weapon(Primary_weapon, 0, 0, 0);
1446         select_weapon(Secondary_weapon, 1, 0, 0);
1447
1448 // Restore the difficulty level
1449         cfread(&Difficulty_level, sizeof(int), 1, fp);
1450
1451 // Restore the cheats enabled flag
1452
1453         cfread(&Cheats_enabled, sizeof(int), 1, fp);
1454
1455         if ( !between_levels )  {
1456                 Do_appearance_effect = 0;                       // Don't do this for middle o' game stuff.
1457
1458                 ObjectStartLocation = cftell(fp);
1459                 //Clear out all the objects from the lvl file
1460                 for (segnum=0; segnum <= Highest_segment_index; segnum++)
1461                         Segments[segnum].objects = -1;
1462                 reset_objects(1);
1463         
1464                 //Read objects, and pop 'em into their respective segments.
1465                 cfread(&i, sizeof(int), 1, fp);
1466                 Highest_object_index = i-1;
1467                 cfread(Objects, sizeof(object), i, fp);
1468         
1469                 Object_next_signature = 0;
1470                 for (i=0; i<=Highest_object_index; i++ )        {
1471                         obj = &Objects[i];
1472                         obj->rtype.pobj_info.alt_textures = -1;
1473                         segnum = obj->segnum;
1474                         obj->next = obj->prev = obj->segnum = -1;
1475                         if ( obj->type != OBJ_NONE )    {
1476                                 obj_link(i,segnum);
1477                                 if ( obj->signature > Object_next_signature )
1478                                         Object_next_signature = obj->signature;
1479                         }
1480
1481                         //look for, and fix, boss with bogus shields
1482                         if (obj->type == OBJ_ROBOT && Robot_info[obj->id].boss_flag) {
1483                                 fix save_shields = obj->shields;
1484
1485                                 copy_defaults_to_robot(obj);            //calculate starting shields
1486
1487                                 //if in valid range, use loaded shield value
1488                                 if (save_shields > 0 && save_shields <= obj->shields)
1489                                         obj->shields = save_shields;
1490                                 else
1491                                         obj->shields /= 2;  //give player a break
1492                         }
1493
1494                 }       
1495                 special_reset_objects();
1496                 Object_next_signature++;
1497         
1498                 //      1 = Didn't die on secret level.
1499                 //      2 = Died on secret level.
1500                 if (secret_restore && (Current_level_num >= 0)) {
1501                         set_pos_from_return_segment();
1502                         if (secret_restore == 2)
1503                                 init_player_stats_new_ship();
1504                 }
1505
1506                 //Restore wall info
1507                 cfread(&i, sizeof(int), 1, fp);
1508                 Num_walls = i;
1509                 cfread(Walls, sizeof(wall), Num_walls, fp);
1510
1511                 //now that we have the walls, check if any sounds are linked to
1512                 //walls that are now open
1513                 for (i=0;i<Num_walls;i++) {
1514                         if (Walls[i].type == WALL_OPEN)
1515                                 digi_kill_sound_linked_to_segment(Walls[i].segnum,Walls[i].sidenum,-1); //-1 means kill any sound
1516                 }
1517
1518                 //Restore exploding wall info
1519                 if (version >= 10) {
1520                         cfread(&i, sizeof(int), 1, fp);
1521                         cfread(expl_wall_list, sizeof(*expl_wall_list), i, fp);
1522                 }
1523
1524                 //Restore door info
1525                 cfread(&i, sizeof(int), 1, fp);
1526                 Num_open_doors = i;
1527                 cfread(ActiveDoors, sizeof(active_door), Num_open_doors, fp);
1528         
1529                 if (version >= 14) {            //Restore cloaking wall info
1530                         cfread(&i, sizeof(int), 1, fp);
1531                         Num_cloaking_walls = i;
1532                         cfread(CloakingWalls, sizeof(cloaking_wall), Num_cloaking_walls, fp);
1533                 }
1534         
1535                 //Restore trigger info
1536                 cfread(&Num_triggers, sizeof(int), 1, fp);
1537                 cfread(Triggers, sizeof(trigger), Num_triggers, fp);
1538         
1539                 //Restore tmap info
1540                 for (i=0; i<=Highest_segment_index; i++ )       {
1541                         for (j=0; j<6; j++ )    {
1542                                 cfread(&Segments[i].sides[j].wall_num, sizeof(short), 1, fp);
1543                                 cfread(&Segments[i].sides[j].tmap_num, sizeof(short), 1, fp);
1544                                 cfread(&Segments[i].sides[j].tmap_num2, sizeof(short), 1, fp);
1545                         }
1546                 }
1547         
1548                 //Restore the fuelcen info
1549                 cfread(&Control_center_destroyed, sizeof(int), 1, fp);
1550                 cfread(&Countdown_timer, sizeof(int), 1, fp);
1551                 cfread(&Num_robot_centers, sizeof(int), 1, fp);
1552                 cfread(RobotCenters, sizeof(matcen_info), Num_robot_centers, fp);
1553                 cfread(&ControlCenterTriggers, sizeof(control_center_triggers), 1, fp);
1554                 cfread(&Num_fuelcenters, sizeof(int), 1, fp);
1555                 cfread(Station, sizeof(FuelCenter), Num_fuelcenters, fp);
1556         
1557                 // Restore the control cen info
1558                 cfread(&Control_center_been_hit, sizeof(int), 1, fp);
1559                 cfread(&Control_center_player_been_seen, sizeof(int), 1, fp);
1560                 cfread(&Control_center_next_fire_time, sizeof(int), 1, fp);
1561                 cfread(&Control_center_present, sizeof(int), 1, fp);
1562                 cfread(&Dead_controlcen_object_num, sizeof(int), 1, fp);
1563         
1564                 // Restore the AI state
1565                 ai_restore_state( fp, version );
1566         
1567                 // Restore the automap visited info
1568                 cfread( Automap_visited, sizeof(ubyte), MAX_SEGMENTS, fp);
1569
1570                 //      Restore hacked up weapon system stuff.
1571                 Fusion_next_sound_time = GameTime;
1572                 Auto_fire_fusion_cannon_time = 0;
1573                 Next_laser_fire_time = GameTime;
1574                 Next_missile_fire_time = GameTime;
1575                 Last_laser_fired_time = GameTime;
1576
1577         }
1578         state_game_id = 0;
1579
1580         if ( version >= 7 )     {
1581                 cfread(&state_game_id, sizeof(uint), 1, fp);
1582                 cfread(&Laser_rapid_fire, sizeof(int), 1, fp);
1583                 cfread(&Lunacy, sizeof(int), 1, fp);            //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
1584                 cfread(&Lunacy, sizeof(int), 1, fp);
1585                 if ( Lunacy )
1586                         do_lunacy_on();
1587         }
1588
1589         if (version >= 17) {
1590                 cfread(MarkerObject, sizeof(MarkerObject), 1, fp);
1591                 cfread(MarkerOwner, sizeof(MarkerOwner), 1, fp);
1592                 cfread(MarkerMessage, sizeof(MarkerMessage), 1, fp);
1593         }
1594         else {
1595                 int num,dummy;
1596
1597                 // skip dummy info
1598
1599                 cfread(&num, sizeof(int), 1, fp);       //was NumOfMarkers
1600                 cfread(&dummy, sizeof(int), 1, fp);     //was CurMarker
1601
1602                 cfseek(fp, num * (sizeof(vms_vector) + 40), SEEK_CUR);
1603
1604                 for (num=0;num<NUM_MARKERS;num++)
1605                         MarkerObject[num] = -1;
1606         }
1607
1608         if (version>=11) {
1609                 if (secret_restore != 1)
1610                         cfread(&Afterburner_charge, sizeof(fix), 1, fp);
1611                 else {
1612                         fix     dummy_fix;
1613                         cfread(&dummy_fix,sizeof(fix), 1, fp);
1614                 }
1615         }
1616         if (version>=12) {
1617                 //read last was super information
1618                 cfread(&Primary_last_was_super, sizeof(Primary_last_was_super), 1, fp);
1619                 cfread(&Secondary_last_was_super, sizeof(Secondary_last_was_super), 1, fp);
1620         }
1621
1622         if (version >= 12) {
1623                 cfread(&Flash_effect, sizeof(int), 1, fp);
1624                 cfread(&Time_flash_last_played, sizeof(int), 1, fp);
1625                 cfread(&PaletteRedAdd, sizeof(int), 1, fp);
1626                 cfread(&PaletteGreenAdd, sizeof(int), 1, fp);
1627                 cfread(&PaletteBlueAdd, sizeof(int), 1, fp);
1628         } else {
1629                 Flash_effect = 0;
1630                 Time_flash_last_played = 0;
1631                 PaletteRedAdd = 0;
1632                 PaletteGreenAdd = 0;
1633                 PaletteBlueAdd = 0;
1634         }
1635
1636         //      Load Light_subtracted
1637         if (version >= 16) {
1638                 cfread(Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS, fp);
1639                 apply_all_changed_light();
1640                 compute_all_static_light();     //      set static_light field in segment struct.  See note at that function.
1641         } else {
1642                 int     i;
1643                 for (i=0; i<=Highest_segment_index; i++)
1644                         Light_subtracted[i] = 0;
1645         }
1646
1647         if (!secret_restore) {
1648                 if (version >= 20) {
1649                         cfread(&First_secret_visit, sizeof(First_secret_visit), 1, fp);
1650                         mprintf((0, "File: [%s] Read First_secret_visit: New value = %i\n", filename, First_secret_visit));
1651                 } else
1652                         First_secret_visit = 1;
1653         } else
1654                 First_secret_visit = 0;
1655
1656         if (version >= 22)
1657         {
1658                 if (secret_restore != 1)
1659                         cfread(&Omega_charge,sizeof(fix), 1, fp);
1660                 else {
1661                         fix     dummy_fix;
1662                         cfread(&dummy_fix,sizeof(fix), 1, fp);
1663                 }
1664         }
1665
1666         cfclose(fp);
1667
1668 #ifdef NETWORK
1669    if (Game_mode & GM_MULTI)   // Get rid of ships that aren't
1670          {                                                                       // connected in the restored game
1671                 for (i=0;i<nplayers;i++)
1672                  {
1673                   mprintf ((0,"Testing %s = %d\n",Players[i].callsign,Players[i].connected));
1674                   if (Players[i].connected!=1)
1675                    {
1676                     network_disconnect_player (i);
1677                create_player_appearance_effect(&Objects[Players[i].objnum]);
1678                          mprintf ((0,"Killing player ship %s!\n",Players[i].callsign));
1679               }
1680                  }
1681                         
1682          }
1683 #endif
1684
1685 // Load in bitmaps, etc..
1686 //!!    piggy_load_level_data();        //already done by StartNewLevelSub()
1687
1688         return 1;
1689 }
1690
1691 //      When loading a saved game, segp->static_light is bogus.
1692 //      This is because apply_all_changed_light, which is supposed to properly update this value,
1693 //      cannot do so because it needs the original light cast from a light which is no longer there.
1694 //      That is, a light has been blown out, so the texture remaining casts 0 light, but the static light
1695 //      which is present in the static_light field contains the light cast from that light.
1696 void compute_all_static_light(void)
1697 {
1698         int     i, j, k;
1699
1700         for (i=0; i<=Highest_segment_index; i++) {
1701                 fix     total_light;
1702                 segment *segp;
1703
1704                 segp = &Segments[i];
1705                 total_light = 0;
1706
1707                 for (j=0; j<MAX_SIDES_PER_SEGMENT; j++) {
1708                         side    *sidep;
1709
1710                         sidep = &segp->sides[j];
1711
1712                         for (k=0; k<4; k++)
1713                                 total_light += sidep->uvls[k].l;
1714                 }
1715
1716                 Segment2s[i].static_light = total_light/(MAX_SIDES_PER_SEGMENT*4);
1717         }
1718
1719 }
1720
1721
1722 int state_get_game_id(char *filename)
1723 {
1724         int version;
1725         CFILE *fp;
1726         int between_levels;
1727         char mission[16];
1728         char desc[DESC_LENGTH+1];
1729         char id[5];
1730         int dumbint;
1731
1732 mprintf((0, "Restoring multigame from [%s]\n", filename));
1733
1734         fp = cfopen(filename, "rb");
1735         if ( !fp ) return 0;
1736
1737 //Read id
1738         cfread(id, sizeof(char)*4, 1, fp);
1739         if ( memcmp( id, dgss_id, 4 )) {
1740                 cfclose(fp);
1741                 return 0;
1742         }
1743
1744 //Read version
1745         cfread(&version, sizeof(int), 1, fp);
1746         if (version < STATE_COMPATIBLE_VERSION) {
1747                 cfclose(fp);
1748                 return 0;
1749         }
1750
1751 // Read description
1752         cfread(desc, sizeof(char)*DESC_LENGTH, 1, fp);
1753
1754 // Skip the current screen shot...
1755         cfseek(fp, THUMBNAIL_W*THUMBNAIL_H, SEEK_CUR);
1756
1757 // And now...skip the palette stuff that somebody forgot to add
1758         cfseek(fp, 768, SEEK_CUR);
1759
1760 // Read the Between levels flag...
1761         cfread(&between_levels, sizeof(int), 1, fp);
1762
1763         Assert(between_levels == 0);    //between levels save ripped out
1764
1765 // Read the mission info...
1766         cfread(mission, sizeof(char), 9, fp);
1767 //Read level info
1768         cfread(&dumbint, sizeof(int), 1, fp);
1769         cfread(&dumbint, sizeof(int), 1, fp);
1770
1771 //Restore GameTime
1772         cfread(&dumbint, sizeof(fix), 1, fp);
1773
1774         cfread(&state_game_id, sizeof(int), 1, fp);
1775
1776         return (state_game_id);
1777  }
1778
1779 #if defined(POLY_ACC)
1780 //void screen_shot_pa(ubyte *dst,ushort *src)
1781 //{
1782 //    //ushort *src = pa_get_buffer_address(0),
1783 //    ushort *s;
1784 //    fix u, v, du, dv;
1785 //    int ui, w, h;
1786 //
1787 //    pa_flush();
1788 //
1789 //    du = (640.0 / (float)THUMBNAIL_W) * 65536.0;
1790 //    dv = (480.0 / (float)THUMBNAIL_H) * 65536.0;
1791 //
1792 //    for(v = h = 0; h != THUMBNAIL_H; ++h)
1793 //    {
1794 //        s = src + f2i(v) * 640;
1795 //        v += dv;
1796 //        for(u = w = 0; w != THUMBNAIL_W; ++w)
1797 //        {
1798 //            ui = f2i(u);
1799 //            *dst++ = gr_find_closest_color((s[ui] >> 9) & 0x3e, (s[ui] >> 4) & 0x3e, (s[ui] << 1) & 0x3e);
1800 //            u += du;
1801 //        }
1802 //    }
1803 //}
1804
1805 void screen_shot_pa(grs_canvas *dcanv,grs_canvas *scanv)
1806 {
1807 #if !defined(MACINTOSH)
1808         ubyte *dst;
1809         ushort *src;
1810         int x,y;
1811
1812         Assert(scanv->cv_w == dcanv->cv_w && scanv->cv_h == dcanv->cv_h);
1813
1814         pa_flush();
1815
1816         src = (ushort *) scanv->cv_bitmap.bm_data;
1817         dst = dcanv->cv_bitmap.bm_data;
1818
1819         #ifdef PA_3DFX_VOODOO
1820    src=(ushort *)pa_set_back_to_read();
1821         #endif
1822
1823         for (y=0; y<scanv->cv_h; y++) {
1824                 for (x=0; x<scanv->cv_w; x++) {
1825                         #ifdef PA_3DFX_VOODOO
1826                         *dst++ = gr_find_closest_color((*src >> 10) & 0x3e, (*src >> 5) & 0x3f, (*src << 1) & 0x3e);
1827                         #else
1828                         *dst++ = gr_find_closest_color((*src >> 9) & 0x3e, (*src >> 4) & 0x3e, (*src << 1) & 0x3e);
1829                         #endif
1830
1831                         src++;
1832                 }
1833                 src = (ushort *) (((ubyte *) src) + (scanv->cv_bitmap.bm_rowsize - (scanv->cv_bitmap.bm_w*PA_BPP)));
1834                 dst += dcanv->cv_bitmap.bm_rowsize - dcanv->cv_bitmap.bm_w;
1835         }
1836         #ifdef PA_3DFX_VOODOO
1837         pa_set_front_to_read();
1838         #endif
1839 #endif
1840 }
1841 #endif
1842