forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersistence.cpp
More file actions
437 lines (354 loc) · 13.3 KB
/
Persistence.cpp
File metadata and controls
437 lines (354 loc) · 13.3 KB
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
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2012 Petr Mrázek ([email protected])
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Core.h"
#include "DFHackVersion.h"
#include "Debug.h"
#include "Internal.h"
#include "LuaTools.h"
#include "MemAccess.h"
#include "modules/DFSDL.h"
#include "modules/Filesystem.h"
#include "modules/Gui.h"
#include "modules/Persistence.h"
#include "modules/World.h"
#include "df/world.h"
#include "df/init.h"
#include <json/json.h>
#include <unordered_map>
namespace DFHack {
DBG_DECLARE(core, persistence, DebugCategory::LINFO);
}
using namespace DFHack;
static std::unordered_map<int, std::multimap<std::string, std::shared_ptr<Persistence::DataEntry>>> store;
static std::unordered_map<size_t, std::shared_ptr<Persistence::DataEntry>> entry_cache;
static uint32_t lastLoadSaveTickCount = 0;
size_t next_entry_id = 0; // goes more positive
int next_fake_df_id = -101; // goes more negative
struct Persistence::DataEntry {
const size_t entry_id;
const int entity_id;
const std::string key;
int fake_df_id;
std::string str_value;
std::array<int, PersistentDataItem::NumInts> int_values;
explicit DataEntry(int entity_id, const std::string &key)
: entry_id(next_entry_id++), entity_id(entity_id), key(key) {
fake_df_id = 0;
for (size_t i = 0; i < PersistentDataItem::NumInts; i++)
int_values.at(i) = -1;
}
explicit DataEntry(int entity_id, Json::Value &json)
: DataEntry(entity_id, json["k"].asString()) {
if (json.isMember("f"))
fake_df_id = json["f"].asInt();
str_value = json["s"].asString();
if (json.isMember("i")) {
for (size_t i = 0; i < PersistentDataItem::NumInts; i++)
int_values.at(i) = json["i"].get(i, Json::Value(-1)).asInt();
}
}
Json::Value toJSON() const {
Json::Value json(Json::objectValue);
json["k"] = key;
if (fake_df_id < 0)
json["f"] = fake_df_id;
if (str_value.size())
json["s"] = str_value;
size_t num_set_ints = 0;
for (size_t i = 0; i < PersistentDataItem::NumInts; i++) {
if (int_values.at(i) != -1)
num_set_ints = i + 1;
}
if (num_set_ints) {
Json::Value ints(Json::arrayValue);
for (size_t i = 0; i < num_set_ints; i++)
ints.append(int_values.at(i));
json["i"] = std::move(ints);
}
return json;
}
bool isReferencedBy(const PersistentDataItem & item) {
return item.data.get() == this;
}
};
int PersistentDataItem::entity_id() const {
CHECK_INVALID_ARGUMENT(isValid());
return data->entity_id;
}
const std::string &PersistentDataItem::key() const
{
CHECK_INVALID_ARGUMENT(isValid());
return data->key;
}
std::string &PersistentDataItem::val()
{
CHECK_INVALID_ARGUMENT(isValid());
return data->str_value;
}
const std::string &PersistentDataItem::val() const
{
CHECK_INVALID_ARGUMENT(isValid());
return data->str_value;
}
int &PersistentDataItem::ival(int i)
{
CHECK_INVALID_ARGUMENT(isValid());
CHECK_INVALID_ARGUMENT(i >= 0 && i < (int)NumInts);
return data->int_values.at(i);
}
int PersistentDataItem::ival(int i) const
{
CHECK_INVALID_ARGUMENT(isValid());
CHECK_INVALID_ARGUMENT(i >= 0 && i < (int)NumInts);
return data->int_values.at(i);
}
const std::string & PersistentDataItem::get_str() {
static const std::string empty;
return isValid() ? val() : empty;
}
bool PersistentDataItem::isValid() const
{
if (data == nullptr)
return false;
CoreSuspender suspend;
return entry_cache.contains(data->entry_id) && entry_cache.at(data->entry_id) == data;
}
int PersistentDataItem::fake_df_id() {
if (!isValid())
return 0;
// set it if unset
if (data->fake_df_id == 0)
data->fake_df_id = next_fake_df_id--;
return data->fake_df_id;
}
void Persistence::Internal::clear(color_ostream& out) {
CoreSuspender suspend;
store.clear();
entry_cache.clear();
next_entry_id = 0;
next_fake_df_id = -101;
}
static std::string filterSaveFileName(std::string s) {
for (auto &ch : s) {
if (!isalnum(ch) && ch != '-' && ch != '_')
ch = '_';
}
return s;
}
static std::filesystem::path getSavePath(const std::string &world) {
return Filesystem::getBaseDir() / "save" / world;
}
static std::filesystem::path getSaveFilePath(const std::string &world, const std::string &name) {
return getSavePath(world) / ("dfhack-" + filterSaveFileName(name) + ".dat");
}
struct LastLoadSaveTickCountUpdater {
~LastLoadSaveTickCountUpdater() {
lastLoadSaveTickCount = Core::getInstance().p->getTickCount();
}
};
void Persistence::Internal::save(color_ostream& out) {
Core &core = Core::getInstance();
if (!core.isWorldLoaded())
return;
CoreSuspender suspend;
LastLoadSaveTickCountUpdater tickCountUpdater;
// write status
{
auto file = std::ofstream(getSaveFilePath("current", "status"));
file << "DF version: " << core.p->getDescriptor()->getVersion() << std::endl;
file << "DFHack version: " << Version::dfhack_version() << " (" << Version::git_commit(true) << ")" << std::endl;
file << "Tagged release: " << (Version::is_release() ? "yes" : "no") << std::endl;
file << "Pre-release: " << (Version::is_prerelease() ? "yes" : "no") << std::endl;
if (strlen(Version::dfhack_run_url())) {
file << "Build url: " << Version::dfhack_run_url() << std::endl;
}
if (df::global::world and df::global::version) {
file << std::endl;
file << "World name: " << World::getWorldName() << " (" << World::getWorldName(true) << ")" << std::endl;
file << "World generated in version: " << df::global::world->original_save_version << std::endl;
file << "World last saved in version: " << df::global::world->save_version << std::endl;
file << "World loaded in version: " << *df::global::version << std::endl;
}
}
// write entity data
for (auto & entity_store_entry : store) {
int entity_id = entity_store_entry.first;
Json::Value json(Json::arrayValue);
for (auto & entries : entity_store_entry.second) {
if (entries.second == nullptr)
continue;
json.append(entries.second->toJSON());
}
std::string name = (entity_id == Persistence::WORLD_ENTITY_ID) ?
"world" : "entity-" + int_to_string(entity_id);
auto file = std::ofstream(getSaveFilePath("current", name));
file << json;
}
// write perf counters
{
auto file = std::ofstream(getSaveFilePath("current", "perf-counters"));
color_ostream_wrapper wrapper(file);
Lua::CallLuaModuleFunction(wrapper, "script-manager", "print_timers");
}
}
static bool get_entity_id(const std::string & fname, int & entity_id) {
if (!fname.starts_with("dfhack-entity-"))
return false;
entity_id = string_to_int(fname.substr(14, fname.length() - 18), -1);
return true;
}
static void add_entry(std::multimap<std::string, std::shared_ptr<Persistence::DataEntry>> & entity_store_entry,
std::shared_ptr<Persistence::DataEntry> entry) {
entity_store_entry.emplace(entry->key, entry);
entry_cache.emplace(entry->entry_id, entry);
}
static void add_entry(int entity_id, std::shared_ptr<Persistence::DataEntry> entry) {
add_entry(store[entity_id], entry);
}
static bool load_file(const std::filesystem::path & path, int entity_id) {
Json::Value json;
try {
std::ifstream file(path);
file >> json;
} catch (std::exception &) {
// empty file?
return false;
}
if (json.isArray()) {
auto & entity_store_entry = store[entity_id];
for (auto & value : json) {
std::shared_ptr<Persistence::DataEntry> entry(new Persistence::DataEntry(entity_id, value));
if (entry->key.empty())
continue;
// ensure fake DF IDs remain globally unique
next_fake_df_id = std::min(next_fake_df_id, entry->fake_df_id - 1);
add_entry(entity_store_entry, entry);
}
}
return true;
}
void Persistence::Internal::load(color_ostream& out) {
CoreSuspender suspend;
LastLoadSaveTickCountUpdater tickCountUpdater;
clear(out);
std::string world_name = World::ReadWorldFolder();
std::filesystem::path save_path = getSavePath(world_name);
std::vector<std::filesystem::path> files;
if (0 != Filesystem::listdir(save_path, files)) {
DEBUG(persistence,out).print("not loading state; save directory doesn't exist: '%s'\n", save_path.c_str());
return;
}
bool found = false;
for (auto & fname : files) {
int entity_id = Persistence::WORLD_ENTITY_ID;
if (fname != "dfhack-world.dat" && !get_entity_id(fname.string(), entity_id))
continue;
found = true;
std::filesystem::path path = save_path / fname;
if (!load_file(path, entity_id))
out.printerr("Cannot load data from: '%s'\n", path.c_str());
}
if (found)
return;
// new file formats not found; attempt to load legacy file
const std::filesystem::path legacy_fname = getSaveFilePath(world_name, "legacy-data");
if (Filesystem::exists(legacy_fname)) {
int synthesized_entity_id = Persistence::WORLD_ENTITY_ID;
if (World::IsSiteLoaded())
synthesized_entity_id = World::GetCurrentSiteId();
load_file(legacy_fname, synthesized_entity_id);
}
}
static bool is_good_entity_id(int entity_id) {
return entity_id == Persistence::WORLD_ENTITY_ID || entity_id >= 0;
}
PersistentDataItem Persistence::addItem(int entity_id, const std::string &key) {
if (!is_good_entity_id(entity_id) || key.empty() || !Core::getInstance().isWorldLoaded())
return PersistentDataItem();
CoreSuspender suspend;
auto ptr = std::shared_ptr<DataEntry>(new DataEntry(entity_id, key));
add_entry(entity_id, ptr);
return PersistentDataItem(ptr);
}
PersistentDataItem Persistence::getByKey(int entity_id, const std::string &key, bool *added) {
if (!is_good_entity_id(entity_id) || key.empty() || !Core::getInstance().isWorldLoaded())
return PersistentDataItem();
CoreSuspender suspend;
bool found = store.contains(entity_id) && store[entity_id].contains(key);
if (added)
*added = !found;
if (found)
return PersistentDataItem(store[entity_id].find(key)->second);
if (!added)
return PersistentDataItem();
return addItem(entity_id, key);
}
bool Persistence::deleteItem(const PersistentDataItem &item) {
if (!item.isValid())
return false;
CoreSuspender suspend;
int entity_id = item.entity_id();
auto range = store[entity_id].equal_range(item.key());
for (auto it = range.first; it != range.second; ++it) {
if (it->second->isReferencedBy(item)) {
entry_cache.erase(it->second->entry_id);
store[entity_id].erase(it);
break;
}
}
return true;
}
void Persistence::getAll(std::vector<PersistentDataItem> &vec, int entity_id) {
vec.clear();
if (!is_good_entity_id(entity_id) || !Core::getInstance().isWorldLoaded())
return;
CoreSuspender suspend;
if (!store.contains(entity_id))
return;
for (auto & entries : store[entity_id])
vec.emplace_back(entries.second);
}
void Persistence::getAllByKeyRange(std::vector<PersistentDataItem> &vec, int entity_id,
const std::string &min, const std::string &max) {
vec.clear();
if (!is_good_entity_id(entity_id) || !Core::getInstance().isWorldLoaded())
return;
CoreSuspender suspend;
if (!store.contains(entity_id))
return;
auto begin = store[entity_id].lower_bound(min);
auto end = store[entity_id].lower_bound(max);
for (auto it = begin; it != end; ++it)
vec.emplace_back(it->second);
}
void Persistence::getAllByKey(std::vector<PersistentDataItem> &vec, int entity_id, const std::string &key) {
vec.clear();
if (!is_good_entity_id(entity_id) || !Core::getInstance().isWorldLoaded())
return;
CoreSuspender suspend;
if (!store.contains(entity_id))
return;
auto range = store[entity_id].equal_range(key);
for (auto it = range.first; it != range.second; ++it)
vec.emplace_back(it->second);
}
uint32_t Persistence::getUnsavedSeconds() {
uint32_t durMS = Core::getInstance().p->getTickCount() - lastLoadSaveTickCount;
return durMS / 1000;
}