UnrealLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file UnrealLoader.cpp
  35. * @brief Implementation of the UNREAL (*.3D) importer class
  36. *
  37. * Sources:
  38. * http://local.wasp.uwa.edu.au/~pbourke/dataformats/unreal/
  39. */
  40. #ifndef ASSIMP_BUILD_NO_3D_IMPORTER
  41. #include "AssetLib/Unreal/UnrealLoader.h"
  42. #include "PostProcessing/ConvertToLHProcess.h"
  43. #include <assimp/ParsingUtils.h>
  44. #include <assimp/StreamReader.h>
  45. #include <assimp/fast_atof.h>
  46. #include <assimp/importerdesc.h>
  47. #include <assimp/scene.h>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/IOSystem.hpp>
  50. #include <assimp/Importer.hpp>
  51. #include <cstdint>
  52. #include <memory>
  53. namespace Assimp {
  54. namespace Unreal {
  55. // Mesh-specific fags.
  56. enum MeshFlags {
  57. MF_INVALID = -1, // Not set
  58. MF_NORMAL_OS = 0, // Normal one-sided
  59. MF_NORMAL_TS = 1, // Normal two-sided
  60. MF_NORMAL_TRANS_TS = 2, // Translucent two-sided
  61. MF_NORMAL_MASKED_TS = 3, // Masked two-sided
  62. MF_NORMAL_MOD_TS = 4, // Modulation blended two-sided
  63. MF_WEAPON_PLACEHOLDER = 8 // Placeholder triangle for weapon positioning (invisible)
  64. };
  65. // a single triangle
  66. struct Triangle {
  67. uint16_t mVertex[3]; // Vertex indices
  68. char mType; // James' Mesh Type
  69. char mColor; // Color for flat and Gourand Shaded
  70. unsigned char mTex[3][2]; // Texture UV coordinates
  71. unsigned char mTextureNum; // Source texture offset
  72. char mFlags; // Unreal Mesh Flags (unused)
  73. unsigned int matIndex; // Material index
  74. };
  75. // temporary representation for a material
  76. struct TempMat {
  77. TempMat() :
  78. type(MF_NORMAL_OS), tex(), numFaces(0) {}
  79. explicit TempMat(const Triangle &in) :
  80. type((Unreal::MeshFlags)in.mType), tex(in.mTextureNum), numFaces(0) {}
  81. // type of mesh
  82. Unreal::MeshFlags type;
  83. // index of texture
  84. unsigned int tex;
  85. // number of faces using us
  86. unsigned int numFaces;
  87. // for std::find
  88. bool operator==(const TempMat &o) {
  89. return (tex == o.tex && type == o.type);
  90. }
  91. };
  92. // A single vertex in an unsigned int 32 bit
  93. struct Vertex {
  94. int32_t X : 11;
  95. int32_t Y : 11;
  96. int32_t Z : 10;
  97. };
  98. // UNREAL vertex compression
  99. inline void CompressVertex(const aiVector3D &v, uint32_t &out) {
  100. union {
  101. Vertex n;
  102. int32_t t;
  103. };
  104. t = 0;
  105. n.X = (int32_t)v.x;
  106. n.Y = (int32_t)v.y;
  107. n.Z = (int32_t)v.z;
  108. ::memcpy(&out, &t, sizeof(int32_t));
  109. }
  110. // UNREAL vertex decompression
  111. inline void DecompressVertex(aiVector3D &v, int32_t in) {
  112. union {
  113. Vertex n;
  114. int32_t i;
  115. };
  116. i = in;
  117. v.x = (float)n.X;
  118. v.y = (float)n.Y;
  119. v.z = (float)n.Z;
  120. }
  121. } // end namespace Unreal
  122. static constexpr aiImporterDesc desc = {
  123. "Unreal Mesh Importer",
  124. "",
  125. "",
  126. "",
  127. aiImporterFlags_SupportTextFlavour,
  128. 0,
  129. 0,
  130. 0,
  131. 0,
  132. "3d uc"
  133. };
  134. // ------------------------------------------------------------------------------------------------
  135. // Constructor to be privately used by Importer
  136. UnrealImporter::UnrealImporter() :
  137. mConfigFrameID(0), mConfigHandleFlags(true) {
  138. // empty
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. // Returns whether the class can handle the format of the given file.
  142. bool UnrealImporter::CanRead(const std::string &filename, IOSystem * /*pIOHandler*/, bool /*checkSig*/) const {
  143. return SimpleExtensionCheck(filename, "3d", "uc");
  144. }
  145. // ------------------------------------------------------------------------------------------------
  146. // Build a string of all file extensions supported
  147. const aiImporterDesc *UnrealImporter::GetInfo() const {
  148. return &desc;
  149. }
  150. // ------------------------------------------------------------------------------------------------
  151. // Setup configuration properties for the loader
  152. void UnrealImporter::SetupProperties(const Importer *pImp) {
  153. // The
  154. // AI_CONFIG_IMPORT_UNREAL_KEYFRAME option overrides the
  155. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  156. mConfigFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_KEYFRAME, -1);
  157. if (static_cast<unsigned int>(-1) == mConfigFrameID) {
  158. mConfigFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME, 0);
  159. }
  160. // AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, default is true
  161. mConfigHandleFlags = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, 1));
  162. }
  163. // ------------------------------------------------------------------------------------------------
  164. // Imports the given file into the given scene structure.
  165. void UnrealImporter::InternReadFile(const std::string &pFile,
  166. aiScene *pScene, IOSystem *pIOHandler) {
  167. // For any of the 3 files being passed get the three correct paths
  168. // First of all, determine file extension
  169. std::string::size_type pos = pFile.find_last_of('.');
  170. std::string extension = GetExtension(pFile);
  171. std::string d_path, a_path, uc_path;
  172. if (extension == "3d") {
  173. // jjjj_d.3d
  174. // jjjj_a.3d
  175. pos = pFile.find_last_of('_');
  176. if (std::string::npos == pos) {
  177. throw DeadlyImportError("UNREAL: Unexpected naming scheme");
  178. }
  179. extension = pFile.substr(0, pos);
  180. } else {
  181. extension = pFile.substr(0, pos);
  182. }
  183. // build proper paths
  184. d_path = extension + "_d.3d";
  185. a_path = extension + "_a.3d";
  186. uc_path = extension + ".uc";
  187. ASSIMP_LOG_DEBUG("UNREAL: data file is ", d_path);
  188. ASSIMP_LOG_DEBUG("UNREAL: aniv file is ", a_path);
  189. ASSIMP_LOG_DEBUG("UNREAL: uc file is ", uc_path);
  190. // and open the files ... we can't live without them
  191. std::unique_ptr<IOStream> p(pIOHandler->Open(d_path));
  192. if (!p)
  193. throw DeadlyImportError("UNREAL: Unable to open _d file");
  194. StreamReaderLE d_reader(pIOHandler->Open(d_path));
  195. const uint16_t numTris = d_reader.GetI2();
  196. const uint16_t numVert = d_reader.GetI2();
  197. d_reader.IncPtr(44);
  198. if (!numTris || numVert < 3) {
  199. throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles");
  200. }
  201. // maximum texture index
  202. unsigned int maxTexIdx = 0;
  203. // collect triangles
  204. std::vector<Unreal::Triangle> triangles(numTris);
  205. for (auto &tri : triangles) {
  206. for (unsigned int i = 0; i < 3; ++i) {
  207. tri.mVertex[i] = d_reader.GetI2();
  208. if (tri.mVertex[i] >= numTris) {
  209. ASSIMP_LOG_WARN("UNREAL: vertex index out of range");
  210. tri.mVertex[i] = 0;
  211. }
  212. }
  213. tri.mType = d_reader.GetI1();
  214. // handle mesh flagss?
  215. if (mConfigHandleFlags) {
  216. tri.mType = Unreal::MF_NORMAL_OS;
  217. } else {
  218. // ignore MOD and MASKED for the moment, treat them as two-sided
  219. if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS)
  220. tri.mType = Unreal::MF_NORMAL_TS;
  221. }
  222. d_reader.IncPtr(1);
  223. for (unsigned int i = 0; i < 3; ++i) {
  224. for (unsigned int i2 = 0; i2 < 2; ++i2) {
  225. tri.mTex[i][i2] = d_reader.GetI1();
  226. }
  227. }
  228. tri.mTextureNum = d_reader.GetI1();
  229. maxTexIdx = std::max(maxTexIdx, (unsigned int)tri.mTextureNum);
  230. d_reader.IncPtr(1);
  231. }
  232. p.reset(pIOHandler->Open(a_path));
  233. if (!p) {
  234. throw DeadlyImportError("UNREAL: Unable to open _a file");
  235. }
  236. StreamReaderLE a_reader(pIOHandler->Open(a_path));
  237. // read number of frames
  238. const uint32_t numFrames = a_reader.GetI2();
  239. if (mConfigFrameID >= numFrames) {
  240. throw DeadlyImportError("UNREAL: The requested frame does not exist");
  241. }
  242. // read aniv file length
  243. if (uint32_t st = a_reader.GetI2(); st != numVert * 4u) {
  244. throw DeadlyImportError("UNREAL: Unexpected aniv file length");
  245. }
  246. // skip to our frame
  247. a_reader.IncPtr(mConfigFrameID * numVert * 4);
  248. // collect vertices
  249. std::vector<aiVector3D> vertices(numVert);
  250. for (auto &vertex : vertices) {
  251. int32_t val = a_reader.GetI4();
  252. Unreal::DecompressVertex(vertex, val);
  253. }
  254. // list of textures.
  255. std::vector<std::pair<unsigned int, std::string>> textures;
  256. // allocate the output scene
  257. aiNode *nd = pScene->mRootNode = new aiNode();
  258. nd->mName.Set("<UnrealRoot>");
  259. // we can live without the uc file if necessary
  260. std::unique_ptr<IOStream> pb(pIOHandler->Open(uc_path));
  261. if (pb) {
  262. std::vector<char> _data;
  263. TextFileToBuffer(pb.get(), _data);
  264. const char *data = &_data[0];
  265. const char *end = &_data[_data.size() - 1] + 1;
  266. std::vector<std::pair<std::string, std::string>> tempTextures;
  267. // do a quick search in the UC file for some known, usually texture-related, tags
  268. for (; *data; ++data) {
  269. if (TokenMatchI(data, "#exec", 5)) {
  270. SkipSpacesAndLineEnd(&data, end);
  271. // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...]
  272. if (TokenMatchI(data, "TEXTURE", 7)) {
  273. SkipSpacesAndLineEnd(&data, end);
  274. if (TokenMatchI(data, "IMPORT", 6)) {
  275. tempTextures.emplace_back();
  276. std::pair<std::string, std::string> &me = tempTextures.back();
  277. for (; !IsLineEnd(*data); ++data) {
  278. if (!ASSIMP_strincmp(data, "NAME=", 5)) {
  279. const char *d = data += 5;
  280. for (; !IsSpaceOrNewLine(*data); ++data)
  281. ;
  282. me.first = std::string(d, (size_t)(data - d));
  283. } else if (!ASSIMP_strincmp(data, "FILE=", 5)) {
  284. const char *d = data += 5;
  285. for (; !IsSpaceOrNewLine(*data); ++data)
  286. ;
  287. me.second = std::string(d, (size_t)(data - d));
  288. }
  289. }
  290. if (!me.first.length() || !me.second.length()) {
  291. tempTextures.pop_back();
  292. }
  293. }
  294. }
  295. // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1
  296. // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2
  297. else if (TokenMatchI(data, "MESHMAP", 7)) {
  298. SkipSpacesAndLineEnd(&data, end);
  299. if (TokenMatchI(data, "SETTEXTURE", 10)) {
  300. textures.emplace_back();
  301. std::pair<unsigned int, std::string> &me = textures.back();
  302. for (; !IsLineEnd(*data); ++data) {
  303. if (!ASSIMP_strincmp(data, "NUM=", 4)) {
  304. data += 4;
  305. me.first = strtoul10(data, &data);
  306. } else if (!ASSIMP_strincmp(data, "TEXTURE=", 8)) {
  307. data += 8;
  308. const char *d = data;
  309. for (; !IsSpaceOrNewLine(*data); ++data);
  310. me.second = std::string(d, (size_t)(data - d));
  311. // try to find matching path names, doesn't care if we don't find them
  312. for (std::vector<std::pair<std::string, std::string>>::const_iterator it = tempTextures.begin();
  313. it != tempTextures.end(); ++it) {
  314. if ((*it).first == me.second) {
  315. me.second = (*it).second;
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. } else if (TokenMatchI(data, "SCALE", 5)) {
  322. for (; !IsLineEnd(*data); ++data) {
  323. if (data[0] == 'X' && data[1] == '=') {
  324. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.a1);
  325. } else if (data[0] == 'Y' && data[1] == '=') {
  326. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.b2);
  327. } else if (data[0] == 'Z' && data[1] == '=') {
  328. data = fast_atoreal_move<float>(data + 2, (float &)nd->mTransformation.c3);
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }
  335. } else {
  336. ASSIMP_LOG_ERROR("Unable to open .uc file");
  337. }
  338. std::vector<Unreal::TempMat> materials;
  339. materials.reserve(textures.size() * 2 + 5);
  340. // find out how many output meshes and materials we'll have and build material indices
  341. for (auto &tri : triangles) {
  342. Unreal::TempMat mat(tri);
  343. auto nt = std::find(materials.begin(), materials.end(), mat);
  344. if (nt == materials.end()) {
  345. // add material
  346. tri.matIndex = static_cast<unsigned int>(materials.size());
  347. mat.numFaces = 1;
  348. materials.push_back(mat);
  349. ++pScene->mNumMeshes;
  350. } else {
  351. tri.matIndex = static_cast<unsigned int>(nt - materials.begin());
  352. ++nt->numFaces;
  353. }
  354. }
  355. if (!pScene->mNumMeshes) {
  356. throw DeadlyImportError("UNREAL: Unable to find valid mesh data");
  357. }
  358. // allocate meshes and bind them to the node graph
  359. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  360. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials = pScene->mNumMeshes];
  361. nd->mNumMeshes = pScene->mNumMeshes;
  362. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  363. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  364. aiMesh *m = pScene->mMeshes[i] = new aiMesh();
  365. m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  366. const unsigned int num = materials[i].numFaces;
  367. m->mFaces = new aiFace[num];
  368. m->mVertices = new aiVector3D[num * 3];
  369. m->mTextureCoords[0] = new aiVector3D[num * 3];
  370. nd->mMeshes[i] = i;
  371. // create materials, too
  372. aiMaterial *mat = new aiMaterial();
  373. pScene->mMaterials[i] = mat;
  374. // all white by default - texture rulez
  375. aiColor3D color(1.f, 1.f, 1.f);
  376. aiString s;
  377. ::ai_snprintf(s.data, AI_MAXLEN, "mat%u_tx%u_", i, materials[i].tex);
  378. // set the two-sided flag
  379. if (materials[i].type == Unreal::MF_NORMAL_TS) {
  380. const int twosided = 1;
  381. mat->AddProperty(&twosided, 1, AI_MATKEY_TWOSIDED);
  382. ::strcat(s.data, "ts_");
  383. } else
  384. ::strcat(s.data, "os_");
  385. // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us
  386. if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) {
  387. const float opac = 0.9f;
  388. mat->AddProperty(&opac, 1, AI_MATKEY_OPACITY);
  389. ::strcat(s.data, "tran_");
  390. } else
  391. ::strcat(s.data, "opaq_");
  392. // a special name for the weapon attachment point
  393. if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) {
  394. s.length = ::ai_snprintf(s.data, AI_MAXLEN, "$WeaponTag$");
  395. color = aiColor3D(0.f, 0.f, 0.f);
  396. }
  397. // set color and name
  398. mat->AddProperty(&color, 1, AI_MATKEY_COLOR_DIFFUSE);
  399. s.length = static_cast<ai_uint32>(::strlen(s.data));
  400. mat->AddProperty(&s, AI_MATKEY_NAME);
  401. // set texture, if any
  402. const unsigned int tex = materials[i].tex;
  403. for (auto it = textures.begin(); it != textures.end(); ++it) {
  404. if ((*it).first == tex) {
  405. s.Set((*it).second);
  406. mat->AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(0));
  407. break;
  408. }
  409. }
  410. }
  411. // fill them.
  412. for (const Unreal::Triangle &tri : triangles) {
  413. Unreal::TempMat mat(tri);
  414. auto nt = std::find(materials.begin(), materials.end(), mat);
  415. aiMesh *mesh = pScene->mMeshes[nt - materials.begin()];
  416. aiFace &f = mesh->mFaces[mesh->mNumFaces++];
  417. f.mIndices = new unsigned int[f.mNumIndices = 3];
  418. for (unsigned int i = 0; i < 3; ++i, mesh->mNumVertices++) {
  419. f.mIndices[i] = mesh->mNumVertices;
  420. mesh->mVertices[mesh->mNumVertices] = vertices[tri.mVertex[i]];
  421. mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D(tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f);
  422. }
  423. }
  424. // convert to RH
  425. MakeLeftHandedProcess hero;
  426. hero.Execute(pScene);
  427. FlipWindingOrderProcess flipper;
  428. flipper.Execute(pScene);
  429. }
  430. } // namespace Assimp
  431. #endif // !! ASSIMP_BUILD_NO_3D_IMPORTER