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