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