ACLoader.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2015, 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 Implementation of the AC3D importer class */
  35. #ifndef ASSIMP_BUILD_NO_AC_IMPORTER
  36. // internal headers
  37. #include "ACLoader.h"
  38. #include "ParsingUtils.h"
  39. #include "fast_atof.h"
  40. #include "Subdivision.h"
  41. #include "Importer.h"
  42. #include "BaseImporter.h"
  43. #include "../include/assimp/Importer.hpp"
  44. #include "../include/assimp/light.h"
  45. #include "../include/assimp/DefaultLogger.hpp"
  46. #include "../include/assimp/material.h"
  47. #include "../include/assimp/scene.h"
  48. #include "../include/assimp/config.h"
  49. #include "../include/assimp/IOSystem.hpp"
  50. #include <boost/scoped_ptr.hpp>
  51. using namespace Assimp;
  52. static const aiImporterDesc desc = {
  53. "AC3D Importer",
  54. "",
  55. "",
  56. "",
  57. aiImporterFlags_SupportTextFlavour,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "ac acc ac3d"
  63. };
  64. // ------------------------------------------------------------------------------------------------
  65. // skip to the next token
  66. #define AI_AC_SKIP_TO_NEXT_TOKEN() \
  67. if (!SkipSpaces(&buffer)) \
  68. { \
  69. DefaultLogger::get()->error("AC3D: Unexpected EOF/EOL"); \
  70. continue; \
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. // read a string (may be enclosed in double quotation marks). buffer must point to "
  74. #define AI_AC_GET_STRING(out) \
  75. ++buffer; \
  76. const char* sz = buffer; \
  77. while ('\"' != *buffer) \
  78. { \
  79. if (IsLineEnd( *buffer )) \
  80. { \
  81. DefaultLogger::get()->error("AC3D: Unexpected EOF/EOL in string"); \
  82. out = "ERROR"; \
  83. break; \
  84. } \
  85. ++buffer; \
  86. } \
  87. if (IsLineEnd( *buffer ))continue; \
  88. out = std::string(sz,(unsigned int)(buffer-sz)); \
  89. ++buffer;
  90. // ------------------------------------------------------------------------------------------------
  91. // read 1 to n floats prefixed with an optional predefined identifier
  92. #define AI_AC_CHECKED_LOAD_FLOAT_ARRAY(name,name_length,num,out) \
  93. AI_AC_SKIP_TO_NEXT_TOKEN(); \
  94. if (name_length) \
  95. { \
  96. if (strncmp(buffer,name,name_length) || !IsSpace(buffer[name_length])) \
  97. { \
  98. DefaultLogger::get()->error("AC3D: Unexpexted token. " name " was expected."); \
  99. continue; \
  100. } \
  101. buffer += name_length+1; \
  102. } \
  103. for (unsigned int i = 0; i < num;++i) \
  104. { \
  105. AI_AC_SKIP_TO_NEXT_TOKEN(); \
  106. buffer = fast_atoreal_move<float>(buffer,((float*)out)[i]); \
  107. }
  108. // ------------------------------------------------------------------------------------------------
  109. // Constructor to be privately used by Importer
  110. AC3DImporter::AC3DImporter()
  111. : buffer(),
  112. configSplitBFCull(),
  113. configEvalSubdivision(),
  114. mNumMeshes(),
  115. mLights(),
  116. lights(),
  117. groups(),
  118. polys(),
  119. worlds()
  120. {
  121. // nothing to be done here
  122. }
  123. // ------------------------------------------------------------------------------------------------
  124. // Destructor, private as well
  125. AC3DImporter::~AC3DImporter()
  126. {
  127. // nothing to be done here
  128. }
  129. // ------------------------------------------------------------------------------------------------
  130. // Returns whether the class can handle the format of the given file.
  131. bool AC3DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  132. {
  133. std::string extension = GetExtension(pFile);
  134. // fixme: are acc and ac3d *really* used? Some sources say they are
  135. if(extension == "ac" || extension == "ac3d" || extension == "acc") {
  136. return true;
  137. }
  138. if (!extension.length() || checkSig) {
  139. uint32_t token = AI_MAKE_MAGIC("AC3D");
  140. return CheckMagicToken(pIOHandler,pFile,&token,1,0);
  141. }
  142. return false;
  143. }
  144. // ------------------------------------------------------------------------------------------------
  145. // Loader meta information
  146. const aiImporterDesc* AC3DImporter::GetInfo () const
  147. {
  148. return &desc;
  149. }
  150. // ------------------------------------------------------------------------------------------------
  151. // Get a pointer to the next line from the file
  152. bool AC3DImporter::GetNextLine( )
  153. {
  154. SkipLine(&buffer);
  155. return SkipSpaces(&buffer);
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. // Parse an object section in an AC file
  159. void AC3DImporter::LoadObjectSection(std::vector<Object>& objects)
  160. {
  161. if (!TokenMatch(buffer,"OBJECT",6))
  162. return;
  163. SkipSpaces(&buffer);
  164. ++mNumMeshes;
  165. objects.push_back(Object());
  166. Object& obj = objects.back();
  167. aiLight* light = NULL;
  168. if (!ASSIMP_strincmp(buffer,"light",5))
  169. {
  170. // This is a light source. Add it to the list
  171. mLights->push_back(light = new aiLight());
  172. // Return a point light with no attenuation
  173. light->mType = aiLightSource_POINT;
  174. light->mColorDiffuse = light->mColorSpecular = aiColor3D(1.f,1.f,1.f);
  175. light->mAttenuationConstant = 1.f;
  176. // Generate a default name for both the light source and the node
  177. // FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
  178. light->mName.length = ::sprintf(light->mName.data,"ACLight_%i",static_cast<unsigned int>(mLights->size())-1);
  179. obj.name = std::string( light->mName.data );
  180. DefaultLogger::get()->debug("AC3D: Light source encountered");
  181. obj.type = Object::Light;
  182. }
  183. else if (!ASSIMP_strincmp(buffer,"group",5))
  184. {
  185. obj.type = Object::Group;
  186. }
  187. else if (!ASSIMP_strincmp(buffer,"world",5))
  188. {
  189. obj.type = Object::World;
  190. }
  191. else obj.type = Object::Poly;
  192. while (GetNextLine())
  193. {
  194. if (TokenMatch(buffer,"kids",4))
  195. {
  196. SkipSpaces(&buffer);
  197. unsigned int num = strtoul10(buffer,&buffer);
  198. GetNextLine();
  199. if (num)
  200. {
  201. // load the children of this object recursively
  202. obj.children.reserve(num);
  203. for (unsigned int i = 0; i < num; ++i)
  204. LoadObjectSection(obj.children);
  205. }
  206. return;
  207. }
  208. else if (TokenMatch(buffer,"name",4))
  209. {
  210. SkipSpaces(&buffer);
  211. AI_AC_GET_STRING(obj.name);
  212. // If this is a light source, we'll also need to store
  213. // the name of the node in it.
  214. if (light)
  215. {
  216. light->mName.Set(obj.name);
  217. }
  218. }
  219. else if (TokenMatch(buffer,"texture",7))
  220. {
  221. SkipSpaces(&buffer);
  222. AI_AC_GET_STRING(obj.texture);
  223. }
  224. else if (TokenMatch(buffer,"texrep",6))
  225. {
  226. SkipSpaces(&buffer);
  227. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texRepeat);
  228. if (!obj.texRepeat.x || !obj.texRepeat.y)
  229. obj.texRepeat = aiVector2D (1.f,1.f);
  230. }
  231. else if (TokenMatch(buffer,"texoff",6))
  232. {
  233. SkipSpaces(&buffer);
  234. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texOffset);
  235. }
  236. else if (TokenMatch(buffer,"rot",3))
  237. {
  238. SkipSpaces(&buffer);
  239. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,9,&obj.rotation);
  240. }
  241. else if (TokenMatch(buffer,"loc",3))
  242. {
  243. SkipSpaces(&buffer);
  244. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&obj.translation);
  245. }
  246. else if (TokenMatch(buffer,"subdiv",6))
  247. {
  248. SkipSpaces(&buffer);
  249. obj.subDiv = strtoul10(buffer,&buffer);
  250. }
  251. else if (TokenMatch(buffer,"crease",6))
  252. {
  253. SkipSpaces(&buffer);
  254. obj.crease = fast_atof(buffer);
  255. }
  256. else if (TokenMatch(buffer,"numvert",7))
  257. {
  258. SkipSpaces(&buffer);
  259. unsigned int t = strtoul10(buffer,&buffer);
  260. if (t >= std::numeric_limits<int32_t>::max() / sizeof(aiVector3D)) {
  261. throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
  262. }
  263. obj.vertices.reserve(t);
  264. for (unsigned int i = 0; i < t;++i)
  265. {
  266. if (!GetNextLine())
  267. {
  268. DefaultLogger::get()->error("AC3D: Unexpected EOF: not all vertices have been parsed yet");
  269. break;
  270. }
  271. else if (!IsNumeric(*buffer))
  272. {
  273. DefaultLogger::get()->error("AC3D: Unexpected token: not all vertices have been parsed yet");
  274. --buffer; // make sure the line is processed a second time
  275. break;
  276. }
  277. obj.vertices.push_back(aiVector3D());
  278. aiVector3D& v = obj.vertices.back();
  279. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&v.x);
  280. }
  281. }
  282. else if (TokenMatch(buffer,"numsurf",7))
  283. {
  284. SkipSpaces(&buffer);
  285. bool Q3DWorkAround = false;
  286. const unsigned int t = strtoul10(buffer,&buffer);
  287. obj.surfaces.reserve(t);
  288. for (unsigned int i = 0; i < t;++i)
  289. {
  290. GetNextLine();
  291. if (!TokenMatch(buffer,"SURF",4))
  292. {
  293. // FIX: this can occur for some files - Quick 3D for
  294. // example writes no surf chunks
  295. if (!Q3DWorkAround)
  296. {
  297. DefaultLogger::get()->warn("AC3D: SURF token was expected");
  298. DefaultLogger::get()->debug("Continuing with Quick3D Workaround enabled");
  299. }
  300. --buffer; // make sure the line is processed a second time
  301. // break; --- see fix notes above
  302. Q3DWorkAround = true;
  303. }
  304. SkipSpaces(&buffer);
  305. obj.surfaces.push_back(Surface());
  306. Surface& surf = obj.surfaces.back();
  307. surf.flags = strtoul_cppstyle(buffer);
  308. while (1)
  309. {
  310. if(!GetNextLine())
  311. {
  312. DefaultLogger::get()->error("AC3D: Unexpected EOF: surface is incomplete");
  313. break;
  314. }
  315. if (TokenMatch(buffer,"mat",3))
  316. {
  317. SkipSpaces(&buffer);
  318. surf.mat = strtoul10(buffer);
  319. }
  320. else if (TokenMatch(buffer,"refs",4))
  321. {
  322. // --- see fix notes above
  323. if (Q3DWorkAround)
  324. {
  325. if (!surf.entries.empty())
  326. {
  327. buffer -= 6;
  328. break;
  329. }
  330. }
  331. SkipSpaces(&buffer);
  332. const unsigned int m = strtoul10(buffer);
  333. surf.entries.reserve(m);
  334. obj.numRefs += m;
  335. for (unsigned int k = 0; k < m; ++k)
  336. {
  337. if(!GetNextLine())
  338. {
  339. DefaultLogger::get()->error("AC3D: Unexpected EOF: surface references are incomplete");
  340. break;
  341. }
  342. surf.entries.push_back(Surface::SurfaceEntry());
  343. Surface::SurfaceEntry& entry = surf.entries.back();
  344. entry.first = strtoul10(buffer,&buffer);
  345. SkipSpaces(&buffer);
  346. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&entry.second);
  347. }
  348. }
  349. else
  350. {
  351. --buffer; // make sure the line is processed a second time
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. }
  358. DefaultLogger::get()->error("AC3D: Unexpected EOF: \'kids\' line was expected");
  359. }
  360. // ------------------------------------------------------------------------------------------------
  361. // Convert a material from AC3DImporter::Material to aiMaterial
  362. void AC3DImporter::ConvertMaterial(const Object& object,
  363. const Material& matSrc,
  364. aiMaterial& matDest)
  365. {
  366. aiString s;
  367. if (matSrc.name.length())
  368. {
  369. s.Set(matSrc.name);
  370. matDest.AddProperty(&s,AI_MATKEY_NAME);
  371. }
  372. if (object.texture.length())
  373. {
  374. s.Set(object.texture);
  375. matDest.AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));
  376. // UV transformation
  377. if (1.f != object.texRepeat.x || 1.f != object.texRepeat.y ||
  378. object.texOffset.x || object.texOffset.y)
  379. {
  380. aiUVTransform transform;
  381. transform.mScaling = object.texRepeat;
  382. transform.mTranslation = object.texOffset;
  383. matDest.AddProperty(&transform,1,AI_MATKEY_UVTRANSFORM_DIFFUSE(0));
  384. }
  385. }
  386. matDest.AddProperty<aiColor3D>(&matSrc.rgb,1, AI_MATKEY_COLOR_DIFFUSE);
  387. matDest.AddProperty<aiColor3D>(&matSrc.amb,1, AI_MATKEY_COLOR_AMBIENT);
  388. matDest.AddProperty<aiColor3D>(&matSrc.emis,1,AI_MATKEY_COLOR_EMISSIVE);
  389. matDest.AddProperty<aiColor3D>(&matSrc.spec,1,AI_MATKEY_COLOR_SPECULAR);
  390. int n;
  391. if (matSrc.shin)
  392. {
  393. n = aiShadingMode_Phong;
  394. matDest.AddProperty<float>(&matSrc.shin,1,AI_MATKEY_SHININESS);
  395. }
  396. else n = aiShadingMode_Gouraud;
  397. matDest.AddProperty<int>(&n,1,AI_MATKEY_SHADING_MODEL);
  398. float f = 1.f - matSrc.trans;
  399. matDest.AddProperty<float>(&f,1,AI_MATKEY_OPACITY);
  400. }
  401. // ------------------------------------------------------------------------------------------------
  402. // Converts the loaded data to the internal verbose representation
  403. aiNode* AC3DImporter::ConvertObjectSection(Object& object,
  404. std::vector<aiMesh*>& meshes,
  405. std::vector<aiMaterial*>& outMaterials,
  406. const std::vector<Material>& materials,
  407. aiNode* parent)
  408. {
  409. aiNode* node = new aiNode();
  410. node->mParent = parent;
  411. if (object.vertices.size())
  412. {
  413. if (!object.surfaces.size() || !object.numRefs)
  414. {
  415. /* " An object with 7 vertices (no surfaces, no materials defined).
  416. This is a good way of getting point data into AC3D.
  417. The Vertex->create convex-surface/object can be used on these
  418. vertices to 'wrap' a 3d shape around them "
  419. (http://www.opencity.info/html/ac3dfileformat.html)
  420. therefore: if no surfaces are defined return point data only
  421. */
  422. DefaultLogger::get()->info("AC3D: No surfaces defined in object definition, "
  423. "a point list is returned");
  424. meshes.push_back(new aiMesh());
  425. aiMesh* mesh = meshes.back();
  426. mesh->mNumFaces = mesh->mNumVertices = (unsigned int)object.vertices.size();
  427. aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  428. aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  429. for (unsigned int i = 0; i < mesh->mNumVertices;++i,++faces,++verts)
  430. {
  431. *verts = object.vertices[i];
  432. faces->mNumIndices = 1;
  433. faces->mIndices = new unsigned int[1];
  434. faces->mIndices[0] = i;
  435. }
  436. // use the primary material in this case. this should be the
  437. // default material if all objects of the file contain points
  438. // and no faces.
  439. mesh->mMaterialIndex = 0;
  440. outMaterials.push_back(new aiMaterial());
  441. ConvertMaterial(object, materials[0], *outMaterials.back());
  442. }
  443. else
  444. {
  445. // need to generate one or more meshes for this object.
  446. // find out how many different materials we have
  447. typedef std::pair< unsigned int, unsigned int > IntPair;
  448. typedef std::vector< IntPair > MatTable;
  449. MatTable needMat(materials.size(),IntPair(0,0));
  450. std::vector<Surface>::iterator it,end = object.surfaces.end();
  451. std::vector<Surface::SurfaceEntry>::iterator it2,end2;
  452. for (it = object.surfaces.begin(); it != end; ++it)
  453. {
  454. unsigned int idx = (*it).mat;
  455. if (idx >= needMat.size())
  456. {
  457. DefaultLogger::get()->error("AC3D: material index is out of range");
  458. idx = 0;
  459. }
  460. if ((*it).entries.empty())
  461. {
  462. DefaultLogger::get()->warn("AC3D: surface her zero vertex references");
  463. }
  464. // validate all vertex indices to make sure we won't crash here
  465. for (it2 = (*it).entries.begin(),
  466. end2 = (*it).entries.end(); it2 != end2; ++it2)
  467. {
  468. if ((*it2).first >= object.vertices.size())
  469. {
  470. DefaultLogger::get()->warn("AC3D: Invalid vertex reference");
  471. (*it2).first = 0;
  472. }
  473. }
  474. if (!needMat[idx].first)++node->mNumMeshes;
  475. switch ((*it).flags & 0xf)
  476. {
  477. // closed line
  478. case 0x1:
  479. needMat[idx].first += (unsigned int)(*it).entries.size();
  480. needMat[idx].second += (unsigned int)(*it).entries.size()<<1u;
  481. break;
  482. // unclosed line
  483. case 0x2:
  484. needMat[idx].first += (unsigned int)(*it).entries.size()-1;
  485. needMat[idx].second += ((unsigned int)(*it).entries.size()-1)<<1u;
  486. break;
  487. // 0 == polygon, else unknown
  488. default:
  489. if ((*it).flags & 0xf)
  490. {
  491. DefaultLogger::get()->warn("AC3D: The type flag of a surface is unknown");
  492. (*it).flags &= ~(0xf);
  493. }
  494. // the number of faces increments by one, the number
  495. // of vertices by surface.numref.
  496. needMat[idx].first++;
  497. needMat[idx].second += (unsigned int)(*it).entries.size();
  498. };
  499. }
  500. unsigned int* pip = node->mMeshes = new unsigned int[node->mNumMeshes];
  501. unsigned int mat = 0;
  502. const size_t oldm = meshes.size();
  503. for (MatTable::const_iterator cit = needMat.begin(), cend = needMat.end();
  504. cit != cend; ++cit, ++mat)
  505. {
  506. if (!(*cit).first)continue;
  507. // allocate a new aiMesh object
  508. *pip++ = (unsigned int)meshes.size();
  509. aiMesh* mesh = new aiMesh();
  510. meshes.push_back(mesh);
  511. mesh->mMaterialIndex = (unsigned int)outMaterials.size();
  512. outMaterials.push_back(new aiMaterial());
  513. ConvertMaterial(object, materials[mat], *outMaterials.back());
  514. // allocate storage for vertices and normals
  515. mesh->mNumFaces = (*cit).first;
  516. aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  517. mesh->mNumVertices = (*cit).second;
  518. aiVector3D* vertices = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  519. unsigned int cur = 0;
  520. // allocate UV coordinates, but only if the texture name for the
  521. // surface is not empty
  522. aiVector3D* uv = NULL;
  523. if(object.texture.length())
  524. {
  525. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  526. mesh->mNumUVComponents[0] = 2;
  527. }
  528. for (it = object.surfaces.begin(); it != end; ++it)
  529. {
  530. if (mat == (*it).mat)
  531. {
  532. const Surface& src = *it;
  533. // closed polygon
  534. unsigned int type = (*it).flags & 0xf;
  535. if (!type)
  536. {
  537. aiFace& face = *faces++;
  538. if((face.mNumIndices = (unsigned int)src.entries.size()))
  539. {
  540. face.mIndices = new unsigned int[face.mNumIndices];
  541. for (unsigned int i = 0; i < face.mNumIndices;++i,++vertices)
  542. {
  543. const Surface::SurfaceEntry& entry = src.entries[i];
  544. face.mIndices[i] = cur++;
  545. // copy vertex positions
  546. if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
  547. throw DeadlyImportError("AC3D: Invalid number of vertices");
  548. }
  549. *vertices = object.vertices[entry.first] + object.translation;
  550. // copy texture coordinates
  551. if (uv)
  552. {
  553. uv->x = entry.second.x;
  554. uv->y = entry.second.y;
  555. ++uv;
  556. }
  557. }
  558. }
  559. }
  560. else
  561. {
  562. it2 = (*it).entries.begin();
  563. // either a closed or an unclosed line
  564. unsigned int tmp = (unsigned int)(*it).entries.size();
  565. if (0x2 == type)--tmp;
  566. for (unsigned int m = 0; m < tmp;++m)
  567. {
  568. aiFace& face = *faces++;
  569. face.mNumIndices = 2;
  570. face.mIndices = new unsigned int[2];
  571. face.mIndices[0] = cur++;
  572. face.mIndices[1] = cur++;
  573. // copy vertex positions
  574. if (it2 == (*it).entries.end() ) {
  575. throw DeadlyImportError("AC3D: Bad line");
  576. }
  577. ai_assert((*it2).first < object.vertices.size());
  578. *vertices++ = object.vertices[(*it2).first];
  579. // copy texture coordinates
  580. if (uv)
  581. {
  582. uv->x = (*it2).second.x;
  583. uv->y = (*it2).second.y;
  584. ++uv;
  585. }
  586. if (0x1 == type && tmp-1 == m)
  587. {
  588. // if this is a closed line repeat its beginning now
  589. it2 = (*it).entries.begin();
  590. }
  591. else ++it2;
  592. // second point
  593. *vertices++ = object.vertices[(*it2).first];
  594. if (uv)
  595. {
  596. uv->x = (*it2).second.x;
  597. uv->y = (*it2).second.y;
  598. ++uv;
  599. }
  600. }
  601. }
  602. }
  603. }
  604. }
  605. // Now apply catmull clark subdivision if necessary. We split meshes into
  606. // materials which is not done by AC3D during smoothing, so we need to
  607. // collect all meshes using the same material group.
  608. if (object.subDiv) {
  609. if (configEvalSubdivision) {
  610. boost::scoped_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
  611. DefaultLogger::get()->info("AC3D: Evaluating subdivision surface: "+object.name);
  612. std::vector<aiMesh*> cpy(meshes.size()-oldm,NULL);
  613. div->Subdivide(&meshes[oldm],cpy.size(),&cpy.front(),object.subDiv,true);
  614. std::copy(cpy.begin(),cpy.end(),meshes.begin()+oldm);
  615. // previous meshes are deleted vy Subdivide().
  616. }
  617. else {
  618. DefaultLogger::get()->info("AC3D: Letting the subdivision surface untouched due to my configuration: "
  619. +object.name);
  620. }
  621. }
  622. }
  623. }
  624. if (object.name.length())
  625. node->mName.Set(object.name);
  626. else
  627. {
  628. // generate a name depending on the type of the node
  629. switch (object.type)
  630. {
  631. case Object::Group:
  632. node->mName.length = ::sprintf(node->mName.data,"ACGroup_%i",groups++);
  633. break;
  634. case Object::Poly:
  635. node->mName.length = ::sprintf(node->mName.data,"ACPoly_%i",polys++);
  636. break;
  637. case Object::Light:
  638. node->mName.length = ::sprintf(node->mName.data,"ACLight_%i",lights++);
  639. break;
  640. // there shouldn't be more than one world, but we don't care
  641. case Object::World:
  642. node->mName.length = ::sprintf(node->mName.data,"ACWorld_%i",worlds++);
  643. break;
  644. }
  645. }
  646. // setup the local transformation matrix of the object
  647. // compute the transformation offset to the parent node
  648. node->mTransformation = aiMatrix4x4 ( object.rotation );
  649. if (object.type == Object::Group || !object.numRefs)
  650. {
  651. node->mTransformation.a4 = object.translation.x;
  652. node->mTransformation.b4 = object.translation.y;
  653. node->mTransformation.c4 = object.translation.z;
  654. }
  655. // add children to the object
  656. if (object.children.size())
  657. {
  658. node->mNumChildren = (unsigned int)object.children.size();
  659. node->mChildren = new aiNode*[node->mNumChildren];
  660. for (unsigned int i = 0; i < node->mNumChildren;++i)
  661. {
  662. node->mChildren[i] = ConvertObjectSection(object.children[i],meshes,outMaterials,materials,node);
  663. }
  664. }
  665. return node;
  666. }
  667. // ------------------------------------------------------------------------------------------------
  668. void AC3DImporter::SetupProperties(const Importer* pImp)
  669. {
  670. configSplitBFCull = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL,1) ? true : false;
  671. configEvalSubdivision = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION,1) ? true : false;
  672. }
  673. // ------------------------------------------------------------------------------------------------
  674. // Imports the given file into the given scene structure.
  675. void AC3DImporter::InternReadFile( const std::string& pFile,
  676. aiScene* pScene, IOSystem* pIOHandler)
  677. {
  678. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  679. // Check whether we can read from the file
  680. if( file.get() == NULL)
  681. throw DeadlyImportError( "Failed to open AC3D file " + pFile + ".");
  682. // allocate storage and copy the contents of the file to a memory buffer
  683. std::vector<char> mBuffer2;
  684. TextFileToBuffer(file.get(),mBuffer2);
  685. buffer = &mBuffer2[0];
  686. mNumMeshes = 0;
  687. lights = polys = worlds = groups = 0;
  688. if (::strncmp(buffer,"AC3D",4)) {
  689. throw DeadlyImportError("AC3D: No valid AC3D file, magic sequence not found");
  690. }
  691. // print the file format version to the console
  692. unsigned int version = HexDigitToDecimal( buffer[4] );
  693. char msg[3];
  694. ASSIMP_itoa10(msg,3,version);
  695. DefaultLogger::get()->info(std::string("AC3D file format version: ") + msg);
  696. std::vector<Material> materials;
  697. materials.reserve(5);
  698. std::vector<Object> rootObjects;
  699. rootObjects.reserve(5);
  700. std::vector<aiLight*> lights;
  701. mLights = & lights;
  702. while (GetNextLine())
  703. {
  704. if (TokenMatch(buffer,"MATERIAL",8))
  705. {
  706. materials.push_back(Material());
  707. Material& mat = materials.back();
  708. // manually parse the material ... sscanf would use the buldin atof ...
  709. // Format: (name) rgb %f %f %f amb %f %f %f emis %f %f %f spec %f %f %f shi %d trans %f
  710. AI_AC_SKIP_TO_NEXT_TOKEN();
  711. if ('\"' == *buffer)
  712. {
  713. AI_AC_GET_STRING(mat.name);
  714. AI_AC_SKIP_TO_NEXT_TOKEN();
  715. }
  716. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("rgb",3,3,&mat.rgb);
  717. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("amb",3,3,&mat.amb);
  718. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("emis",4,3,&mat.emis);
  719. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("spec",4,3,&mat.spec);
  720. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("shi",3,1,&mat.shin);
  721. AI_AC_CHECKED_LOAD_FLOAT_ARRAY("trans",5,1,&mat.trans);
  722. }
  723. LoadObjectSection(rootObjects);
  724. }
  725. if (rootObjects.empty() || !mNumMeshes)
  726. {
  727. throw DeadlyImportError("AC3D: No meshes have been loaded");
  728. }
  729. if (materials.empty())
  730. {
  731. DefaultLogger::get()->warn("AC3D: No material has been found");
  732. materials.push_back(Material());
  733. }
  734. mNumMeshes += (mNumMeshes>>2u) + 1;
  735. std::vector<aiMesh*> meshes;
  736. meshes.reserve(mNumMeshes);
  737. std::vector<aiMaterial*> omaterials;
  738. materials.reserve(mNumMeshes);
  739. // generate a dummy root if there are multiple objects on the top layer
  740. Object* root;
  741. if (1 == rootObjects.size())
  742. root = &rootObjects[0];
  743. else
  744. {
  745. root = new Object();
  746. }
  747. // now convert the imported stuff to our output data structure
  748. pScene->mRootNode = ConvertObjectSection(*root,meshes,omaterials,materials);
  749. if (1 != rootObjects.size())delete root;
  750. if (!::strncmp( pScene->mRootNode->mName.data, "Node", 4))
  751. pScene->mRootNode->mName.Set("<AC3DWorld>");
  752. // copy meshes
  753. if (meshes.empty())
  754. {
  755. throw DeadlyImportError("An unknown error occured during converting");
  756. }
  757. pScene->mNumMeshes = (unsigned int)meshes.size();
  758. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  759. ::memcpy(pScene->mMeshes,&meshes[0],pScene->mNumMeshes*sizeof(void*));
  760. // copy materials
  761. pScene->mNumMaterials = (unsigned int)omaterials.size();
  762. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  763. ::memcpy(pScene->mMaterials,&omaterials[0],pScene->mNumMaterials*sizeof(void*));
  764. // copy lights
  765. pScene->mNumLights = (unsigned int)lights.size();
  766. if (lights.size())
  767. {
  768. pScene->mLights = new aiLight*[lights.size()];
  769. ::memcpy(pScene->mLights,&lights[0],lights.size()*sizeof(void*));
  770. }
  771. }
  772. #endif //!defined ASSIMP_BUILD_NO_AC_IMPORTER