asset_manager.cpp 11.7 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

namespace {

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

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

49
50
	auto split_path(const std::string& path)
	{
51
		auto filename_delim_end = last_of(path, '/').get_or(last_of(path, '\\').get_or(0));
52

53
		return std::make_tuple(path.substr(0, filename_delim_end - 1),
54
55
56
57
		                       path.substr(filename_delim_end, std::string::npos));
	}


58
59
	std::vector<std::string> list_files(const std::string& dir,
	                                    const std::string& prefix,
60
61
	                                    const std::string& suffix) noexcept
	{
62
63
		std::vector<std::string> res;

64
		char** rc = PHYSFS_enumerateFiles(dir.c_str());
65

66
		for(char** i = rc; *i != nullptr; i++) {
67
68
			std::string str(*i);

69
70
			if((prefix.length() == 0 || str.find(prefix) == 0)
			   && (suffix.length() == 0 || str.find(suffix) == str.length() - suffix.length()))
71
72
73
74
75
76
77
				res.emplace_back(std::move(str));
		}

		PHYSFS_freeList(rc);

		return res;
	}
78
79
	std::vector<std::string> list_wildcard_files(const std::string& wildcard_path)
	{
80
		auto   spr  = split_path(wildcard_path);
81
82
83
		auto&& path = std::get<0>(spr);
		auto&& file = std::get<1>(spr);

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

88
89
		auto prefix = file.substr(0, wildcard - 1);
		auto suffix = wildcard < file.length() ? file.substr(0, wildcard - 1) : std::string();
90
91
92
93
94
95
96
97
98

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

		return files;
	}

99
100
	bool exists_file(const std::string path)
	{
101
		if(!PHYSFS_exists(path.c_str()))
102
103
104
			return false;

		auto stat = PHYSFS_Stat{};
105
		if(!PHYSFS_stat(path.c_str(), &stat))
106
107
108
			return false;

		return stat.filetype == PHYSFS_FILETYPE_REGULAR;
109
	}
110
111
	bool exists_dir(const std::string path)
	{
112
		if(!PHYSFS_exists(path.c_str()))
113
114
115
			return false;

		auto stat = PHYSFS_Stat{};
116
		if(!PHYSFS_stat(path.c_str(), &stat))
117
118
119
			return false;

		return stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
120
121
	}

122
	template <typename Callback>
123
124
	void print_dir_recursiv(const std::string& dir, uint8_t depth, Callback&& callback)
	{
125
		std::string p;
126
127
		for(uint8_t i = 0; i < depth; i++)
			p += "  ";
128

129
		callback(p + dir);
130
131
		depth++;
		for(auto&& f : list_files(dir, "", "")) {
132
			if(depth >= 5)
133
				callback(p + "  " + f);
134
			else
135
136
137
138
				print_dir_recursiv(f, depth, callback);
		}
	}

139
140
	void init_physicsfs(const std::string& exe_name)
	{
141
142
143
144
		if(PHYSFS_isInit())
			return;

		if(!PHYSFS_init(exe_name.empty() ? nullptr : exe_name.c_str())) {
145
146
			throw std::system_error(static_cast<mirrage::asset::Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to initalize PhysicsFS.");
147
		}
148
149
150
151
152
153

		if(!PHYSFS_mount(PHYSFS_getBaseDir(), nullptr, 1)
		   || !PHYSFS_mount(append_file(PHYSFS_getBaseDir(), "..").c_str(), nullptr, 1)
		   || !PHYSFS_mount(mirrage::asset::pwd().c_str(), nullptr, 1))
			throw std::system_error(static_cast<mirrage::asset::Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to setup default search path.");
154
155
	}

156
	constexpr auto default_source = {std::make_tuple("assets", false), std::make_tuple("assets.zip", true)};
157
} // namespace
158

159
namespace mirrage::asset {
160

161
162
	std::string pwd()
	{
163
164
		char cCurrentPath[FILENAME_MAX];

165
166
167
#ifdef WINDOWS
		_getcwd(cCurrentPath, sizeof(cCurrentPath));
#else
168
169
170
		if(getcwd(cCurrentPath, sizeof(cCurrentPath)) == nullptr) {
			MIRRAGE_FAIL("getcwd with max length " << FILENAME_MAX << " failed with error code " << errno);
		}
171
#endif
172
173
174

		return cCurrentPath;
	}
175
176
	std::string write_dir(const std::string& exe_name,
	                      const std::string& org_name,
177
178
	                      const std::string& app_name)
	{
179
		init_physicsfs(exe_name);
180

181
		if(exists_dir("write_dir")) {
182
			return std::string(PHYSFS_getRealDir("write_dir")) + "/write_dir";
183
		}
184

185
		return PHYSFS_getPrefDir(org_name.c_str(), app_name.c_str());
186
	}
187

188

189
190
	Asset_manager::Asset_manager(const std::string& exe_name,
	                             const std::string& org_name,
191
192
	                             const std::string& app_name)
	{
193
		init_physicsfs(exe_name);
194

195
		auto write_dir = ::mirrage::asset::write_dir(exe_name, org_name, app_name);
196
		create_dir(write_dir);
197
		LOG(plog::debug) << "Write dir: " << write_dir;
198

199
		if(!PHYSFS_mount(write_dir.c_str(), nullptr, 0))
200
201
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to construct search path.");
202

203
		if(!PHYSFS_setWriteDir(write_dir.c_str()))
204
205
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to set write-dir: "s + write_dir);
206
207
208


		auto add_source = [](const char* path) {
209
			LOG(plog::info) << "Added FS directory: " << path;
210
211
212
			if(!PHYSFS_mount(path, nullptr, 1))
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "Error adding custom archive: "s + path);
213
214
		};

215
		if(!exists_file("archives.lst")) {
216
217
218
			bool lost = true;
			for(auto& s : default_source) {
				const char* path;
219
				bool        file;
220
221
222
223
224
225
226
227
228
229

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

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

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

233
234
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "No archives.lst found.");
235
			} else {
236
				LOG(plog::info) << "No archives.lst found. Using defaults.";
237
238
			}
		} else {
239
240
			auto in = _open("cfg:archives.lst"_aid, "archives.lst");

241
			// load other archives
242
243
244
245
			for(auto&& l : in.lines()) {
				if(l.find_last_of('*') != std::string::npos) {
					for(auto& file : list_wildcard_files(l)) {
						add_source(file.c_str());
246
					}
247
					continue;
248
				}
249
250
				add_source(l.c_str());
			}
251
252
253
254
255
		}

		_reload_dispatchers();
	}

256
257
	Asset_manager::~Asset_manager()
	{
258
259
		_containers.clear();
		if(!PHYSFS_deinit()) {
260
261
			MIRRAGE_FAIL(
			        "Unable to shutdown PhysicsFS: " << PHYSFS_getErrorByCode((PHYSFS_getLastErrorCode())));
262
		}
263
264
	}

265
266
	void Asset_manager::reload()
	{
267
		_reload_dispatchers();
268

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
		// 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();
284
285
		}
	}
286
287
	void Asset_manager::shrink_to_fit() noexcept
	{
288
		auto lock = std::scoped_lock{_containers_mutex};
289

290
291
292
		for(auto& container : _containers) {
			container.second->shrink_to_fit();
		}
293
294
	}

295
296
	auto Asset_manager::exists(const AID& id) const noexcept -> bool
	{
297
298
		return resolve(id).process(false, [](auto&& path) { return exists_file(path); });
	}
299
300
	auto Asset_manager::try_delete(const AID& id) -> bool
	{
301
		return resolve(id).process(true, [](auto&& path) { return PHYSFS_delete(path.c_str()) == 0; });
302
	}
303

304
305
	auto Asset_manager::open(const AID& id) -> util::maybe<istream>
	{
306
307
308
309
310
		auto path = resolve(id);

		if(path.is_some() && exists_file(path.get_or_throw()))
			return _open(id, path.get_or_throw());
		else
311
			return util::nothing;
312
	}
313
314
	auto Asset_manager::open_rw(const AID& id) -> ostream
	{
315
316
317
318
319
320
		auto path = resolve(id);
		if(path.is_nothing()) {
			path = resolve(AID{id.type(), ""}).process(id.str(), [&](auto&& prefix) {
				return append_file(prefix, id.str());
			});
		};
321

322
323
324
325
		if(exists_file(path.get_or_throw()))
			PHYSFS_delete(path.get_or_throw().c_str());

		return _open_rw(id, path.get_or_throw());
326
327
	}

328
329
	auto Asset_manager::list(Asset_type type) -> std::vector<AID>
	{
330
331
		auto lock = std::shared_lock{_dispatchers_mutex};

332
333
		std::vector<AID> res;

334
		for(auto& d : _dispatchers) {
335
			if(d.first.type() == type && d.first.name().size() > 0)
336
337
338
				res.emplace_back(d.first);
		}

339
		_base_dir(type).process([&](const std::string& dir) {
340
341
342
343
344
345
346
347
348
			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;
	}
349
350
	auto Asset_manager::last_modified(const AID& id) const noexcept -> util::maybe<std::int64_t>
	{
351
		using namespace std::literals;
352

353
		return resolve(id).process([&](auto& path) { return _last_modified(path); });
354
355
	}

356
	auto Asset_manager::resolve(const AID& id, bool only_preexisting) const noexcept
357
358
	        -> util::maybe<std::string>
	{
359
		auto lock = std::shared_lock{_dispatchers_mutex};
360

361
		auto res = _dispatchers.find(id);
362

363
		if(res != _dispatchers.end() && (exists_file(res->second) || !only_preexisting))
364
			return res->second;
365

366
367
		else if(exists_file(id.name()))
			return id.name();
368
369
370
371
372
373
374


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

		if(baseDir.is_some()) {
			auto path = append_file(baseDir.get_or_throw(), id.name());
			if(exists_file(path))
375
				return std::move(path);
376
377
378
379
380
381
382
383
384

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

		if(!only_preexisting) {
			return id.name();
385
386
		}

387
		return util::nothing;
388
	}
389
390
	auto Asset_manager::resolve_reverse(std::string_view path) -> util::maybe<AID>
	{
391
		auto lock = std::shared_lock{_dispatchers_mutex};
392

393
394
395
		for(auto& e : _dispatchers) {
			if(e.second == path)
				return e.first;
396
397
		}

398
		return util::nothing;
399
400
	}

401
	void Asset_manager::_post_write() {}
402

403
404
	auto Asset_manager::_base_dir(Asset_type type) const -> util::maybe<std::string>
	{
405
		auto lock = std::shared_lock{_dispatchers_mutex};
406

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

409
		if(dir == _dispatchers.end())
410
411
			return util::nothing;

412
413
		std::string bdir = dir->second;
		return bdir;
414
415
	}

416
417
	void Asset_manager::_reload_dispatchers()
	{
418
		auto lock = std::unique_lock{_dispatchers_mutex};
419

420
		_dispatchers.clear();
421

422
		for(auto&& df : list_files("", "assets", ".map")) {
423
			LOG(plog::info) << "Added asset mapping: " << df;
424
425
426
427
428
429
			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));
430
431
432
433
434
				}
			}
		}
	}

435
436
	auto Asset_manager::_last_modified(const std::string& path) const -> int64_t
	{
437
		auto stat = PHYSFS_Stat{};
438
439
		if(!PHYSFS_stat(path.c_str(), &stat))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()));
440

441
		return stat.modtime;
442
	}
443
444
	auto Asset_manager::_open(const asset::AID& id, const std::string& path) -> istream
	{
445
		return {id, *this, path};
446
	}
447
448
	auto Asset_manager::_open_rw(const asset::AID& id, const std::string& path) -> ostream
	{
449
		return {id, *this, path};
450
451
	}

452
} // namespace mirrage::asset