ACLoader.cpp 37 KB

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