Q3DLoader.cpp 18 KB

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