Q3DLoader.cpp 18 KB

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