Line data Source code
1 : /* Copyright (C) 2026 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 : #include "precompiled.h"
19 :
20 : #include "ColladaManager.h"
21 :
22 : #include "lib/debug.h"
23 : #include "lib/file/file_system.h"
24 : #include "lib/file/io/write_buffer.h"
25 : #include "lib/file/vfs/vfs_util.h"
26 : #include "lib/path.h"
27 : #include "lib/status.h"
28 : #include "maths/MD5.h"
29 : #include "ps/CLogger.h"
30 : #include "ps/CStr.h"
31 : #include "ps/CacheLoader.h"
32 : #include "ps/DllLoader.h"
33 : #include "ps/Errors.h"
34 : #include "ps/Filesystem.h"
35 :
36 : #include <algorithm>
37 : #include <cstddef>
38 : #include <string>
39 : #include <vector>
40 :
41 : namespace Collada
42 : {
43 : #include "collada/DLL.h"
44 : }
45 :
46 : namespace
47 : {
48 45 : void ColladaLog(void* cb_data, int severity, const char* text)
49 : {
50 45 : VfsPath* path = static_cast<VfsPath*>(cb_data);
51 :
52 45 : if (severity == LOG_INFO)
53 164 : LOGMESSAGE("{}: {}", path->string8(), text);
54 4 : else if (severity == LOG_WARNING)
55 0 : LOGWARNING("{}: {}", path->string8(), text);
56 : else
57 16 : LOGERROR("{}: {}", path->string8(), text);
58 45 : }
59 :
60 8 : void ColladaOutput(void* cb_data, const char* data, unsigned int length)
61 : {
62 8 : WriteBuffer* writeBuffer = static_cast<WriteBuffer*>(cb_data);
63 8 : writeBuffer->Append(data, (size_t)length);
64 8 : }
65 : }
66 :
67 : class CColladaManagerImpl
68 : {
69 : DllLoader dll;
70 :
71 : void (*set_logger)(Collada::LogFn logger, void* cb_data);
72 : int (*set_skeleton_definitions)(const char* xml, int length);
73 : int (*convert_dae_to_pmd)(const char* dae, Collada::OutputFn pmd_writer, void* cb_data);
74 : int (*convert_dae_to_psa)(const char* dae, Collada::OutputFn psa_writer, void* cb_data);
75 :
76 : public:
77 12 : CColladaManagerImpl(const PIVFS& vfs)
78 12 : : dll("Collada"), m_VFS(vfs), m_skeletonHashInvalidated(true)
79 : {
80 : // Support hotloading
81 12 : RegisterFileReloadFunc(ReloadChangedFileCB, this);
82 12 : }
83 :
84 12 : ~CColladaManagerImpl()
85 : {
86 12 : if (dll.IsLoaded())
87 6 : set_logger(NULL, NULL); // unregister the log handler
88 12 : UnregisterFileReloadFunc(ReloadChangedFileCB, this);
89 36 : }
90 :
91 0 : Status ReloadChangedFile(const VfsPath& path)
92 : {
93 : // Ignore files that aren't in the right path
94 0 : if (!path.string().starts_with(L"art/skeletons/"))
95 : return INFO::OK;
96 :
97 0 : if (path.Extension() != L".xml")
98 0 : return INFO::OK;
99 :
100 0 : m_skeletonHashInvalidated = true;
101 :
102 : // If the file doesn't exist (e.g. it was deleted), don't bother reloading
103 : // or 'unloading' since that isn't possible
104 0 : if (!VfsFileExists(path))
105 : return INFO::OK;
106 :
107 0 : if (!dll.IsLoaded() && !TryLoadDLL())
108 : return ERR::FAIL;
109 :
110 0 : LOGMESSAGE("Hotloading skeleton definitions from '{}'", path.string8());
111 : // Set the filename for the logger to report
112 0 : set_logger(ColladaLog, const_cast<void*>(static_cast<const void*>(&path)));
113 :
114 0 : CVFSFile skeletonFile;
115 0 : if (skeletonFile.Load(m_VFS, path) != PSRETURN_OK)
116 : {
117 0 : LOGERROR("Failed to read skeleton definitions from '{}'", path.string8());
118 0 : return ERR::FAIL;
119 : }
120 :
121 0 : int ok = set_skeleton_definitions((const char*)skeletonFile.GetBuffer(), (int)skeletonFile.GetBufferSize());
122 0 : if (ok < 0)
123 : {
124 0 : LOGERROR("Failed to load skeleton definitions from '{}'", path.string8());
125 0 : return ERR::FAIL;
126 : }
127 :
128 : return INFO::OK;
129 0 : }
130 :
131 0 : static Status ReloadChangedFileCB(void* param, const VfsPath& path)
132 : {
133 0 : return static_cast<CColladaManagerImpl*>(param)->ReloadChangedFile(path);
134 : }
135 :
136 7 : bool Convert(const VfsPath& daeFilename, const VfsPath& pmdFilename, CColladaManager::FileType type)
137 : {
138 : // To avoid always loading the DLL when it's usually not going to be
139 : // used (and to do the same on Linux where delay-loading won't help),
140 : // and to avoid compile-time dependencies (because it's a minor pain
141 : // to get all the right libraries to build the COLLADA DLL), we load
142 : // it dynamically when it is required, instead of using the exported
143 : // functions and binding at link-time.
144 7 : if (!dll.IsLoaded())
145 : {
146 7 : if (!TryLoadDLL())
147 : return false;
148 :
149 7 : if (!LoadSkeletonDefinitions())
150 : {
151 1 : dll.Unload(); // Error should have been logged already
152 1 : return false;
153 : }
154 : }
155 :
156 : // Set the filename for the logger to report
157 6 : set_logger(ColladaLog, const_cast<void*>(static_cast<const void*>(&daeFilename)));
158 :
159 : // We need to null-terminate the buffer, so do it (possibly inefficiently)
160 : // by converting to a CStr
161 6 : CStr daeData;
162 6 : {
163 6 : CVFSFile daeFile;
164 6 : if (daeFile.Load(m_VFS, daeFilename) != PSRETURN_OK)
165 0 : return false;
166 12 : daeData = daeFile.GetAsString();
167 6 : }
168 :
169 : // Do the conversion into a memory buffer
170 : // We need to check the result, as archive builder needs to know if the source dae
171 : // was sucessfully converted to .pmd/psa
172 6 : int result = -1;
173 6 : WriteBuffer writeBuffer;
174 6 : switch (type)
175 : {
176 6 : case CColladaManager::PMD:
177 6 : result = convert_dae_to_pmd(daeData.c_str(), ColladaOutput, &writeBuffer);
178 : break;
179 0 : case CColladaManager::PSA:
180 0 : result = convert_dae_to_psa(daeData.c_str(), ColladaOutput, &writeBuffer);
181 : break;
182 : }
183 :
184 : // don't create zero-length files (as happens in test_invalid_dae when
185 : // we deliberately pass invalid XML data) because the VFS caching
186 : // logic warns when asked to load such.
187 6 : if (writeBuffer.Size())
188 : {
189 5 : Status ret = m_VFS->CreateFile(pmdFilename, {writeBuffer.Data().get(), writeBuffer.Size()});
190 5 : ENSURE(ret == INFO::OK);
191 : }
192 :
193 6 : return (result == 0);
194 13 : }
195 :
196 7 : bool TryLoadDLL()
197 : {
198 7 : if (!dll.LoadDLL())
199 : {
200 0 : LOGERROR("Failed to load COLLADA conversion DLL");
201 0 : return false;
202 : }
203 :
204 7 : try
205 : {
206 7 : dll.LoadSymbol("set_logger", set_logger);
207 7 : dll.LoadSymbol("set_skeleton_definitions", set_skeleton_definitions);
208 7 : dll.LoadSymbol("convert_dae_to_pmd", convert_dae_to_pmd);
209 14 : dll.LoadSymbol("convert_dae_to_psa", convert_dae_to_psa);
210 : }
211 0 : catch (PSERROR_DllLoader&)
212 : {
213 0 : LOGERROR("Failed to load symbols from COLLADA conversion DLL");
214 0 : dll.Unload();
215 0 : return false;
216 0 : }
217 : return true;
218 : }
219 :
220 7 : bool LoadSkeletonDefinitions()
221 : {
222 7 : VfsPaths pathnames;
223 14 : if (vfs::GetPathnames(m_VFS, L"art/skeletons/", L"*.xml", pathnames) < 0)
224 : {
225 0 : LOGERROR("No skeleton definition files present");
226 0 : return false;
227 : }
228 :
229 7 : bool loaded = false;
230 14 : for (const VfsPath& path : pathnames)
231 : {
232 21 : LOGMESSAGE("Loading skeleton definitions from '{}'", path.string8());
233 : // Set the filename for the logger to report
234 7 : set_logger(ColladaLog, const_cast<void*>(static_cast<const void*>(&path)));
235 :
236 7 : CVFSFile skeletonFile;
237 7 : if (skeletonFile.Load(m_VFS, path) != PSRETURN_OK)
238 : {
239 0 : LOGERROR("Failed to read skeleton definitions from '{}'", path.string8());
240 0 : continue;
241 0 : }
242 :
243 7 : int ok = set_skeleton_definitions((const char*)skeletonFile.GetBuffer(), (int)skeletonFile.GetBufferSize());
244 7 : if (ok < 0)
245 : {
246 3 : LOGERROR("Failed to load skeleton definitions from '{}'", path.string8());
247 1 : continue;
248 1 : }
249 :
250 6 : loaded = true;
251 7 : }
252 :
253 7 : if (!loaded)
254 2 : LOGERROR("Failed to load any skeleton definitions");
255 :
256 : return loaded;
257 7 : }
258 :
259 : /**
260 : * Creates MD5 hash key from skeletons.xml info and COLLADA converter version,
261 : * used to invalidate cached .pmd/psas
262 : *
263 : * @param[out] hash resulting MD5 hash
264 : * @param[out] version version passed to CCacheLoader, used if code change should force
265 : * cache invalidation
266 : */
267 13 : void PrepareCacheKey(MD5& hash, std::uint32_t& version)
268 : {
269 : // Add converter version to the hash
270 13 : version = COLLADA_CONVERTER_VERSION;
271 :
272 : // Cache the skeleton files hash data
273 13 : if (m_skeletonHashInvalidated)
274 : {
275 12 : VfsPaths paths;
276 24 : if (vfs::GetPathnames(m_VFS, L"art/skeletons/", L"*.xml", paths) != INFO::OK)
277 : {
278 0 : LOGWARNING("Failed to load skeleton definitions");
279 0 : return;
280 : }
281 :
282 : // Sort the paths to not invalidate the cache if mods are mounted in different order
283 : // (No need to stable_sort as the VFS gurantees that we have no duplicates)
284 12 : std::sort(paths.begin(), paths.end());
285 :
286 : // We need two u64s per file
287 12 : m_skeletonHashes.clear();
288 12 : m_skeletonHashes.reserve(paths.size()*2);
289 :
290 12 : CFileInfo fileInfo;
291 24 : for (const VfsPath& path : paths)
292 : {
293 : // This will cause an assertion failure if *it doesn't exist,
294 : // because fileinfo is not a NULL pointer, which is annoying but that
295 : // should never happen, unless there really is a problem
296 12 : if (m_VFS->GetFileInfo(path, &fileInfo) != INFO::OK)
297 : {
298 0 : LOGERROR("Failed to stat '{}' for DAE caching", path.string8());
299 : }
300 : else
301 : {
302 12 : m_skeletonHashes.push_back(static_cast<std::uint64_t>(fileInfo.MTime()) & ~1); //skip lowest bit, since zip and FAT don't preserve it
303 12 : m_skeletonHashes.push_back(static_cast<std::uint64_t>(fileInfo.Size()));
304 : }
305 : }
306 :
307 : // Check if we were able to load any skeleton files
308 12 : if (m_skeletonHashes.empty())
309 0 : LOGERROR("Failed to stat any skeleton definitions for DAE caching");
310 : // We can continue, something else will break if we try loading a skeletal model
311 :
312 12 : m_skeletonHashInvalidated = false;
313 12 : }
314 :
315 39 : for (const std::uint64_t& h : m_skeletonHashes)
316 26 : hash.Update(reinterpret_cast<const std::uint8_t*>(&h), sizeof(h));
317 : }
318 :
319 : private:
320 : PIVFS m_VFS;
321 : bool m_skeletonHashInvalidated;
322 : std::vector<std::uint64_t> m_skeletonHashes;
323 : };
324 :
325 12 : CColladaManager::CColladaManager(const PIVFS& vfs)
326 12 : : m(new CColladaManagerImpl(vfs)), m_VFS(vfs)
327 : {
328 12 : }
329 :
330 12 : CColladaManager::~CColladaManager()
331 : {
332 12 : delete m;
333 12 : }
334 :
335 13 : VfsPath CColladaManager::GetLoadablePath(const VfsPath& pathnameNoExtension, FileType type)
336 : {
337 13 : std::wstring extn;
338 13 : switch (type)
339 : {
340 13 : case PMD: extn = L".pmd"; break;
341 0 : case PSA: extn = L".psa"; break;
342 : // no other alternatives
343 : }
344 :
345 : /*
346 :
347 : Algorithm:
348 : * Calculate hash of skeletons.xml and converter version.
349 : * Use CCacheLoader to check for archived or loose cached .pmd/psa.
350 : * If cached version exists:
351 : * Return pathname of cached .pmd/psa.
352 : * Else, if source .dae for this model exists:
353 : * Convert it to cached .pmd/psa.
354 : * If converter succeeded:
355 : * Return pathname of cached .pmd/psa.
356 : * Else, fail (return empty path).
357 : * Else, if uncached .pmd/psa exists:
358 : * Return pathname of uncached .pmd/psa.
359 : * Else, fail (return empty path).
360 :
361 : Since we use CCacheLoader which automatically hashes file size and mtime,
362 : and handles archived files and loose cache, when preparing the cache key
363 : we add converter version number (so updates of the converter cause
364 : regeneration of the .pmd/psa) and the global skeletons.xml file size and
365 : mtime, as modelers frequently change the contents of skeletons.xml and get
366 : perplexed if the in-game models haven't updated as expected (we don't know
367 : which models were affected by the skeletons.xml change, if any, so we just
368 : regenerate all of them)
369 :
370 : TODO (maybe): The .dae -> .pmd/psa conversion may fail (e.g. if the .dae is
371 : invalid or unsupported), but it may take a long time to start the conversion
372 : then realise it's not going to work. That will delay the loading of the game
373 : every time, which is annoying, so maybe it should cache the error message
374 : until the .dae is updated and fixed. (Alternatively, avoid having that many
375 : broken .daes in the game.)
376 :
377 : */
378 :
379 : // Now we're looking for cached files
380 26 : CCacheLoader cacheLoader(m_VFS, extn);
381 13 : MD5 hash;
382 13 : std::uint32_t version;
383 13 : m->PrepareCacheKey(hash, version);
384 :
385 26 : VfsPath cachePath;
386 26 : VfsPath sourcePath = pathnameNoExtension.ChangeExtension(L".dae");
387 13 : Status ret = cacheLoader.TryLoadingCached(sourcePath, hash, version, cachePath);
388 :
389 13 : if (ret == INFO::OK)
390 : // Found a valid cached version
391 1 : return cachePath;
392 :
393 : // No valid cached version, check if we have a source .dae
394 12 : if (ret != INFO::SKIPPED)
395 : {
396 : // No valid cached version was found, and no source .dae exists
397 5 : ENSURE(ret < 0);
398 :
399 : // Check if source (uncached) .pmd/psa exists
400 25 : sourcePath = pathnameNoExtension.ChangeExtension(extn);
401 5 : if (m_VFS->GetFileInfo(sourcePath, NULL) != INFO::OK)
402 : {
403 : // Broken reference, the caller will need to handle this
404 2 : return L"";
405 : }
406 : else
407 : {
408 3 : return sourcePath;
409 : }
410 : }
411 :
412 : // No valid cached version was found - but source .dae exists
413 : // We'll try converting it
414 :
415 : // We have a source .dae and invalid cached version, so regenerate cached version
416 7 : if (! m->Convert(sourcePath, cachePath, type))
417 : {
418 : // The COLLADA converter failed for some reason, this will need to be handled
419 : // by the caller
420 2 : return L"";
421 : }
422 :
423 5 : return cachePath;
424 13 : }
425 :
426 0 : bool CColladaManager::GenerateCachedFile(const VfsPath& sourcePath, FileType type, VfsPath& archiveCachePath)
427 : {
428 0 : std::wstring extn;
429 0 : switch (type)
430 : {
431 0 : case PMD: extn = L".pmd"; break;
432 0 : case PSA: extn = L".psa"; break;
433 : // no other alternatives
434 : }
435 :
436 0 : CCacheLoader cacheLoader(m_VFS, extn);
437 :
438 0 : archiveCachePath = cacheLoader.ArchiveCachePath(sourcePath);
439 :
440 0 : return m->Convert(sourcePath, VfsPath("cache") / archiveCachePath, type);
441 0 : }
|