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