aboutsummaryrefslogtreecommitdiff
path: root/engines/sword25/kernel/persistenceservice.cpp
blob: 977312174075a965e432617e155e7533e9713cac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// -----------------------------------------------------------------------------
// This file is part of Broken Sword 2.5
// Copyright (c) Malte Thiesen, Daniel Queteschiner and Michael Elsd�rfer
//
// Broken Sword 2.5 is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Broken Sword 2.5 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Broken Sword 2.5; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------

#include "sword25/kernel/kernel.h"
#include "sword25/kernel/persistenceservice.h"
#include "sword25/kernel/inputpersistenceblock.h"
#include "sword25/kernel/outputpersistenceblock.h"
#include "sword25/kernel/filesystemutil.h"
#include "sword25/gfx/graphicengine.h"
#include "sword25/sfx/soundengine.h"
#include "sword25/input/inputengine.h"
#include "sword25/math/regionregistry.h"
#include "sword25/script/script.h"
#include "sword25/kernel/debug/debugtools.h"
#include <zlib.h>

#include "sword25/kernel/memlog_off.h"
#include <sstream>
#include <fstream>
#include <algorithm>
#include <locale>
#include "sword25/kernel/memlog_on.h"

using namespace std;

#define BS_LOG_PREFIX "PERSISTENCESERVICE"

// -----------------------------------------------------------------------------
// Konstanten und Hilfsfunktionen
// -----------------------------------------------------------------------------

namespace
{
	const char *		SAVEGAME_EXTENSION = ".b25s";
	const char *		SAVEGAME_DIRECTORY = "saves";
	const char *		FILE_MARKER = "BS25SAVEGAME";
	const unsigned int	SLOT_COUNT = 18;
	const unsigned int	FILE_COPY_BUFFER_SIZE = 1024 * 10;

	// -------------------------------------------------------------------------

	string GenerateSavegameFilename(unsigned int SlotID)
	{
		ostringstream oss;
		oss << SlotID << SAVEGAME_EXTENSION;
		return oss.str();
	}

	// -------------------------------------------------------------------------

	string GenerateSavegamePath(unsigned int SlotID)
	{
		ostringstream oss;
		oss << BS_PersistenceService::GetSavegameDirectory() << BS_FileSystemUtil::GetInstance().GetPathSeparator() << GenerateSavegameFilename(SlotID);
		return oss.str();
	}

	// -------------------------------------------------------------------------

	string FormatTimestamp(time_t Time)
	{
		// Zeitstempel in Einzelkomponenten aufl�sen.
		tm * Timeinfo = localtime(&Time);

		// Zeitangabe im lokalen Format in einen String-Stream schreiben.
		locale Locale("");
		ostringstream StringBuilder;
		StringBuilder.imbue(Locale);
		char * Pattern = "%x %X";
		use_facet<time_put<char> >(Locale).put(StringBuilder,
			StringBuilder, StringBuilder.fill(), Timeinfo, Pattern, Pattern + strlen(Pattern));

		// Formatierten String zur�ckgeben.
		return StringBuilder.str();
	}
}

// -----------------------------------------------------------------------------
// Private Implementation (Pimpl-Pattern)
// -----------------------------------------------------------------------------

struct SavegameInformation
{
	bool			IsOccupied;
	bool			IsCompatible;
	string			Description;
	string			Filename;
	unsigned int	GamedataLength;
	unsigned int	GamedataOffset;
	unsigned int	GamedataUncompressedLength;

	SavegameInformation() { Clear(); }

	void Clear()
	{
		IsOccupied = false;
		IsCompatible = false;
		Description = "";
		Filename = "";
		GamedataLength = 0;
		GamedataOffset = 0;
		GamedataUncompressedLength = 0;
	}
};

struct BS_PersistenceService::Impl
{
	SavegameInformation m_SavegameInformations[SLOT_COUNT];

	// -----------------------------------------------------------------------------

	Impl()
	{
		ReloadSlots();
	}

	// -----------------------------------------------------------------------------

	void ReloadSlots()
	{
		// �ber alle Spielstanddateien iterieren und deren Infos einlesen.
		for (unsigned int i = 0; i < SLOT_COUNT; ++i)
		{
			ReadSlotSavegameInformation(i);
		}
	}

	void ReadSlotSavegameInformation(unsigned int SlotID)
	{
		// Aktuelle Slotinformationen in den Ausgangszustand versetzen, er wird im Folgenden neu gef�llt.
		SavegameInformation & CurSavegameInfo = m_SavegameInformations[SlotID];
		CurSavegameInfo.Clear();

		// Den Dateinamen f�r den Spielstand des Slots generieren.
		string Filename = GenerateSavegamePath(SlotID);

		// Feststellen, ob eine Spielstanddatei dieses Namens existiert.
		if (BS_FileSystemUtil::GetInstance().FileExists(Filename))
		{
			// Die Spielstanddatei �ffnen.
			ifstream File(Filename.c_str(), ifstream::binary);
			if (File.good() && File.is_open())
			{
				// Die Headerdaten einlesen.
				string StoredMarker, StoredVersionID;
				File >> StoredMarker >> StoredVersionID >> CurSavegameInfo.GamedataLength >> CurSavegameInfo.GamedataUncompressedLength;

				// Falls die Headerdaten gelesen werden konnten und der Marker stimmt, nehmen wir an eine g�ltige Spielstanddatei zu haben.
				if (File.good() && StoredMarker == FILE_MARKER)
				{
					// Der Slot wird als belegt markiert.
					CurSavegameInfo.IsOccupied = true;
					// Speichern, ob der Spielstand kompatibel mit der aktuellen Engine-Version ist.
					CurSavegameInfo.IsCompatible = (StoredVersionID == BS_Debugtools::GetVersionID());
					// Dateinamen des Spielstandes speichern.
					CurSavegameInfo.Filename = GenerateSavegameFilename(SlotID);
					// Die Beschreibung des Spielstandes besteht aus einer textuellen Darstellung des �nderungsdatums der Spielstanddatei.
					CurSavegameInfo.Description = FormatTimestamp(BS_FileSystemUtil::GetInstance().GetFileTime(Filename));
					// Den Offset zu den gespeicherten Spieldaten innerhalb der Datei speichern.
					// Dieses entspricht der aktuellen Position + 1, da nach der letzten Headerinformation noch ein Leerzeichen als trenner folgt.
					CurSavegameInfo.GamedataOffset = static_cast<unsigned int>(File.tellg()) + 1;
				}

			}
		}
	}
};

// -----------------------------------------------------------------------------
// Construction / Destruction
// -----------------------------------------------------------------------------

BS_PersistenceService & BS_PersistenceService::GetInstance()
{
	static BS_PersistenceService Instance;
	return Instance;
}

// -----------------------------------------------------------------------------

BS_PersistenceService::BS_PersistenceService() : m_impl(new Impl)
{
}

// -----------------------------------------------------------------------------

BS_PersistenceService::~BS_PersistenceService()
{
	delete m_impl;
}

// -----------------------------------------------------------------------------
// Implementation
// -----------------------------------------------------------------------------

void BS_PersistenceService::ReloadSlots()
{
	m_impl->ReloadSlots();
}

// -----------------------------------------------------------------------------

unsigned int BS_PersistenceService::GetSlotCount()
{
	return SLOT_COUNT;
}

// -----------------------------------------------------------------------------

std::string BS_PersistenceService::GetSavegameDirectory()
{
	return BS_FileSystemUtil::GetInstance().GetUserdataDirectory() + BS_FileSystemUtil::GetInstance().GetPathSeparator() + SAVEGAME_DIRECTORY;
}

// -----------------------------------------------------------------------------

namespace
{
	bool CheckSlotID(unsigned int SlotID)
	{
		// �berpr�fen, ob die Slot-ID zul�ssig ist.
		if (SlotID >= SLOT_COUNT)
		{
			BS_LOG_ERRORLN("Tried to access an invalid slot (%d). Only slot ids from 0 to %d are allowed.", SlotID, SLOT_COUNT - 1);
			return false;
		}
		else
		{
			return true;
		}
	}
}

// -----------------------------------------------------------------------------

bool BS_PersistenceService::IsSlotOccupied(unsigned int SlotID)
{
	if (!CheckSlotID(SlotID)) return false;
	return m_impl->m_SavegameInformations[SlotID].IsOccupied;
}

// -----------------------------------------------------------------------------

bool BS_PersistenceService::IsSavegameCompatible(unsigned int SlotID)
{
	if (!CheckSlotID(SlotID)) return false;
	return m_impl->m_SavegameInformations[SlotID].IsCompatible;
}

// -----------------------------------------------------------------------------

string & BS_PersistenceService::GetSavegameDescription(unsigned int SlotID)
{
	static string EmptyString;
	if (!CheckSlotID(SlotID)) return EmptyString;
	return m_impl->m_SavegameInformations[SlotID].Description;
}

// -----------------------------------------------------------------------------

string & BS_PersistenceService::GetSavegameFilename(unsigned int SlotID)
{
	static string EmptyString;
	if (!CheckSlotID(SlotID)) return EmptyString;
	return m_impl->m_SavegameInformations[SlotID].Filename;
}

// -----------------------------------------------------------------------------

bool BS_PersistenceService::SaveGame(unsigned int SlotID, const std::string & ScreenshotFilename)
{
	// �berpr�fen, ob die Slot-ID zul�ssig ist.
	if (SlotID >= SLOT_COUNT)
	{
		BS_LOG_ERRORLN("Tried to save to an invalid slot (%d). Only slot ids form 0 to %d are allowed.", SlotID, SLOT_COUNT - 1);
		return false;
	}

	// Dateinamen erzeugen.
	string Filename = GenerateSavegamePath(SlotID).c_str();

	try
	{
		// Sicherstellen, dass das Verzeichnis f�r die Spielstanddateien existiert.
		BS_FileSystemUtil::GetInstance().CreateDirectory(GetSavegameDirectory());

		// Spielstanddatei �ffnen und die Headerdaten schreiben.
		ofstream File(Filename.c_str(), ofstream::binary);
		File << string(FILE_MARKER) << " " << string(BS_Debugtools::GetVersionID()) << " ";
		if (!File.good())
		{
			BS_LOG_ERRORLN("Unable to write header data to savegame file \"%s\".", Filename.c_str());
			throw 0;
		}

		// Alle notwendigen Module persistieren.
		BS_OutputPersistenceBlock Writer;
		bool Success = true;
		Success &= BS_Kernel::GetInstance()->GetScript()->Persist(Writer);
		Success &= BS_RegionRegistry::GetInstance().Persist(Writer);
		Success &= BS_Kernel::GetInstance()->GetGfx()->Persist(Writer);
		Success &= BS_Kernel::GetInstance()->GetSfx()->Persist(Writer);
		Success &= BS_Kernel::GetInstance()->GetInput()->Persist(Writer);
		if (!Success)
		{
			BS_LOG_ERRORLN("Unable to persist modules for savegame file \"%s\".", Filename.c_str());
			throw 0;
		}

		// Daten komprimieren.
		vector<unsigned char> CompressionBuffer(Writer.GetDataSize() + (Writer.GetDataSize() + 500) / 1000 + 12);
		uLongf CompressedLength = CompressionBuffer.size();
		if (compress2(&CompressionBuffer[0], &CompressedLength, reinterpret_cast<const Bytef *>(Writer.GetData()), Writer.GetDataSize(), 6) != Z_OK)
		{
			BS_LOG_ERRORLN("Unable to compress savegame data in savegame file \"%s\".", Filename.c_str());
			throw 0;
		}

		// L�nge der komprimierten Daten und der unkomprimierten Daten in die Datei schreiben.
		File << CompressedLength << " " << Writer.GetDataSize() << " ";

		// Komprimierte Daten in die Datei schreiben.
		File.write(reinterpret_cast<char *>(&CompressionBuffer[0]), CompressedLength);
		if (!File.good())
		{
			BS_LOG_ERRORLN("Unable to write game data to savegame file \"%s\".", Filename.c_str());
			throw 0;
		}

		// Screenshotdatei an die Datei anf�gen.
		if (BS_FileSystemUtil::GetInstance().FileExists(ScreenshotFilename))
		{
			ifstream ScreenshotFile(ScreenshotFilename.c_str(), ifstream::binary);

			vector<char> Buffer(FILE_COPY_BUFFER_SIZE);
			while (ScreenshotFile.good())
			{
				ScreenshotFile.read(&Buffer[0], Buffer.size());
				File.write(&Buffer[0], ScreenshotFile.gcount());
			}
		}
		else
		{
			BS_LOG_WARNINGLN("The screenshot file \"%s\" does not exist. Savegame is written without a screenshot.", Filename.c_str());
		}

		// Savegameinformationen f�r diesen Slot aktualisieren.
		m_impl->ReadSlotSavegameInformation(SlotID);
	}
	catch(...)
	{
		BS_LOG_ERRORLN("An error occured while create savegame file \"%s\".", Filename.c_str());

		// Es ist ein Fehler aufgetreten, die Spielstanddatei wird gel�scht, da sie keinen konsistenten Zustand besitzt.
		::remove(Filename.c_str());

		// Misserfolg signalisieren.
		return false;
	}

	// Erfolg signalisieren.
	return true;
}

// -----------------------------------------------------------------------------

bool BS_PersistenceService::LoadGame(unsigned int SlotID)
{
	// �berpr�fen, ob die Slot-ID zul�ssig ist.
	if (SlotID >= SLOT_COUNT)
	{
		BS_LOG_ERRORLN("Tried to load from an invalid slot (%d). Only slot ids form 0 to %d are allowed.", SlotID, SLOT_COUNT - 1);
		return false;
	}

	SavegameInformation & CurSavegameInfo = m_impl->m_SavegameInformations[SlotID];

	// �berpr�fen, ob der Slot belegt ist.
	if (!CurSavegameInfo.IsOccupied)
	{
		BS_LOG_ERRORLN("Tried to load from an empty slot (%d).", SlotID);
		return false;
	}

	// �berpr�fen, ob der Spielstand im angegebenen Slot mit der aktuellen Engine-Version kompatibel ist.
	// Im Debug-Modus wird dieser Test �bersprungen. F�r das Testen ist es hinderlich auf die Einhaltung dieser strengen Bedingung zu bestehen,
	// da sich die Versions-ID bei jeder Code�nderung mit�ndert.
#ifndef DEBUG
	if (!CurSavegameInfo.IsCompatible)
	{
		BS_LOG_ERRORLN("Tried to load a savegame (%d) that is not compatible with this engine version.", SlotID);
		return false;
	}
#endif

	vector<unsigned char> UncompressedDataBuffer(CurSavegameInfo.GamedataUncompressedLength);
	{
		// Komprimierte gespeicherte Spieldaten laden.
		vector<unsigned char> CompressedDataBuffer(CurSavegameInfo.GamedataLength);
		{
			ifstream File(GenerateSavegamePath(SlotID).c_str(), ifstream::binary);
			File.seekg(CurSavegameInfo.GamedataOffset);
			File.read(reinterpret_cast<char *>(&CompressedDataBuffer[0]), CurSavegameInfo.GamedataLength);
			if (!File.good())
			{
				BS_LOG_ERRORLN("Unable to load the gamedata from the savegame file \"%s\".", CurSavegameInfo.Filename.c_str());
				return false;
			}
		}

		// Spieldaten dekomprimieren.
		uLongf UncompressedBufferSize = UncompressedDataBuffer.size();
		if (uncompress(reinterpret_cast<Bytef *>(&UncompressedDataBuffer[0]), &UncompressedBufferSize,
			reinterpret_cast<Bytef *>(&CompressedDataBuffer[0]), CompressedDataBuffer.size()) != Z_OK)
		{
			BS_LOG_ERRORLN("Unable to decompress the gamedata from savegame file \"%s\".", CurSavegameInfo.Filename.c_str());
			return false;
		}
	}

	BS_InputPersistenceBlock Reader(&UncompressedDataBuffer[0], UncompressedDataBuffer.size());

	// Einzelne Engine-Module depersistieren.
	bool Success = true;
	Success &= BS_Kernel::GetInstance()->GetScript()->Unpersist(Reader);
	// Muss unbedingt nach Script passieren. Da sonst die bereits wiederhergestellten Regions per Garbage-Collection gekillt werden.
	Success &= BS_RegionRegistry::GetInstance().Unpersist(Reader);
	Success &= BS_Kernel::GetInstance()->GetGfx()->Unpersist(Reader);
	Success &= BS_Kernel::GetInstance()->GetSfx()->Unpersist(Reader);
	Success &= BS_Kernel::GetInstance()->GetInput()->Unpersist(Reader);

	if (!Success)
	{
		BS_LOG_ERRORLN("Unable to unpersist the gamedata from savegame file \"%s\".", CurSavegameInfo.Filename.c_str());
		return false;
	}

	return true;
}