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