DEADSOFTWARE

flush screenshot after writing
[d2df-sdl.git] / src / game / g_saveload.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_saveload;
18 interface
20 uses
21 SysUtils, Classes,
22 e_graphics, g_phys, g_textures;
25 function g_GetSaveName (n: Integer; out valid: Boolean): AnsiString;
27 function g_SaveGameTo (const filename: AnsiString; const aname: AnsiString; deleteOnError: Boolean=true): Boolean;
28 function g_LoadGameFrom (const filename: AnsiString): Boolean;
30 function g_SaveGame (n: Integer; const aname: AnsiString): Boolean;
31 function g_LoadGame (n: Integer): Boolean;
33 procedure Obj_SaveState (st: TStream; o: PObj);
34 procedure Obj_LoadState (o: PObj; st: TStream);
37 implementation
39 uses
40 MAPDEF, utils, xstreams,
41 g_game, g_items, g_map, g_monsters, g_triggers,
42 g_basic, g_main, Math, wadreader,
43 g_weapons, g_player, g_console,
44 e_log, e_res, g_language;
46 const
47 SAVE_SIGNATURE = $56534644; // 'DFSV'
48 SAVE_VERSION = $07;
49 END_MARKER_STRING = 'END';
50 PLAYER_VIEW_SIGNATURE = $57564C50; // 'PLVW'
51 OBJ_SIGNATURE = $4A424F5F; // '_OBJ'
54 procedure Obj_SaveState (st: TStream; o: PObj);
55 begin
56 if (st = nil) then exit;
57 // Ñèãíàòóðà îáúåêòà
58 utils.writeSign(st, '_OBJ');
59 utils.writeInt(st, Byte(0)); // version
60 // Ïîëîæåíèå ïî-ãîðèçîíòàëè
61 utils.writeInt(st, LongInt(o^.X));
62 // Ïîëîæåíèå ïî-âåðòèêàëè
63 utils.writeInt(st, LongInt(o^.Y));
64 // Îãðàíè÷èâàþùèé ïðÿìîóãîëüíèê
65 utils.writeInt(st, LongInt(o^.Rect.X));
66 utils.writeInt(st, LongInt(o^.Rect.Y));
67 utils.writeInt(st, Word(o^.Rect.Width));
68 utils.writeInt(st, Word(o^.Rect.Height));
69 // Ñêîðîñòü
70 utils.writeInt(st, LongInt(o^.Vel.X));
71 utils.writeInt(st, LongInt(o^.Vel.Y));
72 // Óñêîðåíèå
73 utils.writeInt(st, LongInt(o^.Accel.X));
74 utils.writeInt(st, LongInt(o^.Accel.Y));
75 end;
78 procedure Obj_LoadState (o: PObj; st: TStream);
79 begin
80 if (st = nil) then exit;
81 // Ñèãíàòóðà îáúåêòà:
82 if not utils.checkSign(st, '_OBJ') then raise XStreamError.Create('invalid object signature');
83 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid object version');
84 // Ïîëîæåíèå ïî-ãîðèçîíòàëè
85 o^.X := utils.readLongInt(st);
86 // Ïîëîæåíèå ïî-âåðòèêàëè
87 o^.Y := utils.readLongInt(st);
88 // Îãðàíè÷èâàþùèé ïðÿìîóãîëüíèê
89 o^.Rect.X := utils.readLongInt(st);
90 o^.Rect.Y := utils.readLongInt(st);
91 o^.Rect.Width := utils.readWord(st);
92 o^.Rect.Height := utils.readWord(st);
93 // Ñêîðîñòü
94 o^.Vel.X := utils.readLongInt(st);
95 o^.Vel.Y := utils.readLongInt(st);
96 // Óñêîðåíèå
97 o^.Accel.X := utils.readLongInt(st);
98 o^.Accel.Y := utils.readLongInt(st);
99 end;
102 function buildSaveName (n: Integer): AnsiString;
103 begin
104 result := 'SAVGAME' + IntToStr(n) + '.DAT'
105 end;
108 function g_GetSaveName (n: Integer; out valid: Boolean): AnsiString;
109 var
110 st: TStream = nil;
111 ver: Byte;
112 stlen: Word;
113 filename: AnsiString;
114 begin
115 valid := false;
116 result := '';
117 if (n < 0) or (n > 65535) then exit;
118 try
119 // Îòêðûâàåì ôàéë ñîõðàíåíèé
120 filename := buildSaveName(n);
121 st := e_OpenResourceRO(SaveDirs, filename);
122 try
123 if not utils.checkSign(st, 'DFSV') then
124 begin
125 e_LogWritefln('GetSaveName: not a save file: ''%s''', [st], TMsgType.Warning);
126 //raise XStreamError.Create('invalid save game signature');
127 exit;
128 end;
129 ver := utils.readByte(st);
130 if (ver < 7) then
131 begin
132 utils.readLongWord(st); // section size
133 stlen := utils.readWord(st);
134 if (stlen < 1) or (stlen > 64) then
135 begin
136 e_LogWritefln('GetSaveName: not a save file: ''%s''', [st], TMsgType.Warning);
137 //raise XStreamError.Create('invalid save game version');
138 exit;
139 end;
140 // Èìÿ ñýéâà
141 SetLength(result, stlen);
142 st.ReadBuffer(result[1], stlen);
143 end
144 else
145 begin
146 // 7+
147 // Èìÿ ñýéâà
148 result := utils.readStr(st, 64);
149 end;
150 valid := (ver = SAVE_VERSION);
151 //if (utils.readByte(st) <> SAVE_VERSION) then raise XStreamError.Create('invalid save game version');
152 finally
153 st.Free();
154 end;
155 except
156 begin
157 //e_WriteLog('GetSaveName Error: '+e.message, MSG_WARNING);
158 //{$IF DEFINED(D2F_DEBUG)}e_WriteStackTrace(e.message);{$ENDIF}
159 result := '';
160 end;
161 end;
162 end;
165 function g_SaveGameTo (const filename: AnsiString; const aname: AnsiString; deleteOnError: Boolean=true): Boolean;
166 var
167 st: TStream = nil;
168 i, k: Integer;
169 PID1, PID2: Word;
170 begin
171 result := false;
172 try
173 st := e_CreateResource(SaveDirs, filename);
174 try
175 utils.writeSign(st, 'DFSV');
176 utils.writeInt(st, Byte(SAVE_VERSION));
177 // Èìÿ ñýéâà
178 utils.writeStr(st, aname, 64);
179 // Ïîëíûé ïóòü ê âàäó è êàðòà
180 //if (Length(gCurrentMapFileName) <> 0) then e_LogWritefln('SAVE: current map is ''%s''...', [gCurrentMapFileName]);
181 utils.writeStr(st, gCurrentMapFileName);
182 // Ïóòü ê êàðòå
183 utils.writeStr(st, gGameSettings.WAD);
184 // Èìÿ êàðòû
185 utils.writeStr(st, g_ExtractFileName(gMapInfo.Map));
186 // Êîëè÷åñòâî èãðîêîâ
187 utils.writeInt(st, Word(g_Player_GetCount));
188 // Èãðîâîå âðåìÿ
189 utils.writeInt(st, LongWord(gTime));
190 // Òèï èãðû
191 utils.writeInt(st, Byte(gGameSettings.GameType));
192 // Ðåæèì èãðû
193 utils.writeInt(st, Byte(gGameSettings.GameMode));
194 // Ëèìèò âðåìåíè
195 utils.writeInt(st, Word(gGameSettings.TimeLimit));
196 // Ëèìèò î÷êîâ
197 utils.writeInt(st, Word(gGameSettings.GoalLimit));
198 // Ëèìèò æèçíåé
199 utils.writeInt(st, Byte(gGameSettings.MaxLives));
200 // Èãðîâûå îïöèè
201 utils.writeInt(st, LongWord(gGameSettings.Options));
202 // Äëÿ êîîïà
203 utils.writeInt(st, Word(gCoopMonstersKilled));
204 utils.writeInt(st, Word(gCoopSecretsFound));
205 utils.writeInt(st, Word(gCoopTotalMonstersKilled));
206 utils.writeInt(st, Word(gCoopTotalSecretsFound));
207 utils.writeInt(st, Word(gCoopTotalMonsters));
208 utils.writeInt(st, Word(gCoopTotalSecrets));
210 ///// Ñîõðàíÿåì ñîñòîÿíèå îáëàñòåé ïðîñìîòðà /////
211 utils.writeSign(st, 'PLVW');
212 utils.writeInt(st, Byte(0)); // version
213 PID1 := 0;
214 PID2 := 0;
215 if (gPlayer1 <> nil) then PID1 := gPlayer1.UID;
216 if (gPlayer2 <> nil) then PID2 := gPlayer2.UID;
217 utils.writeInt(st, Word(PID1));
218 utils.writeInt(st, Word(PID2));
219 ///// /////
221 ///// Ñîñòîÿíèå êàðòû /////
222 g_Map_SaveState(st);
223 ///// /////
225 ///// Ñîñòîÿíèå ïðåäìåòîâ /////
226 g_Items_SaveState(st);
227 ///// /////
229 ///// Ñîñòîÿíèå òðèããåðîâ /////
230 g_Triggers_SaveState(st);
231 ///// /////
233 ///// Ñîñòîÿíèå îðóæèÿ /////
234 g_Weapon_SaveState(st);
235 ///// /////
237 ///// Ñîñòîÿíèå ìîíñòðîâ /////
238 g_Monsters_SaveState(st);
239 ///// /////
241 ///// Ñîñòîÿíèå òðóïîâ /////
242 g_Player_Corpses_SaveState(st);
243 ///// /////
245 ///// Ñîõðàíÿåì èãðîêîâ (â òîì ÷èñëå áîòîâ) /////
246 if (g_Player_GetCount > 0) then
247 begin
248 k := 0;
249 for i := 0 to High(gPlayers) do
250 begin
251 if (gPlayers[i] <> nil) then
252 begin
253 // Ñîñòîÿíèå èãðîêà
254 gPlayers[i].SaveState(st);
255 Inc(k);
256 end;
257 end;
259 // Âñå ëè èãðîêè íà ìåñòå
260 if (k <> g_Player_GetCount) then raise XStreamError.Create('g_SaveGame: wrong players count');
261 end;
262 ///// /////
264 ///// Ìàðêåð îêîí÷àíèÿ /////
265 utils.writeSign(st, 'END');
266 utils.writeInt(st, Byte(0));
267 ///// /////
268 result := true;
269 finally
270 st.Free();
271 end;
273 except
274 on e: Exception do
275 begin
276 st.Free();
277 g_Console_Add(_lc[I_GAME_ERROR_SAVE]);
278 e_WriteLog('SaveState Error: '+e.message, TMsgType.Warning);
279 if deleteOnError then DeleteFile(filename);
280 {$IF DEFINED(D2F_DEBUG)}e_WriteStackTrace(e.message);{$ENDIF}
281 e_WriteStackTrace(e.message);
282 result := false;
283 end;
284 end;
285 end;
288 function g_LoadGameFrom (const filename: AnsiString): Boolean;
289 var
290 st: TStream = nil;
291 WAD_Path, Map_Name: AnsiString;
292 nPlayers: Integer;
293 Game_Type, Game_Mode, Game_MaxLives: Byte;
294 Game_TimeLimit, Game_GoalLimit: Word;
295 Game_Time, Game_Options: Cardinal;
296 Game_CoopMonstersKilled,
297 Game_CoopSecretsFound,
298 Game_CoopTotalMonstersKilled,
299 Game_CoopTotalSecretsFound,
300 Game_CoopTotalMonsters,
301 Game_CoopTotalSecrets,
302 PID1, PID2: Word;
303 i: Integer;
304 gameCleared: Boolean = false;
305 curmapfile: AnsiString = '';
306 {$IF DEFINED(D2F_DEBUG)}
307 errpos: LongWord = 0;
308 {$ENDIF}
309 begin
310 result := false;
312 try
313 st := e_OpenResourceRO(SaveDirs, filename);
314 try
315 if not utils.checkSign(st, 'DFSV') then raise XStreamError.Create('invalid save game signature');
316 if (utils.readByte(st) <> SAVE_VERSION) then raise XStreamError.Create('invalid save game version');
318 e_WriteLog('Loading saved game...', TMsgType.Notify);
320 {$IF DEFINED(D2F_DEBUG)}try{$ENDIF}
321 //g_Game_Free(false); // don't free textures for the same map
322 g_Game_ClearLoading();
323 g_Game_SetLoadingText(_lc[I_LOAD_SAVE_FILE], 0, False);
324 gLoadGameMode := True;
326 ///// Çàãðóæàåì ñîñòîÿíèå èãðû /////
327 // Èìÿ ñýéâà
328 {str :=} utils.readStr(st, 64);
330 // Ïîëíûé ïóòü ê âàäó è êàðòà
331 curmapfile := utils.readStr(st);
333 if (Length(gCurrentMapFileName) <> 0) then e_LogWritefln('LOAD: previous map was ''%s''...', [gCurrentMapFileName]);
334 if (Length(curmapfile) <> 0) then e_LogWritefln('LOAD: new map is ''%s''...', [curmapfile]);
335 // À âîò òóò, íàêîíåö, ÷èñòèì ðåñóðñû
336 g_Game_Free(curmapfile <> gCurrentMapFileName); // don't free textures for the same map
337 gameCleared := true;
339 // Ïóòü ê êàðòå
340 WAD_Path := utils.readStr(st);
341 // Èìÿ êàðòû
342 Map_Name := utils.readStr(st);
343 // Êîëè÷åñòâî èãðîêîâ
344 nPlayers := utils.readWord(st);
345 // Èãðîâîå âðåìÿ
346 Game_Time := utils.readLongWord(st);
347 // Òèï èãðû
348 Game_Type := utils.readByte(st);
349 // Ðåæèì èãðû
350 Game_Mode := utils.readByte(st);
351 // Ëèìèò âðåìåíè
352 Game_TimeLimit := utils.readWord(st);
353 // Ëèìèò î÷êîâ
354 Game_GoalLimit := utils.readWord(st);
355 // Ëèìèò æèçíåé
356 Game_MaxLives := utils.readByte(st);
357 // Èãðîâûå îïöèè
358 Game_Options := utils.readLongWord(st);
359 // Äëÿ êîîïà
360 Game_CoopMonstersKilled := utils.readWord(st);
361 Game_CoopSecretsFound := utils.readWord(st);
362 Game_CoopTotalMonstersKilled := utils.readWord(st);
363 Game_CoopTotalSecretsFound := utils.readWord(st);
364 Game_CoopTotalMonsters := utils.readWord(st);
365 Game_CoopTotalSecrets := utils.readWord(st);
366 ///// /////
368 ///// Çàãðóæàåì ñîñòîÿíèå îáëàñòåé ïðîñìîòðà /////
369 if not utils.checkSign(st, 'PLVW') then raise XStreamError.Create('invalid viewport signature');
370 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid viewport version');
371 PID1 := utils.readWord(st);
372 PID2 := utils.readWord(st);
373 ///// /////
375 // Çàãðóæàåì êàðòó:
376 ZeroMemory(@gGameSettings, sizeof(TGameSettings));
377 gAimLine := false;
378 gShowMap := false;
379 if (Game_Type = GT_NONE) or (Game_Type = GT_SINGLE) then
380 begin
381 // Íàñòðîéêè èãðû
382 gGameSettings.GameType := GT_SINGLE;
383 gGameSettings.MaxLives := 0;
384 gGameSettings.Options := gGameSettings.Options+GAME_OPTION_ALLOWEXIT;
385 gGameSettings.Options := gGameSettings.Options+GAME_OPTION_MONSTERS;
386 gGameSettings.Options := gGameSettings.Options+GAME_OPTION_BOTVSMONSTER;
387 gSwitchGameMode := GM_SINGLE;
388 end
389 else
390 begin
391 // Íàñòðîéêè èãðû
392 gGameSettings.GameType := GT_CUSTOM;
393 gGameSettings.GameMode := Game_Mode;
394 gSwitchGameMode := Game_Mode;
395 gGameSettings.TimeLimit := Game_TimeLimit;
396 gGameSettings.GoalLimit := Game_GoalLimit;
397 gGameSettings.MaxLives := IfThen(Game_Mode = GM_CTF, 0, Game_MaxLives);
398 gGameSettings.Options := Game_Options;
399 end;
400 g_Game_ExecuteEvent('ongamestart');
402 // Óñòàíîâêà ðàçìåðîâ îêîí èãðîêîâ
403 g_Game_SetupScreenSize();
405 // Çàãðóçêà è çàïóñê êàðòû
406 //FIXME: save/load `asMegawad`
407 if not g_Game_StartMap(false{asMegawad}, WAD_Path+':\'+Map_Name, True, curmapfile) then
408 begin
409 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [WAD_Path + ':\' + Map_Name]));
410 exit;
411 end;
413 // Íàñòðîéêè èãðîêîâ è áîòîâ
414 g_Player_Init();
416 // Óñòàíàâëèâàåì âðåìÿ
417 gTime := Game_Time;
418 // Âîçâðàùàåì ñòàòû
419 gCoopMonstersKilled := Game_CoopMonstersKilled;
420 gCoopSecretsFound := Game_CoopSecretsFound;
421 gCoopTotalMonstersKilled := Game_CoopTotalMonstersKilled;
422 gCoopTotalSecretsFound := Game_CoopTotalSecretsFound;
423 gCoopTotalMonsters := Game_CoopTotalMonsters;
424 gCoopTotalSecrets := Game_CoopTotalSecrets;
426 ///// Çàãðóæàåì ñîñòîÿíèå êàðòû /////
427 g_Map_LoadState(st);
428 ///// /////
430 ///// Çàãðóæàåì ñîñòîÿíèå ïðåäìåòîâ /////
431 g_Items_LoadState(st);
432 ///// /////
434 ///// Çàãðóæàåì ñîñòîÿíèå òðèããåðîâ /////
435 g_Triggers_LoadState(st);
436 ///// /////
438 ///// Çàãðóæàåì ñîñòîÿíèå îðóæèÿ /////
439 g_Weapon_LoadState(st);
440 ///// /////
442 ///// Çàãðóæàåì ñîñòîÿíèå ìîíñòðîâ /////
443 g_Monsters_LoadState(st);
444 ///// /////
446 ///// Çàãðóæàåì ñîñòîÿíèå òðóïîâ /////
447 g_Player_Corpses_LoadState(st);
448 ///// /////
450 ///// Çàãðóæàåì èãðîêîâ (â òîì ÷èñëå áîòîâ) /////
451 if nPlayers > 0 then
452 begin
453 // Çàãðóæàåì
454 for i := 0 to nPlayers-1 do g_Player_CreateFromState(st);
455 end;
457 // Ïðèâÿçûâàåì îñíîâíûõ èãðîêîâ ê îáëàñòÿì ïðîñìîòðà
458 gPlayer1 := g_Player_Get(PID1);
459 gPlayer2 := g_Player_Get(PID2);
461 if (gPlayer1 <> nil) then
462 begin
463 gPlayer1.Name := gPlayer1Settings.Name;
464 gPlayer1.FPreferredTeam := gPlayer1Settings.Team;
465 gPlayer1.FActualModelName := gPlayer1Settings.Model;
466 gPlayer1.SetModel(gPlayer1.FActualModelName);
467 gPlayer1.SetColor(gPlayer1Settings.Color);
468 end;
470 if (gPlayer2 <> nil) then
471 begin
472 gPlayer2.Name := gPlayer2Settings.Name;
473 gPlayer2.FPreferredTeam := gPlayer2Settings.Team;
474 gPlayer2.FActualModelName := gPlayer2Settings.Model;
475 gPlayer2.SetModel(gPlayer2.FActualModelName);
476 gPlayer2.SetColor(gPlayer2Settings.Color);
477 end;
478 ///// /////
480 ///// Ìàðêåð îêîí÷àíèÿ /////
481 if not utils.checkSign(st, 'END') then raise XStreamError.Create('no end marker');
482 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid end marker');
483 ///// /////
485 // Èùåì òðèããåðû ñ óñëîâèåì ñìåðòè ìîíñòðîâ
486 if (gTriggers <> nil) then g_Map_ReAdd_DieTriggers();
488 // done
489 gLoadGameMode := false;
490 result := true;
491 {$IF DEFINED(D2F_DEBUG)}
492 except
493 begin
494 errpos := LongWord(st.position);
495 raise;
496 end;
497 end;
498 {$ENDIF}
499 finally
500 st.Free();
501 end;
502 except
503 on e: EFileNotFoundException do
504 begin
505 g_Console_Add(_lc[I_GAME_ERROR_LOAD]);
506 g_Console_Add('LoadState Error: '+e.message);
507 e_WriteLog('LoadState Error: '+e.message, TMsgType.Warning);
508 gLoadGameMode := false;
509 result := false;
510 end;
511 on e: Exception do
512 begin
513 g_Console_Add(_lc[I_GAME_ERROR_LOAD]);
514 g_Console_Add('LoadState Error: '+e.message);
515 e_WriteLog('LoadState Error: '+e.message, TMsgType.Warning);
516 {$IF DEFINED(D2F_DEBUG)}e_LogWritefln('stream error position: 0x%08x', [errpos], TMsgType.Warning);{$ENDIF}
517 gLoadGameMode := false;
518 result := false;
519 if gState <> STATE_MENU then
520 g_FatalError(_lc[I_GAME_ERROR_LOAD])
521 else if not gameCleared then
522 g_Game_Free();
523 {$IF DEFINED(D2F_DEBUG)}e_WriteStackTrace(e.message);{$ENDIF}
524 end;
525 end;
526 end;
529 function g_SaveGame (n: Integer; const aname: AnsiString): Boolean;
530 begin
531 result := g_SaveGameTo(buildSaveName(n), aname, true);
532 end;
535 function g_LoadGame (n: Integer): Boolean;
536 begin
537 result := g_LoadGameFrom(buildSaveName(n));
538 end;
541 end.