1 /* Copyright (C) 2018 Wildfire Games.
2  * This file is part of 0 A.D.
3  *
4  * 0 A.D. is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * 0 A.D. is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #ifndef INCLUDED_CACHELOADER
19 #define INCLUDED_CACHELOADER
20 
21 #include "lib/file/vfs/vfs.h"
22 
23 class MD5;
24 
25 /**
26  * Helper class for systems that have an expensive cacheable conversion process
27  * when loading files.
28  *
29  * Conversion output can be automatically cached as loose files, indexed by a hash
30  * of the file's timestamp and size plus any other data the caller provides.
31  * This allows developers and modders to easily produce new files, with the conversion
32  * happening transparently.
33  *
34  * For release packages, files can be precached by appending ".cached.{extension}"
35  * to their name, which will be used instead of doing runtime conversion.
36  * These cache files will typically be packed into an archive for faster loading;
37  * if no archive cache is available then the source file will be converted and stored
38  * as a loose cache file instead.
39  */
40 class CCacheLoader
41 {
42 public:
43 	CCacheLoader(PIVFS vfs, const std::wstring& fileExtension);
44 
45 	/**
46 	 * Attempts to find a valid cached which can be loaded.
47 	 * Returns INFO::OK and sets loadPath to the cached file if there is one.
48 	 * Returns INFO::SKIPPED and sets loadPath to the desire loose cache name if there isn't one.
49 	 * Returns a value < 0 on error (e.g. the source file doesn't exist). No error is logged or thrown.
50 	 */
51 	Status TryLoadingCached(const VfsPath& sourcePath, const MD5& initialHash, u32 version, VfsPath& loadPath);
52 
53 	/**
54 	 * Determines whether we can safely use the archived cache file, or need to
55 	 * re-convert the source file.
56 	 */
57 	bool CanUseArchiveCache(const VfsPath& sourcePath, const VfsPath& archiveCachePath);
58 
59 	/**
60 	 * Return the path of the archive cache for the given source file.
61 	 */
62 	VfsPath ArchiveCachePath(const VfsPath& sourcePath) const;
63 
64 	/**
65 	 * Return the path of the loose cache for the given source file.
66 	 */
67 	VfsPath LooseCachePath(const VfsPath& sourcePath, const MD5& initialHash, u32 version);
68 
69 private:
70 	PIVFS m_VFS;
71 	std::wstring m_FileExtension;
72 };
73 
74 #endif // INCLUDED_CACHELOADER
75