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

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

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

#include <physfs.h>

#include <cstdio>
12
#include <cstring>
13

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


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

namespace {

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

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

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

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


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

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

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

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

		PHYSFS_freeList(rc);

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

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

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

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

		return files;
	}

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

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

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

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

		return stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
121
122
	}

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

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

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

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

		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.");
155
156
	}

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

160
namespace mirrage::asset {
161

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

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

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

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

186
		return PHYSFS_getPrefDir(org_name.c_str(), app_name.c_str());
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
209
210
211
212
213
214
215
216
217
218
219
		for(auto ea : Embedded_asset::instances()) {
			LOG(plog::info) << "Include embedded asset \"" << ea->name() << "\": " << ea->data().size()
			                << " bytes";
			if(!PHYSFS_mountMemory(ea->data().data(),
			                       static_cast<PHYSFS_uint64>(ea->data().size_bytes()),
			                       nullptr,
			                       "embedded.zip",
			                       nullptr,
			                       0)) {
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "Unable to add embedded archive: "s + ea->name());
			}
		}
220
221

		auto add_source = [](const char* path) {
222
			LOG(plog::info) << "Added FS directory: " << path;
223
224
225
			if(!PHYSFS_mount(path, nullptr, 1))
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "Error adding custom archive: "s + path);
226
227
		};

228
		if(!exists_file("archives.lst")) {
229
230
231
			bool lost = true;
			for(auto& s : default_source) {
				const char* path;
232
				bool        file;
233
234
235
236
237
238
239
240
241
242

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

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

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

246
247
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "No archives.lst found.");
248
			} else {
249
				LOG(plog::info) << "No archives.lst found. Using defaults.";
250
251
			}
		} else {
252
253
			auto in = _open("cfg:archives.lst"_aid, "archives.lst");

254
			// load other archives
255
256
257
258
			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());
259
					}
260
					continue;
261
				}
262
263
				add_source(l.c_str());
			}
264
265
266
267
268
		}

		_reload_dispatchers();
	}

269
270
	Asset_manager::~Asset_manager()
	{
271
272
		_containers.clear();
		if(!PHYSFS_deinit()) {
273
274
			MIRRAGE_FAIL(
			        "Unable to shutdown PhysicsFS: " << PHYSFS_getErrorByCode((PHYSFS_getLastErrorCode())));
275
		}
276
277
	}

278
279
	void Asset_manager::reload()
	{
280
		_reload_dispatchers();
281

282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
		// 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();
297
298
		}
	}
299
300
	void Asset_manager::shrink_to_fit() noexcept
	{
301
		auto lock = std::scoped_lock{_containers_mutex};
302

303
304
305
		for(auto& container : _containers) {
			container.second->shrink_to_fit();
		}
306
307
	}

308
309
	auto Asset_manager::exists(const AID& id) const noexcept -> bool
	{
310
311
		return resolve(id).process(false, [](auto&& path) { return exists_file(path); });
	}
312
313
	auto Asset_manager::try_delete(const AID& id) -> bool
	{
314
		return resolve(id).process(true, [](auto&& path) { return PHYSFS_delete(path.c_str()) == 0; });
315
	}
316

317
318
	auto Asset_manager::open(const AID& id) -> util::maybe<istream>
	{
319
320
321
322
323
		auto path = resolve(id);

		if(path.is_some() && exists_file(path.get_or_throw()))
			return _open(id, path.get_or_throw());
		else
324
			return util::nothing;
325
	}
326
327
	auto Asset_manager::open_rw(const AID& id) -> ostream
	{
328
329
330
331
332
333
		auto path = resolve(id);
		if(path.is_nothing()) {
			path = resolve(AID{id.type(), ""}).process(id.str(), [&](auto&& prefix) {
				return append_file(prefix, id.str());
			});
		};
334

335
336
337
338
		if(exists_file(path.get_or_throw()))
			PHYSFS_delete(path.get_or_throw().c_str());

		return _open_rw(id, path.get_or_throw());
339
340
	}

341
342
	auto Asset_manager::list(Asset_type type) -> std::vector<AID>
	{
343
344
		auto lock = std::shared_lock{_dispatchers_mutex};

345
346
		std::vector<AID> res;

347
		for(auto& d : _dispatchers) {
348
			if(d.first.type() == type && d.first.name().size() > 0)
349
350
351
				res.emplace_back(d.first);
		}

352
		_base_dir(type).process([&](const std::string& dir) {
353
354
355
356
357
358
359
360
361
			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;
	}
362
363
	auto Asset_manager::last_modified(const AID& id) const noexcept -> util::maybe<std::int64_t>
	{
364
		using namespace std::literals;
365

366
		return resolve(id).process([&](auto& path) { return _last_modified(path); });
367
368
	}

369
	auto Asset_manager::resolve(const AID& id, bool only_preexisting) const noexcept
370
371
	        -> util::maybe<std::string>
	{
372
		auto lock = std::shared_lock{_dispatchers_mutex};
373

374
		auto res = _dispatchers.find(id);
375

376
		if(res != _dispatchers.end() && (exists_file(res->second) || !only_preexisting))
377
			return res->second;
378

379
380
		else if(exists_file(id.name()))
			return id.name();
381
382
383
384
385
386
387


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

		if(baseDir.is_some()) {
			auto path = append_file(baseDir.get_or_throw(), id.name());
			if(exists_file(path))
388
				return std::move(path);
389
390
391
392
393
394
395
396
397

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

		if(!only_preexisting) {
			return id.name();
398
399
		}

400
		return util::nothing;
401
	}
402
403
	auto Asset_manager::resolve_reverse(std::string_view path) -> util::maybe<AID>
	{
404
		auto lock = std::shared_lock{_dispatchers_mutex};
405

406
407
408
		for(auto& e : _dispatchers) {
			if(e.second == path)
				return e.first;
409
410
		}

411
		return util::nothing;
412
413
	}

414
	void Asset_manager::_post_write() {}
415

416
417
	auto Asset_manager::_base_dir(Asset_type type) const -> util::maybe<std::string>
	{
418
		auto lock = std::shared_lock{_dispatchers_mutex};
419

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

422
		if(dir == _dispatchers.end())
423
424
			return util::nothing;

425
426
		std::string bdir = dir->second;
		return bdir;
427
428
	}

429
430
	void Asset_manager::_reload_dispatchers()
	{
431
		auto lock = std::unique_lock{_dispatchers_mutex};
432

433
		_dispatchers.clear();
434

435
		for(auto&& df : list_files("", "assets", ".map")) {
436
			LOG(plog::info) << "Added asset mapping: " << df;
437
438
439
440
441
442
			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));
443
444
445
446
447
				}
			}
		}
	}

448
449
	auto Asset_manager::_last_modified(const std::string& path) const -> int64_t
	{
450
		auto stat = PHYSFS_Stat{};
451
452
		if(!PHYSFS_stat(path.c_str(), &stat))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()));
453

454
		return stat.modtime;
455
	}
456
457
	auto Asset_manager::_open(const asset::AID& id, const std::string& path) -> istream
	{
458
		return {id, *this, path};
459
	}
460
461
	auto Asset_manager::_open_rw(const asset::AID& id, const std::string& path) -> ostream
	{
462
		return {id, *this, path};
463
464
	}

465
} // namespace mirrage::asset