asset_manager.cpp 11.6 KB
Newer Older
1
2
#include <mirrage/asset/asset_manager.hpp>

3
4
#include <mirrage/asset/error.hpp>

5
#include <mirrage/utils/log.hpp>
6
#include <mirrage/utils/template_utils.hpp>
7
8
9
10

#include <physfs.h>

#include <cstdio>
11
#include <cstring>
12

Florian Oetke's avatar
Florian Oetke committed
13
#ifdef _WIN32
14
15
#include <direct.h>
#include <windows.h>
16
#else
17
18
#include <sys/stat.h>
#include <unistd.h>
19
20
21
#endif


22
using namespace mirrage::util;
23
using namespace std::string_literals;
24
25
26
27
28

namespace {

	std::string append_file(const std::string& folder, const std::string file) {
		if(ends_with(folder, "/") || starts_with(file, "/"))
29
			return folder + file;
30
		else
31
			return folder + "/" + file;
32
33
	}
	void create_dir(const std::string& dir) {
Florian Oetke's avatar
Florian Oetke committed
34
#ifdef _WIN32
35
36
37
38
39
40
41
42
		CreateDirectory(dir.c_str(), NULL);
#else
		mkdir(dir.c_str(), 0777);
#endif
	}

	auto last_of(const std::string& str, char c) {
		auto idx = str.find_last_of(c);
43
		return idx != std::string::npos ? mirrage::util::just(idx + 1) : mirrage::util::nothing;
44
45
46
	}

	auto split_path(const std::string& path) {
47
		auto filename_delim_end = last_of(path, '/').get_or(last_of(path, '\\').get_or(0));
48

49
		return std::make_tuple(path.substr(0, filename_delim_end - 1),
50
51
52
53
		                       path.substr(filename_delim_end, std::string::npos));
	}


54
55
56
	std::vector<std::string> list_files(const std::string& dir,
	                                    const std::string& prefix,
	                                    const std::string& suffix) noexcept {
57
58
		std::vector<std::string> res;

59
		char** rc = PHYSFS_enumerateFiles(dir.c_str());
60

61
		for(char** i = rc; *i != nullptr; i++) {
62
63
			std::string str(*i);

64
65
			if((prefix.length() == 0 || str.find(prefix) == 0)
			   && (suffix.length() == 0 || str.find(suffix) == str.length() - suffix.length()))
66
67
68
69
70
71
72
73
				res.emplace_back(std::move(str));
		}

		PHYSFS_freeList(rc);

		return res;
	}
	std::vector<std::string> list_wildcard_files(const std::string& wildcard_path) {
74
		auto   spr  = split_path(wildcard_path);
75
76
77
		auto&& path = std::get<0>(spr);
		auto&& file = std::get<1>(spr);

78
		auto wildcard = last_of(file, '*').get_or(file.length());
79
80
		LOG_IF(plog::warning, wildcard != file.find_first_of('*') + 1)
		        << "More than one wildcard ist currently not supported. Found in: " << wildcard_path;
81

82
83
		auto prefix = file.substr(0, wildcard - 1);
		auto suffix = wildcard < file.length() ? file.substr(0, wildcard - 1) : std::string();
84
85
86
87
88
89
90
91
92
93

		auto files = list_files(path, prefix, suffix);
		for(auto& file : files) {
			file = path + "/" + file;
		}

		return files;
	}

	bool exists_file(const std::string path) {
94
		if(!PHYSFS_exists(path.c_str()))
95
96
97
			return false;

		auto stat = PHYSFS_Stat{};
98
		if(!PHYSFS_stat(path.c_str(), &stat))
99
100
101
			return false;

		return stat.filetype == PHYSFS_FILETYPE_REGULAR;
102
103
	}
	bool exists_dir(const std::string path) {
104
		if(!PHYSFS_exists(path.c_str()))
105
106
107
			return false;

		auto stat = PHYSFS_Stat{};
108
		if(!PHYSFS_stat(path.c_str(), &stat))
109
110
111
			return false;

		return stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
112
113
	}

114
115
	template <typename Callback>
	void print_dir_recursiv(const std::string& dir, uint8_t depth, Callback&& callback) {
116
		std::string p;
117
118
		for(uint8_t i = 0; i < depth; i++)
			p += "  ";
119

120
		callback(p + dir);
121
122
		depth++;
		for(auto&& f : list_files(dir, "", "")) {
123
			if(depth >= 5)
124
				callback(p + "  " + f);
125
			else
126
127
128
129
130
131
132
133
				print_dir_recursiv(f, depth, callback);
		}
	}

	void init_physicsfs(const std::string& exe_name) {
		if(!PHYSFS_isInit() && !PHYSFS_init(exe_name.empty() ? nullptr : exe_name.c_str())) {
			throw std::system_error(static_cast<mirrage::asset::Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to initalize PhysicsFS.");
134
135
136
		}
	}

137
	constexpr auto default_source = {std::make_tuple("assets", false), std::make_tuple("assets.zip", true)};
138
} // namespace
139

140
namespace mirrage::asset {
141
142
143
144

	std::string pwd() {
		char cCurrentPath[FILENAME_MAX];

145
146
147
#ifdef WINDOWS
		_getcwd(cCurrentPath, sizeof(cCurrentPath));
#else
148
149
150
		if(getcwd(cCurrentPath, sizeof(cCurrentPath)) == nullptr) {
			MIRRAGE_FAIL("getcwd with max length " << FILENAME_MAX << " failed with error code " << errno);
		}
151
#endif
152
153
154

		return cCurrentPath;
	}
155
156
157
158
	std::string write_dir(const std::string& exe_name,
	                      const std::string& org_name,
	                      const std::string& app_name) {
		init_physicsfs(exe_name);
159

160
161
162
		if(exists_dir("write_dir")) {
			return "write_dir";
		}
163

164
		return PHYSFS_getPrefDir(org_name.c_str(), app_name.c_str());
165
	}
166

167

168
169
170
	Asset_manager::Asset_manager(const std::string& exe_name,
	                             const std::string& org_name,
	                             const std::string& app_name) {
171
		init_physicsfs(exe_name);
172

173
		auto write_dir = ::mirrage::asset::write_dir(exe_name, org_name, app_name);
174

175
176
177
178
179
		if(!PHYSFS_mount(PHYSFS_getBaseDir(), nullptr, 1)
		   || !PHYSFS_mount(append_file(PHYSFS_getBaseDir(), "..").c_str(), nullptr, 1)
		   || !PHYSFS_mount(pwd().c_str(), nullptr, 1))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to setup default search path.");
180

181
182
		create_dir(write_dir);

183
		LOG(plog::debug) << "Write dir: " << write_dir;
184

185
		if(!PHYSFS_mount(write_dir.c_str(), nullptr, 0))
186
187
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to construct search path.");
188

189
		if(!PHYSFS_setWriteDir(write_dir.c_str()))
190
191
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to set write-dir: "s + write_dir);
192
193
194


		auto add_source = [](const char* path) {
195
196
197
			if(!PHYSFS_mount(path, nullptr, 1))
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "Error adding custom archive: "s + path);
198
199
		};

200
		if(!exists_file("archives.lst")) {
201
202
203
			bool lost = true;
			for(auto& s : default_source) {
				const char* path;
204
				bool        file;
205
206
207
208
209
210
211
212
213
214

				std::tie(path, file) = s;

				if(file ? exists_file(path) : exists_dir(path)) {
					add_source(path);
					lost = false;
				}
			}

			if(lost) {
215
216
				LOG(plog::fatal) << "No archives.lst found. printing search-path...\n";
				print_dir_recursiv("/", 0, [](auto&& path) { LOG(plog::fatal) << path; });
217

218
219
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "No archives.lst found.");
220
221

			} else {
222
				LOG(plog::info) << "No archives.lst found. Using defaults.";
223
224
225
			}

		} else {
226
227
			auto in = _open("cfg:archives.lst"_aid, "archives.lst");

228
			// load other archives
229
230
231
			for(auto&& l : in.lines()) {
				if(l.find_last_of('*') != std::string::npos) {
					for(auto& file : list_wildcard_files(l)) {
232
						LOG(plog::info) << "Added FS directory: " << file;
233
						add_source(file.c_str());
234
					}
235
					continue;
236
				}
237
238
				add_source(l.c_str());
			}
239
240
241
242
243
244
		}

		_reload_dispatchers();
	}

	Asset_manager::~Asset_manager() {
245
246
		_containers.clear();
		if(!PHYSFS_deinit()) {
247
248
			MIRRAGE_FAIL(
			        "Unable to shutdown PhysicsFS: " << PHYSFS_getErrorByCode((PHYSFS_getLastErrorCode())));
249
		}
250
251
	}

252
253
	void Asset_manager::reload() {
		_reload_dispatchers();
254

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
		// The container lock must not be held during reload, because the reload of an asset calls
		//   third-party code that might call into the asset_manager.
		// So we first collect all relevant containers and then iterate over that list.
		auto containers = std::vector<detail::Asset_container_base*>();
		{
			auto lock = std::scoped_lock{_containers_mutex};
			containers.reserve(_containers.size());

			for(auto& container : _containers) {
				containers.emplace_back(container.second.get());
			}
		}

		for(auto& c : containers) {
			c->reload();
270
271
		}
	}
272
273
	void Asset_manager::shrink_to_fit() noexcept {
		auto lock = std::scoped_lock{_containers_mutex};
274

275
276
277
		for(auto& container : _containers) {
			container.second->shrink_to_fit();
		}
278
279
	}

280
281
282
283
	auto Asset_manager::exists(const AID& id) const noexcept -> bool {
		return resolve(id).process(false, [](auto&& path) { return exists_file(path); });
	}
	auto Asset_manager::try_delete(const AID& id) -> bool {
284
		return resolve(id).process(true, [](auto&& path) { return PHYSFS_delete(path.c_str()) == 0; });
285
	}
286

287
288
289
290
291
292
	auto Asset_manager::open(const AID& id) -> util::maybe<istream> {
		auto path = resolve(id);

		if(path.is_some() && exists_file(path.get_or_throw()))
			return _open(id, path.get_or_throw());
		else
293
			return util::nothing;
294
295
296
297
298
299
300
301
	}
	auto Asset_manager::open_rw(const AID& id) -> ostream {
		auto path = resolve(id);
		if(path.is_nothing()) {
			path = resolve(AID{id.type(), ""}).process(id.str(), [&](auto&& prefix) {
				return append_file(prefix, id.str());
			});
		};
302

303
304
305
306
		if(exists_file(path.get_or_throw()))
			PHYSFS_delete(path.get_or_throw().c_str());

		return _open_rw(id, path.get_or_throw());
307
308
	}

309
310
311
	auto Asset_manager::list(Asset_type type) -> std::vector<AID> {
		auto lock = std::shared_lock{_dispatchers_mutex};

312
313
		std::vector<AID> res;

314
		for(auto& d : _dispatchers) {
315
			if(d.first.type() == type && d.first.name().size() > 0)
316
317
318
				res.emplace_back(d.first);
		}

319
		_base_dir(type).process([&](const std::string& dir) {
320
321
322
323
324
325
326
327
328
			for(auto&& f : list_files(dir, "", ""))
				res.emplace_back(type, f);
		});

		sort(res.begin(), res.end());
		res.erase(std::unique(res.begin(), res.end()), res.end());

		return res;
	}
329
330
	auto Asset_manager::last_modified(const AID& id) const noexcept -> util::maybe<std::int64_t> {
		using namespace std::literals;
331

332
		return resolve(id).process([&](auto& path) { return _last_modified(path); });
333
334
	}

335
336
	auto Asset_manager::resolve(const AID& id, bool only_preexisting) const noexcept
	        -> util::maybe<std::string> {
337
		auto lock = std::shared_lock{_dispatchers_mutex};
338

339
		auto res = _dispatchers.find(id);
340

341
		if(res != _dispatchers.end() && (exists_file(res->second) || !only_preexisting))
342
			return res->second;
343

344
345
		else if(exists_file(id.name()))
			return id.name();
346
347
348
349
350
351
352


		auto baseDir = _base_dir(id.type());

		if(baseDir.is_some()) {
			auto path = append_file(baseDir.get_or_throw(), id.name());
			if(exists_file(path))
353
				return std::move(path);
354
355
356
357
358
359
360
361
362

			else if(!only_preexisting) {
				PHYSFS_mkdir(baseDir.get_or_throw().c_str());
				return std::move(path);
			}
		}

		if(!only_preexisting) {
			return id.name();
363
364
		}

365
		return util::nothing;
366
	}
367
368
	auto Asset_manager::resolve_reverse(std::string_view path) -> util::maybe<AID> {
		auto lock = std::shared_lock{_dispatchers_mutex};
369

370
371
372
		for(auto& e : _dispatchers) {
			if(e.second == path)
				return e.first;
373
374
		}

375
		return util::nothing;
376
377
	}

378
	void Asset_manager::_post_write() {}
379

380
381
	auto Asset_manager::_base_dir(Asset_type type) const -> util::maybe<std::string> {
		auto lock = std::shared_lock{_dispatchers_mutex};
382

383
		auto dir = _dispatchers.find(AID{type, ""}); // search for prefix-entry
384

385
		if(dir == _dispatchers.end())
386
387
			return util::nothing;

388
389
		std::string bdir = dir->second;
		return bdir;
390
391
	}

392
393
	void Asset_manager::_reload_dispatchers() {
		auto lock = std::unique_lock{_dispatchers_mutex};
394

395
		_dispatchers.clear();
396

397
		for(auto&& df : list_files("", "assets", ".map")) {
398
			LOG(plog::info) << "Added asset mapping: " << df;
399
400
401
402
403
404
			auto in = _open({}, df);
			for(auto&& l : in.lines()) {
				auto        kvp  = util::split(l, "=");
				std::string path = util::trim_copy(kvp.second);
				if(!path.empty()) {
					_dispatchers.emplace(AID{kvp.first}, std::move(path));
405
406
407
408
409
				}
			}
		}
	}

410
411
	auto Asset_manager::_last_modified(const std::string& path) const -> int64_t {
		auto stat = PHYSFS_Stat{};
412
413
		if(!PHYSFS_stat(path.c_str(), &stat))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()));
414

415
		return stat.modtime;
416
	}
417
418
	auto Asset_manager::_open(const asset::AID& id, const std::string& path) -> istream {
		return {id, *this, path};
419
	}
420
421
	auto Asset_manager::_open_rw(const asset::AID& id, const std::string& path) -> ostream {
		return {id, *this, path};
422
423
	}

424
} // namespace mirrage::asset