Q3DLoader.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 Q3DLoader.cpp
  35. * @brief Implementation of the Q3D importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_Q3D_IMPORTER
  38. // internal headers
  39. #include "Q3DLoader.h"
  40. #include <assimp/StringUtils.h>
  41. #include <assimp/StreamReader.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/importerdesc.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/DefaultLogger.hpp>
  46. #include <assimp/IOSystem.hpp>
  47. using namespace Assimp;
  48. static const aiImporterDesc desc = {
  49. "Quick3D Importer",
  50. "",
  51. "",
  52. "http://www.quick3d.com/",
  53. aiImporterFlags_SupportBinaryFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "q3o q3s"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Constructor to be privately used by Importer
  62. Q3DImporter::Q3DImporter() {
  63. // empty
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // Destructor, private as well
  67. Q3DImporter::~Q3DImporter() {
  68. // empty
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Returns whether the class can handle the format of the given file.
  72. bool Q3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  73. static const char *tokens[] = { "quick3Do", "quick3Ds" };
  74. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. const aiImporterDesc *Q3DImporter::GetInfo() const {
  78. return &desc;
  79. }
  80. // ------------------------------------------------------------------------------------------------
  81. // Imports the given file into the given scene structure.
  82. void Q3DImporter::InternReadFile(const std::string &pFile,
  83. aiScene *pScene, IOSystem *pIOHandler) {
  84. auto file = pIOHandler->Open(pFile, "rb");
  85. if (!file)
  86. throw DeadlyImportError("Quick3D: Could not open ", pFile);
  87. StreamReaderLE stream(file);
  88. // The header is 22 bytes large
  89. if (stream.GetRemainingSize() < 22)
  90. throw DeadlyImportError("File is either empty or corrupt: ", pFile);
  91. // Check the file's signature
  92. if (ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Do", 8) &&
  93. ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Ds", 8)) {
  94. throw DeadlyImportError("Not a Quick3D file. Signature string is: ", ai_str_toprintable((const char *)stream.GetPtr(), 8));
  95. }
  96. // Print the file format version
  97. ASSIMP_LOG_INFO("Quick3D File format version: ",
  98. std::string(&((const char *)stream.GetPtr())[8], 2));
  99. // ... an store it
  100. char major = ((const char *)stream.GetPtr())[8];
  101. char minor = ((const char *)stream.GetPtr())[9];
  102. stream.IncPtr(10);
  103. unsigned int numMeshes = (unsigned int)stream.GetI4();
  104. unsigned int numMats = (unsigned int)stream.GetI4();
  105. unsigned int numTextures = (unsigned int)stream.GetI4();
  106. std::vector<Material> materials;
  107. materials.reserve(numMats);
  108. std::vector<Mesh> meshes;
  109. meshes.reserve(numMeshes);
  110. // Allocate the scene root node
  111. pScene->mRootNode = new aiNode();
  112. aiColor3D fgColor(0.6f, 0.6f, 0.6f);
  113. // Now read all file chunks
  114. while (true) {
  115. if (stream.GetRemainingSize() < 1) break;
  116. char c = stream.GetI1();
  117. switch (c) {
  118. // Meshes chunk
  119. case 'm': {
  120. for (unsigned int quak = 0; quak < numMeshes; ++quak) {
  121. meshes.push_back(Mesh());
  122. Mesh &mesh = meshes.back();
  123. // read all vertices
  124. unsigned int numVerts = (unsigned int)stream.GetI4();
  125. if (!numVerts)
  126. throw DeadlyImportError("Quick3D: Found mesh with zero vertices");
  127. std::vector<aiVector3D> &verts = mesh.verts;
  128. verts.resize(numVerts);
  129. for (unsigned int i = 0; i < numVerts; ++i) {
  130. verts[i].x = stream.GetF4();
  131. verts[i].y = stream.GetF4();
  132. verts[i].z = stream.GetF4();
  133. }
  134. // read all faces
  135. numVerts = (unsigned int)stream.GetI4();
  136. if (!numVerts)
  137. throw DeadlyImportError("Quick3D: Found mesh with zero faces");
  138. std::vector<Face> &faces = mesh.faces;
  139. faces.reserve(numVerts);
  140. // number of indices
  141. for (unsigned int i = 0; i < numVerts; ++i) {
  142. faces.push_back(Face(stream.GetI2()));
  143. if (faces.back().indices.empty())
  144. throw DeadlyImportError("Quick3D: Found face with zero indices");
  145. }
  146. // indices
  147. for (unsigned int i = 0; i < numVerts; ++i) {
  148. Face &vec = faces[i];
  149. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a)
  150. vec.indices[a] = stream.GetI4();
  151. }
  152. // material indices
  153. for (unsigned int i = 0; i < numVerts; ++i) {
  154. faces[i].mat = (unsigned int)stream.GetI4();
  155. }
  156. // read all normals
  157. numVerts = (unsigned int)stream.GetI4();
  158. std::vector<aiVector3D> &normals = mesh.normals;
  159. normals.resize(numVerts);
  160. for (unsigned int i = 0; i < numVerts; ++i) {
  161. normals[i].x = stream.GetF4();
  162. normals[i].y = stream.GetF4();
  163. normals[i].z = stream.GetF4();
  164. }
  165. numVerts = (unsigned int)stream.GetI4();
  166. if (numTextures && numVerts) {
  167. // read all texture coordinates
  168. std::vector<aiVector3D> &uv = mesh.uv;
  169. uv.resize(numVerts);
  170. for (unsigned int i = 0; i < numVerts; ++i) {
  171. uv[i].x = stream.GetF4();
  172. uv[i].y = stream.GetF4();
  173. }
  174. // UV indices
  175. for (unsigned int i = 0; i < (unsigned int)faces.size(); ++i) {
  176. Face &vec = faces[i];
  177. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a) {
  178. vec.uvindices[a] = stream.GetI4();
  179. if (!i && !a)
  180. mesh.prevUVIdx = vec.uvindices[a];
  181. else if (vec.uvindices[a] != mesh.prevUVIdx)
  182. mesh.prevUVIdx = UINT_MAX;
  183. }
  184. }
  185. }
  186. // we don't need the rest, but we need to get to the next chunk
  187. stream.IncPtr(36);
  188. if (minor > '0' && major == '3')
  189. stream.IncPtr(mesh.faces.size());
  190. }
  191. // stream.IncPtr(4); // unknown value here
  192. } break;
  193. // materials chunk
  194. case 'c':
  195. for (unsigned int i = 0; i < numMats; ++i) {
  196. materials.push_back(Material());
  197. Material &mat = materials.back();
  198. // read the material name
  199. c = stream.GetI1();
  200. while (c) {
  201. mat.name.data[mat.name.length++] = c;
  202. c = stream.GetI1();
  203. }
  204. // add the terminal character
  205. mat.name.data[mat.name.length] = '\0';
  206. // read the ambient color
  207. mat.ambient.r = stream.GetF4();
  208. mat.ambient.g = stream.GetF4();
  209. mat.ambient.b = stream.GetF4();
  210. // read the diffuse color
  211. mat.diffuse.r = stream.GetF4();
  212. mat.diffuse.g = stream.GetF4();
  213. mat.diffuse.b = stream.GetF4();
  214. // read the ambient color
  215. mat.specular.r = stream.GetF4();
  216. mat.specular.g = stream.GetF4();
  217. mat.specular.b = stream.GetF4();
  218. // read the transparency
  219. mat.transparency = stream.GetF4();
  220. // unknown value here
  221. // stream.IncPtr(4);
  222. // FIX: it could be the texture index ...
  223. mat.texIdx = (unsigned int)stream.GetI4();
  224. }
  225. break;
  226. // texture chunk
  227. case 't':
  228. pScene->mNumTextures = numTextures;
  229. if (!numTextures) {
  230. break;
  231. }
  232. pScene->mTextures = new aiTexture *[pScene->mNumTextures];
  233. // to make sure we won't crash if we leave through an exception
  234. ::memset(pScene->mTextures, 0, sizeof(void *) * pScene->mNumTextures);
  235. for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {
  236. aiTexture *tex = pScene->mTextures[i] = new aiTexture;
  237. // skip the texture name
  238. while (stream.GetI1())
  239. ;
  240. // read texture width and height
  241. tex->mWidth = (unsigned int)stream.GetI4();
  242. tex->mHeight = (unsigned int)stream.GetI4();
  243. if (!tex->mWidth || !tex->mHeight) {
  244. throw DeadlyImportError("Quick3D: Invalid texture. Width or height is zero");
  245. }
  246. unsigned int mul = tex->mWidth * tex->mHeight;
  247. aiTexel *begin = tex->pcData = new aiTexel[mul];
  248. aiTexel *const end = &begin[mul - 1] + 1;
  249. for (; begin != end; ++begin) {
  250. begin->r = stream.GetI1();
  251. begin->g = stream.GetI1();
  252. begin->b = stream.GetI1();
  253. begin->a = 0xff;
  254. }
  255. }
  256. break;
  257. // scene chunk
  258. case 's': {
  259. // skip position and rotation
  260. stream.IncPtr(12);
  261. for (unsigned int i = 0; i < 4; ++i)
  262. for (unsigned int a = 0; a < 4; ++a)
  263. pScene->mRootNode->mTransformation[i][a] = stream.GetF4();
  264. stream.IncPtr(16);
  265. // now setup a single camera
  266. pScene->mNumCameras = 1;
  267. pScene->mCameras = new aiCamera *[1];
  268. aiCamera *cam = pScene->mCameras[0] = new aiCamera();
  269. cam->mPosition.x = stream.GetF4();
  270. cam->mPosition.y = stream.GetF4();
  271. cam->mPosition.z = stream.GetF4();
  272. cam->mName.Set("Q3DCamera");
  273. // skip eye rotation for the moment
  274. stream.IncPtr(12);
  275. // read the default material color
  276. fgColor.r = stream.GetF4();
  277. fgColor.g = stream.GetF4();
  278. fgColor.b = stream.GetF4();
  279. // skip some unimportant properties
  280. stream.IncPtr(29);
  281. // setup a single point light with no attenuation
  282. pScene->mNumLights = 1;
  283. pScene->mLights = new aiLight *[1];
  284. aiLight *light = pScene->mLights[0] = new aiLight();
  285. light->mName.Set("Q3DLight");
  286. light->mType = aiLightSource_POINT;
  287. light->mAttenuationConstant = 1;
  288. light->mAttenuationLinear = 0;
  289. light->mAttenuationQuadratic = 0;
  290. light->mColorDiffuse.r = stream.GetF4();
  291. light->mColorDiffuse.g = stream.GetF4();
  292. light->mColorDiffuse.b = stream.GetF4();
  293. light->mColorSpecular = light->mColorDiffuse;
  294. // We don't need the rest, but we need to know where this chunk ends.
  295. unsigned int temp = (unsigned int)(stream.GetI4() * stream.GetI4());
  296. // skip the background file name
  297. while (stream.GetI1())
  298. ;
  299. // skip background texture data + the remaining fields
  300. stream.IncPtr(temp * 3 + 20); // 4 bytes of unknown data here
  301. // TODO
  302. goto outer;
  303. } break;
  304. default:
  305. throw DeadlyImportError("Quick3D: Unknown chunk");
  306. break;
  307. };
  308. }
  309. outer:
  310. // If we have no mesh loaded - break here
  311. if (meshes.empty())
  312. throw DeadlyImportError("Quick3D: No meshes loaded");
  313. // If we have no materials loaded - generate a default mat
  314. if (materials.empty()) {
  315. ASSIMP_LOG_INFO("Quick3D: No material found, generating one");
  316. materials.push_back(Material());
  317. materials.back().diffuse = fgColor;
  318. }
  319. // find out which materials we'll need
  320. typedef std::pair<unsigned int, unsigned int> FaceIdx;
  321. typedef std::vector<FaceIdx> FaceIdxArray;
  322. FaceIdxArray *fidx = new FaceIdxArray[materials.size()];
  323. unsigned int p = 0;
  324. for (std::vector<Mesh>::iterator it = meshes.begin(), end = meshes.end();
  325. it != end; ++it, ++p) {
  326. unsigned int q = 0;
  327. for (std::vector<Face>::iterator fit = (*it).faces.begin(), fend = (*it).faces.end();
  328. fit != fend; ++fit, ++q) {
  329. if ((*fit).mat >= materials.size()) {
  330. ASSIMP_LOG_WARN("Quick3D: Material index overflow");
  331. (*fit).mat = 0;
  332. }
  333. if (fidx[(*fit).mat].empty()) ++pScene->mNumMeshes;
  334. fidx[(*fit).mat].push_back(FaceIdx(p, q));
  335. }
  336. }
  337. pScene->mNumMaterials = pScene->mNumMeshes;
  338. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  339. pScene->mMeshes = new aiMesh *[pScene->mNumMaterials];
  340. for (unsigned int i = 0, real = 0; i < (unsigned int)materials.size(); ++i) {
  341. if (fidx[i].empty()) continue;
  342. // Allocate a mesh and a material
  343. aiMesh *mesh = pScene->mMeshes[real] = new aiMesh();
  344. aiMaterial *mat = new aiMaterial();
  345. pScene->mMaterials[real] = mat;
  346. mesh->mMaterialIndex = real;
  347. // Build the output material
  348. Material &srcMat = materials[i];
  349. mat->AddProperty(&srcMat.diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  350. mat->AddProperty(&srcMat.specular, 1, AI_MATKEY_COLOR_SPECULAR);
  351. mat->AddProperty(&srcMat.ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  352. // NOTE: Ignore transparency for the moment - it seems
  353. // unclear how to interpret the data
  354. #if 0
  355. if (!(minor > '0' && major == '3'))
  356. srcMat.transparency = 1.0f - srcMat.transparency;
  357. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_OPACITY);
  358. #endif
  359. // add shininess - Quick3D seems to use it ins its viewer
  360. srcMat.transparency = 16.f;
  361. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_SHININESS);
  362. int m = (int)aiShadingMode_Phong;
  363. mat->AddProperty(&m, 1, AI_MATKEY_SHADING_MODEL);
  364. if (srcMat.name.length)
  365. mat->AddProperty(&srcMat.name, AI_MATKEY_NAME);
  366. // Add a texture
  367. if (srcMat.texIdx < pScene->mNumTextures || real < pScene->mNumTextures) {
  368. srcMat.name.data[0] = '*';
  369. srcMat.name.length = ASSIMP_itoa10(&srcMat.name.data[1], 1000,
  370. (srcMat.texIdx < pScene->mNumTextures ? srcMat.texIdx : real));
  371. mat->AddProperty(&srcMat.name, AI_MATKEY_TEXTURE_DIFFUSE(0));
  372. }
  373. mesh->mNumFaces = (unsigned int)fidx[i].size();
  374. aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  375. // Now build the output mesh. First find out how many
  376. // vertices we'll need
  377. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  378. it != end; ++it) {
  379. mesh->mNumVertices += (unsigned int)meshes[(*it).first].faces[(*it).second].indices.size();
  380. }
  381. aiVector3D *verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  382. aiVector3D *norms = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  383. aiVector3D *uv = nullptr;
  384. if (real < pScene->mNumTextures) {
  385. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  386. mesh->mNumUVComponents[0] = 2;
  387. }
  388. // Build the final array
  389. unsigned int cnt = 0;
  390. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  391. it != end; ++it, ++faces) {
  392. Mesh &curMesh = meshes[(*it).first];
  393. Face &face = curMesh.faces[(*it).second];
  394. faces->mNumIndices = (unsigned int)face.indices.size();
  395. faces->mIndices = new unsigned int[faces->mNumIndices];
  396. aiVector3D faceNormal;
  397. bool fnOK = false;
  398. for (unsigned int n = 0; n < faces->mNumIndices; ++n, ++cnt, ++norms, ++verts) {
  399. if (face.indices[n] >= curMesh.verts.size()) {
  400. ASSIMP_LOG_WARN("Quick3D: Vertex index overflow");
  401. face.indices[n] = 0;
  402. }
  403. // copy vertices
  404. *verts = curMesh.verts[face.indices[n]];
  405. if (face.indices[n] >= curMesh.normals.size() && faces->mNumIndices >= 3) {
  406. // we have no normal here - assign the face normal
  407. if (!fnOK) {
  408. const aiVector3D &pV1 = curMesh.verts[face.indices[0]];
  409. const aiVector3D &pV2 = curMesh.verts[face.indices[1]];
  410. const aiVector3D &pV3 = curMesh.verts[face.indices.size() - 1];
  411. faceNormal = (pV2 - pV1) ^ (pV3 - pV1).Normalize();
  412. fnOK = true;
  413. }
  414. *norms = faceNormal;
  415. } else {
  416. *norms = curMesh.normals[face.indices[n]];
  417. }
  418. // copy texture coordinates
  419. if (uv && curMesh.uv.size()) {
  420. if (curMesh.prevUVIdx != 0xffffffff && curMesh.uv.size() >= curMesh.verts.size()) // workaround
  421. {
  422. *uv = curMesh.uv[face.indices[n]];
  423. } else {
  424. if (face.uvindices[n] >= curMesh.uv.size()) {
  425. ASSIMP_LOG_WARN("Quick3D: Texture coordinate index overflow");
  426. face.uvindices[n] = 0;
  427. }
  428. *uv = curMesh.uv[face.uvindices[n]];
  429. }
  430. uv->y = 1.f - uv->y;
  431. ++uv;
  432. }
  433. // setup the new vertex index
  434. faces->mIndices[n] = cnt;
  435. }
  436. }
  437. ++real;
  438. }
  439. // Delete our nice helper array
  440. delete[] fidx;
  441. // Now we need to attach the meshes to the root node of the scene
  442. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  443. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  444. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i)
  445. pScene->mRootNode->mMeshes[i] = i;
  446. /*pScene->mRootNode->mTransformation *= aiMatrix4x4(
  447. 1.f, 0.f, 0.f, 0.f,
  448. 0.f, -1.f,0.f, 0.f,
  449. 0.f, 0.f, 1.f, 0.f,
  450. 0.f, 0.f, 0.f, 1.f);*/
  451. // Add cameras and light sources to the scene root node
  452. pScene->mRootNode->mNumChildren = pScene->mNumLights + pScene->mNumCameras;
  453. if (pScene->mRootNode->mNumChildren) {
  454. pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  455. // the light source
  456. aiNode *nd = pScene->mRootNode->mChildren[0] = new aiNode();
  457. nd->mParent = pScene->mRootNode;
  458. nd->mName.Set("Q3DLight");
  459. nd->mTransformation = pScene->mRootNode->mTransformation;
  460. nd->mTransformation.Inverse();
  461. // camera
  462. nd = pScene->mRootNode->mChildren[1] = new aiNode();
  463. nd->mParent = pScene->mRootNode;
  464. nd->mName.Set("Q3DCamera");
  465. nd->mTransformation = pScene->mRootNode->mChildren[0]->mTransformation;
  466. }
  467. }
  468. #endif // !! ASSIMP_BUILD_NO_Q3D_IMPORTER