C4DImporter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file C4DImporter.cpp
  34. * @brief Implementation of the Cinema4D importer class.
  35. */
  36. #ifndef ASSIMP_BUILD_NO_C4D_IMPORTER
  37. // no #ifdefing here, Cinema4D support is carried out in a branch of assimp
  38. // where it is turned on in the CMake settings.
  39. #ifndef _MSC_VER
  40. # error C4D support is currently MSVC only
  41. #endif
  42. #include "C4DImporter.h"
  43. #include "TinyFormatter.h"
  44. #if defined(_M_X64) || defined(__amd64__)
  45. # define __C4D_64BIT
  46. #endif
  47. #define __PC
  48. #include "c4d_file.h"
  49. #include "default_alien_overloads.h"
  50. using namespace _melange_;
  51. // overload this function and fill in your own unique data
  52. void GetWriterInfo(LONG &id, String &appname)
  53. {
  54. id = 2424226;
  55. appname = "Open Asset Import Library";
  56. }
  57. using namespace Assimp;
  58. using namespace Assimp::Formatter;
  59. namespace Assimp {
  60. template<> const std::string LogFunctions<C4DImporter>::log_prefix = "C4D: ";
  61. }
  62. static const aiImporterDesc desc = {
  63. "Cinema4D Importer",
  64. "",
  65. "",
  66. "",
  67. aiImporterFlags_SupportBinaryFlavour,
  68. 0,
  69. 0,
  70. 0,
  71. 0,
  72. "c4d"
  73. };
  74. // ------------------------------------------------------------------------------------------------
  75. C4DImporter::C4DImporter()
  76. {}
  77. // ------------------------------------------------------------------------------------------------
  78. C4DImporter::~C4DImporter()
  79. {}
  80. // ------------------------------------------------------------------------------------------------
  81. bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  82. {
  83. const std::string& extension = GetExtension(pFile);
  84. if (extension == "c4d") {
  85. return true;
  86. }
  87. else if ((!extension.length() || checkSig) && pIOHandler) {
  88. // TODO
  89. }
  90. return false;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. const aiImporterDesc* C4DImporter::GetInfo () const
  94. {
  95. return &desc;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. void C4DImporter::SetupProperties(const Importer* /*pImp*/)
  99. {
  100. // nothing to be done for the moment
  101. }
  102. // ------------------------------------------------------------------------------------------------
  103. // Imports the given file into the given scene structure.
  104. void C4DImporter::InternReadFile( const std::string& pFile,
  105. aiScene* pScene, IOSystem* pIOHandler)
  106. {
  107. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  108. if( file.get() == NULL) {
  109. ThrowException("failed to open file " + pFile);
  110. }
  111. const size_t file_size = file->FileSize();
  112. std::vector<uint8_t> mBuffer(file_size);
  113. file->Read(&mBuffer[0], 1, file_size);
  114. Filename f;
  115. f.SetMemoryReadMode(&mBuffer[0], file_size);
  116. // open document first
  117. BaseDocument* doc = LoadDocument(f, SCENEFILTER_OBJECTS | SCENEFILTER_MATERIALS);
  118. if(doc == NULL) {
  119. ThrowException("failed to read document " + pFile);
  120. }
  121. pScene->mRootNode = new aiNode("<C4DRoot>");
  122. // first convert all materials
  123. ReadMaterials(doc->GetFirstMaterial());
  124. // process C4D scenegraph recursively
  125. try {
  126. RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode);
  127. }
  128. catch(...) {
  129. BOOST_FOREACH(aiMesh* mesh, meshes) {
  130. delete mesh;
  131. }
  132. BaseDocument::Free(doc);
  133. throw;
  134. }
  135. BaseDocument::Free(doc);
  136. // copy meshes over
  137. pScene->mNumMeshes = static_cast<unsigned int>(meshes.size());
  138. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  139. std::copy(meshes.begin(), meshes.end(), pScene->mMeshes);
  140. // copy materials over, adding a default material if necessary
  141. unsigned int mat_count = static_cast<unsigned int>(materials.size());
  142. BOOST_FOREACH(aiMesh* mesh, meshes) {
  143. ai_assert(mesh->mMaterialIndex <= mat_count);
  144. if(mesh->mMaterialIndex >= mat_count) {
  145. ++mat_count;
  146. ScopeGuard<aiMaterial> def_material(new aiMaterial());
  147. const aiString name(AI_DEFAULT_MATERIAL_NAME);
  148. def_material->AddProperty(&name, AI_MATKEY_NAME);
  149. materials.push_back(def_material.dismiss());
  150. break;
  151. }
  152. }
  153. pScene->mNumMaterials = static_cast<unsigned int>(materials.size());
  154. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  155. std::copy(materials.begin(), materials.end(), pScene->mMaterials);
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. bool C4DImporter::ReadShader(aiMaterial* out, _melange_::BaseShader* shader)
  159. {
  160. // based on Melange sample code (C4DImportExport.cpp)
  161. while(shader) {
  162. if(shader->GetType() == Xlayer) {
  163. BaseContainer* container = shader->GetDataInstance();
  164. GeData blend = container->GetData(SLA_LAYER_BLEND);
  165. iBlendDataType* blend_list = reinterpret_cast<iBlendDataType*>(blend.GetCustomDataType(CUSTOMDATA_BLEND_LIST));
  166. if (!blend_list)
  167. {
  168. LogWarn("ignoring XLayer shader: no blend list given");
  169. continue;
  170. }
  171. LayerShaderLayer *lsl = dynamic_cast<LayerShaderLayer*>(blend_list->m_BlendLayers.GetObject(0));
  172. // Ignore the actual layer blending - models for real-time rendering should not
  173. // use them in a non-trivial way. Just try to find textures that we can apply
  174. // to the model.
  175. while (lsl)
  176. {
  177. if (lsl->GetType() == TypeFolder)
  178. {
  179. BlendFolder* const folder = dynamic_cast<BlendFolder*>(lsl);
  180. LayerShaderLayer *subLsl = dynamic_cast<LayerShaderLayer*>(folder->m_Children.GetObject(0));
  181. while (subLsl)
  182. {
  183. if (subLsl->GetType() == TypeShader) {
  184. BlendShader* const shader = dynamic_cast<BlendShader*>(subLsl);
  185. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  186. return true;
  187. }
  188. }
  189. subLsl = subLsl->GetNext();
  190. }
  191. }
  192. else if (lsl->GetType() == TypeShader) {
  193. BlendShader* const shader = dynamic_cast<BlendShader*>(lsl);
  194. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  195. return true;
  196. }
  197. }
  198. lsl = lsl->GetNext();
  199. }
  200. }
  201. else if ( shader->GetType() == Xbitmap )
  202. {
  203. aiString path;
  204. shader->GetFileName().GetString().GetCString(path.data, MAXLEN-1);
  205. path.length = ::strlen(path.data);
  206. out->AddProperty(&path, AI_MATKEY_TEXTURE_DIFFUSE(0));
  207. return true;
  208. }
  209. else {
  210. LogWarn("ignoring shader type: " + std::string(GetObjectTypeName(shader->GetType())));
  211. }
  212. shader = shader->GetNext();
  213. }
  214. return false;
  215. }
  216. // ------------------------------------------------------------------------------------------------
  217. void C4DImporter::ReadMaterials(_melange_::BaseMaterial* mat)
  218. {
  219. // based on Melange sample code
  220. while (mat)
  221. {
  222. const String& name = mat->GetName();
  223. if (mat->GetType() == Mmaterial)
  224. {
  225. aiMaterial* out = new aiMaterial();
  226. material_mapping[mat] = static_cast<unsigned int>(materials.size());
  227. materials.push_back(out);
  228. aiString ai_name;
  229. name.GetCString(ai_name.data, MAXLEN-1);
  230. ai_name.length = ::strlen(ai_name.data);
  231. out->AddProperty(&ai_name, AI_MATKEY_NAME);
  232. Material& m = dynamic_cast<Material&>(*mat);
  233. if (m.GetChannelState(CHANNEL_COLOR))
  234. {
  235. GeData data;
  236. mat->GetParameter(MATERIAL_COLOR_COLOR, data);
  237. Vector color = data.GetVector();
  238. mat->GetParameter(MATERIAL_COLOR_BRIGHTNESS, data);
  239. const Real brightness = data.GetReal();
  240. color *= brightness;
  241. aiVector3D v;
  242. v.x = color.x;
  243. v.y = color.y;
  244. v.z = color.z;
  245. out->AddProperty(&v, 1, AI_MATKEY_COLOR_DIFFUSE);
  246. }
  247. BaseShader* const shader = m.GetShader(MATERIAL_COLOR_SHADER);
  248. if(shader) {
  249. ReadShader(out, shader);
  250. }
  251. }
  252. else
  253. {
  254. LogWarn("ignoring plugin material: " + std::string(GetObjectTypeName(mat->GetType())));
  255. }
  256. mat = mat->GetNext();
  257. }
  258. }
  259. // ------------------------------------------------------------------------------------------------
  260. void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent)
  261. {
  262. ai_assert(parent != NULL);
  263. std::vector<aiNode*> nodes;
  264. // based on Melange sample code
  265. while (object)
  266. {
  267. const String& name = object->GetName();
  268. const LONG type = object->GetType();
  269. const Matrix& ml = object->GetMl();
  270. aiString string;
  271. name.GetCString(string.data, MAXLEN-1);
  272. string.length = ::strlen(string.data);
  273. aiNode* const nd = new aiNode();
  274. nd->mParent = parent;
  275. nd->mName = string;
  276. nd->mTransformation.a1 = ml.v1.x;
  277. nd->mTransformation.b1 = ml.v1.y;
  278. nd->mTransformation.c1 = ml.v1.z;
  279. nd->mTransformation.a2 = ml.v2.x;
  280. nd->mTransformation.b2 = ml.v2.y;
  281. nd->mTransformation.c2 = ml.v2.z;
  282. nd->mTransformation.a3 = ml.v3.x;
  283. nd->mTransformation.b3 = ml.v3.y;
  284. nd->mTransformation.c3 = ml.v3.z;
  285. nd->mTransformation.a4 = ml.off.x;
  286. nd->mTransformation.b4 = ml.off.y;
  287. nd->mTransformation.c4 = ml.off.z;
  288. nodes.push_back(nd);
  289. GeData data;
  290. if (type == Ocamera)
  291. {
  292. object->GetParameter(CAMERAOBJECT_FOV, data);
  293. // TODO: read camera
  294. }
  295. else if (type == Olight)
  296. {
  297. // TODO: read light
  298. }
  299. else if (type == Opolygon)
  300. {
  301. aiMesh* const mesh = ReadMesh(object);
  302. if(mesh != NULL) {
  303. nd->mNumMeshes = 1;
  304. nd->mMeshes = new unsigned int[1];
  305. nd->mMeshes[0] = static_cast<unsigned int>(meshes.size());
  306. meshes.push_back(mesh);
  307. }
  308. }
  309. else {
  310. LogWarn("ignoring object: " + std::string(GetObjectTypeName(type)));
  311. }
  312. RecurseHierarchy(object->GetDown(), nd);
  313. object = object->GetNext();
  314. }
  315. // copy nodes over to parent
  316. parent->mNumChildren = static_cast<unsigned int>(nodes.size());
  317. parent->mChildren = new aiNode*[parent->mNumChildren]();
  318. std::copy(nodes.begin(), nodes.end(), parent->mChildren);
  319. }
  320. // ------------------------------------------------------------------------------------------------
  321. aiMesh* C4DImporter::ReadMesh(BaseObject* object)
  322. {
  323. assert(object != NULL && object->GetType() == Opolygon);
  324. // based on Melange sample code
  325. PolygonObject* const polyObject = dynamic_cast<PolygonObject*>(object);
  326. ai_assert(polyObject != NULL);
  327. const LONG pointCount = polyObject->GetPointCount();
  328. const LONG polyCount = polyObject->GetPolygonCount();
  329. if(!polyObject || !pointCount) {
  330. LogWarn("ignoring mesh with zero vertices or faces");
  331. return NULL;
  332. }
  333. const Vector* points = polyObject->GetPointR();
  334. ai_assert(points != NULL);
  335. const CPolygon* polys = polyObject->GetPolygonR();
  336. ai_assert(polys != NULL);
  337. ScopeGuard<aiMesh> mesh(new aiMesh());
  338. mesh->mNumFaces = static_cast<unsigned int>(polyCount);
  339. aiFace* face = mesh->mFaces = new aiFace[mesh->mNumFaces]();
  340. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  341. mesh->mMaterialIndex = 0;
  342. unsigned int vcount = 0;
  343. // first count vertices
  344. for (LONG i = 0; i < polyCount; i++)
  345. {
  346. vcount += 3;
  347. // TODO: do we also need to handle lines or points with similar checks?
  348. if (polys[i].c != polys[i].d)
  349. {
  350. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  351. ++vcount;
  352. }
  353. }
  354. ai_assert(vcount > 0);
  355. mesh->mNumVertices = vcount;
  356. aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  357. aiVector3D* normals, *uvs, *tangents, *bitangents;
  358. unsigned int n = 0;
  359. // check if there are normals, tangents or UVW coordinates
  360. BaseTag* tag = object->GetTag(Tnormal);
  361. NormalTag* normals_src = NULL;
  362. if(tag) {
  363. normals_src = dynamic_cast<NormalTag*>(tag);
  364. normals = mesh->mNormals = new aiVector3D[mesh->mNumVertices]();
  365. }
  366. tag = object->GetTag(Ttangent);
  367. TangentTag* tangents_src = NULL;
  368. if(tag) {
  369. tangents_src = dynamic_cast<TangentTag*>(tag);
  370. tangents = mesh->mTangents = new aiVector3D[mesh->mNumVertices]();
  371. bitangents = mesh->mBitangents = new aiVector3D[mesh->mNumVertices]();
  372. }
  373. tag = object->GetTag(Tuvw);
  374. UVWTag* uvs_src = NULL;
  375. if(tag) {
  376. uvs_src = dynamic_cast<UVWTag*>(tag);
  377. uvs = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices]();
  378. }
  379. // copy vertices and extra channels over and populate faces
  380. for (LONG i = 0; i < polyCount; ++i, ++face)
  381. {
  382. ai_assert(polys[i].a < pointCount && polys[i].a >= 0);
  383. const Vector& pointA = points[polys[i].a];
  384. verts->x = pointA.x;
  385. verts->y = pointA.y;
  386. verts->z = pointA.z;
  387. ++verts;
  388. ai_assert(polys[i].b < pointCount && polys[i].b >= 0);
  389. const Vector& pointB = points[polys[i].b];
  390. verts->x = pointB.x;
  391. verts->y = pointB.y;
  392. verts->z = pointB.z;
  393. ++verts;
  394. ai_assert(polys[i].c < pointCount && polys[i].c >= 0);
  395. const Vector& pointC = points[polys[i].c];
  396. verts->x = pointC.x;
  397. verts->y = pointC.y;
  398. verts->z = pointC.z;
  399. ++verts;
  400. // TODO: do we also need to handle lines or points with similar checks?
  401. if (polys[i].c != polys[i].d)
  402. {
  403. ai_assert(polys[i].d < pointCount && polys[i].d >= 0);
  404. face->mNumIndices = 4;
  405. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  406. const Vector& pointD = points[polys[i].d];
  407. verts->x = pointD.x;
  408. verts->y = pointD.y;
  409. verts->z = pointD.z;
  410. ++verts;
  411. }
  412. else {
  413. face->mNumIndices = 3;
  414. }
  415. face->mIndices = new unsigned int[face->mNumIndices];
  416. for(unsigned int j = 0; j < face->mNumIndices; ++j) {
  417. face->mIndices[j] = n++;
  418. }
  419. // copy normals
  420. if (normals_src) {
  421. if(i >= normals_src->GetNormalCount()) {
  422. LogError("unexpected number of normals, ignoring");
  423. }
  424. else {
  425. const NormalStruct& nor = normals_src->GetNormals(i);
  426. normals->x = nor.a.x;
  427. normals->y = nor.a.y;
  428. normals->z = nor.a.z;
  429. ++normals;
  430. normals->x = nor.b.x;
  431. normals->y = nor.b.y;
  432. normals->z = nor.b.z;
  433. ++normals;
  434. normals->x = nor.c.x;
  435. normals->y = nor.c.y;
  436. normals->z = nor.c.z;
  437. ++normals;
  438. if(face->mNumIndices == 4) {
  439. normals->x = nor.d.x;
  440. normals->y = nor.d.y;
  441. normals->z = nor.d.z;
  442. ++normals;
  443. }
  444. }
  445. }
  446. // copy tangents and bitangents
  447. if (tangents_src) {
  448. for(unsigned int k = 0; k < face->mNumIndices; ++k) {
  449. LONG l;
  450. switch(k) {
  451. case 0:
  452. l = polys[i].a;
  453. break;
  454. case 1:
  455. l = polys[i].b;
  456. break;
  457. case 2:
  458. l = polys[i].c;
  459. break;
  460. case 3:
  461. l = polys[i].d;
  462. break;
  463. default:
  464. ai_assert(false);
  465. }
  466. if(l >= tangents_src->GetDataCount()) {
  467. LogError("unexpected number of tangents, ignoring");
  468. break;
  469. }
  470. Tangent tan = tangents_src->GetDataR()[l];
  471. tangents->x = tan.vl.x;
  472. tangents->y = tan.vl.y;
  473. tangents->z = tan.vl.z;
  474. ++tangents;
  475. bitangents->x = tan.vr.x;
  476. bitangents->y = tan.vr.y;
  477. bitangents->z = tan.vr.z;
  478. ++bitangents;
  479. }
  480. }
  481. // copy UVs
  482. if (uvs_src) {
  483. if(i >= uvs_src->GetDataCount()) {
  484. LogError("unexpected number of UV coordinates, ignoring");
  485. }
  486. else {
  487. UVWStruct uvw;
  488. uvs_src->Get(uvs_src->GetDataAddressR(),i,uvw);
  489. uvs->x = uvw.a.x;
  490. uvs->y = 1.0f-uvw.a.y;
  491. uvs->z = uvw.a.z;
  492. ++uvs;
  493. uvs->x = uvw.b.x;
  494. uvs->y = 1.0f-uvw.b.y;
  495. uvs->z = uvw.b.z;
  496. ++uvs;
  497. uvs->x = uvw.c.x;
  498. uvs->y = 1.0f-uvw.c.y;
  499. uvs->z = uvw.c.z;
  500. ++uvs;
  501. if(face->mNumIndices == 4) {
  502. uvs->x = uvw.d.x;
  503. uvs->y = 1.0f-uvw.d.y;
  504. uvs->z = uvw.d.z;
  505. ++uvs;
  506. }
  507. }
  508. }
  509. }
  510. mesh->mMaterialIndex = ResolveMaterial(polyObject);
  511. return mesh.dismiss();
  512. }
  513. // ------------------------------------------------------------------------------------------------
  514. unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj)
  515. {
  516. ai_assert(obj != NULL);
  517. const unsigned int mat_count = static_cast<unsigned int>(materials.size());
  518. BaseTag* tag = obj->GetTag(Ttexture);
  519. if(tag == NULL) {
  520. return mat_count;
  521. }
  522. TextureTag& ttag = dynamic_cast<TextureTag&>(*tag);
  523. BaseMaterial* const mat = ttag.GetMaterial();
  524. assert(mat != NULL);
  525. const MaterialMap::const_iterator it = material_mapping.find(mat);
  526. if(it == material_mapping.end()) {
  527. return mat_count;
  528. }
  529. ai_assert((*it).second < mat_count);
  530. return (*it).second;
  531. }
  532. #endif // ASSIMP_BUILD_NO_C4D_IMPORTER