Debian Codegraph @

similar/main/state.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Functions to save/restore game state.
23 *
24 */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <math.h>
29 #include <string.h>
30 #include <ranges>
31
32 #include "pstypes.h"
33 #include "inferno.h"
34 #include "segment.h"
35 #include "textures.h"
36 #include "wall.h"
37 #include "object.h"
38 #include "dxxerror.h"
39 #include "console.h"
40 #include "gamefont.h"
41 #include "gameseg.h"
42 #include "switch.h"
43 #include "game.h"
44 #include "newmenu.h"
45 #include "fuelcen.h"
46 #include "hash.h"
47 #include "piggy.h"
48 #include "player.h"
49 #include "playsave.h"
50 #include "cntrlcen.h"
51 #include "morph.h"
52 #include "weapon.h"
53 #include "render.h"
54 #include "gameseq.h"
55 #include "event.h"
56 #include "robot.h"
57 #include "newdemo.h"
58 #include "automap.h"
59 #include "piggy.h"
60 #include "text.h"
61 #include "mission.h"
62 #include "u_mem.h"
63 #include "args.h"
64 #include "ai.h"
65 #include "fireball.h"
66 #include "controls.h"
67 #include "hudmsg.h"
68 #include "state.h"
69 #include "multi.h"
70 #include "gr.h"
71 #if DXX_USE_OGL
72 #include "ogl_init.h"
73 #endif
74
75 #if DXX_USE_EDITOR
76 #include "editor/editor.h"
77 #endif
78
79 #include "compiler-range_for.h"
80 #include "d_construct.h"
81 #include "d_levelstate.h"
82 #include "d_range.h"
83 #include "d_enumerate.h"
84 #include "partial_range.h"
85 #include "d_zip.h"
86 #include <utility>
87
88 #if DXX_BUILD_DESCENT == 1
89 #define STATE_VERSION 7
90 #define STATE_MATCEN_VERSION 25 // specific version of metcen info written into D1 savegames. Currenlty equal to GAME_VERSION (see gamesave.cpp). If changed, then only along with STATE_VERSION.
91 #define STATE_COMPATIBLE_VERSION 6
92 #elif DXX_BUILD_DESCENT == 2
93 #define STATE_VERSION 22
94 #define STATE_COMPATIBLE_VERSION 20
95 #endif
96 // 0 - Put DGSS (Descent Game State Save) id at tof.
97 // 1 - Added Difficulty level save
98 // 2 - Added cheats.enabled flag
99 // 3 - Added between levels save.
100 // 4 - Added mission support
101 // 5 - Mike changed ai and object structure.
102 // 6 - Added buggin' cheat save
103 // 7 - Added other cheat saves and game_id.
104 // 8 - Added AI stuff for escort and thief.
105 // 9 - Save palette with screen shot
106 // 12- Saved last_was_super array
107 // 13- Saved palette flash stuff
108 // 14- Save cloaking wall stuff
109 // 15- Save additional ai info
110 // 16- Save Light_subtracted
111 // 17- New marker save
112 // 18- Took out saving of old cheat status
113 // 19- Saved cheats.enabled flag
114 // 20- First_secret_visit
115 // 22- Omega_charge
116
117 #define THUMBNAIL_W 100
118 #define THUMBNAIL_H 50
119
120 constexpr char dgss_id[4] = {'D', 'G', 'S', 'S'};
121
122 unsigned state_game_id;
123
124 namespace dcx {
125
126 namespace {
127
128 constexpr unsigned NUM_SAVES = d_game_unique_state::MAXIMUM_SAVE_SLOTS.value;
129
130 struct relocated_player_data
131 {
132 fix shields;
133 int16_t num_robots_level;
134 int16_t num_robots_total;
135 uint16_t hostages_total;
136 uint8_t hostages_level;
137 };
138
139 struct savegame_mission_path {
140 std::array<char, 9> original;
141 std::array<char, DXX_MAX_MISSION_PATH_LENGTH> full;
142 };
143
144 enum class savegame_mission_name_abi : uint8_t
145 {
146 original,
147 pathname,
148 };
149
150 static_assert(sizeof(savegame_mission_path) == sizeof(savegame_mission_path::original) + sizeof(savegame_mission_path::full), "padding error");
151
152 }
153
154 }
155
156 namespace dsx {
157
158 namespace {
159
160 struct savegame_newmenu_items
161 {
162 struct error_no_saves_found
163 {
164 };
165 static constexpr unsigned decorative_item_count = 1;
166 using imenu_description_buffers_array = std::array<ntstring<NM_MAX_TEXT_LEN>, NUM_SAVES>;
167 d_game_unique_state::savegame_description *const caller_savegame_description;
168 d_game_unique_state::savegame_file_path &savegame_file_path;
169 enumerated_array<d_game_unique_state::savegame_file_path, NUM_SAVES, d_game_unique_state::save_slot> savegame_file_paths;
170 enumerated_array<d_game_unique_state::savegame_description, NUM_SAVES, d_game_unique_state::save_slot> savegame_descriptions;
171 enumerated_array<grs_bitmap_ptr, NUM_SAVES, d_game_unique_state::save_slot> sc_bmp;
172 std::array<newmenu_item, NUM_SAVES + decorative_item_count> m;
173 /* For saving a game, savegame_description is a
174 * caller-supplied buffer into which the user's text is placed, so
175 * that the caller can write that text into the file.
176 *
177 * For loading a game, savegame_description is nullptr.
178 */
179 savegame_newmenu_items(d_game_unique_state::savegame_description *savegame_description, d_game_unique_state::savegame_file_path &savegame_file_path, imenu_description_buffers_array *);
180 /* Test whether `selection` is an index that could be a valid
181 * choice. If `selection` can never be a valid choice, return
182 * false. If `selection` would be valid for a user who has every
183 * savegame slot in use, return true. This does not test whether
184 * there currently exists a savegame in the specified slot.
185 */
186 static unsigned valid_savegame_index(const d_game_unique_state::savegame_description *const user_entered_savegame_descriptions, const d_game_unique_state::save_slot selection)
187 {
188 return user_entered_savegame_descriptions
189 ? GameUniqueState.valid_save_slot(selection)
190 : GameUniqueState.valid_load_slot(selection);
191 }
192 unsigned valid_savegame_index(const d_game_unique_state::save_slot selection) const
193 {
194 return valid_savegame_index(caller_savegame_description, selection);
195 }
196 std::size_t get_count_valid_menuitem_entries(d_game_unique_state::savegame_description *const savegame_description) const
197 {
198 return savegame_description ? m.size() - 1 : m.size();
199 }
200 };
201
202 struct savegame_chooser_newmenu final : savegame_newmenu_items, newmenu
203 {
204 enum class trailing_storage_size : std::size_t
205 {
206 };
207 static void *operator new(std::size_t bytes) = delete;
208 static void *operator new(std::size_t bytes, const trailing_storage_size extra_bytes)
209 {
210 return ::operator new(bytes + static_cast<std::size_t>(extra_bytes));
211 }
212 static void operator delete(void *p)
213 {
214 ::operator delete(p);
215 }
216 static void operator delete(void *p, trailing_storage_size)
217 {
218 ::operator delete(p);
219 }
220 virtual window_event_result event_handler(const d_event &) override;
221 static std::unique_ptr<savegame_chooser_newmenu> create(menu_subtitle caption, grs_canvas &src, d_game_unique_state::savegame_description *const savegame_description, d_game_unique_state::savegame_file_path &savegame_file_path);
222 private:
223 void draw_handler(grs_canvas &canvas, const grs_bitmap &bmp);
224 void draw_handler();
225 savegame_chooser_newmenu(menu_subtitle caption, grs_canvas &src, d_game_unique_state::savegame_description *, d_game_unique_state::savegame_file_path &);
226 d_game_unique_state::save_slot build_save_slot_from_citem() const
227 {
228 if (citem < decorative_item_count)
229 return d_game_unique_state::save_slot::None;
230 return static_cast<d_game_unique_state::save_slot>(citem - decorative_item_count);
231 }
232 };
233
234 std::unique_ptr<savegame_chooser_newmenu> savegame_chooser_newmenu::create(menu_subtitle caption, grs_canvas &src, d_game_unique_state::savegame_description *const savegame_description, d_game_unique_state::savegame_file_path &savegame_file_path)
235 {
236 /* If savegame_description is not nullptr, then this is a request to
237 * create a "Save game" menu. Otherwise, it is a request to create a
238 * "Load game" menu.
239 */
240 const savegame_chooser_newmenu::trailing_storage_size extra_bytes{
241 savegame_description ? sizeof(savegame_chooser_newmenu::imenu_description_buffers_array) : 0
242 };
243 return std::unique_ptr<savegame_chooser_newmenu>(new (extra_bytes) savegame_chooser_newmenu(caption, src, savegame_description, savegame_file_path));
244 }
245
246 savegame_chooser_newmenu::savegame_chooser_newmenu(menu_subtitle subtitle, grs_canvas &src, d_game_unique_state::savegame_description *const savegame_description, d_game_unique_state::savegame_file_path &savegame_file_path) :
247 savegame_newmenu_items(savegame_description, savegame_file_path, savegame_description ? reinterpret_cast<savegame_newmenu_items::imenu_description_buffers_array *>(this + 1) : nullptr),
248 newmenu(menu_title{nullptr}, subtitle, menu_filename{nullptr}, tiny_mode_flag::normal, tab_processing_flag::ignore, adjusted_citem::create(unchecked_partial_range(m, get_count_valid_menuitem_entries(savegame_description)), decorative_item_count), src)
249 {
250 }
251
252 void savegame_chooser_newmenu::draw_handler(grs_canvas &canvas, const grs_bitmap &bmp)
253 {
254 const auto &&fspacx = FSPACX();
255 const auto &&fspacy = FSPACY();
256 #if DXX_USE_OGL
257 auto temp_canv = gr_create_canvas(THUMBNAIL_W * 2, THUMBNAIL_H * 24 / 10);
258 #else
259 auto temp_canv = gr_create_canvas(fspacx(THUMBNAIL_W), fspacy(THUMBNAIL_H));
260 #endif
261 const std::array<grs_point, 3> vertbuf{{
262 {0, 0},
263 {0, 0},
264 {i2f(THUMBNAIL_W * 2), i2f(THUMBNAIL_H * 24 / 10)}
265 }};
266 scale_bitmap(bmp, vertbuf, 0, temp_canv->cv_bitmap);
267 const auto bx = (canvas.cv_bitmap.bm_w / 2) - fspacx(THUMBNAIL_W / 2);
268 #if DXX_USE_OGL
269 ogl_ubitmapm_cs(canvas, bx, m[0].y - fspacy(3), fspacx(THUMBNAIL_W), fspacy(THUMBNAIL_H), temp_canv->cv_bitmap, ogl_colors::white);
270 #else
271 gr_bitmap(canvas, bx, m[0].y - 3, temp_canv->cv_bitmap);
272 #endif
273 }
274
275 void savegame_chooser_newmenu::draw_handler()
276 {
277 const auto choice = build_save_slot_from_citem();
278 if (!sc_bmp.valid_index(choice))
279 return;
280 if (auto &bmp = sc_bmp[choice])
281 draw_handler(w_canv, *bmp);
282 }
283
284 window_event_result savegame_chooser_newmenu::event_handler(const d_event &event)
285 {
286 switch (event.type)
287 {
288 case event_type::newmenu_draw:
289 draw_handler();
290 return window_event_result::handled;
291 case event_type::newmenu_selected:
292 {
293 const auto citem = static_cast<const d_select_event &>(event).citem;
294 const auto choice = static_cast<d_game_unique_state::save_slot>(citem - decorative_item_count);
295 if (!valid_savegame_index(choice))
296 return window_event_result::close;
297 GameUniqueState.quicksave_selection = choice;
298 savegame_file_path = savegame_file_paths[choice];
299 if (const auto desc = caller_savegame_description)
300 {
301 auto &d = savegame_descriptions[choice];
302 if (d.front())
303 *desc = d;
304 else
305 {
306 const time_t t = time(nullptr);
307 if (const struct tm *ptm = (t == -1) ? nullptr : localtime(&t))
308 strftime(desc->data(), desc->size(), "%m-%d %H:%M:%S", ptm);
309 else
310 strcpy(desc->data(), "-no title-");
311 }
312 }
313 }
314 return window_event_result::close;
315 default:
316 break;
317 }
318 return newmenu::event_handler(event);
319 }
320
321 // Following functions convert object to object_rw and back to be written to/read from Savegames. Mostly object differs to object_rw in terms of timer values (fix/fix64). as we reset GameTime64 for writing so it can fit into fix it's not necessary to increment savegame version. But if we once store something else into object which might be useful after restoring, it might be handy to increment Savegame version and actually store these new infos.
322 // turn object to object_rw to be saved to Savegame.
323
324 static void state_object_to_object_rw(const object &obj, object_rw *const obj_rw)
325 {
326 const auto otype{obj.type};
327 obj_rw->type = otype;
328 obj_rw->signature = static_cast<uint16_t>(obj.signature);
329 obj_rw->id = obj.id;
330 obj_rw->next = obj.next;
331 obj_rw->prev = obj.prev;
332 obj_rw->control_source = underlying_value(obj.control_source);
333 obj_rw->movement_source = underlying_value(obj.movement_source);
334 const auto rtype = obj.render_type;
335 obj_rw->render_type = underlying_value(rtype);
336 obj_rw->flags = obj.flags;
337 obj_rw->segnum = obj.segnum;
338 obj_rw->attached_obj = obj.attached_obj;
339 obj_rw->pos.x = obj.pos.x;
340 obj_rw->pos.y = obj.pos.y;
341 obj_rw->pos.z = obj.pos.z;
342 obj_rw->orient.rvec.x = obj.orient.rvec.x;
343 obj_rw->orient.rvec.y = obj.orient.rvec.y;
344 obj_rw->orient.rvec.z = obj.orient.rvec.z;
345 obj_rw->orient.fvec.x = obj.orient.fvec.x;
346 obj_rw->orient.fvec.y = obj.orient.fvec.y;
347 obj_rw->orient.fvec.z = obj.orient.fvec.z;
348 obj_rw->orient.uvec.x = obj.orient.uvec.x;
349 obj_rw->orient.uvec.y = obj.orient.uvec.y;
350 obj_rw->orient.uvec.z = obj.orient.uvec.z;
351 obj_rw->size = obj.size;
352 obj_rw->shields = obj.shields;
353 obj_rw->last_pos = obj.pos;
354 obj_rw->contains_type = underlying_value(obj.contains.type);
355 obj_rw->contains_id = underlying_value(obj.contains.id.robot);
356 obj_rw->contains_count= obj.contains.count;
357 obj_rw->matcen_creator= obj.matcen_creator;
358 obj_rw->lifeleft = obj.lifeleft;
359
360 switch (typename object::movement_type{obj_rw->movement_source})
361 {
362 case object::movement_type::None:
363 obj_rw->mtype = {};
364 break;
365 case object::movement_type::physics:
366 obj_rw->mtype.phys_info.velocity.x = obj.mtype.phys_info.velocity.x;
367 obj_rw->mtype.phys_info.velocity.y = obj.mtype.phys_info.velocity.y;
368 obj_rw->mtype.phys_info.velocity.z = obj.mtype.phys_info.velocity.z;
369 obj_rw->mtype.phys_info.thrust.x = obj.mtype.phys_info.thrust.x;
370 obj_rw->mtype.phys_info.thrust.y = obj.mtype.phys_info.thrust.y;
371 obj_rw->mtype.phys_info.thrust.z = obj.mtype.phys_info.thrust.z;
372 obj_rw->mtype.phys_info.mass = obj.mtype.phys_info.mass;
373 obj_rw->mtype.phys_info.drag = obj.mtype.phys_info.drag;
374 obj_rw->mtype.phys_info.obsolete_brakes = 0;
375 obj_rw->mtype.phys_info.rotvel.x = obj.mtype.phys_info.rotvel.x;
376 obj_rw->mtype.phys_info.rotvel.y = obj.mtype.phys_info.rotvel.y;
377 obj_rw->mtype.phys_info.rotvel.z = obj.mtype.phys_info.rotvel.z;
378 obj_rw->mtype.phys_info.rotthrust.x = obj.mtype.phys_info.rotthrust.x;
379 obj_rw->mtype.phys_info.rotthrust.y = obj.mtype.phys_info.rotthrust.y;
380 obj_rw->mtype.phys_info.rotthrust.z = obj.mtype.phys_info.rotthrust.z;
381 obj_rw->mtype.phys_info.turnroll = obj.mtype.phys_info.turnroll;
382 obj_rw->mtype.phys_info.flags = obj.mtype.phys_info.flags;
383 break;
384
385 case object::movement_type::spinning:
386 obj_rw->mtype.spin_rate.x = obj.mtype.spin_rate.x;
387 obj_rw->mtype.spin_rate.y = obj.mtype.spin_rate.y;
388 obj_rw->mtype.spin_rate.z = obj.mtype.spin_rate.z;
389 break;
390 }
391
392 switch (typename object::control_type{obj_rw->control_source})
393 {
394 case object::control_type::weapon:
395 obj_rw->ctype.laser_info.parent_type = obj.ctype.laser_info.parent_type;
396 obj_rw->ctype.laser_info.parent_num = obj.ctype.laser_info.parent_num;
397 obj_rw->ctype.laser_info.parent_signature = static_cast<uint16_t>(obj.ctype.laser_info.parent_signature);
398 if (obj.ctype.laser_info.creation_time - GameTime64 < F1_0*(-18000))
399 obj_rw->ctype.laser_info.creation_time = F1_0*(-18000);
400 else
401 obj_rw->ctype.laser_info.creation_time = obj.ctype.laser_info.creation_time - GameTime64;
402 obj_rw->ctype.laser_info.last_hitobj = obj.ctype.laser_info.get_last_hitobj();
403 obj_rw->ctype.laser_info.track_goal = obj.ctype.laser_info.track_goal;
404 obj_rw->ctype.laser_info.multiplier = obj.ctype.laser_info.multiplier;
405 break;
406
407 case object::control_type::explosion:
408 obj_rw->ctype.expl_info.spawn_time = obj.ctype.expl_info.spawn_time;
409 obj_rw->ctype.expl_info.delete_time = obj.ctype.expl_info.delete_time;
410 obj_rw->ctype.expl_info.delete_objnum = obj.ctype.expl_info.delete_objnum;
411 obj_rw->ctype.expl_info.attach_parent = obj.ctype.expl_info.attach_parent;
412 obj_rw->ctype.expl_info.prev_attach = obj.ctype.expl_info.prev_attach;
413 obj_rw->ctype.expl_info.next_attach = obj.ctype.expl_info.next_attach;
414 break;
415
416 case object::control_type::ai:
417 {
418 obj_rw->ctype.ai_info.behavior = static_cast<uint8_t>(obj.ctype.ai_info.behavior);
419 obj_rw->ctype.ai_info.flags[0] = underlying_value(obj.ctype.ai_info.CURRENT_GUN);
420 obj_rw->ctype.ai_info.flags[1] = obj.ctype.ai_info.CURRENT_STATE;
421 obj_rw->ctype.ai_info.flags[2] = obj.ctype.ai_info.GOAL_STATE;
422 obj_rw->ctype.ai_info.flags[3] = obj.ctype.ai_info.PATH_DIR;
423 #if DXX_BUILD_DESCENT == 1
424 obj_rw->ctype.ai_info.flags[4] = obj.ctype.ai_info.SUBMODE;
425 #elif DXX_BUILD_DESCENT == 2
426 obj_rw->ctype.ai_info.flags[4] = obj.ctype.ai_info.SUB_FLAGS;
427 #endif
428 obj_rw->ctype.ai_info.flags[5] = underlying_value(obj.ctype.ai_info.GOALSIDE);
429 obj_rw->ctype.ai_info.flags[6] = obj.ctype.ai_info.CLOAKED;
430 obj_rw->ctype.ai_info.flags[7] = obj.ctype.ai_info.SKIP_AI_COUNT;
431 obj_rw->ctype.ai_info.flags[8] = obj.ctype.ai_info.REMOTE_OWNER;
432 obj_rw->ctype.ai_info.flags[9] = obj.ctype.ai_info.REMOTE_SLOT_NUM;
433 obj_rw->ctype.ai_info.hide_segment = obj.ctype.ai_info.hide_segment;
434 obj_rw->ctype.ai_info.hide_index = obj.ctype.ai_info.hide_index;
435 obj_rw->ctype.ai_info.path_length = obj.ctype.ai_info.path_length;
436 obj_rw->ctype.ai_info.cur_path_index = obj.ctype.ai_info.cur_path_index;
437 obj_rw->ctype.ai_info.danger_laser_num = obj.ctype.ai_info.danger_laser_num;
438 if (obj.ctype.ai_info.danger_laser_num != object_none)
439 obj_rw->ctype.ai_info.danger_laser_signature = static_cast<uint16_t>(obj.ctype.ai_info.danger_laser_signature);
440 else
441 obj_rw->ctype.ai_info.danger_laser_signature = 0;
442 #if DXX_BUILD_DESCENT == 1
443 obj_rw->ctype.ai_info.follow_path_start_seg = segment_none;
444 obj_rw->ctype.ai_info.follow_path_end_seg = segment_none;
445 #elif DXX_BUILD_DESCENT == 2
446 obj_rw->ctype.ai_info.dying_sound_playing = obj.ctype.ai_info.dying_sound_playing;
447 if (obj.ctype.ai_info.dying_start_time == 0) // if bot not dead, anything but 0 will kill it
448 obj_rw->ctype.ai_info.dying_start_time = 0;
449 else
450 obj_rw->ctype.ai_info.dying_start_time = obj.ctype.ai_info.dying_start_time - GameTime64;
451 #endif
452 break;
453 }
454
455 case object::control_type::light:
456 obj_rw->ctype.light_info.intensity = obj.ctype.light_info.intensity;
457 break;
458
459 case object::control_type::powerup:
460 obj_rw->ctype.powerup_info.count = obj.ctype.powerup_info.count;
461 #if DXX_BUILD_DESCENT == 2
462 if (obj.ctype.powerup_info.creation_time - GameTime64 < F1_0*(-18000))
463 obj_rw->ctype.powerup_info.creation_time = F1_0*(-18000);
464 else
465 obj_rw->ctype.powerup_info.creation_time = obj.ctype.powerup_info.creation_time - GameTime64;
466 obj_rw->ctype.powerup_info.flags = obj.ctype.powerup_info.flags;
467 #endif
468 break;
469 case object::control_type::None:
470 case object::control_type::flying:
471 case object::control_type::slew:
472 case object::control_type::flythrough:
473 case object::control_type::repaircen:
474 case object::control_type::morph:
475 case object::control_type::debris:
476 case object::control_type::remote:
477 default:
478 break;
479 }
480
481 switch (rtype)
482 {
483 case render_type::RT_NONE:
484 if (obj.type != OBJ_GHOST) // HACK: when a player is dead or not connected yet, clients still expect to get polyobj data - even if render_type == RT_NONE at this time. Here it's not important, but it might be for Multiplayer Savegames.
485 break;
486 [[fallthrough]];
487 case render_type::RT_MORPH:
488 case render_type::RT_POLYOBJ:
489 {
490 int i;
491 obj_rw->rtype.pobj_info.model_num = underlying_value(obj.rtype.pobj_info.model_num);
492 for (i=0;i<MAX_SUBMODELS;i++)
493 {
494 obj_rw->rtype.pobj_info.anim_angles[i].p = obj.rtype.pobj_info.anim_angles[i].p;
495 obj_rw->rtype.pobj_info.anim_angles[i].b = obj.rtype.pobj_info.anim_angles[i].b;
496 obj_rw->rtype.pobj_info.anim_angles[i].h = obj.rtype.pobj_info.anim_angles[i].h;
497 }
498 obj_rw->rtype.pobj_info.subobj_flags = obj.rtype.pobj_info.subobj_flags;
499 obj_rw->rtype.pobj_info.tmap_override = obj.rtype.pobj_info.tmap_override;
500 obj_rw->rtype.pobj_info.alt_textures = obj.rtype.pobj_info.alt_textures;
501 break;
502 }
503
504 case render_type::RT_WEAPON_VCLIP:
505 case render_type::RT_HOSTAGE:
506 case render_type::RT_POWERUP:
507 case render_type::RT_FIREBALL:
508 obj_rw->rtype.vclip_info.vclip_num = underlying_value(obj.rtype.vclip_info.vclip_num);
509 obj_rw->rtype.vclip_info.frametime = obj.rtype.vclip_info.frametime;
510 obj_rw->rtype.vclip_info.framenum = obj.rtype.vclip_info.framenum;
511 break;
512
513 case render_type::RT_LASER:
514 break;
515
516 }
517 }
518
519 // turn object_rw to object after reading from Savegame
520 static void state_object_rw_to_object(const object_rw *const obj_rw, object &obj)
521 {
522 obj = {};
523 DXX_POISON_VAR(obj, 0xfd);
524 set_object_type(obj, obj_rw->type);
525 if (obj.type == OBJ_NONE)
526 {
527 obj.signature = object_signature_t{0};
528 return;
529 }
530
531 obj.signature = object_signature_t{static_cast<uint16_t>(obj_rw->signature)};
532 obj.id = obj_rw->id;
533 obj.next = obj_rw->next;
534 obj.prev = obj_rw->prev;
535 obj.control_source = typename object::control_type{obj_rw->control_source};
536 obj.movement_source = typename object::movement_type{obj_rw->movement_source};
537 if (const auto rtype = obj_rw->render_type; valid_render_type(rtype))
538 obj.render_type = render_type{rtype};
539 else
540 {
541 con_printf(CON_URGENT, "save file used bogus render type %#x for object %p; using none instead", rtype, &obj);
542 obj.render_type = render_type::RT_NONE;
543 }
544 obj.flags = obj_rw->flags;
545 obj.segnum = vmsegidx_t::check_nothrow_index(obj_rw->segnum).value_or(segment_none);
546 obj.attached_obj = obj_rw->attached_obj;
547 obj.pos.x = obj_rw->pos.x;
548 obj.pos.y = obj_rw->pos.y;
549 obj.pos.z = obj_rw->pos.z;
550 obj.orient.rvec.x = obj_rw->orient.rvec.x;
551 obj.orient.rvec.y = obj_rw->orient.rvec.y;
552 obj.orient.rvec.z = obj_rw->orient.rvec.z;
553 obj.orient.fvec.x = obj_rw->orient.fvec.x;
554 obj.orient.fvec.y = obj_rw->orient.fvec.y;
555 obj.orient.fvec.z = obj_rw->orient.fvec.z;
556 obj.orient.uvec.x = obj_rw->orient.uvec.x;
557 obj.orient.uvec.y = obj_rw->orient.uvec.y;
558 obj.orient.uvec.z = obj_rw->orient.uvec.z;
559 obj.size = obj_rw->size;
560 obj.shields = obj_rw->shields;
561 obj.contains = build_contained_object_parameters_from_untrusted(obj_rw->contains_type, obj_rw->contains_id, obj_rw->contains_count);
562 obj.matcen_creator= obj_rw->matcen_creator;
563 obj.lifeleft = obj_rw->lifeleft;
564
565 switch (obj.movement_source)
566 {
567 case object::movement_type::None:
568 break;
569 case object::movement_type::physics:
570 obj.mtype.phys_info.velocity.x = obj_rw->mtype.phys_info.velocity.x;
571 obj.mtype.phys_info.velocity.y = obj_rw->mtype.phys_info.velocity.y;
572 obj.mtype.phys_info.velocity.z = obj_rw->mtype.phys_info.velocity.z;
573 obj.mtype.phys_info.thrust.x = obj_rw->mtype.phys_info.thrust.x;
574 obj.mtype.phys_info.thrust.y = obj_rw->mtype.phys_info.thrust.y;
575 obj.mtype.phys_info.thrust.z = obj_rw->mtype.phys_info.thrust.z;
576 obj.mtype.phys_info.mass = obj_rw->mtype.phys_info.mass;
577 obj.mtype.phys_info.drag = obj_rw->mtype.phys_info.drag;
578 obj.mtype.phys_info.rotvel.x = obj_rw->mtype.phys_info.rotvel.x;
579 obj.mtype.phys_info.rotvel.y = obj_rw->mtype.phys_info.rotvel.y;
580 obj.mtype.phys_info.rotvel.z = obj_rw->mtype.phys_info.rotvel.z;
581 obj.mtype.phys_info.rotthrust.x = obj_rw->mtype.phys_info.rotthrust.x;
582 obj.mtype.phys_info.rotthrust.y = obj_rw->mtype.phys_info.rotthrust.y;
583 obj.mtype.phys_info.rotthrust.z = obj_rw->mtype.phys_info.rotthrust.z;
584 obj.mtype.phys_info.turnroll = obj_rw->mtype.phys_info.turnroll;
585 obj.mtype.phys_info.flags = obj_rw->mtype.phys_info.flags;
586 break;
587
588 case object::movement_type::spinning:
589 obj.mtype.spin_rate.x = obj_rw->mtype.spin_rate.x;
590 obj.mtype.spin_rate.y = obj_rw->mtype.spin_rate.y;
591 obj.mtype.spin_rate.z = obj_rw->mtype.spin_rate.z;
592 break;
593 }
594
595 switch (obj.control_source)
596 {
597 case object::control_type::weapon:
598 obj.ctype.laser_info.parent_type = obj_rw->ctype.laser_info.parent_type;
599 obj.ctype.laser_info.parent_num = obj_rw->ctype.laser_info.parent_num;
600 obj.ctype.laser_info.parent_signature = object_signature_t{static_cast<uint16_t>(obj_rw->ctype.laser_info.parent_signature)};
601 obj.ctype.laser_info.creation_time = obj_rw->ctype.laser_info.creation_time;
602 /* Use vcobjidx_t so that `object_none` fails the test and uses the
603 * `else` path. `reset_hitobj` can accept `object_none`, but it
604 * cannot accept invalid indexes, such as the corrupted value
605 * `0x1ff` produced by certain <0.60 builds, when they ran
606 * `laser_info.hitobj_list[-1] = 1;` due to using `object_none`
607 * (`-1` back then) as if it were a valid index. That bug was
608 * fixed in 14cdf1b3521ff82701c58c04e47a6c1deefe8e43, but some old
609 * save games were corrupted by it, so trap that error here.
610 */
611 if (const auto last_hitobj{vcobjidx_t::check_nothrow_index(obj_rw->ctype.laser_info.last_hitobj)})
612 obj.ctype.laser_info.reset_hitobj(*last_hitobj);
613 else
614 obj.ctype.laser_info.clear_hitobj();
615 obj.ctype.laser_info.track_goal = obj_rw->ctype.laser_info.track_goal;
616 obj.ctype.laser_info.multiplier = obj_rw->ctype.laser_info.multiplier;
617 #if DXX_BUILD_DESCENT == 2
618 obj.ctype.laser_info.last_afterburner_time = 0;
619 #endif
620 break;
621
622 case object::control_type::explosion:
623 obj.ctype.expl_info.spawn_time = obj_rw->ctype.expl_info.spawn_time;
624 obj.ctype.expl_info.delete_time = obj_rw->ctype.expl_info.delete_time;
625 obj.ctype.expl_info.delete_objnum = obj_rw->ctype.expl_info.delete_objnum;
626 obj.ctype.expl_info.attach_parent = obj_rw->ctype.expl_info.attach_parent;
627 obj.ctype.expl_info.prev_attach = obj_rw->ctype.expl_info.prev_attach;
628 obj.ctype.expl_info.next_attach = obj_rw->ctype.expl_info.next_attach;
629 break;
630
631 case object::control_type::ai:
632 {
633 obj.ctype.ai_info.behavior = static_cast<ai_behavior>(obj_rw->ctype.ai_info.behavior);
634 {
635 const uint8_t gun_num = obj_rw->ctype.ai_info.flags[0];
636 obj.ctype.ai_info.CURRENT_GUN = (gun_num < MAX_GUNS) ? robot_gun_number{gun_num} : robot_gun_number{};
637 }
638 obj.ctype.ai_info.CURRENT_STATE = build_ai_state_from_untrusted(obj_rw->ctype.ai_info.flags[1]).value();
639 obj.ctype.ai_info.GOAL_STATE = build_ai_state_from_untrusted(obj_rw->ctype.ai_info.flags[2]).value();
640 obj.ctype.ai_info.PATH_DIR = obj_rw->ctype.ai_info.flags[3];
641 #if DXX_BUILD_DESCENT == 1
642 obj.ctype.ai_info.SUBMODE = obj_rw->ctype.ai_info.flags[4];
643 #elif DXX_BUILD_DESCENT == 2
644 obj.ctype.ai_info.SUB_FLAGS = obj_rw->ctype.ai_info.flags[4];
645 #endif
646 obj.ctype.ai_info.GOALSIDE = build_sidenum_from_untrusted(obj_rw->ctype.ai_info.flags[5]).value();
647 obj.ctype.ai_info.CLOAKED = obj_rw->ctype.ai_info.flags[6];
648 obj.ctype.ai_info.SKIP_AI_COUNT = obj_rw->ctype.ai_info.flags[7];
649 obj.ctype.ai_info.REMOTE_OWNER = obj_rw->ctype.ai_info.flags[8];
650 obj.ctype.ai_info.REMOTE_SLOT_NUM = obj_rw->ctype.ai_info.flags[9];
651 obj.ctype.ai_info.hide_segment = vmsegidx_t::check_nothrow_index(obj_rw->ctype.ai_info.hide_segment).value_or(segment_none);
652 obj.ctype.ai_info.hide_index = obj_rw->ctype.ai_info.hide_index;
653 obj.ctype.ai_info.path_length = obj_rw->ctype.ai_info.path_length;
654 obj.ctype.ai_info.cur_path_index = obj_rw->ctype.ai_info.cur_path_index;
655 obj.ctype.ai_info.danger_laser_num = obj_rw->ctype.ai_info.danger_laser_num;
656 if (obj.ctype.ai_info.danger_laser_num != object_none)
657 obj.ctype.ai_info.danger_laser_signature = object_signature_t{static_cast<uint16_t>(obj_rw->ctype.ai_info.danger_laser_signature)};
658 #if DXX_BUILD_DESCENT == 1
659 #elif DXX_BUILD_DESCENT == 2
660 obj.ctype.ai_info.dying_sound_playing = obj_rw->ctype.ai_info.dying_sound_playing;
661 obj.ctype.ai_info.dying_start_time = obj_rw->ctype.ai_info.dying_start_time;
662 #endif
663 break;
664 }
665
666 case object::control_type::light:
667 obj.ctype.light_info.intensity = obj_rw->ctype.light_info.intensity;
668 break;
669
670 case object::control_type::powerup:
671 obj.ctype.powerup_info.count = obj_rw->ctype.powerup_info.count;
672 #if DXX_BUILD_DESCENT == 1
673 obj.ctype.powerup_info.creation_time = 0;
674 obj.ctype.powerup_info.flags = 0;
675 #elif DXX_BUILD_DESCENT == 2
676 obj.ctype.powerup_info.creation_time = obj_rw->ctype.powerup_info.creation_time;
677 obj.ctype.powerup_info.flags = obj_rw->ctype.powerup_info.flags;
678 #endif
679 break;
680 case object::control_type::cntrlcen:
681 {
682 if (obj.type == OBJ_GHOST)
683 {
684 /* Boss missions convert the reactor into OBJ_GHOST
685 * instead of freeing it. Old releases (before
686 * ed46a05296f9d480f934d8c951c4755ebac1d5e7 ("Update
687 * control_type when ghosting reactor")) did not update
688 * `control_type`, so games saved by those releases have an
689 * object with obj->type == OBJ_GHOST and obj->control_source ==
690 * object::control_type::cntrlcen. That inconsistency triggers an assertion down
691 * in `calc_controlcen_gun_point` because obj->type !=
692 * OBJ_CNTRLCEN.
693 *
694 * Add a special case here to correct this
695 * inconsistency.
696 */
697 obj.control_source = object::control_type::None;
698 break;
699 }
700 // gun points of reactor now part of the object but of course not saved in object_rw and overwritten due to reset_objects(). Let's just recompute them.
701 calc_controlcen_gun_point(obj);
702 break;
703 }
704 case object::control_type::None:
705 case object::control_type::flying:
706 case object::control_type::slew:
707 case object::control_type::flythrough:
708 case object::control_type::repaircen:
709 case object::control_type::morph:
710 case object::control_type::debris:
711 case object::control_type::remote:
712 default:
713 break;
714 }
715
716 switch (obj.render_type)
717 {
718 case render_type::RT_NONE:
719 if (obj.type != OBJ_GHOST) // HACK: when a player is dead or not connected yet, clients still expect to get polyobj data - even if render_type == RT_NONE at this time. Here it's not important, but it might be for Multiplayer Savegames.
720 break;
721 [[fallthrough]];
722 case render_type::RT_MORPH:
723 case render_type::RT_POLYOBJ:
724 {
725 int i;
726 obj.rtype.pobj_info.model_num = build_polygon_model_index_from_untrusted(obj_rw->rtype.pobj_info.model_num);
727 for (i=0;i<MAX_SUBMODELS;i++)
728 {
729 obj.rtype.pobj_info.anim_angles[i].p = obj_rw->rtype.pobj_info.anim_angles[i].p;
730 obj.rtype.pobj_info.anim_angles[i].b = obj_rw->rtype.pobj_info.anim_angles[i].b;
731 obj.rtype.pobj_info.anim_angles[i].h = obj_rw->rtype.pobj_info.anim_angles[i].h;
732 }
733 obj.rtype.pobj_info.subobj_flags = obj_rw->rtype.pobj_info.subobj_flags;
734 obj.rtype.pobj_info.tmap_override = obj_rw->rtype.pobj_info.tmap_override;
735 obj.rtype.pobj_info.alt_textures = obj_rw->rtype.pobj_info.alt_textures;
736 break;
737 }
738
739 case render_type::RT_WEAPON_VCLIP:
740 case render_type::RT_HOSTAGE:
741 case render_type::RT_POWERUP:
742 case render_type::RT_FIREBALL:
743 obj.rtype.vclip_info.vclip_num = build_vclip_index_from_untrusted(obj_rw->rtype.vclip_info.vclip_num);
744 obj.rtype.vclip_info.frametime = obj_rw->rtype.vclip_info.frametime;
745 obj.rtype.vclip_info.framenum = obj_rw->rtype.vclip_info.framenum;
746 break;
747
748 case render_type::RT_LASER:
749 break;
750
751 }
752 }
753
754 }
755
756 deny_save_result deny_save_game(fvcobjptr &vcobjptr, const d_level_unique_control_center_state &LevelUniqueControlCenterState, const d_game_unique_state &GameUniqueState)
757 {
758 #if DXX_BUILD_DESCENT == 1
759 (void)GameUniqueState;
760 #elif DXX_BUILD_DESCENT == 2
761 if (Current_level_num < 0)
762 return deny_save_result::denied;
763 if (GameUniqueState.Final_boss_countdown_time) //don't allow save while final boss is dying
764 return deny_save_result::denied;
765 #endif
766 return deny_save_game(vcobjptr, LevelUniqueControlCenterState);
767 }
768
769 namespace {
770
771 // Following functions convert player to player_rw and back to be written to/read from Savegames. player only differ to player_rw in terms of timer values (fix/fix64). as we reset GameTime64 for writing so it can fit into fix it's not necessary to increment savegame version. But if we once store something else into object which might be useful after restoring, it might be handy to increment Savegame version and actually store these new infos.
772 // turn player to player_rw to be saved to Savegame.
773 static void state_player_to_player_rw(const relocated_player_data &rpd, const player *pl, player_rw *pl_rw, const player_info &pl_info)
774 {
775 pl_rw->callsign = pl->callsign;
776 memset(pl_rw->net_address, 0, 6);
777 pl_rw->connected = underlying_value(pl->connected);
778 pl_rw->objnum = pl->objnum;
779 pl_rw->n_packets_got = 0;
780 pl_rw->n_packets_sent = 0;
781 pl_rw->flags = pl_info.powerup_flags.get_player_flags();
782 pl_rw->energy = pl_info.energy;
783 pl_rw->shields = rpd.shields;
784 /*
785 * The savegame only allocates a uint8_t for this value. If the
786 * player has exceeded the maximum representable value, cap at that
787 * value. This is better than truncating the value, since the
788 * player will get to keep more lives this way than with truncation.
789 */
790 pl_rw->lives = std::min<unsigned>(pl->lives, std::numeric_limits<uint8_t>::max());
791 pl_rw->level = pl->level;
792 pl_rw->laser_level = static_cast<uint8_t>(pl_info.laser_level);
793 pl_rw->starting_level = pl->starting_level;
794 pl_rw->killer_objnum = pl_info.killer_objnum;
795 pl_rw->primary_weapon_flags = pl_info.primary_weapon_flags;
796 #if DXX_BUILD_DESCENT == 1
797 // make sure no side effects for Mac demo
798 pl_rw->secondary_weapon_flags = 0x0f | (pl_info.secondary_ammo[secondary_weapon_index_t::MEGA_INDEX] > 0) << underlying_value(secondary_weapon_index_t::MEGA_INDEX);
799 #elif DXX_BUILD_DESCENT == 2
800 // make sure no side effects for PC demo
801 pl_rw->secondary_weapon_flags = 0xef | (pl_info.secondary_ammo[secondary_weapon_index_t::MEGA_INDEX] > 0) << underlying_value(secondary_weapon_index_t::MEGA_INDEX)
802 | (pl_info.secondary_ammo[secondary_weapon_index_t::SMISSILE4_INDEX] > 0) << underlying_value(secondary_weapon_index_t::SMISSILE4_INDEX) // mercury missile
803 | (pl_info.secondary_ammo[secondary_weapon_index_t::SMISSILE5_INDEX] > 0) << underlying_value(secondary_weapon_index_t::SMISSILE5_INDEX); // earthshaker missile
804 #endif
805 pl_rw->obsolete_primary_ammo = {};
806 pl_rw->vulcan_ammo = pl_info.vulcan_ammo;
807 for (const auto &&[iw, r] : enumerate(pl_info.secondary_ammo))
808 pl_rw->secondary_ammo[underlying_value(iw)] = r;
809 #if DXX_BUILD_DESCENT == 2
810 pl_rw->pad = 0;
811 #endif
812 pl_rw->last_score = pl_info.mission.last_score;
813 pl_rw->score = pl_info.mission.score;
814 pl_rw->time_level = pl->time_level;
815 pl_rw->time_total = pl->time_total;
816 if (!(pl_info.powerup_flags & PLAYER_FLAGS_CLOAKED) || pl_info.cloak_time - GameTime64 < F1_0*(-18000))
817 pl_rw->cloak_time = F1_0*(-18000);
818 else
819 pl_rw->cloak_time = pl_info.cloak_time - GameTime64;
820 if (!(pl_info.powerup_flags & PLAYER_FLAGS_INVULNERABLE) || pl_info.invulnerable_time - GameTime64 < F1_0*(-18000))
821 pl_rw->invulnerable_time = F1_0*(-18000);
822 else
823 pl_rw->invulnerable_time = pl_info.invulnerable_time - GameTime64;
824 #if DXX_BUILD_DESCENT == 2
825 pl_rw->KillGoalCount = pl_info.KillGoalCount;
826 #endif
827 pl_rw->net_killed_total = pl_info.net_killed_total;
828 pl_rw->net_kills_total = pl_info.net_kills_total;
829 pl_rw->num_kills_level = pl->num_kills_level;
830 pl_rw->num_kills_total = pl->num_kills_total;
831 pl_rw->num_robots_level = LevelUniqueObjectState.accumulated_robots;
832 pl_rw->num_robots_total = GameUniqueState.accumulated_robots;
833 pl_rw->hostages_rescued_total = pl_info.mission.hostages_rescued_total;
834 pl_rw->hostages_total = GameUniqueState.total_hostages;
835 pl_rw->hostages_on_board = pl_info.mission.hostages_on_board;
836 pl_rw->hostages_level = LevelUniqueObjectState.total_hostages;
837 pl_rw->homing_object_dist = pl_info.homing_object_dist;
838 pl_rw->hours_level = pl->hours_level;
839 pl_rw->hours_total = pl->hours_total;
840 }
841
842 // turn player_rw to player after reading from Savegame
843
844 static void state_player_rw_to_player(const player_rw *pl_rw, player *pl, player_info &pl_info, relocated_player_data &rpd)
845 {
846 pl->callsign = pl_rw->callsign;
847 pl->connected = player_connection_status{pl_rw->connected};
848 pl->objnum = pl_rw->objnum;
849 pl_info.powerup_flags = player_flags(pl_rw->flags);
850 pl_info.energy = pl_rw->energy;
851 rpd.shields = pl_rw->shields;
852 pl->lives = pl_rw->lives;
853 pl->level = pl_rw->level;
854 pl_info.laser_level = laser_level{pl_rw->laser_level};
855 pl->starting_level = pl_rw->starting_level;
856 pl_info.killer_objnum = pl_rw->killer_objnum;
857 pl_info.primary_weapon_flags = pl_rw->primary_weapon_flags;
858 pl_info.vulcan_ammo = pl_rw->vulcan_ammo;
859 for (const auto &&[ir, w] : enumerate(pl_info.secondary_ammo))
860 w = pl_rw->secondary_ammo[underlying_value(ir)];
861 pl_info.mission.last_score = pl_rw->last_score;
862 pl_info.mission.score = pl_rw->score;
863 pl->time_level = pl_rw->time_level;
864 pl->time_total = pl_rw->time_total;
865 pl_info.cloak_time = pl_rw->cloak_time;
866 pl_info.invulnerable_time = pl_rw->invulnerable_time;
867 #if DXX_BUILD_DESCENT == 1
868 pl_info.KillGoalCount = 0;
869 #elif DXX_BUILD_DESCENT == 2
870 pl_info.KillGoalCount = pl_rw->KillGoalCount;
871 #endif
872 pl_info.net_killed_total = pl_rw->net_killed_total;
873 pl_info.net_kills_total = pl_rw->net_kills_total;
874 pl->num_kills_level = pl_rw->num_kills_level;
875 pl->num_kills_total = pl_rw->num_kills_total;
876 rpd.num_robots_level = pl_rw->num_robots_level;
877 rpd.num_robots_total = pl_rw->num_robots_total;
878 pl_info.mission.hostages_rescued_total = pl_rw->hostages_rescued_total;
879 rpd.hostages_total = pl_rw->hostages_total;
880 pl_info.mission.hostages_on_board = pl_rw->hostages_on_board;
881 rpd.hostages_level = pl_rw->hostages_level;
882 pl_info.homing_object_dist = pl_rw->homing_object_dist;
883 pl->hours_level = pl_rw->hours_level;
884 pl->hours_total = pl_rw->hours_total;
885 }
886
887 static void state_write_player(PHYSFS_File *fp, const player &pl, const relocated_player_data &rpd, const player_info &pl_info)
888 {
889 player_rw pl_rw;
890 state_player_to_player_rw(rpd, &pl, &pl_rw, pl_info);
891 PHYSFSX_writeBytes(fp, &pl_rw, sizeof(pl_rw));
892 }
893
894 static void state_read_player(PHYSFS_File *fp, player &pl, const physfsx_endian swap, player_info &pl_info, relocated_player_data &rpd)
895 {
896 player_rw pl_rw;
897 PHYSFSX_readBytes(fp, &pl_rw, sizeof(pl_rw));
898 player_rw_swap(&pl_rw, swap);
899 state_player_rw_to_player(&pl_rw, &pl, pl_info, rpd);
900 }
901
902 }
903
904 }
905
906 namespace dcx {
907
908 namespace {
909
910 void state_format_savegame_filename(d_game_unique_state::savegame_file_path &filename, const unsigned i)
911 {
912 snprintf(filename.data(), filename.size(), PLAYER_DIRECTORY_STRING("%.8s.%cg%x"), static_cast<const char *>(InterfaceUniqueState.PilotName), (Game_mode & GM_MULTI_COOP) ? 'm' : 's', i);
913 }
914
915 void state_autosave_game(const int multiplayer)
916 {
917 d_game_unique_state::savegame_description desc;
918 const char *p;
919 time_t t = time(nullptr);
920 if (struct tm *ptm = (t == -1) ? nullptr : localtime(&t))
921 {
922 p = desc.data();
923 strftime(desc.data(), desc.size(), "auto %m-%d %H:%M:%S", ptm);
924 }
925 else
926 p = "<autosave>";
927 if (multiplayer)
928 {
929 const auto &&player_range = partial_const_range(Players, N_players);
930 multi_execute_save_game(d_game_unique_state::save_slot::_autosave, desc, player_range);
931 }
932 else
933 {
934 d_game_unique_state::savegame_file_path filename;
935 state_format_savegame_filename(filename, NUM_SAVES - 1);
936 if (state_save_all_sub(filename.data(), p))
937 con_printf(CON_NORMAL, "Autosave written to \"%s\"", filename.data());
938 }
939 }
940
941 }
942
943 }
944
945 namespace dsx {
946
947 namespace {
948
949 uint8_t read_savegame_properties(const std::size_t savegame_index, d_game_unique_state::savegame_file_path &filename, d_game_unique_state::savegame_description *const dsc, grs_bitmap_ptr *const sc_bmp)
950 {
951 state_format_savegame_filename(filename, savegame_index);
952 const auto fp = PHYSFSX_openReadBuffered(filename.data()).first;
953 if (!fp)
954 return 0;
955 //Read id
956 char id[4]{};
957 if (PHYSFSX_readBytes(fp, id, sizeof(id)) != sizeof(id))
958 return 0;
959 if (memcmp(id, dgss_id, 4))
960 return 0;
961 //Read version
962 unsigned version;
963 if (PHYSFSX_readBytes(fp, &version, sizeof(version)) != sizeof(version))
964 return 0;
965 if (!(version >= STATE_COMPATIBLE_VERSION || SWAPINT(version) >= STATE_COMPATIBLE_VERSION))
966 return 0;
967 // In case it's Coop, handle state_game_id & callsign as well
968 if (Game_mode & GM_MULTI_COOP)
969 {
970 PHYSFS_seek(fp, PHYSFS_tell(fp) + sizeof(PHYSFS_sint32) + sizeof(char)*CALLSIGN_LEN+1); // skip state_game_id, callsign
971 }
972 d_game_unique_state::savegame_description desc_storage;
973 d_game_unique_state::savegame_description &desc = dsc ? *dsc : desc_storage;
974 // Read description
975 if (const std::size_t buffer_size{std::size(desc)}; PHYSFSX_readBytes(fp, std::data(desc), buffer_size) != buffer_size)
976 return 0;
977 desc.back() = 0;
978 if (sc_bmp)
979 {
980 // Read thumbnail
981 grs_bitmap_ptr bmp = gr_create_bitmap(THUMBNAIL_W, THUMBNAIL_H);
982 if (constexpr std::size_t buffer_size{THUMBNAIL_W * THUMBNAIL_H}; PHYSFSX_readBytes(fp, bmp->get_bitmap_data(), buffer_size) != buffer_size)
983 return 0;
984 #if DXX_BUILD_DESCENT == 2
985 if (version >= 9)
986 {
987 palette_array_t pal;
988 if (constexpr std::size_t buffer_size{sizeof(pal[0]) * std::size(pal)}; PHYSFSX_readBytes(fp, pal, buffer_size) != buffer_size)
989 return 0;
990 gr_remap_bitmap_good(*bmp.get(), pal, -1, -1);
991 }
992 #endif
993 *sc_bmp = std::move(bmp);
994 }
995 return 1;
996 }
997
998 savegame_newmenu_items::savegame_newmenu_items(d_game_unique_state::savegame_description *const savegame_description, d_game_unique_state::savegame_file_path &savegame_file_path, imenu_description_buffers_array *const user_entered_savegame_descriptions) :
999 caller_savegame_description(savegame_description),
1000 savegame_file_path(savegame_file_path)
1001 {
1002 unsigned nsaves{0};
1003 /* Always start at offset `decorative_item_count` to skip the fixed
1004 * text leader. Conditionally subtract 1 if the call is for saving,
1005 * since interactive saves should not access the last slot. The
1006 * last slot is reserved for autosaves.
1007 */
1008 const unsigned max_slots_shown = get_count_valid_menuitem_entries(savegame_description);
1009 for (const auto &&[savegame_index, mi, filename, desc, sc_bmp] : enumerate(zip(partial_range(m, decorative_item_count, max_slots_shown), savegame_file_paths, savegame_descriptions, sc_bmp)))
1010 {
1011 const auto existing_savegame_found = read_savegame_properties(savegame_index, filename, &desc, &sc_bmp);
1012 if (existing_savegame_found)
1013 ++nsaves;
1014 else
1015 /* Defer setting a default value to here. This allows the
1016 * value to be written only if a better one was not
1017 * retrieved from a save game file.
1018 */
1019 strcpy(desc.data(), TXT_EMPTY);
1020 mi.text = desc.data();
1021 mi.type = savegame_description
1022 /* If saving, use input_menu so that the user can pick an
1023 * element and convert it into a text entry field to receive
1024 * the save game title.
1025 */
1026 ? nm_type::input_menu
1027 /* If restoring, use text. Valid save games will switch the
1028 * type. Invalid save slots will remain set as text.
1029 */
1030 : (existing_savegame_found
1031 ? nm_type::menu
1032 : nm_type::text);
1033 if (user_entered_savegame_descriptions)
1034 mi.initialize_imenu(desc, (*user_entered_savegame_descriptions)[savegame_index]);
1035 }
1036 if (!savegame_description && nsaves < 1)
1037 throw error_no_saves_found();
1038 nm_set_item_text(m[0], "\n\n\n\n");
1039 }
1040
1041 }
1042
1043 void state_set_immediate_autosave(d_game_unique_state &GameUniqueState)
1044 {
1045 GameUniqueState.Next_autosave = {};
1046 }
1047
1048 void state_set_next_autosave(d_game_unique_state &GameUniqueState, const std::chrono::steady_clock::time_point now, const autosave_interval_type interval)
1049 {
1050 GameUniqueState.Next_autosave = now + interval;
1051 }
1052
1053 void state_set_next_autosave(d_game_unique_state &GameUniqueState, const autosave_interval_type interval)
1054 {
1055 const auto now = std::chrono::steady_clock::now();
1056 state_set_next_autosave(GameUniqueState, now, interval);
1057 }
1058
1059 void state_poll_autosave_game(d_game_unique_state &GameUniqueState, const d_level_unique_object_state &LevelUniqueObjectState)
1060 {
1061 const auto multiplayer{Game_mode & GM_MULTI};
1062 if (multiplayer && !multi_i_am_master())
1063 return;
1064 const auto interval = (multiplayer ? static_cast<const d_gameplay_options &>(Netgame.MPGameplayOptions) : PlayerCfg.SPGameplayOptions).AutosaveInterval;
1065 if (interval.count() <= 0)
1066 /* Autosave is disabled */
1067 return;
1068 auto &LevelUniqueControlCenterState = LevelUniqueObjectState.ControlCenterState;
1069 auto &Objects = LevelUniqueObjectState.Objects;
1070 if (deny_save_game(Objects.vcptr, LevelUniqueControlCenterState, GameUniqueState) != deny_save_result::allowed)
1071 return;
1072 if (Newdemo_state != ND_STATE_NORMAL && Newdemo_state != ND_STATE_RECORDING)
1073 return;
1074 const auto now = std::chrono::steady_clock::now();
1075 if (now < GameUniqueState.Next_autosave)
1076 return;
1077 state_set_next_autosave(GameUniqueState, now, interval);
1078 state_autosave_game(multiplayer);
1079 }
1080
1081 namespace {
1082
1083 /* Present a menu for selection of a savegame filename.
1084 * For saving, dsc should be a pre-allocated buffer into which the new
1085 * savegame description will be stored.
1086 * For restoring, dsc should be NULL, in which case empty slots will not be
1087 * selectable and savagames descriptions will not be editable.
1088 */
1089 static d_game_unique_state::save_slot state_get_savegame_filename(grs_canvas &canvas, d_game_unique_state::savegame_file_path &fname, d_game_unique_state::savegame_description *const dsc, const menu_subtitle caption, const blind_save entry_blind)
1090 {
1091 const auto quicksave_selection = GameUniqueState.quicksave_selection;
1092 if (entry_blind != blind_save::no &&
1093 /* The user requested a non-blind save. This block only handles
1094 * blind saves, so skip down to the general handler.
1095 */
1096 savegame_chooser_newmenu::valid_savegame_index(dsc, quicksave_selection))
1097 {
1098 /* The cached slot is valid, so a save/load might work.
1099 */
1100 if (read_savegame_properties(static_cast<std::size_t>(quicksave_selection), fname, dsc, nullptr))
1101 /* The data was read from the savegame. Return early and
1102 * skip the dialog.
1103 */
1104 return quicksave_selection;
1105 /* Fall through and run the interactive dialog, whether the user
1106 * requested one or not.
1107 */
1108 }
1109 std::unique_ptr<savegame_chooser_newmenu> win;
1110 try {
1111 win = savegame_chooser_newmenu::create(caption, canvas, dsc, fname);
1112 }
1113 catch (const savegame_chooser_newmenu::error_no_saves_found &)
1114 {
1115 struct error_no_saves_found : passive_messagebox
1116 {
1117 error_no_saves_found(grs_canvas &canvas) :
1118 passive_messagebox(menu_title{nullptr}, menu_subtitle{"No saved games were found!"}, TXT_OK, canvas)
1119 {
1120 }
1121 };
1122 run_blocking_newmenu<error_no_saves_found>(canvas);
1123 return d_game_unique_state::save_slot::None;
1124 }
1125 win->send_creation_events();
1126 const auto citem = savegame_chooser_newmenu::process_until_closed(win.release());
1127 /* win is now invalid */
1128 if (citem <= 0)
1129 return d_game_unique_state::save_slot::None;
1130 const auto choice = static_cast<d_game_unique_state::save_slot>(citem - savegame_chooser_newmenu::decorative_item_count);
1131 assert(savegame_chooser_newmenu::valid_savegame_index(dsc, choice));
1132 return choice;
1133 }
1134
1135 }
1136
1137 d_game_unique_state::save_slot state_get_save_file(grs_canvas &canvas, d_game_unique_state::savegame_file_path &fname, d_game_unique_state::savegame_description *const dsc, const blind_save blind_save)
1138 {
1139 return state_get_savegame_filename(canvas, fname, dsc, menu_subtitle{"Save Game"}, blind_save);
1140 }
1141
1142 d_game_unique_state::save_slot state_get_restore_file(grs_canvas &canvas, d_game_unique_state::savegame_file_path &fname, blind_save blind_save)
1143 {
1144 return state_get_savegame_filename(canvas, fname, nullptr, menu_subtitle{"Select Game to Restore"}, blind_save);
1145 }
1146
1147 #if DXX_BUILD_DESCENT == 1
1148 #elif DXX_BUILD_DESCENT == 2
1149 namespace {
1150
1151 // -----------------------------------------------------------------------------------
1152 // Imagine if C had a function to copy a file...
1153 static int copy_file(const char *old_file, const char *new_file)
1154 {
1155 RAIIPHYSFS_File in_file{PHYSFS_openRead(old_file)};
1156 if (!in_file)
1157 return -2;
1158 RAIIPHYSFS_File out_file{PHYSFS_openWrite(new_file)};
1159 if (!out_file)
1160 return -1;
1161
1162 constexpr std::size_t buf_size = 512 * 1024;
1163 const auto buf = std::make_unique<uint8_t[]>(buf_size);
1164 const auto pbuf = buf.get();
1165 while (!PHYSFS_eof(in_file))
1166 {
1167 const auto bytes_read{PHYSFSX_readBytes(in_file, pbuf, buf_size)};
1168 if (bytes_read < 0)
1169 Error("Cannot read from file <%s>: %s", old_file, PHYSFS_getLastError());
1170
1171 if (PHYSFSX_writeBytes(out_file, pbuf, bytes_read) < bytes_read)
1172 Error("Cannot write to file <%s>: %s", new_file, PHYSFS_getLastError());
1173 }
1174 if (!out_file.close())
1175 return -4;
1176
1177 return 0;
1178 }
1179
1180 static void format_secret_sgc_filename(std::array<char, PATH_MAX> &fname, const d_game_unique_state::save_slot filenum)
1181 {
1182 snprintf(fname.data(), fname.size(), PLAYER_DIRECTORY_STRING("%xsecret.sgc"), static_cast<unsigned>(filenum));
1183 }
1184
1185 }
1186 #endif
1187
1188 // -----------------------------------------------------------------------------------
1189 #if DXX_BUILD_DESCENT == 1
1190 int state_save_all(const blind_save blind_save)
1191 #elif DXX_BUILD_DESCENT == 2
1192 int state_save_all(const secret_save secret, const blind_save blind_save)
1193 #endif
1194 {
1195 #if DXX_BUILD_DESCENT == 1
1196 static constexpr std::integral_constant<secret_save, secret_save::none> secret{};
1197 #elif DXX_BUILD_DESCENT == 2
1198 auto &LevelUniqueControlCenterState = LevelUniqueObjectState.ControlCenterState;
1199 if (Current_level_num < 0 && secret == secret_save::none)
1200 {
1201 HUD_init_message_literal(HM_DEFAULT, "Can't save in secret level!" );
1202 return 0;
1203 }
1204
1205 if (GameUniqueState.Final_boss_countdown_time) //don't allow save while final boss is dying
1206 return 0;
1207 #endif
1208
1209 if ( Game_mode & GM_MULTI )
1210 {
1211 if (Game_mode & GM_MULTI_COOP)
1212 multi_initiate_save_game();
1213 return 0;
1214 }
1215
1216 #if DXX_BUILD_DESCENT == 2
1217 // If this is a secret save and the control center has been destroyed, don't allow
1218 // return to the base level.
1219 if (secret != secret_save::none && LevelUniqueControlCenterState.Control_center_destroyed)
1220 {
1221 PHYSFS_delete(SECRETB_FILENAME);
1222 return 0;
1223 }
1224 #endif
1225
1226 d_game_unique_state::savegame_file_path filename_storage;
1227 const char *filename;
1228 d_game_unique_state::savegame_description desc{};
1229 d_game_unique_state::save_slot filenum = d_game_unique_state::save_slot::None;
1230 {
1231 pause_game_world_time p;
1232
1233 #if DXX_BUILD_DESCENT == 2
1234 if (secret == secret_save::b) {
1235 filename = SECRETB_FILENAME;
1236 } else if (secret == secret_save::c) {
1237 filename = SECRETC_FILENAME;
1238 } else
1239 #endif
1240 {
1241 filenum = state_get_save_file(*grd_curcanv, filename_storage, &desc, blind_save);
1242 if (!GameUniqueState.valid_save_slot(filenum))
1243 return 0;
1244 filename = filename_storage.data();
1245 }
1246 #if DXX_BUILD_DESCENT == 2
1247 // MK, 1/1/96
1248 // Do special secret level stuff.
1249 // If secret.sgc exists, then copy it to Nsecret.sgc (where N = filenum).
1250 // If it doesn't exist, then delete Nsecret.sgc
1251 if (secret == secret_save::none && !(Game_mode & GM_MULTI_COOP)) {
1252 if (filenum != d_game_unique_state::save_slot::None)
1253 {
1254 std::array<char, PATH_MAX> fname;
1255 const auto temp_fname = fname.data();
1256 format_secret_sgc_filename(fname, filenum);
1257 if (PHYSFS_exists(temp_fname))
1258 {
1259 if (!PHYSFS_delete(temp_fname))
1260 Error("Cannot delete file <%s>: %s", temp_fname, PHYSFS_getLastError());
1261 }
1262
1263 if (PHYSFS_exists(SECRETC_FILENAME))
1264 {
1265 const int rval = copy_file(SECRETC_FILENAME, temp_fname);
1266 Assert(rval == 0); // Oops, error copying secret.sgc to temp_fname!
1267 (void)rval;
1268 }
1269 }
1270 }
1271 #endif
1272 }
1273
1274 const int rval = state_save_all_sub(filename, desc.data());
1275
1276 if (rval && secret == secret_save::none)
1277 HUD_init_message(HM_DEFAULT, "Game saved to \"%s\": \"%s\"", filename, desc.data());
1278
1279 return rval;
1280 }
1281
1282 int state_save_all_sub(const char *filename, const char *desc)
1283 {
1284 auto &LevelUniqueControlCenterState = LevelUniqueObjectState.ControlCenterState;
1285 auto &Objects = LevelUniqueObjectState.Objects;
1286 auto &vcobjptr = Objects.vcptr;
1287 auto &vmobjptr = Objects.vmptr;
1288 auto &LevelUniqueMorphObjectState = LevelUniqueObjectState.MorphObjectState;
1289 auto &RobotCenters = LevelSharedRobotcenterState.RobotCenters;
1290 auto &Station = LevelUniqueFuelcenterState.Station;
1291 fix tmptime32{0};
1292
1293 #ifndef NDEBUG
1294 if (CGameArg.SysUsePlayersDir && strncmp(filename, PLAYER_DIRECTORY_TEXT, sizeof(PLAYER_DIRECTORY_TEXT) - 1))
1295 Int3();
1296 #endif
1297
1298 auto &&[fp, physfserr] = PHYSFSX_openWriteBuffered(filename);
1299 if (!fp)
1300 {
1301 const auto errstr = PHYSFS_getErrorByCode(physfserr);
1302 con_printf(CON_URGENT, "Failed to open savegame %s: %s", filename, errstr);
1303 struct error_writing_savegame :
1304 std::array<char, 96>,
1305 passive_messagebox
1306 {
1307 error_writing_savegame(const char *filename, const char *errstr) :
1308 passive_messagebox(menu_title{TXT_ERROR}, menu_subtitle{prepare_subtitle(*this, filename, errstr)}, "Return to unsaved game", grd_curscreen->sc_canvas)
1309 {
1310 }
1311 static const char *prepare_subtitle(std::array<char, 96> &b, const char *filename, const char *errstr)
1312 {
1313 auto r = b.data();
1314 std::snprintf(r, b.size(), "Failed to write savegame\n%s\n\n%s", filename, errstr);
1315 return r;
1316 }
1317 };
1318 run_blocking_newmenu<error_writing_savegame>(filename, errstr);
1319 return 0;
1320 }
1321
1322 pause_game_world_time p;
1323
1324 //Save id
1325 PHYSFSX_writeBytes(fp, dgss_id, sizeof(char) * 4);
1326
1327 //Save version
1328 {
1329 const int i = STATE_VERSION;
1330 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1331 }
1332
1333 // Save Coop state_game_id and this Player's callsign. Oh the redundancy... we have this one later on but Coop games want to read this before loading a state so for easy access save this here, too
1334 if (Game_mode & GM_MULTI_COOP)
1335 {
1336 PHYSFSX_writeBytes(fp, &state_game_id, sizeof(unsigned));
1337 PHYSFSX_writeBytes(fp, &get_local_player().callsign, sizeof(char) * CALLSIGN_LEN + 1);
1338 }
1339
1340 //Save description
1341 PHYSFSX_writeBytes(fp, desc, 20);
1342
1343 // Save the current screen shot...
1344
1345 auto cnv = gr_create_canvas( THUMBNAIL_W, THUMBNAIL_H );
1346 {
1347 {
1348 window_rendered_data window;
1349 render_frame(*cnv, 0, window);
1350 }
1351
1352 {
1353 #if DXX_USE_OGL
1354 const auto buf = std::make_unique<uint8_t[]>(THUMBNAIL_W * THUMBNAIL_H * 4);
1355 #if !DXX_USE_OGLES
1356 GLint gl_draw_buffer;
1357 glGetIntegerv(GL_DRAW_BUFFER, &gl_draw_buffer);
1358 glReadBuffer(gl_draw_buffer);
1359 #endif
1360 glReadPixels(0, SHEIGHT - THUMBNAIL_H, THUMBNAIL_W, THUMBNAIL_H, GL_RGBA, GL_UNSIGNED_BYTE, buf.get());
1361 int k;
1362 k = THUMBNAIL_H;
1363 for (unsigned i = 0; i < THUMBNAIL_W * THUMBNAIL_H; i++)
1364 {
1365 int j;
1366 if (!(j = i % THUMBNAIL_W))
1367 k--;
1368 cnv->cv_bitmap.get_bitmap_data()[THUMBNAIL_W * k + j] =
1369 gr_find_closest_color(buf[4*i]/4, buf[4*i+1]/4, buf[4*i+2]/4);
1370 }
1371 #endif
1372 }
1373
1374 PHYSFSX_writeBytes(fp, cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H);
1375 #if DXX_BUILD_DESCENT == 2
1376 PHYSFSX_writeBytes(fp, gr_palette.data(), sizeof(gr_palette[0]) * gr_palette.size());
1377 #endif
1378 }
1379
1380 // Save the Between levels flag...
1381 {
1382 const int i = 0;
1383 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1384 }
1385
1386 // Save the mission info...
1387 savegame_mission_path mission_pathname{};
1388 #if DXX_BUILD_DESCENT == 2
1389 mission_pathname.original[1] = static_cast<uint8_t>(Current_mission->descent_version);
1390 #endif
1391 mission_pathname.original.back() = static_cast<uint8_t>(savegame_mission_name_abi::pathname);
1392 auto Current_mission_pathname = Current_mission->path.c_str();
1393 // Current_mission_filename is not necessarily 9 bytes long so for saving we use a proper string - preventing corruptions
1394 snprintf(mission_pathname.full.data(), mission_pathname.full.size(), "%s", Current_mission_pathname);
1395 PHYSFSX_writeBytes(fp, &mission_pathname, sizeof(mission_pathname));
1396
1397 //Save level info
1398 PHYSFSX_writeBytes(fp, &Current_level_num, sizeof(int));
1399 PHYSFS_writeULE32(fp, 0);
1400
1401 //Save GameTime
1402 // NOTE: GameTime now is GameTime64 with fix64 since GameTime could only last 9 hrs. To even help old Savegames, we do not increment Savegame version but rather RESET GameTime64 to 0 on every save! ALL variables based on GameTime64 now will get the current GameTime64 value substracted and saved to fix size as well.
1403 tmptime32 = 0;
1404 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
1405
1406 //Save player info
1407 const auto &plrobj = get_local_plrobj();
1408 auto &player_info = plrobj.ctype.player_info;
1409 state_write_player(fp, get_local_player(), relocated_player_data{
1410 plrobj.shields,
1411 static_cast<int16_t>(LevelUniqueObjectState.accumulated_robots),
1412 static_cast<int16_t>(GameUniqueState.accumulated_robots),
1413 static_cast<uint16_t>(GameUniqueState.total_hostages),
1414 static_cast<uint8_t>(LevelUniqueObjectState.total_hostages)
1415 }, player_info);
1416
1417 // Save the current weapon info
1418 {
1419 const int8_t v = static_cast<int8_t>(player_info.Primary_weapon.get_active());
1420 PHYSFSX_writeBytes(fp, &v, sizeof(int8_t));
1421 }
1422 {
1423 const int8_t v = static_cast<int8_t>(player_info.Secondary_weapon.get_active());
1424 PHYSFSX_writeBytes(fp, &v, sizeof(int8_t));
1425 }
1426
1427 // Save the difficulty level
1428 {
1429 const int Difficulty_level = underlying_value(GameUniqueState.Difficulty_level);
1430 PHYSFSX_writeBytes(fp, &Difficulty_level, sizeof(int));
1431 }
1432
1433 // Save cheats enabled
1434 PHYSFS_writeULE32(fp, cheats.enabled ? UINT32_MAX : 0);
1435 #if DXX_BUILD_DESCENT == 1
1436 PHYSFS_writeULE32(fp, cheats.turbo ? UINT32_MAX : 0);
1437 #endif
1438
1439 //Finish all morph objects
1440 for (auto &obj : vmobjptr)
1441 {
1442 if (obj.type != OBJ_NONE && obj.render_type == render_type::RT_MORPH)
1443 {
1444 if (const auto umd = find_morph_data(LevelUniqueMorphObjectState, obj))
1445 {
1446 const auto md = umd->get();
1447 md->obj->control_source = md->morph_save_control_type;
1448 md->obj->movement_source = md->morph_save_movement_type;
1449 md->obj->render_type = render_type::RT_POLYOBJ;
1450 md->obj->mtype.phys_info = md->morph_save_phys_info;
1451 umd->reset();
1452 } else { //maybe loaded half-morphed from disk
1453 obj.flags |= OF_SHOULD_BE_DEAD;
1454 obj.render_type = render_type::RT_POLYOBJ;
1455 obj.control_source = object::control_type::None;
1456 obj.movement_source = object::movement_type::None;
1457 }
1458 }
1459 }
1460
1461 //Save object info
1462 {
1463 const int i = Highest_object_index+1;
1464 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1465 }
1466 {
1467 object_rw None{};
1468 None.type = OBJ_NONE;
1469 for (auto &obj : vcobjptr)
1470 {
1471 object_rw obj_rw;
1472 PHYSFSX_writeBytes(fp, obj.type == OBJ_NONE ? &None : (state_object_to_object_rw(obj, &obj_rw), &obj_rw), sizeof(obj_rw));
1473 }
1474 }
1475
1476 //Save wall info
1477 {
1478 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1479 auto &vcwallptr = Walls.vcptr;
1480 {
1481 const int i = Walls.get_count();
1482 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1483 }
1484 for (auto &w : vcwallptr)
1485 wall_write(fp, w, 0x7fff);
1486
1487 #if DXX_BUILD_DESCENT == 2
1488 //Save exploding wall info
1489 expl_wall_write(Walls.vmptr, fp);
1490 #endif
1491 }
1492
1493 //Save door info
1494 {
1495 auto &ActiveDoors = LevelUniqueWallSubsystemState.ActiveDoors;
1496 {
1497 const int i = ActiveDoors.get_count();
1498 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1499 }
1500 for (auto &ad : ActiveDoors.vcptr)
1501 active_door_write(fp, ad);
1502 }
1503
1504 #if DXX_BUILD_DESCENT == 2
1505 //Save cloaking wall info
1506 {
1507 auto &CloakingWalls = LevelUniqueWallSubsystemState.CloakingWalls;
1508 {
1509 const int i = CloakingWalls.get_count();
1510 PHYSFSX_writeBytes(fp, &i, sizeof(int));
1511 }
1512 for (auto &w : CloakingWalls.vcptr)
1513 cloaking_wall_write(w, fp);
1514 }
1515 #endif
1516
1517 //Save trigger info
1518 {
1519 auto &Triggers = LevelUniqueWallSubsystemState.Triggers;
1520 {
1521 unsigned num_triggers = Triggers.get_count();
1522 PHYSFSX_writeBytes(fp, &num_triggers, sizeof(int));
1523 }
1524 for (auto &vt : Triggers.vcptr)
1525 trigger_write(fp, vt);
1526 }
1527
1528 //Save tmap info
1529 for (auto &seg : vcsegptr)
1530 {
1531 for (auto &&[ss, us] : zip(seg.shared_segment::sides, seg.unique_segment::sides)) // d_zip
1532 {
1533 segment_side_wall_tmap_write(fp, ss, us);
1534 }
1535 }
1536
1537 // Save the fuelcen info
1538 {
1539 const int Control_center_destroyed = LevelUniqueControlCenterState.Control_center_destroyed;
1540 PHYSFSX_writeBytes(fp, &Control_center_destroyed, sizeof(int));
1541 }
1542 #if DXX_BUILD_DESCENT == 1
1543 PHYSFSX_writeBytes(fp, &LevelUniqueControlCenterState.Countdown_seconds_left, sizeof(int));
1544 #elif DXX_BUILD_DESCENT == 2
1545 PHYSFSX_writeBytes(fp, &LevelUniqueControlCenterState.Countdown_timer, sizeof(int));
1546 #endif
1547 const unsigned Num_robot_centers = LevelSharedRobotcenterState.Num_robot_centers;
1548 PHYSFSX_writeBytes(fp, &Num_robot_centers, sizeof(int));
1549 range_for (auto &r, partial_const_range(RobotCenters, Num_robot_centers))
1550 #if DXX_BUILD_DESCENT == 1
1551 matcen_info_write(fp, r, STATE_MATCEN_VERSION);
1552 #elif DXX_BUILD_DESCENT == 2
1553 matcen_info_write(fp, r, 0x7f);
1554 #endif
1555 control_center_triggers_write(ControlCenterTriggers, fp);
1556 const auto Num_fuelcenters = LevelUniqueFuelcenterState.Num_fuelcenters;
1557 PHYSFSX_writeBytes(fp, &Num_fuelcenters, sizeof(int));
1558 range_for (auto &s, partial_range(Station, Num_fuelcenters))
1559 {
1560 #if DXX_BUILD_DESCENT == 1
1561 // NOTE: Usually Descent1 handles countdown by Timer value of the Reactor Station. Since we now use Descent2 code to handle countdown (which we do in case there IS NO Reactor Station which causes potential trouble in Multiplayer), let's find the Reactor here and store the timer in it.
1562 if (s.Type == segment_special::controlcen)
1563 s.Timer = LevelUniqueControlCenterState.Countdown_timer;
1564 #endif
1565 fuelcen_write(fp, s);
1566 }
1567
1568 // Save the control cen info
1569 {
1570 const int Control_center_been_hit = LevelUniqueControlCenterState.Control_center_been_hit;
1571 PHYSFSX_writeBytes(fp, &Control_center_been_hit, sizeof(int));
1572 }
1573 {
1574 const auto cc = static_cast<int>(LevelUniqueControlCenterState.Control_center_player_been_seen);
1575 PHYSFSX_writeBytes(fp, &cc, sizeof(int));
1576 }
1577 PHYSFSX_writeBytes(fp, &LevelUniqueControlCenterState.Frametime_until_next_fire, sizeof(int));
1578 {
1579 const int Control_center_present = LevelUniqueControlCenterState.Control_center_present;
1580 PHYSFSX_writeBytes(fp, &Control_center_present, sizeof(int));
1581 }
1582 {
1583 const auto Dead_controlcen_object_num = LevelUniqueControlCenterState.Dead_controlcen_object_num;
1584 int dead_controlcen_object_num = Dead_controlcen_object_num == object_none ? -1 : Dead_controlcen_object_num;
1585 PHYSFSX_writeBytes(fp, &dead_controlcen_object_num, sizeof(int));
1586 }
1587
1588 // Save the AI state
1589 ai_save_state( fp );
1590
1591 // Save the automap visited info
1592 PHYSFSX_writeBytes(fp, LevelUniqueAutomapState.Automap_visited.data(), std::max<std::size_t>(Highest_segment_index + 1, MAX_SEGMENTS_ORIGINAL));
1593
1594 PHYSFSX_writeBytes(fp, &state_game_id, sizeof(unsigned));
1595 {
1596 PHYSFS_writeULE32(fp, cheats.rapidfire ? UINT32_MAX : 0);
1597 #if DXX_BUILD_DESCENT == 1
1598 PHYSFS_writeULE32(fp, 0); // was Ugly_robot_cheat
1599 PHYSFS_writeULE32(fp, 0); // was Ugly_robot_texture
1600 PHYSFS_writeULE32(fp, cheats.ghostphysics ? UINT32_MAX : 0);
1601 #endif
1602 PHYSFS_writeULE32(fp, 0); // was Lunacy
1603 #if DXX_BUILD_DESCENT == 2
1604 PHYSFS_writeULE32(fp, 0); // was Lunacy, too... and one was Ugly robot stuff a long time ago...
1605
1606 // Save automap marker info
1607
1608 range_for (int m, MarkerState.imobjidx)
1609 {
1610 if (m == object_none)
1611 m = -1;
1612 PHYSFSX_writeBytes(fp, &m, sizeof(m));
1613 }
1614 PHYSFS_seek(fp, PHYSFS_tell(fp) + (NUM_MARKERS)*(CALLSIGN_LEN+1)); // MarkerOwner is obsolete
1615 range_for (const auto &m, MarkerState.message)
1616 PHYSFSX_writeBytes(fp, m.data(), m.size());
1617
1618 PHYSFSX_writeBytes(fp, &Afterburner_charge, sizeof(fix));
1619
1620 //save last was super information
1621 {
1622 auto &Primary_last_was_super = player_info.Primary_last_was_super;
1623 std::array<uint8_t, MAX_PRIMARY_WEAPONS> last_was_super{};
1624 /* Descent 2 shipped with Primary_last_was_super and
1625 * Secondary_last_was_super each sized to contain MAX_*_WEAPONS,
1626 * but only the first half of those are ever used.
1627 * Unfortunately, the save file format is defined as saving
1628 * MAX_*_WEAPONS for each. Copy into a temporary, then write
1629 * the temporary to the file.
1630 */
1631 for (uint8_t j = static_cast<uint8_t>(primary_weapon_index_t::VULCAN_INDEX); j != static_cast<uint8_t>(primary_weapon_index_t::SUPER_LASER_INDEX); ++j)
1632 {
1633 if (Primary_last_was_super & HAS_PRIMARY_FLAG(primary_weapon_index_t{j}))
1634 last_was_super[j] = 1;
1635 }
1636 PHYSFSX_writeBytes(fp, &last_was_super, MAX_PRIMARY_WEAPONS);
1637 }
1638 {
1639 auto &Secondary_last_was_super = player_info.Secondary_last_was_super;
1640 std::array<uint8_t, MAX_SECONDARY_WEAPONS> last_was_super{};
1641 for (uint8_t j = static_cast<uint8_t>(secondary_weapon_index_t::CONCUSSION_INDEX); j != static_cast<uint8_t>(secondary_weapon_index_t::SMISSILE1_INDEX); ++j)
1642 {
1643 if (Secondary_last_was_super & HAS_SECONDARY_FLAG(secondary_weapon_index_t{j}))
1644 last_was_super[j] = 1;
1645 }
1646 PHYSFSX_writeBytes(fp, &last_was_super, MAX_SECONDARY_WEAPONS);
1647 }
1648
1649 // Save flash effect stuff
1650 PHYSFSX_writeBytes(fp, &Flash_effect, sizeof(int));
1651 if (Time_flash_last_played - GameTime64 < F1_0*(-18000))
1652 tmptime32 = F1_0*(-18000);
1653 else
1654 tmptime32 = Time_flash_last_played - GameTime64;
1655 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
1656 PHYSFSX_writeBytes(fp, &PaletteRedAdd, sizeof(int));
1657 PHYSFSX_writeBytes(fp, &PaletteGreenAdd, sizeof(int));
1658 PHYSFSX_writeBytes(fp, &PaletteBlueAdd, sizeof(int));
1659 {
1660 union {
1661 std::array<uint8_t, MAX_SEGMENTS> light_subtracted;
1662 std::array<uint8_t, MAX_SEGMENTS_ORIGINAL> light_subtracted_original;
1663 };
1664 const std::ranges::subrange r{vcsegptr};
1665 /* For compatibility with old game versions, always write at
1666 * least MAX_SEGMENTS_ORIGINAL entries. If the level is larger
1667 * than that, then write as many entries as needed for the
1668 * level.
1669 */
1670 const unsigned count = (Highest_segment_index + 1 > MAX_SEGMENTS_ORIGINAL)
1671 /* Every written element will be filled by the loop, so
1672 * there is no need to initialize the storage area.
1673 */
1674 ? vcsegptr.count()
1675 /* The loop may fill fewer than MAX_SEGMENTS_ORIGINAL
1676 * entries, but MAX_SEGMENTS_ORIGINAL entries will be
1677 * written, so zero-initialize the elements first.
1678 */
1679 : (light_subtracted_original = {}, MAX_SEGMENTS_ORIGINAL);
1680 auto j = light_subtracted.begin();
1681 for (const unique_segment &useg : r)
1682 *j++ = underlying_value(useg.light_subtracted);
1683 PHYSFSX_writeBytes(fp, light_subtracted.data(), count);
1684 }
1685 PHYSFSX_writeBytes(fp, &First_secret_visit, sizeof(First_secret_visit));
1686 auto &Omega_charge = player_info.Omega_charge;
1687 PHYSFSX_writeBytes(fp, &Omega_charge, sizeof(Omega_charge));
1688 #endif
1689 }
1690
1691 // Save Coop Info
1692 if (Game_mode & GM_MULTI_COOP)
1693 {
1694 /* Write local player's shields for everyone. Remote players'
1695 * shields are ignored, and using local everywhere is cheaper
1696 * than using it only for the one slot where it may matter.
1697 */
1698 const auto shields{plrobj.shields};
1699 const relocated_player_data rpd{shields, 0, 0, 0, 0};
1700 // I know, I know we only allow 4 players in coop. I screwed that up. But if we ever allow 8 players in coop, who's gonna laugh then?
1701 range_for (auto &i, partial_const_range(Players, MAX_PLAYERS))
1702 {
1703 state_write_player(fp, i, rpd, player_info);
1704 }
1705 PHYSFSX_writeBytes(fp, Netgame.mission_title.data(), Netgame.mission_title.size());
1706 PHYSFSX_writeBytes(fp, Netgame.mission_name.data(), Netgame.mission_name.size());
1707 PHYSFSX_writeBytes(fp, &Netgame.levelnum, sizeof(int));
1708 PHYSFSX_writeBytes(fp, &Netgame.difficulty, sizeof(ubyte));
1709 PHYSFSX_writeBytes(fp, &Netgame.game_status, sizeof(ubyte));
1710 PHYSFSX_writeBytes(fp, &Netgame.numplayers, sizeof(ubyte));
1711 PHYSFSX_writeBytes(fp, &Netgame.max_numplayers, sizeof(ubyte));
1712 PHYSFSX_writeBytes(fp, &Netgame.numconnected, sizeof(ubyte));
1713 PHYSFSX_writeBytes(fp, &Netgame.level_time, sizeof(int));
1714 }
1715 return 1;
1716 }
1717
1718 // -----------------------------------------------------------------------------------
1719 // Set the player's position from the globals Secret_return_segment and Secret_return_orient.
1720 #if DXX_BUILD_DESCENT == 2
1721 void set_pos_from_return_segment(void)
1722 {
1723 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1724 auto &Objects = LevelUniqueObjectState.Objects;
1725 auto &Vertices = LevelSharedVertexState.get_vertices();
1726 auto &vmobjptr = Objects.vmptr;
1727 auto &vmobjptridx = Objects.vmptridx;
1728 const auto &&plobjnum = vmobjptridx(get_local_player().objnum);
1729 const auto &&segp = vmsegptridx(LevelSharedSegmentState.Secret_return_segment);
1730 auto &vcvertptr = Vertices.vcptr;
1731 plobjnum->pos = compute_segment_center(vcvertptr, segp);
1732 obj_relink(vmobjptr, vmsegptr, plobjnum, segp);
1733 plobjnum->orient = LevelSharedSegmentState.Secret_return_orient;
1734 reset_player_object(*plobjnum);
1735 }
1736 #endif
1737
1738 // -----------------------------------------------------------------------------------
1739 #if DXX_BUILD_DESCENT == 1
1740 int state_restore_all(const int in_game, std::nullptr_t, const blind_save blind)
1741 #elif DXX_BUILD_DESCENT == 2
1742 int state_restore_all(const int in_game, const secret_restore secret, const char *const filename_override, const blind_save blind)
1743 #endif
1744 {
1745
1746 #if DXX_BUILD_DESCENT == 1
1747 static constexpr std::integral_constant<secret_restore, secret_restore::none> secret{};
1748 #elif DXX_BUILD_DESCENT == 2
1749 if (in_game && Current_level_num < 0 && secret == secret_restore::none)
1750 {
1751 HUD_init_message_literal(HM_DEFAULT, "Can't restore in secret level!" );
1752 return 0;
1753 }
1754 #endif
1755
1756 if ( Newdemo_state == ND_STATE_RECORDING )
1757 newdemo_stop_recording();
1758
1759 if ( Newdemo_state != ND_STATE_NORMAL )
1760 return 0;
1761
1762 if ( Game_mode & GM_MULTI )
1763 {
1764 if (Game_mode & GM_MULTI_COOP)
1765 multi_initiate_restore_game();
1766 return 0;
1767 }
1768
1769 d_game_unique_state::savegame_file_path filename_storage;
1770 const char *filename;
1771 d_game_unique_state::save_slot filenum = d_game_unique_state::save_slot::None;
1772 {
1773 pause_game_world_time p;
1774
1775 #if DXX_BUILD_DESCENT == 2
1776 if (filename_override) {
1777 filename = filename_override;
1778 filenum = d_game_unique_state::save_slot::secret_save_filename_override; // place outside of save slots
1779 } else
1780 #endif
1781 {
1782 filenum = state_get_restore_file(*grd_curcanv, filename_storage, blind);
1783 if (!GameUniqueState.valid_load_slot(filenum))
1784 {
1785 return 0;
1786 }
1787 filename = filename_storage.data();
1788 }
1789 #if DXX_BUILD_DESCENT == 2
1790 // MK, 1/1/96
1791 // Do special secret level stuff.
1792 // If Nsecret.sgc (where N = filenum) exists, then copy it to secret.sgc.
1793 // If it doesn't exist, then delete secret.sgc
1794 if (secret == secret_restore::none)
1795 {
1796 int rval;
1797
1798 if (filenum != d_game_unique_state::save_slot::None)
1799 {
1800 std::array<char, PATH_MAX> fname;
1801 const auto temp_fname = fname.data();
1802 format_secret_sgc_filename(fname, filenum);
1803 if (PHYSFS_exists(temp_fname))
1804 {
1805 rval = copy_file(temp_fname, SECRETC_FILENAME);
1806 Assert(rval == 0); // Oops, error copying temp_fname to secret.sgc!
1807 (void)rval;
1808 } else
1809 PHYSFS_delete(SECRETC_FILENAME);
1810 }
1811 }
1812 #endif
1813 if (secret == secret_restore::none && in_game && blind == blind_save::no)
1814 {
1815 const auto choice = nm_messagebox_str(menu_title{nullptr}, nm_messagebox_tie(TXT_YES, TXT_NO), menu_subtitle{"Restore Game?"});
1816 if ( choice != 0 ) {
1817 return 0;
1818 }
1819 }
1820 }
1821 return state_restore_all_sub(
1822 #if DXX_BUILD_DESCENT == 2
1823 LevelSharedSegmentState.DestructibleLights, secret,
1824 #endif
1825 filename);
1826 }
1827
1828 #if DXX_BUILD_DESCENT == 1
1829 int state_restore_all_sub(const char *filename)
1830 #elif DXX_BUILD_DESCENT == 2
1831 int state_restore_all_sub(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, const secret_restore secret, const char *const filename)
1832 #endif
1833 {
1834 auto &LevelUniqueControlCenterState = LevelUniqueObjectState.ControlCenterState;
1835 auto &Objects = LevelUniqueObjectState.Objects;
1836 auto &vmobjptr = Objects.vmptr;
1837 auto &vmobjptridx = Objects.vmptridx;
1838 auto &RobotCenters = LevelSharedRobotcenterState.RobotCenters;
1839 auto &Station = LevelUniqueFuelcenterState.Station;
1840 int coop_player_got[MAX_PLAYERS], coop_org_objnum = get_local_player().objnum;
1841 std::array<per_side_array<texture1_value>, MAX_SEGMENTS> TempTmapNum;
1842 std::array<per_side_array<texture2_value>, MAX_SEGMENTS> TempTmapNum2;
1843
1844 #if DXX_BUILD_DESCENT == 1
1845 static constexpr std::integral_constant<secret_restore, secret_restore::none> secret{};
1846 #elif DXX_BUILD_DESCENT == 2
1847 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
1848 const auto old_gametime{GameTime64};
1849 #endif
1850
1851 #ifndef NDEBUG
1852 if (CGameArg.SysUsePlayersDir && strncmp(filename, PLAYER_DIRECTORY_TEXT, sizeof(PLAYER_DIRECTORY_TEXT) - 1))
1853 Int3();
1854 #endif
1855
1856 auto fp = PHYSFSX_openReadBuffered(filename).first;
1857 if ( !fp ) return 0;
1858
1859 //Read id
1860 char id[5]{};
1861 PHYSFSX_readBytes(fp, id, sizeof(char) * 4);
1862 if ( memcmp( id, dgss_id, 4 )) {
1863 return 0;
1864 }
1865
1866 //Read version
1867 //Check for swapped file here, as dgss_id is written as a string (i.e. endian independent)
1868 int version{};
1869 PHYSFSX_readBytes(fp, &version, sizeof(int));
1870 const physfsx_endian swap{
1871 (version & 0xffff0000)
1872 ? (version = SWAPINT(version), physfsx_endian::foreign)
1873 : physfsx_endian::native
1874 }; // if file is not endian native, have to swap all shorts and ints
1875
1876 if (version < STATE_COMPATIBLE_VERSION) {
1877 return 0;
1878 }
1879
1880 // Read Coop state_game_id. Oh the redundancy... we have this one later on but Coop games want to read this before loading a state so for easy access we have this here
1881 if (Game_mode & GM_MULTI_COOP)
1882 {
1883 callsign_t saved_callsign;
1884 state_game_id = PHYSFSX_readSXE32(fp, swap);
1885 PHYSFSX_readBytes(fp, &saved_callsign, sizeof(char) * CALLSIGN_LEN + 1);
1886 if (!(saved_callsign == get_local_player().callsign)) // check the callsign of the palyer who saved this state. It MUST match. If we transferred this savegame from pilot A to pilot B, others won't be able to restore us. So bail out here if this is the case.
1887 {
1888 return 0;
1889 }
1890 }
1891
1892 // Read description
1893 d_game_unique_state::savegame_description desc;
1894 PHYSFSX_readBytes(fp, desc.data(), 20);
1895 desc.back() = 0;
1896
1897 // Skip the current screen shot...
1898 PHYSFS_seek(fp, PHYSFS_tell(fp) + THUMBNAIL_W * THUMBNAIL_H);
1899 #if DXX_BUILD_DESCENT == 2
1900 // And now...skip the goddamn palette stuff that somebody forgot to add
1901 PHYSFS_seek(fp, PHYSFS_tell(fp) + 768);
1902 #endif
1903 // Read the Between levels flag...
1904 PHYSFSX_skipBytes<4>(fp);
1905
1906 // Read the mission info...
1907 savegame_mission_path mission_pathname{};
1908 PHYSFSX_readBytes(fp, mission_pathname.original.data(), mission_pathname.original.size());
1909 mission_name_type name_match_mode;
1910 mission_entry_predicate mission_predicate;
1911 switch (static_cast<savegame_mission_name_abi>(mission_pathname.original.back()))
1912 {
1913 case savegame_mission_name_abi::original: /* Save game without the ability to do extended mission names */
1914 name_match_mode = mission_name_type::basename;
1915 mission_predicate.filesystem_name = mission_pathname.original.data();
1916 #if DXX_BUILD_DESCENT == 2
1917 mission_predicate.check_version = false;
1918 #endif
1919 break;
1920 case savegame_mission_name_abi::pathname: /* Save game with extended mission name */
1921 {
1922 PHYSFSX_readBytes(fp, mission_pathname.full.data(), mission_pathname.full.size());
1923 if (mission_pathname.full.back())
1924 {
1925 struct error_unknown_mission_format : passive_messagebox
1926 {
1927 error_unknown_mission_format() :
1928 passive_messagebox(menu_title{TXT_ERROR}, menu_subtitle{"Unable to load game\nUnrecognized mission name format"}, TXT_OK, grd_curscreen->sc_canvas)
1929 {
1930 }
1931 };
1932 run_blocking_newmenu<error_unknown_mission_format>();
1933 return 0;
1934 }
1935 }
1936 name_match_mode = mission_name_type::pathname;
1937 mission_predicate.filesystem_name = mission_pathname.full.data();
1938 #if DXX_BUILD_DESCENT == 2
1939 mission_predicate.check_version = true;
1940 mission_predicate.descent_version = static_cast<Mission::descent_version_type>(mission_pathname.original[1]);
1941 #endif
1942 break;
1943 default: /* Save game written by a future version of Rebirth. ABI unknown. */
1944 {
1945 struct error_unknown_save_format : passive_messagebox
1946 {
1947 error_unknown_save_format() :
1948 passive_messagebox(menu_title{TXT_ERROR}, menu_subtitle{"Unable to load game\nUnrecognized save game format"}, TXT_OK, grd_curscreen->sc_canvas)
1949 {
1950 }
1951 };
1952 run_blocking_newmenu<error_unknown_save_format>();
1953 }
1954 return 0;
1955 }
1956
1957 if (const auto errstr = load_mission_by_name(mission_predicate, name_match_mode))
1958 {
1959 nm_messagebox(menu_title{TXT_ERROR}, {TXT_OK}, "Unable to load mission\n'%s'\n\n%s", mission_pathname.full.data(), errstr);
1960 return 0;
1961 }
1962
1963 //Read level info
1964 const auto current_level{PHYSFSX_readSXE32(fp, swap)};
1965 PHYSFSX_skipBytes<4>(fp); // skip Next_level_num
1966
1967 //Restore GameTime
1968 GameTime64 = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
1969
1970 // Start new game....
1971 callsign_t org_callsign;
1972 LevelUniqueObjectState.accumulated_robots = 0;
1973 LevelUniqueObjectState.total_hostages = 0;
1974 GameUniqueState.accumulated_robots = 0;
1975 GameUniqueState.total_hostages = 0;
1976 if (!(Game_mode & GM_MULTI_COOP))
1977 {
1978 Game_mode = GM_NORMAL;
1979 change_playernum_to(0);
1980 N_players = 1;
1981 auto &callsign = vmplayerptr(0u)->callsign;
1982 callsign = InterfaceUniqueState.PilotName;
1983 org_callsign = callsign;
1984 if (secret == secret_restore::none)
1985 {
1986 InitPlayerObject(); //make sure player's object set up
1987 init_player_stats_game(0); //clear all stats
1988 }
1989 }
1990 else // in coop we want to stay the player we are already.
1991 {
1992 org_callsign = get_local_player().callsign;
1993 if (secret == secret_restore::none)
1994 init_player_stats_game(Player_num);
1995 }
1996
1997 if (const auto g = Game_wind)
1998 g->set_visible(0);
1999
2000 //Read player info
2001
2002 {
2003 player_info pl_info;
2004 relocated_player_data rpd;
2005 #if DXX_BUILD_DESCENT == 2
2006 player_info ret_pl_info;
2007 ret_pl_info.mission.hostages_on_board = get_local_plrobj().ctype.player_info.mission.hostages_on_board;
2008 #endif
2009 {
2010 #if DXX_USE_EDITOR
2011 // Don't bother with the other game sequence stuff if loading saved game in editor
2012 if (EditorWindow)
2013 LoadLevel(current_level, 1);
2014 else
2015 #endif
2016 StartNewLevelSub(LevelSharedRobotInfoState.Robot_info, current_level, 1, secret);
2017
2018 auto &plr = get_local_player();
2019 #if DXX_BUILD_DESCENT == 2
2020 auto &plrobj = get_local_plrobj();
2021 if (secret != secret_restore::none) {
2022 player dummy_player;
2023 state_read_player(fp, dummy_player, swap, pl_info, rpd);
2024 if (secret == secret_restore::survived) { // This means he didn't die, so he keeps what he got in the secret level.
2025 const auto hostages_on_board = ret_pl_info.mission.hostages_on_board;
2026 ret_pl_info = plrobj.ctype.player_info;
2027 ret_pl_info.mission.hostages_on_board = hostages_on_board;
2028 rpd.shields = plrobj.shields;
2029 plr.level = dummy_player.level;
2030 plr.time_level = dummy_player.time_level;
2031
2032 ret_pl_info.homing_object_dist = -1;
2033 plr.hours_level = dummy_player.hours_level;
2034 plr.hours_total = dummy_player.hours_total;
2035 do_cloak_invul_secret_stuff(old_gametime, ret_pl_info);
2036 } else {
2037 plr = dummy_player;
2038 // Keep keys even if they died on secret level (otherwise game becomes impossible)
2039 // Example: Cameron 'Stryker' Fultz's Area 51
2040 pl_info.powerup_flags |= (plrobj.ctype.player_info.powerup_flags &
2041 (PLAYER_FLAGS_BLUE_KEY |
2042 PLAYER_FLAGS_RED_KEY |
2043 PLAYER_FLAGS_GOLD_KEY));
2044 }
2045 } else
2046 #endif
2047 {
2048 state_read_player(fp, plr, swap, pl_info, rpd);
2049 }
2050 LevelUniqueObjectState.accumulated_robots = rpd.num_robots_level;
2051 LevelUniqueObjectState.total_hostages = rpd.hostages_level;
2052 GameUniqueState.accumulated_robots = rpd.num_robots_total;
2053 GameUniqueState.total_hostages = rpd.hostages_total;
2054 }
2055 {
2056 auto &plr = get_local_player();
2057 plr.callsign = org_callsign;
2058 if (Game_mode & GM_MULTI_COOP)
2059 plr.objnum = coop_org_objnum;
2060 }
2061
2062 auto &Primary_weapon = pl_info.Primary_weapon;
2063 // Restore the weapon states
2064 {
2065 uint8_t v{};
2066 PHYSFSX_readBytes(fp, &v, sizeof(v));
2067 Primary_weapon = primary_weapon_index_t{v};
2068 }
2069 auto &Secondary_weapon = pl_info.Secondary_weapon;
2070 {
2071 uint8_t v{};
2072 PHYSFSX_readBytes(fp, &v, sizeof(v));
2073 Secondary_weapon = secondary_weapon_index_t{v};
2074 }
2075
2076 select_primary_weapon(pl_info, nullptr, Primary_weapon, 0);
2077 select_secondary_weapon(pl_info, nullptr, Secondary_weapon, 0);
2078
2079 // Restore the difficulty level
2080 {
2081 const unsigned u = PHYSFSX_readSXE32(fp, swap);
2082 GameUniqueState.Difficulty_level = cast_clamp_difficulty(u);
2083 }
2084
2085 // Restore the cheats enabled flag
2086 game_disable_cheats(); // disable cheats first
2087 cheats.enabled = !!PHYSFSX_readULE32(fp);
2088 #if DXX_BUILD_DESCENT == 1
2089 cheats.turbo = !!PHYSFSX_readULE32(fp);
2090 #endif
2091
2092 Do_appearance_effect = 0; // Don't do this for middle o' game stuff.
2093
2094 //Clear out all the objects from the lvl file
2095 for (unique_segment &useg : vmsegptr)
2096 useg.objects = object_none;
2097 reset_objects(LevelUniqueObjectState, 1);
2098
2099 //Read objects, and pop 'em into their respective segments.
2100 {
2101 const auto i{PHYSFSX_readSXE32(fp, swap)};
2102 Objects.set_count(i);
2103 }
2104 for (auto &obj : vmobjptr)
2105 {
2106 object_rw obj_rw;
2107 PHYSFSX_readBytes(fp, &obj_rw, sizeof(obj_rw));
2108 object_rw_swap(&obj_rw, swap);
2109 state_object_rw_to_object(&obj_rw, obj);
2110 }
2111
2112 range_for (const auto &&obj, vmobjptridx)
2113 {
2114 obj->rtype.pobj_info.alt_textures = -1;
2115 if ( obj->type != OBJ_NONE ) {
2116 const auto segnum = obj->segnum;
2117 obj_link_unchecked(Objects.vmptr, obj, Segments.vmptridx(segnum));
2118 }
2119 #if DXX_BUILD_DESCENT == 2
2120 //look for, and fix, boss with bogus shields
2121 if (obj->type == OBJ_ROBOT && Robot_info[get_robot_id(obj)].boss_flag != boss_robot_id::None)
2122 {
2123 fix save_shields = obj->shields;
2124
2125 copy_defaults_to_robot(Robot_info, obj); //calculate starting shields
2126
2127 //if in valid range, use loaded shield value
2128 if (save_shields > 0 && save_shields <= obj->shields)
2129 obj->shields = save_shields;
2130 else
2131 obj->shields /= 2; //give player a break
2132 }
2133 #endif
2134 }
2135 special_reset_objects(LevelUniqueObjectState, LevelSharedRobotInfoState.Robot_info);
2136 /* Reload plrobj reference. The player's object number may have
2137 * been changed by the state_object_rw_to_object call.
2138 */
2139 auto &plrobj = get_local_plrobj();
2140 plrobj.shields = rpd.shields;
2141 #if DXX_BUILD_DESCENT == 2
2142 if (secret == secret_restore::survived)
2143 { // This means he didn't die, so he keeps what he got in the secret level.
2144 ret_pl_info.mission.last_score = pl_info.mission.last_score;
2145 plrobj.ctype.player_info = ret_pl_info;
2146 }
2147 else
2148 #endif
2149 plrobj.ctype.player_info = pl_info;
2150 }
2151 /* Reload plrobj reference. This is unnecessary for correctness,
2152 * but is required by scoping rules, since the previous correct copy
2153 * goes out of scope when pl_info goes out of scope, and that needs
2154 * to be removed from scope to avoid a shadow warning when
2155 * cooperative players are loaded below.
2156 */
2157 auto &plrobj = get_local_plrobj();
2158
2159 // 1 = Didn't die on secret level.
2160 // 2 = Died on secret level.
2161 if (secret != secret_restore::none && (Current_level_num >= 0)) {
2162 set_pos_from_return_segment();
2163 #if DXX_BUILD_DESCENT == 2
2164 if (secret == secret_restore::died)
2165 init_player_stats_new_ship(Player_num);
2166 #endif
2167 }
2168
2169 //Restore wall info
2170 init_exploding_walls();
2171 {
2172 auto &Walls = LevelUniqueWallSubsystemState.Walls;
2173 Walls.set_count(PHYSFSX_readSXE32(fp, swap));
2174 for (auto &w : Walls.vmptr)
2175 wall_read(fp, w);
2176
2177 #if DXX_BUILD_DESCENT == 2
2178 //now that we have the walls, check if any sounds are linked to
2179 //walls that are now open
2180 for (const auto &w : Walls.vcptr)
2181 {
2182 if (w.type == WALL_OPEN)
2183 digi_kill_sound_linked_to_segment(w.segnum, w.sidenum, sound_effect::None); // sound_effect::None means kill any sound
2184 }
2185
2186 //Restore exploding wall info
2187 if (version >= 10) {
2188 unsigned i = PHYSFSX_readSXE32(fp, swap);
2189 expl_wall_read_n_swap(Walls.vmptr, fp, swap, i);
2190 }
2191 #endif
2192 }
2193
2194 //Restore door info
2195 {
2196 auto &ActiveDoors = LevelUniqueWallSubsystemState.ActiveDoors;
2197 ActiveDoors.set_count(PHYSFSX_readSXE32(fp, swap));
2198 for (auto &ad : ActiveDoors.vmptr)
2199 active_door_read(fp, ad);
2200 }
2201
2202 #if DXX_BUILD_DESCENT == 2
2203 if (version >= 14) { //Restore cloaking wall info
2204 unsigned num_cloaking_walls = PHYSFSX_readSXE32(fp, swap);
2205 auto &CloakingWalls = LevelUniqueWallSubsystemState.CloakingWalls;
2206 CloakingWalls.set_count(num_cloaking_walls);
2207 for (auto &w : CloakingWalls.vmptr)
2208 cloaking_wall_read(w, fp);
2209 }
2210 #endif
2211
2212 //Restore trigger info
2213 {
2214 auto &Triggers = LevelUniqueWallSubsystemState.Triggers;
2215 Triggers.set_count(PHYSFSX_readSXE32(fp, swap));
2216 for (auto &t : Triggers.vmptr)
2217 trigger_read(fp, t);
2218 }
2219
2220 //Restore tmap info (to temp values so we can use compiled-in tmap info to compute static_light
2221 range_for (const auto &&segp, vmsegptridx)
2222 {
2223 for (const auto j : MAX_SIDES_PER_SEGMENT)
2224 {
2225 segp->shared_segment::sides[j].wall_num = wallnum_t{PHYSFSX_readUXE16(fp, swap)};
2226 TempTmapNum[segp][j] = texture1_value{PHYSFSX_readUXE16(fp, swap)};
2227 TempTmapNum2[segp][j] = texture2_value{PHYSFSX_readUXE16(fp, swap)};
2228 }
2229 }
2230
2231 //Restore the fuelcen info
2232 LevelUniqueControlCenterState.Control_center_destroyed = PHYSFSX_readSXE32(fp, swap);
2233 #if DXX_BUILD_DESCENT == 1
2234 LevelUniqueControlCenterState.Countdown_seconds_left = {PHYSFSX_readSXE32(fp, swap)};
2235 LevelUniqueControlCenterState.Countdown_timer = 0;
2236 #elif DXX_BUILD_DESCENT == 2
2237 LevelUniqueControlCenterState.Countdown_timer = {PHYSFSX_readSXE32(fp, swap)};
2238 #endif
2239 const unsigned Num_robot_centers = PHYSFSX_readSXE32(fp, swap);
2240 LevelSharedRobotcenterState.Num_robot_centers = Num_robot_centers;
2241 range_for (auto &r, partial_range(RobotCenters, Num_robot_centers))
2242 #if DXX_BUILD_DESCENT == 1
2243 matcen_info_read(fp, r, STATE_MATCEN_VERSION);
2244 #elif DXX_BUILD_DESCENT == 2
2245 matcen_info_read(fp, r);
2246 #endif
2247 reconstruct_at(ControlCenterTriggers, control_center_triggers_read, fp);
2248 const unsigned Num_fuelcenters = PHYSFSX_readSXE32(fp, swap);
2249 LevelUniqueFuelcenterState.Num_fuelcenters = Num_fuelcenters;
2250 range_for (auto &s, partial_range(Station, Num_fuelcenters))
2251 {
2252 fuelcen_read(fp, s);
2253 #if DXX_BUILD_DESCENT == 1
2254 // NOTE: Usually Descent1 handles countdown by Timer value of the Reactor Station. Since we now use Descent2 code to handle countdown (which we do in case there IS NO Reactor Station which causes potential trouble in Multiplayer), let's find the Reactor here and read the timer from it.
2255 if (s.Type == segment_special::controlcen)
2256 LevelUniqueControlCenterState.Countdown_timer = s.Timer;
2257 #endif
2258 }
2259
2260 // Restore the control cen info
2261 LevelUniqueControlCenterState.Control_center_been_hit = PHYSFSX_readSXE32(fp, swap);
2262 LevelUniqueControlCenterState.Control_center_player_been_seen = static_cast<player_visibility_state>(PHYSFSX_readSXE32(fp, swap));
2263 LevelUniqueControlCenterState.Frametime_until_next_fire = {PHYSFSX_readSXE32(fp, swap)};
2264 LevelUniqueControlCenterState.Control_center_present = PHYSFSX_readSXE32(fp, swap);
2265 LevelUniqueControlCenterState.Dead_controlcen_object_num = PHYSFSX_readSXE32(fp, swap);
2266 if (LevelUniqueControlCenterState.Control_center_destroyed)
2267 LevelUniqueControlCenterState.Total_countdown_time = LevelUniqueControlCenterState.Countdown_timer / F0_5; // we do not need to know this, but it should not be 0 either...
2268
2269 // Restore the AI state
2270 ai_restore_state(LevelSharedRobotInfoState.Robot_info, fp, version, swap);
2271
2272 {
2273 auto &Automap_visited = LevelUniqueAutomapState.Automap_visited;
2274 // Restore the automap visited info
2275 Automap_visited = {};
2276 DXX_MAKE_MEM_UNDEFINED(std::span(Automap_visited));
2277 PHYSFSX_readBytes(fp, Automap_visited.data(), std::max<std::size_t>(Highest_segment_index + 1, MAX_SEGMENTS_ORIGINAL));
2278 }
2279
2280 {
2281 // Restore hacked up weapon system stuff.
2282 auto &player_info = plrobj.ctype.player_info;
2283 /* These values were never saved, so coerce them to a sane default.
2284 */
2285 player_info.Fusion_charge = 0;
2286 player_info.Player_eggs_dropped = false;
2287 player_info.FakingInvul = false;
2288 player_info.lavafall_hiss_playing = false;
2289 player_info.missile_gun = 0;
2290 player_info.Spreadfire_toggle = 0;
2291 #if DXX_BUILD_DESCENT == 2
2292 player_info.Helix_orientation = 0;
2293 #endif
2294 player_info.Last_bumped_local_player = 0;
2295 auto &Next_laser_fire_time = player_info.Next_laser_fire_time;
2296 auto &Next_missile_fire_time = player_info.Next_missile_fire_time;
2297 player_info.Auto_fire_fusion_cannon_time = 0;
2298 player_info.Next_flare_fire_time = {GameTime64};
2299 Next_laser_fire_time = {GameTime64};
2300 Next_missile_fire_time = {GameTime64};
2301
2302 state_game_id = 0;
2303
2304 if ( version >= 7 ) {
2305 state_game_id = PHYSFSX_readSXE32(fp, swap);
2306 cheats.rapidfire = !!PHYSFSX_readULE32(fp);
2307 // PHYSFSX_readSXE32(fp, swap); // was Lunacy
2308 // PHYSFSX_readSXE32(fp, swap); // was Lunacy, too... and one was Ugly robot stuff a long time ago...
2309 PHYSFSX_skipBytes<8>(fp);
2310 #if DXX_BUILD_DESCENT == 1
2311 cheats.ghostphysics = !!PHYSFSX_readULE32(fp);
2312 PHYSFSX_skipBytes<4>(fp);
2313 #endif
2314 }
2315
2316 #if DXX_BUILD_DESCENT == 2
2317 if (version >= 17) {
2318 range_for (auto &i, MarkerState.imobjidx)
2319 i = vcobjidx_t::check_nothrow_index(PHYSFSX_readUXE32(fp, swap)).value_or(object_none);
2320 PHYSFS_seek(fp, PHYSFS_tell(fp) + (NUM_MARKERS)*(CALLSIGN_LEN+1)); // skip obsolete MarkerOwner
2321 range_for (auto &i, MarkerState.message)
2322 {
2323 std::array<char, MARKER_MESSAGE_LEN> a;
2324 PHYSFSX_readBytes(fp, a, a.size());
2325 i.copy_if(a);
2326 }
2327 }
2328 else {
2329 // skip dummy info
2330 const auto num{PHYSFSX_readSXE32(fp, swap)}; // was NumOfMarkers
2331 PHYSFSX_skipBytes<4>(fp); // was CurMarker
2332
2333 PHYSFS_seek(fp, PHYSFS_tell(fp) + num * (sizeof(vms_vector) + 40));
2334
2335 range_for (auto &i, MarkerState.imobjidx)
2336 i = object_none;
2337 }
2338
2339 if (version>=11) {
2340 if (secret != secret_restore::survived)
2341 Afterburner_charge = {PHYSFSX_readSXE32(fp, swap)};
2342 else {
2343 PHYSFSX_skipBytes<4>(fp);
2344 }
2345 }
2346 if (version>=12) {
2347 //read last was super information
2348 std::array<uint8_t, MAX_PRIMARY_WEAPONS> last_was_super;
2349 /* Descent 2 shipped with Primary_last_was_super and
2350 * Secondary_last_was_super each sized to contain MAX_*_WEAPONS,
2351 * but only the first half of those are ever used.
2352 * Unfortunately, the save file format is defined as saving
2353 * MAX_*_WEAPONS for each. Read into a temporary, then copy the
2354 * meaningful elements to the live data.
2355 */
2356 PHYSFSX_readBytes(fp, &last_was_super, MAX_PRIMARY_WEAPONS);
2357 uint8_t Primary_last_was_super{};
2358 for (uint8_t j = static_cast<uint8_t>(primary_weapon_index_t::VULCAN_INDEX); j != static_cast<uint8_t>(primary_weapon_index_t::SUPER_LASER_INDEX); ++j)
2359 {
2360 if (last_was_super[j])
2361 Primary_last_was_super |= HAS_PRIMARY_FLAG(primary_weapon_index_t{j});
2362 }
2363 player_info.Primary_last_was_super = Primary_last_was_super;
2364 PHYSFSX_readBytes(fp, &last_was_super, MAX_SECONDARY_WEAPONS);
2365 uint8_t Secondary_last_was_super{};
2366 for (uint8_t j = static_cast<uint8_t>(secondary_weapon_index_t::CONCUSSION_INDEX); j != static_cast<uint8_t>(secondary_weapon_index_t::SMISSILE1_INDEX); ++j)
2367 {
2368 if (last_was_super[j])
2369 Secondary_last_was_super |= HAS_SECONDARY_FLAG(secondary_weapon_index_t{j});
2370 }
2371 player_info.Secondary_last_was_super = Secondary_last_was_super;
2372 }
2373
2374 if (version >= 12) {
2375 Flash_effect = {PHYSFSX_readSXE32(fp, swap)};
2376 Time_flash_last_played = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
2377 PaletteRedAdd = {PHYSFSX_readSXE32(fp, swap)};
2378 PaletteGreenAdd = {PHYSFSX_readSXE32(fp, swap)};
2379 PaletteBlueAdd = {PHYSFSX_readSXE32(fp, swap)};
2380 } else {
2381 Flash_effect = 0;
2382 Time_flash_last_played = 0;
2383 PaletteRedAdd = 0;
2384 PaletteGreenAdd = 0;
2385 PaletteBlueAdd = 0;
2386 }
2387
2388 // Load Light_subtracted
2389 if (version >= 16) {
2390 if ( Highest_segment_index+1 > MAX_SEGMENTS_ORIGINAL )
2391 {
2392 for (unique_segment &useg : vmsegptr)
2393 {
2394 PHYSFSX_readBytes(fp, &useg.light_subtracted, sizeof(useg.light_subtracted));
2395 }
2396 }
2397 else
2398 {
2399 range_for (unique_segment &i, partial_range(Segments, MAX_SEGMENTS_ORIGINAL))
2400 {
2401 PHYSFSX_readBytes(fp, &i.light_subtracted, sizeof(i.light_subtracted));
2402 }
2403 }
2404 apply_all_changed_light(LevelSharedDestructibleLightState, Segments.vmptridx);
2405 } else {
2406 for (unique_segment &useg : vmsegptr)
2407 useg.light_subtracted = {};
2408 }
2409
2410 if (secret == secret_restore::none)
2411 {
2412 if (version >= 20) {
2413 First_secret_visit = PHYSFSX_readSXE32(fp, swap);
2414 } else
2415 First_secret_visit = 1;
2416 } else
2417 First_secret_visit = 0;
2418
2419 if (secret != secret_restore::survived)
2420 {
2421 player_info.Omega_charge = 0;
2422 /* The savegame does not record this, so pick a value. Be
2423 * nice to the player: let the cannon recharge immediately.
2424 */
2425 player_info.Omega_recharge_delay = 0;
2426 }
2427 if (version >= 22)
2428 {
2429 const auto i{PHYSFSX_readSXE32(fp, swap)};
2430 if (secret != secret_restore::survived)
2431 {
2432 player_info.Omega_charge = i;
2433 }
2434 }
2435 #endif
2436 }
2437
2438 // static_light should now be computed - now actually set tmap info
2439 range_for (const auto &&segp, vmsegptridx)
2440 {
2441 for (auto &&[uside, t1, t2] : zip(segp->unique_segment::sides, TempTmapNum[segp], TempTmapNum2[segp]))
2442 {
2443 uside.tmap_num = t1;
2444 uside.tmap_num2 = t2;
2445 }
2446 }
2447
2448 // Read Coop Info
2449 if (Game_mode & GM_MULTI_COOP)
2450 {
2451 player restore_players[MAX_PLAYERS];
2452 object restore_objects[MAX_PLAYERS];
2453
2454 for (playernum_t i = 0; i < MAX_PLAYERS; i++)
2455 {
2456 // prepare arrays for mapping our players below
2457 coop_player_got[i] = 0;
2458
2459 // read the stored players
2460 player_info pl_info;
2461 relocated_player_data rpd;
2462 /* No need to reload num_robots_level again. It was already
2463 * restored above when the local player was restored.
2464 */
2465 state_read_player(fp, restore_players[i], swap, pl_info, rpd);
2466
2467 // make all (previous) player objects to ghosts but store them first for later remapping
2468 const auto &&obj = vmobjptr(restore_players[i].objnum);
2469 if (restore_players[i].connected == player_connection_status::playing && obj->type == OBJ_PLAYER)
2470 {
2471 obj->ctype.player_info = pl_info;
2472 obj->shields = rpd.shields;
2473 restore_objects[i] = *obj;
2474 obj->type = OBJ_GHOST;
2475 multi_reset_player_object(obj);
2476 }
2477 }
2478 for (playernum_t i = 0; i < MAX_PLAYERS; i++) // copy restored players to the current slots
2479 {
2480 for (unsigned j = 0; j < MAX_PLAYERS; j++)
2481 {
2482 // map stored players to current players depending on their unique (which we made sure) callsign
2483 if (vcplayerptr(i)->connected == player_connection_status::playing && restore_players[j].connected == player_connection_status::playing && vcplayerptr(i)->callsign == restore_players[j].callsign)
2484 {
2485 auto &p = *vmplayerptr(i);
2486 p = restore_players[j];
2487 coop_player_got[i] = 1;
2488
2489 const auto &&obj = vmobjptridx(vcplayerptr(i)->objnum);
2490 // since a player always uses the same object, we just have to copy the saved object properties to the existing one. i hate you...
2491 obj->control_source = restore_objects[j].control_source;
2492 obj->movement_source = restore_objects[j].movement_source;
2493 obj->render_type = restore_objects[j].render_type;
2494 obj->flags = restore_objects[j].flags;
2495 obj->pos = restore_objects[j].pos;
2496 obj->orient = restore_objects[j].orient;
2497 obj->size = restore_objects[j].size;
2498 obj->shields = restore_objects[j].shields;
2499 obj->lifeleft = restore_objects[j].lifeleft;
2500 obj->mtype.phys_info = restore_objects[j].mtype.phys_info;
2501 obj->rtype.pobj_info = restore_objects[j].rtype.pobj_info;
2502 // make this restored player object an actual player again
2503 assert(obj->type == OBJ_GHOST);
2504 obj->type = OBJ_PLAYER;
2505 set_player_id(obj, i); // assign player object id to player number
2506 multi_reset_player_object(obj);
2507 update_object_seg(vmobjptr, LevelSharedSegmentState, LevelUniqueSegmentState, obj);
2508 }
2509 }
2510 }
2511 {
2512 std::array<char, MISSION_NAME_LEN + 1> a;
2513 PHYSFSX_readBytes(fp, a, a.size());
2514 Netgame.mission_title.copy_if(a);
2515 }
2516 {
2517 std::array<char, 9> a;
2518 PHYSFSX_readBytes(fp, a, a.size());
2519 Netgame.mission_name.copy_if(a);
2520 }
2521 Netgame.levelnum = {PHYSFSX_readSXE32(fp, swap)};
2522 PHYSFSX_readBytes(fp, &Netgame.difficulty, sizeof(ubyte));
2523 PHYSFSX_readBytes(fp, &Netgame.game_status, sizeof(ubyte));
2524 PHYSFSX_readBytes(fp, &Netgame.numplayers, sizeof(ubyte));
2525 PHYSFSX_readBytes(fp, &Netgame.max_numplayers, sizeof(ubyte));
2526 PHYSFSX_readBytes(fp, &Netgame.numconnected, sizeof(ubyte));
2527 Netgame.level_time = {PHYSFSX_readSXE32(fp, swap)};
2528 for (playernum_t i = 0; i < MAX_PLAYERS; i++)
2529 {
2530 const auto &&objp = vmobjptr(vcplayerptr(i)->objnum);
2531 auto &pi = objp->ctype.player_info;
2532 Netgame.killed[i] = pi.net_killed_total;
2533 Netgame.player_score[i] = pi.mission.score;
2534 Netgame.net_player_flags[i] = pi.powerup_flags;
2535 }
2536 for (playernum_t i = 0; i < MAX_PLAYERS; i++) // Disconnect connected players not available in this Savegame
2537 if (!coop_player_got[i] && vcplayerptr(i)->connected == player_connection_status::playing)
2538 multi_disconnect_player(i);
2539 Viewer = ConsoleObject = &get_local_plrobj(); // make sure Viewer and ConsoleObject are set up (which we skipped by not using InitPlayerObject but we need since objects changed while loading)
2540 special_reset_objects(LevelUniqueObjectState, LevelSharedRobotInfoState.Robot_info); // since we juggled around with objects to remap coop players rebuild the index of free objects
2541 state_set_next_autosave(GameUniqueState, Netgame.MPGameplayOptions.AutosaveInterval);
2542 }
2543 else
2544 state_set_next_autosave(GameUniqueState, PlayerCfg.SPGameplayOptions.AutosaveInterval);
2545 if (const auto g = Game_wind)
2546 if (!g->is_visible())
2547 g->set_visible(1);
2548 reset_time();
2549
2550 return 1;
2551 }
2552
2553 deny_save_result deny_save_game(fvcobjptr &vcobjptr, const d_level_unique_control_center_state &LevelUniqueControlCenterState)
2554 {
2555 if (LevelUniqueControlCenterState.Control_center_destroyed)
2556 return deny_save_result::denied;
2557 if (Game_mode & GM_MULTI)
2558 {
2559 if (!(Game_mode & GM_MULTI_COOP))
2560 /* Deathmatch games can never be saved */
2561 return deny_save_result::denied;
2562 if (multi_common_deny_save_game(vcobjptr, partial_const_range(Players, N_players)))
2563 return deny_save_result::denied;
2564 }
2565 return deny_save_result::allowed;
2566 }
2567
2568 }
2569
2570 namespace dcx {
2571
2572 int state_get_game_id(const d_game_unique_state::savegame_file_path &filename)
2573 {
2574 callsign_t saved_callsign;
2575
2576 #ifndef NDEBUG
2577 if (CGameArg.SysUsePlayersDir && strncmp(filename.data(), PLAYER_DIRECTORY_TEXT, sizeof(PLAYER_DIRECTORY_TEXT) - 1))
2578 Int3();
2579 #endif
2580
2581 if (!(Game_mode & GM_MULTI_COOP))
2582 return 0;
2583
2584 auto fp = PHYSFSX_openReadBuffered(filename.data()).first;
2585 if ( !fp ) return 0;
2586
2587 //Read id
2588 char id[5]{};
2589 PHYSFSX_readBytes(fp, id, sizeof(char) * 4);
2590 if ( memcmp( id, dgss_id, 4 )) {
2591 return 0;
2592 }
2593
2594 //Read version
2595 //Check for swapped file here, as dgss_id is written as a string (i.e. endian independent)
2596 int version{};
2597 PHYSFSX_readBytes(fp, &version, sizeof(int));
2598 const physfsx_endian swap{
2599 (version & 0xffff0000)
2600 ? (version = SWAPINT(version), physfsx_endian::foreign)
2601 : physfsx_endian::native
2602 }; // if file is not endian native, have to swap all shorts and ints
2603
2604 if (version < STATE_COMPATIBLE_VERSION) {
2605 return 0;
2606 }
2607
2608 // Read Coop state_game_id to validate the savegame we are about to load matches the others
2609 state_game_id = PHYSFSX_readSXE32(fp, swap);
2610 PHYSFSX_readBytes(fp, &saved_callsign, sizeof(char) * CALLSIGN_LEN + 1);
2611 if (!(saved_callsign == get_local_player().callsign)) // check the callsign of the palyer who saved this state. It MUST match. If we transferred this savegame from pilot A to pilot B, others won't be able to restore us. So bail out here if this is the case.
2612 return 0;
2613
2614 return state_game_id;
2615 }
2616
2617 }