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