Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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 BlenderLoader.cpp
  34. * @brief Implementation of the Blender3D importer class.
  35. */
  36. #include "AssimpPCH.h"
  37. //#define ASSIMP_BUILD_NO_COMPRESSED_BLEND
  38. // Uncomment this to disable support for (gzip)compressed .BLEND files
  39. #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
  40. #include "BlenderIntermediate.h"
  41. #include "BlenderModifier.h"
  42. #include "BlenderBMesh.h"
  43. #include "StreamReader.h"
  44. #include "MemoryIOWrapper.h"
  45. // zlib is needed for compressed blend files
  46. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  47. # ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  48. # include <zlib.h>
  49. # else
  50. # include "../contrib/zlib/zlib.h"
  51. # endif
  52. #endif
  53. namespace Assimp {
  54. template<> const std::string LogFunctions<BlenderImporter>::log_prefix = "BLEND: ";
  55. }
  56. using namespace Assimp;
  57. using namespace Assimp::Blender;
  58. using namespace Assimp::Formatter;
  59. static const aiImporterDesc blenderDesc = {
  60. "Blender 3D Importer \nhttp://www.blender3d.org",
  61. "",
  62. "",
  63. "No animation support yet",
  64. aiImporterFlags_SupportBinaryFlavour,
  65. 0,
  66. 0,
  67. 2,
  68. 50,
  69. "blend"
  70. };
  71. // ------------------------------------------------------------------------------------------------
  72. // Constructor to be privately used by Importer
  73. BlenderImporter::BlenderImporter()
  74. : modifier_cache(new BlenderModifierShowcase())
  75. {}
  76. // ------------------------------------------------------------------------------------------------
  77. // Destructor, private as well
  78. BlenderImporter::~BlenderImporter()
  79. {
  80. delete modifier_cache;
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Returns whether the class can handle the format of the given file.
  84. bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  85. {
  86. const std::string& extension = GetExtension(pFile);
  87. if (extension == "blend") {
  88. return true;
  89. }
  90. else if ((!extension.length() || checkSig) && pIOHandler) {
  91. // note: this won't catch compressed files
  92. const char* tokens[] = {"BLENDER"};
  93. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  94. }
  95. return false;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. // List all extensions handled by this loader
  99. void BlenderImporter::GetExtensionList(std::set<std::string>& app)
  100. {
  101. app.insert("blend");
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. // Loader registry entry
  105. const aiImporterDesc* BlenderImporter::GetInfo () const
  106. {
  107. return &blenderDesc;
  108. }
  109. // ------------------------------------------------------------------------------------------------
  110. // Setup configuration properties for the loader
  111. void BlenderImporter::SetupProperties(const Importer* /*pImp*/)
  112. {
  113. // nothing to be done for the moment
  114. }
  115. struct free_it
  116. {
  117. free_it(void* free) : free(free) {}
  118. ~free_it() {
  119. ::free(this->free);
  120. }
  121. void* free;
  122. };
  123. // ------------------------------------------------------------------------------------------------
  124. // Imports the given file into the given scene structure.
  125. void BlenderImporter::InternReadFile( const std::string& pFile,
  126. aiScene* pScene, IOSystem* pIOHandler)
  127. {
  128. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  129. Bytef* dest = NULL;
  130. free_it free_it_really(dest);
  131. #endif
  132. FileDatabase file;
  133. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb"));
  134. if (!stream) {
  135. ThrowException("Could not open file for reading");
  136. }
  137. char magic[8] = {0};
  138. stream->Read(magic,7,1);
  139. if (strcmp(magic,"BLENDER")) {
  140. // Check for presence of the gzip header. If yes, assume it is a
  141. // compressed blend file and try uncompressing it, else fail. This is to
  142. // avoid uncompressing random files which our loader might end up with.
  143. #ifdef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  144. ThrowException("BLENDER magic bytes are missing, is this file compressed (Assimp was built without decompression support)?");
  145. #else
  146. if (magic[0] != 0x1f || static_cast<uint8_t>(magic[1]) != 0x8b) {
  147. ThrowException("BLENDER magic bytes are missing, couldn't find GZIP header either");
  148. }
  149. LogDebug("Found no BLENDER magic word but a GZIP header, might be a compressed file");
  150. if (magic[2] != 8) {
  151. ThrowException("Unsupported GZIP compression method");
  152. }
  153. // http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
  154. stream->Seek(0L,aiOrigin_SET);
  155. boost::shared_ptr<StreamReaderLE> reader = boost::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
  156. // build a zlib stream
  157. z_stream zstream;
  158. zstream.opaque = Z_NULL;
  159. zstream.zalloc = Z_NULL;
  160. zstream.zfree = Z_NULL;
  161. zstream.data_type = Z_BINARY;
  162. // http://hewgill.com/journal/entries/349-how-to-decompress-gzip-stream-with-zlib
  163. inflateInit2(&zstream, 16+MAX_WBITS);
  164. zstream.next_in = reinterpret_cast<Bytef*>( reader->GetPtr() );
  165. zstream.avail_in = reader->GetRemainingSize();
  166. size_t total = 0l;
  167. // and decompress the data .... do 1k chunks in the hope that we won't kill the stack
  168. #define MYBLOCK 1024
  169. Bytef block[MYBLOCK];
  170. int ret;
  171. do {
  172. zstream.avail_out = MYBLOCK;
  173. zstream.next_out = block;
  174. ret = inflate(&zstream, Z_NO_FLUSH);
  175. if (ret != Z_STREAM_END && ret != Z_OK) {
  176. ThrowException("Failure decompressing this file using gzip, seemingly it is NOT a compressed .BLEND file");
  177. }
  178. const size_t have = MYBLOCK - zstream.avail_out;
  179. total += have;
  180. dest = reinterpret_cast<Bytef*>( realloc(dest,total) );
  181. memcpy(dest + total - have,block,have);
  182. }
  183. while (ret != Z_STREAM_END);
  184. // terminate zlib
  185. inflateEnd(&zstream);
  186. // replace the input stream with a memory stream
  187. stream.reset(new MemoryIOStream(reinterpret_cast<uint8_t*>(dest),total));
  188. // .. and retry
  189. stream->Read(magic,7,1);
  190. if (strcmp(magic,"BLENDER")) {
  191. ThrowException("Found no BLENDER magic word in decompressed GZIP file");
  192. }
  193. #endif
  194. }
  195. file.i64bit = (stream->Read(magic,1,1),magic[0]=='-');
  196. file.little = (stream->Read(magic,1,1),magic[0]=='v');
  197. stream->Read(magic,3,1);
  198. magic[3] = '\0';
  199. LogInfo((format(),"Blender version is ",magic[0],".",magic+1,
  200. " (64bit: ",file.i64bit?"true":"false",
  201. ", little endian: ",file.little?"true":"false",")"
  202. ));
  203. ParseBlendFile(file,stream);
  204. Scene scene;
  205. ExtractScene(scene,file);
  206. ConvertBlendFile(pScene,scene,file);
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. void BlenderImporter::ParseBlendFile(FileDatabase& out, boost::shared_ptr<IOStream> stream)
  210. {
  211. out.reader = boost::shared_ptr<StreamReaderAny>(new StreamReaderAny(stream,out.little));
  212. DNAParser dna_reader(out);
  213. const DNA* dna = NULL;
  214. out.entries.reserve(128); { // even small BLEND files tend to consist of many file blocks
  215. SectionParser parser(*out.reader.get(),out.i64bit);
  216. // first parse the file in search for the DNA and insert all other sections into the database
  217. while ((parser.Next(),1)) {
  218. const FileBlockHead& head = parser.GetCurrent();
  219. if (head.id == "ENDB") {
  220. break; // only valid end of the file
  221. }
  222. else if (head.id == "DNA1") {
  223. dna_reader.Parse();
  224. dna = &dna_reader.GetDNA();
  225. continue;
  226. }
  227. out.entries.push_back(head);
  228. }
  229. }
  230. if (!dna) {
  231. ThrowException("SDNA not found");
  232. }
  233. std::sort(out.entries.begin(),out.entries.end());
  234. }
  235. // ------------------------------------------------------------------------------------------------
  236. void BlenderImporter::ExtractScene(Scene& out, const FileDatabase& file)
  237. {
  238. const FileBlockHead* block = NULL;
  239. std::map<std::string,size_t>::const_iterator it = file.dna.indices.find("Scene");
  240. if (it == file.dna.indices.end()) {
  241. ThrowException("There is no `Scene` structure record");
  242. }
  243. const Structure& ss = file.dna.structures[(*it).second];
  244. // we need a scene somewhere to start with.
  245. for_each(const FileBlockHead& bl,file.entries) {
  246. // Fix: using the DNA index is more reliable to locate scenes
  247. //if (bl.id == "SC") {
  248. if (bl.dna_index == (*it).second) {
  249. block = &bl;
  250. break;
  251. }
  252. }
  253. if (!block) {
  254. ThrowException("There is not a single `Scene` record to load");
  255. }
  256. file.reader->SetCurrentPos(block->start);
  257. ss.Convert(out,file);
  258. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  259. DefaultLogger::get()->info((format(),
  260. "(Stats) Fields read: " ,file.stats().fields_read,
  261. ", pointers resolved: " ,file.stats().pointers_resolved,
  262. ", cache hits: " ,file.stats().cache_hits,
  263. ", cached objects: " ,file.stats().cached_objects
  264. ));
  265. #endif
  266. }
  267. // ------------------------------------------------------------------------------------------------
  268. void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileDatabase& file)
  269. {
  270. ConversionData conv(file);
  271. // FIXME it must be possible to take the hierarchy directly from
  272. // the file. This is terrible. Here, we're first looking for
  273. // all objects which don't have parent objects at all -
  274. std::deque<const Object*> no_parents;
  275. for (boost::shared_ptr<Base> cur = boost::static_pointer_cast<Base> ( in.base.first ); cur; cur = cur->next) {
  276. if (cur->object) {
  277. if(!cur->object->parent) {
  278. no_parents.push_back(cur->object.get());
  279. }
  280. else conv.objects.insert(cur->object.get());
  281. }
  282. }
  283. for (boost::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
  284. if (cur->object) {
  285. if(cur->object->parent) {
  286. conv.objects.insert(cur->object.get());
  287. }
  288. }
  289. }
  290. if (no_parents.empty()) {
  291. ThrowException("Expected at least one object with no parent");
  292. }
  293. aiNode* root = out->mRootNode = new aiNode("<BlenderRoot>");
  294. root->mNumChildren = static_cast<unsigned int>(no_parents.size());
  295. root->mChildren = new aiNode*[root->mNumChildren]();
  296. for (unsigned int i = 0; i < root->mNumChildren; ++i) {
  297. root->mChildren[i] = ConvertNode(in, no_parents[i], conv, aiMatrix4x4());
  298. root->mChildren[i]->mParent = root;
  299. }
  300. BuildMaterials(conv);
  301. if (conv.meshes->size()) {
  302. out->mMeshes = new aiMesh*[out->mNumMeshes = static_cast<unsigned int>( conv.meshes->size() )];
  303. std::copy(conv.meshes->begin(),conv.meshes->end(),out->mMeshes);
  304. conv.meshes.dismiss();
  305. }
  306. if (conv.lights->size()) {
  307. out->mLights = new aiLight*[out->mNumLights = static_cast<unsigned int>( conv.lights->size() )];
  308. std::copy(conv.lights->begin(),conv.lights->end(),out->mLights);
  309. conv.lights.dismiss();
  310. }
  311. if (conv.cameras->size()) {
  312. out->mCameras = new aiCamera*[out->mNumCameras = static_cast<unsigned int>( conv.cameras->size() )];
  313. std::copy(conv.cameras->begin(),conv.cameras->end(),out->mCameras);
  314. conv.cameras.dismiss();
  315. }
  316. if (conv.materials->size()) {
  317. out->mMaterials = new aiMaterial*[out->mNumMaterials = static_cast<unsigned int>( conv.materials->size() )];
  318. std::copy(conv.materials->begin(),conv.materials->end(),out->mMaterials);
  319. conv.materials.dismiss();
  320. }
  321. if (conv.textures->size()) {
  322. out->mTextures = new aiTexture*[out->mNumTextures = static_cast<unsigned int>( conv.textures->size() )];
  323. std::copy(conv.textures->begin(),conv.textures->end(),out->mTextures);
  324. conv.textures.dismiss();
  325. }
  326. // acknowledge that the scene might come out incomplete
  327. // by Assimps definition of `complete`: blender scenes
  328. // can consist of thousands of cameras or lights with
  329. // not a single mesh between them.
  330. if (!out->mNumMeshes) {
  331. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  332. }
  333. }
  334. // ------------------------------------------------------------------------------------------------
  335. void BlenderImporter::ResolveImage(aiMaterial* out, const Material* mat, const MTex* tex, const Image* img, ConversionData& conv_data)
  336. {
  337. (void)mat; (void)tex; (void)conv_data;
  338. aiString name;
  339. // check if the file contents are bundled with the BLEND file
  340. if (img->packedfile) {
  341. name.data[0] = '*';
  342. name.length = 1+ ASSIMP_itoa10(name.data+1,MAXLEN-1,conv_data.textures->size());
  343. conv_data.textures->push_back(new aiTexture());
  344. aiTexture* tex = conv_data.textures->back();
  345. // usually 'img->name' will be the original file name of the embedded textures,
  346. // so we can extract the file extension from it.
  347. const size_t nlen = strlen( img->name );
  348. const char* s = img->name+nlen, *e = s;
  349. while (s >= img->name && *s != '.')--s;
  350. tex->achFormatHint[0] = s+1>e ? '\0' : ::tolower( s[1] );
  351. tex->achFormatHint[1] = s+2>e ? '\0' : ::tolower( s[2] );
  352. tex->achFormatHint[2] = s+3>e ? '\0' : ::tolower( s[3] );
  353. tex->achFormatHint[3] = '\0';
  354. // tex->mHeight = 0;
  355. tex->mWidth = img->packedfile->size;
  356. uint8_t* ch = new uint8_t[tex->mWidth];
  357. conv_data.db.reader->SetCurrentPos(static_cast<size_t>( img->packedfile->data->val));
  358. conv_data.db.reader->CopyAndAdvance(ch,tex->mWidth);
  359. tex->pcData = reinterpret_cast<aiTexel*>(ch);
  360. LogInfo("Reading embedded texture, original file was "+std::string(img->name));
  361. }
  362. else {
  363. name = aiString( img->name );
  364. }
  365. aiTextureType texture_type = aiTextureType_UNKNOWN;
  366. MTex::MapType map_type = tex->mapto;
  367. if (map_type & MTex::MapType_COL)
  368. texture_type = aiTextureType_DIFFUSE;
  369. else if (map_type & MTex::MapType_NORM) {
  370. if (tex->tex->imaflag & Tex::ImageFlags_NORMALMAP) {
  371. texture_type = aiTextureType_NORMALS;
  372. }
  373. else {
  374. texture_type = aiTextureType_HEIGHT;
  375. }
  376. out->AddProperty(&tex->norfac,1,AI_MATKEY_BUMPSCALING);
  377. }
  378. else if (map_type & MTex::MapType_COLSPEC)
  379. texture_type = aiTextureType_SPECULAR;
  380. else if (map_type & MTex::MapType_COLMIR)
  381. texture_type = aiTextureType_REFLECTION;
  382. //else if (map_type & MTex::MapType_REF)
  383. else if (map_type & MTex::MapType_SPEC)
  384. texture_type = aiTextureType_SHININESS;
  385. else if (map_type & MTex::MapType_EMIT)
  386. texture_type = aiTextureType_EMISSIVE;
  387. //else if (map_type & MTex::MapType_ALPHA)
  388. //else if (map_type & MTex::MapType_HAR)
  389. //else if (map_type & MTex::MapType_RAYMIRR)
  390. //else if (map_type & MTex::MapType_TRANSLU)
  391. else if (map_type & MTex::MapType_AMB)
  392. texture_type = aiTextureType_AMBIENT;
  393. else if (map_type & MTex::MapType_DISPLACE)
  394. texture_type = aiTextureType_DISPLACEMENT;
  395. //else if (map_type & MTex::MapType_WARP)
  396. out->AddProperty(&name,AI_MATKEY_TEXTURE(texture_type,
  397. conv_data.next_texture[texture_type]++));
  398. }
  399. // ------------------------------------------------------------------------------------------------
  400. void BlenderImporter::AddSentinelTexture(aiMaterial* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  401. {
  402. (void)mat; (void)tex; (void)conv_data;
  403. aiString name;
  404. name.length = sprintf(name.data, "Procedural,num=%i,type=%s",conv_data.sentinel_cnt++,
  405. GetTextureTypeDisplayString(tex->tex->type)
  406. );
  407. out->AddProperty(&name,AI_MATKEY_TEXTURE_DIFFUSE(
  408. conv_data.next_texture[aiTextureType_DIFFUSE]++)
  409. );
  410. }
  411. // ------------------------------------------------------------------------------------------------
  412. void BlenderImporter::ResolveTexture(aiMaterial* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  413. {
  414. const Tex* rtex = tex->tex.get();
  415. if(!rtex || !rtex->type) {
  416. return;
  417. }
  418. // We can't support most of the texture types because they're mostly procedural.
  419. // These are substituted by a dummy texture.
  420. const char* dispnam = "";
  421. switch( rtex->type )
  422. {
  423. // these are listed in blender's UI
  424. case Tex::Type_CLOUDS :
  425. case Tex::Type_WOOD :
  426. case Tex::Type_MARBLE :
  427. case Tex::Type_MAGIC :
  428. case Tex::Type_BLEND :
  429. case Tex::Type_STUCCI :
  430. case Tex::Type_NOISE :
  431. case Tex::Type_PLUGIN :
  432. case Tex::Type_MUSGRAVE :
  433. case Tex::Type_VORONOI :
  434. case Tex::Type_DISTNOISE :
  435. case Tex::Type_ENVMAP :
  436. // these do no appear in the UI, why?
  437. case Tex::Type_POINTDENSITY :
  438. case Tex::Type_VOXELDATA :
  439. LogWarn(std::string("Encountered a texture with an unsupported type: ")+dispnam);
  440. AddSentinelTexture(out, mat, tex, conv_data);
  441. break;
  442. case Tex::Type_IMAGE :
  443. if (!rtex->ima) {
  444. LogError("A texture claims to be an Image, but no image reference is given");
  445. break;
  446. }
  447. ResolveImage(out, mat, tex, rtex->ima.get(),conv_data);
  448. break;
  449. default:
  450. ai_assert(false);
  451. };
  452. }
  453. // ------------------------------------------------------------------------------------------------
  454. void BlenderImporter::BuildMaterials(ConversionData& conv_data)
  455. {
  456. conv_data.materials->reserve(conv_data.materials_raw.size());
  457. // add a default material if necessary
  458. unsigned int index = static_cast<unsigned int>( -1 );
  459. for_each( aiMesh* mesh, conv_data.meshes.get() ) {
  460. if (mesh->mMaterialIndex == static_cast<unsigned int>( -1 )) {
  461. if (index == static_cast<unsigned int>( -1 )) {
  462. // ok, we need to add a dedicated default material for some poor material-less meshes
  463. boost::shared_ptr<Material> p(new Material());
  464. strcpy( p->id.name+2, AI_DEFAULT_MATERIAL_NAME );
  465. p->r = p->g = p->b = 0.6f;
  466. p->specr = p->specg = p->specb = 0.6f;
  467. p->ambr = p->ambg = p->ambb = 0.0f;
  468. p->mirr = p->mirg = p->mirb = 0.0f;
  469. p->emit = 0.f;
  470. p->alpha = 0.f;
  471. // XXX add more / or add default c'tor to Material
  472. index = static_cast<unsigned int>( conv_data.materials_raw.size() );
  473. conv_data.materials_raw.push_back(p);
  474. LogInfo("Adding default material ...");
  475. }
  476. mesh->mMaterialIndex = index;
  477. }
  478. }
  479. for_each(boost::shared_ptr<Material> mat, conv_data.materials_raw) {
  480. // reset per material global counters
  481. for (size_t i = 0; i < sizeof(conv_data.next_texture)/sizeof(conv_data.next_texture[0]);++i) {
  482. conv_data.next_texture[i] = 0 ;
  483. }
  484. aiMaterial* mout = new aiMaterial();
  485. conv_data.materials->push_back(mout);
  486. // set material name
  487. aiString name = aiString(mat->id.name+2); // skip over the name prefix 'MA'
  488. mout->AddProperty(&name,AI_MATKEY_NAME);
  489. // basic material colors
  490. aiColor3D col(mat->r,mat->g,mat->b);
  491. if (mat->r || mat->g || mat->b ) {
  492. // Usually, zero diffuse color means no diffuse color at all in the equation.
  493. // So we omit this member to express this intent.
  494. mout->AddProperty(&col,1,AI_MATKEY_COLOR_DIFFUSE);
  495. if (mat->emit) {
  496. aiColor3D emit_col(mat->emit * mat->r, mat->emit * mat->g, mat->emit * mat->b) ;
  497. mout->AddProperty(&emit_col, 1, AI_MATKEY_COLOR_EMISSIVE) ;
  498. }
  499. }
  500. col = aiColor3D(mat->specr,mat->specg,mat->specb);
  501. mout->AddProperty(&col,1,AI_MATKEY_COLOR_SPECULAR);
  502. // is hardness/shininess set?
  503. if( mat->har ) {
  504. const float har = mat->har;
  505. mout->AddProperty(&har,1,AI_MATKEY_SHININESS);
  506. }
  507. col = aiColor3D(mat->ambr,mat->ambg,mat->ambb);
  508. mout->AddProperty(&col,1,AI_MATKEY_COLOR_AMBIENT);
  509. col = aiColor3D(mat->mirr,mat->mirg,mat->mirb);
  510. mout->AddProperty(&col,1,AI_MATKEY_COLOR_REFLECTIVE);
  511. for(size_t i = 0; i < sizeof(mat->mtex) / sizeof(mat->mtex[0]); ++i) {
  512. if (!mat->mtex[i]) {
  513. continue;
  514. }
  515. ResolveTexture(mout,mat.get(),mat->mtex[i].get(),conv_data);
  516. }
  517. }
  518. }
  519. // ------------------------------------------------------------------------------------------------
  520. void BlenderImporter::CheckActualType(const ElemBase* dt, const char* check)
  521. {
  522. ai_assert(dt);
  523. if (strcmp(dt->dna_type,check)) {
  524. ThrowException((format(),
  525. "Expected object at ",std::hex,dt," to be of type `",check,
  526. "`, but it claims to be a `",dt->dna_type,"`instead"
  527. ));
  528. }
  529. }
  530. // ------------------------------------------------------------------------------------------------
  531. void BlenderImporter::NotSupportedObjectType(const Object* obj, const char* type)
  532. {
  533. LogWarn((format(), "Object `",obj->id.name,"` - type is unsupported: `",type, "`, skipping" ));
  534. }
  535. // ------------------------------------------------------------------------------------------------
  536. void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, const Mesh* mesh,
  537. ConversionData& conv_data, TempArray<std::vector,aiMesh>& temp
  538. )
  539. {
  540. BlenderBMeshConverter BMeshConverter( mesh );
  541. if ( BMeshConverter.ContainsBMesh( ) )
  542. {
  543. mesh = BMeshConverter.TriangulateBMesh( );
  544. }
  545. typedef std::pair<const int,size_t> MyPair;
  546. if ((!mesh->totface && !mesh->totloop) || !mesh->totvert) {
  547. return;
  548. }
  549. // some sanity checks
  550. if (static_cast<size_t> ( mesh->totface ) > mesh->mface.size() ){
  551. ThrowException("Number of faces is larger than the corresponding array");
  552. }
  553. if (static_cast<size_t> ( mesh->totvert ) > mesh->mvert.size()) {
  554. ThrowException("Number of vertices is larger than the corresponding array");
  555. }
  556. if (static_cast<size_t> ( mesh->totloop ) > mesh->mloop.size()) {
  557. ThrowException("Number of vertices is larger than the corresponding array");
  558. }
  559. // collect per-submesh numbers
  560. std::map<int,size_t> per_mat;
  561. std::map<int,size_t> per_mat_verts;
  562. for (int i = 0; i < mesh->totface; ++i) {
  563. const MFace& mf = mesh->mface[i];
  564. per_mat[ mf.mat_nr ]++;
  565. per_mat_verts[ mf.mat_nr ] += mf.v4?4:3;
  566. }
  567. for (int i = 0; i < mesh->totpoly; ++i) {
  568. const MPoly& mp = mesh->mpoly[i];
  569. per_mat[ mp.mat_nr ]++;
  570. per_mat_verts[ mp.mat_nr ] += mp.totloop;
  571. }
  572. // ... and allocate the corresponding meshes
  573. const size_t old = temp->size();
  574. temp->reserve(temp->size() + per_mat.size());
  575. std::map<size_t,size_t> mat_num_to_mesh_idx;
  576. for_each(MyPair& it, per_mat) {
  577. mat_num_to_mesh_idx[it.first] = temp->size();
  578. temp->push_back(new aiMesh());
  579. aiMesh* out = temp->back();
  580. out->mVertices = new aiVector3D[per_mat_verts[it.first]];
  581. out->mNormals = new aiVector3D[per_mat_verts[it.first]];
  582. //out->mNumFaces = 0
  583. //out->mNumVertices = 0
  584. out->mFaces = new aiFace[it.second]();
  585. // all submeshes created from this mesh are named equally. this allows
  586. // curious users to recover the original adjacency.
  587. out->mName = aiString(mesh->id.name+2);
  588. // skip over the name prefix 'ME'
  589. // resolve the material reference and add this material to the set of
  590. // output materials. The (temporary) material index is the index
  591. // of the material entry within the list of resolved materials.
  592. if (mesh->mat) {
  593. if (static_cast<size_t> ( it.first ) >= mesh->mat.size() ) {
  594. ThrowException("Material index is out of range");
  595. }
  596. boost::shared_ptr<Material> mat = mesh->mat[it.first];
  597. const std::deque< boost::shared_ptr<Material> >::iterator has = std::find(
  598. conv_data.materials_raw.begin(),
  599. conv_data.materials_raw.end(),mat
  600. );
  601. if (has != conv_data.materials_raw.end()) {
  602. out->mMaterialIndex = static_cast<unsigned int>( std::distance(conv_data.materials_raw.begin(),has));
  603. }
  604. else {
  605. out->mMaterialIndex = static_cast<unsigned int>( conv_data.materials_raw.size() );
  606. conv_data.materials_raw.push_back(mat);
  607. }
  608. }
  609. else out->mMaterialIndex = static_cast<unsigned int>( -1 );
  610. }
  611. for (int i = 0; i < mesh->totface; ++i) {
  612. const MFace& mf = mesh->mface[i];
  613. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mf.mat_nr ] ];
  614. aiFace& f = out->mFaces[out->mNumFaces++];
  615. f.mIndices = new unsigned int[ f.mNumIndices = mf.v4?4:3 ];
  616. aiVector3D* vo = out->mVertices + out->mNumVertices;
  617. aiVector3D* vn = out->mNormals + out->mNumVertices;
  618. // XXX we can't fold this easily, because we are restricted
  619. // to the member names from the BLEND file (v1,v2,v3,v4)
  620. // which are assigned by the genblenddna.py script and
  621. // cannot be changed without breaking the entire
  622. // import process.
  623. if (mf.v1 >= mesh->totvert) {
  624. ThrowException("Vertex index v1 out of range");
  625. }
  626. const MVert* v = &mesh->mvert[mf.v1];
  627. vo->x = v->co[0];
  628. vo->y = v->co[1];
  629. vo->z = v->co[2];
  630. vn->x = v->no[0];
  631. vn->y = v->no[1];
  632. vn->z = v->no[2];
  633. f.mIndices[0] = out->mNumVertices++;
  634. ++vo;
  635. ++vn;
  636. // if (f.mNumIndices >= 2) {
  637. if (mf.v2 >= mesh->totvert) {
  638. ThrowException("Vertex index v2 out of range");
  639. }
  640. v = &mesh->mvert[mf.v2];
  641. vo->x = v->co[0];
  642. vo->y = v->co[1];
  643. vo->z = v->co[2];
  644. vn->x = v->no[0];
  645. vn->y = v->no[1];
  646. vn->z = v->no[2];
  647. f.mIndices[1] = out->mNumVertices++;
  648. ++vo;
  649. ++vn;
  650. if (mf.v3 >= mesh->totvert) {
  651. ThrowException("Vertex index v3 out of range");
  652. }
  653. // if (f.mNumIndices >= 3) {
  654. v = &mesh->mvert[mf.v3];
  655. vo->x = v->co[0];
  656. vo->y = v->co[1];
  657. vo->z = v->co[2];
  658. vn->x = v->no[0];
  659. vn->y = v->no[1];
  660. vn->z = v->no[2];
  661. f.mIndices[2] = out->mNumVertices++;
  662. ++vo;
  663. ++vn;
  664. if (mf.v4 >= mesh->totvert) {
  665. ThrowException("Vertex index v4 out of range");
  666. }
  667. // if (f.mNumIndices >= 4) {
  668. if (mf.v4) {
  669. v = &mesh->mvert[mf.v4];
  670. vo->x = v->co[0];
  671. vo->y = v->co[1];
  672. vo->z = v->co[2];
  673. vn->x = v->no[0];
  674. vn->y = v->no[1];
  675. vn->z = v->no[2];
  676. f.mIndices[3] = out->mNumVertices++;
  677. ++vo;
  678. ++vn;
  679. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  680. }
  681. else out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  682. // }
  683. // }
  684. // }
  685. }
  686. for (int i = 0; i < mesh->totpoly; ++i) {
  687. const MPoly& mf = mesh->mpoly[i];
  688. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mf.mat_nr ] ];
  689. aiFace& f = out->mFaces[out->mNumFaces++];
  690. f.mIndices = new unsigned int[ f.mNumIndices = mf.totloop ];
  691. aiVector3D* vo = out->mVertices + out->mNumVertices;
  692. aiVector3D* vn = out->mNormals + out->mNumVertices;
  693. // XXX we can't fold this easily, because we are restricted
  694. // to the member names from the BLEND file (v1,v2,v3,v4)
  695. // which are assigned by the genblenddna.py script and
  696. // cannot be changed without breaking the entire
  697. // import process.
  698. for (int j = 0;j < mf.totloop; ++j)
  699. {
  700. const MLoop& loop = mesh->mloop[mf.loopstart + j];
  701. if (loop.v >= mesh->totvert) {
  702. ThrowException("Vertex index out of range");
  703. }
  704. const MVert& v = mesh->mvert[loop.v];
  705. vo->x = v.co[0];
  706. vo->y = v.co[1];
  707. vo->z = v.co[2];
  708. vn->x = v.no[0];
  709. vn->y = v.no[1];
  710. vn->z = v.no[2];
  711. f.mIndices[j] = out->mNumVertices++;
  712. ++vo;
  713. ++vn;
  714. }
  715. if (mf.totloop == 3)
  716. {
  717. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  718. }
  719. else
  720. {
  721. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  722. }
  723. }
  724. // collect texture coordinates, they're stored in a separate per-face buffer
  725. if (mesh->mtface || mesh->mloopuv) {
  726. if (mesh->totface > static_cast<int> ( mesh->mtface.size())) {
  727. ThrowException("Number of UV faces is larger than the corresponding UV face array (#1)");
  728. }
  729. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  730. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  731. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  732. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  733. }
  734. for (int i = 0; i < mesh->totface; ++i) {
  735. const MTFace* v = &mesh->mtface[i];
  736. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  737. const aiFace& f = out->mFaces[out->mNumFaces++];
  738. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  739. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  740. vo->x = v->uv[i][0];
  741. vo->y = v->uv[i][1];
  742. }
  743. }
  744. for (int i = 0; i < mesh->totpoly; ++i) {
  745. const MPoly& v = mesh->mpoly[i];
  746. aiMesh* const out = temp[ mat_num_to_mesh_idx[ v.mat_nr ] ];
  747. const aiFace& f = out->mFaces[out->mNumFaces++];
  748. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  749. for (unsigned int j = 0; j < f.mNumIndices; ++j,++vo,++out->mNumVertices) {
  750. const MLoopUV& uv = mesh->mloopuv[v.loopstart + j];
  751. vo->x = uv.uv[0];
  752. vo->y = uv.uv[1];
  753. }
  754. }
  755. }
  756. // collect texture coordinates, old-style (marked as deprecated in current blender sources)
  757. if (mesh->tface) {
  758. if (mesh->totface > static_cast<int> ( mesh->tface.size())) {
  759. ThrowException("Number of faces is larger than the corresponding UV face array (#2)");
  760. }
  761. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  762. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  763. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  764. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  765. }
  766. for (int i = 0; i < mesh->totface; ++i) {
  767. const TFace* v = &mesh->tface[i];
  768. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  769. const aiFace& f = out->mFaces[out->mNumFaces++];
  770. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  771. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  772. vo->x = v->uv[i][0];
  773. vo->y = v->uv[i][1];
  774. }
  775. }
  776. }
  777. // collect vertex colors, stored separately as well
  778. if (mesh->mcol || mesh->mloopcol) {
  779. if (mesh->totface > static_cast<int> ( (mesh->mcol.size()/4)) ) {
  780. ThrowException("Number of faces is larger than the corresponding color face array");
  781. }
  782. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  783. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  784. (*it)->mColors[0] = new aiColor4D[(*it)->mNumVertices];
  785. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  786. }
  787. for (int i = 0; i < mesh->totface; ++i) {
  788. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  789. const aiFace& f = out->mFaces[out->mNumFaces++];
  790. aiColor4D* vo = &out->mColors[0][out->mNumVertices];
  791. for (unsigned int n = 0; n < f.mNumIndices; ++n, ++vo,++out->mNumVertices) {
  792. const MCol* col = &mesh->mcol[(i<<2)+n];
  793. vo->r = col->r;
  794. vo->g = col->g;
  795. vo->b = col->b;
  796. vo->a = col->a;
  797. }
  798. for (unsigned int n = f.mNumIndices; n < 4; ++n);
  799. }
  800. for (int i = 0; i < mesh->totpoly; ++i) {
  801. const MPoly& v = mesh->mpoly[i];
  802. aiMesh* const out = temp[ mat_num_to_mesh_idx[ v.mat_nr ] ];
  803. const aiFace& f = out->mFaces[out->mNumFaces++];
  804. aiColor4D* vo = &out->mColors[0][out->mNumVertices];
  805. for (unsigned int j = 0; j < f.mNumIndices; ++j,++vo,++out->mNumVertices) {
  806. const MLoopCol& col = mesh->mloopcol[v.loopstart + j];
  807. vo->r = col.r;
  808. vo->g = col.g;
  809. vo->b = col.b;
  810. vo->a = col.a;
  811. }
  812. }
  813. }
  814. return;
  815. }
  816. // ------------------------------------------------------------------------------------------------
  817. aiCamera* BlenderImporter::ConvertCamera(const Scene& /*in*/, const Object* obj, const Camera* camera, ConversionData& /*conv_data*/)
  818. {
  819. ScopeGuard<aiCamera> out(new aiCamera());
  820. out->mName = obj->id.name+2;
  821. out->mPosition = aiVector3D(0.f, 0.f, 0.f);
  822. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  823. out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  824. return out.dismiss();
  825. }
  826. // ------------------------------------------------------------------------------------------------
  827. aiLight* BlenderImporter::ConvertLight(const Scene& in, const Object* obj, const Lamp* lamp, ConversionData& conv_data)
  828. {
  829. ScopeGuard<aiLight> out(new aiLight());
  830. out->mName = obj->id.name+2;
  831. switch (lamp->type)
  832. {
  833. case Lamp::Type_Local:
  834. out->mType = aiLightSource_POINT;
  835. break;
  836. case Lamp::Type_Sun:
  837. out->mType = aiLightSource_DIRECTIONAL;
  838. // blender orients directional lights as facing toward -z
  839. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  840. break;
  841. default:
  842. break;
  843. }
  844. out->mColorAmbient = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  845. out->mColorSpecular = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  846. out->mColorDiffuse = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  847. return out.dismiss();
  848. }
  849. // ------------------------------------------------------------------------------------------------
  850. aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, ConversionData& conv_data, const aiMatrix4x4& parentTransform)
  851. {
  852. std::deque<const Object*> children;
  853. for(std::set<const Object*>::iterator it = conv_data.objects.begin(); it != conv_data.objects.end() ;) {
  854. const Object* object = *it;
  855. if (object->parent == obj) {
  856. children.push_back(object);
  857. conv_data.objects.erase(it++);
  858. continue;
  859. }
  860. ++it;
  861. }
  862. ScopeGuard<aiNode> node(new aiNode(obj->id.name+2)); // skip over the name prefix 'OB'
  863. if (obj->data) {
  864. switch (obj->type)
  865. {
  866. case Object :: Type_EMPTY:
  867. break; // do nothing
  868. // supported object types
  869. case Object :: Type_MESH: {
  870. const size_t old = conv_data.meshes->size();
  871. CheckActualType(obj->data.get(),"Mesh");
  872. ConvertMesh(in,obj,static_cast<const Mesh*>(obj->data.get()),conv_data,conv_data.meshes);
  873. if (conv_data.meshes->size() > old) {
  874. node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size()-old)];
  875. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  876. node->mMeshes[i] = i + old;
  877. }
  878. }}
  879. break;
  880. case Object :: Type_LAMP: {
  881. CheckActualType(obj->data.get(),"Lamp");
  882. aiLight* mesh = ConvertLight(in,obj,static_cast<const Lamp*>(
  883. obj->data.get()),conv_data);
  884. if (mesh) {
  885. conv_data.lights->push_back(mesh);
  886. }}
  887. break;
  888. case Object :: Type_CAMERA: {
  889. CheckActualType(obj->data.get(),"Camera");
  890. aiCamera* mesh = ConvertCamera(in,obj,static_cast<const Camera*>(
  891. obj->data.get()),conv_data);
  892. if (mesh) {
  893. conv_data.cameras->push_back(mesh);
  894. }}
  895. break;
  896. // unsupported object types / log, but do not break
  897. case Object :: Type_CURVE:
  898. NotSupportedObjectType(obj,"Curve");
  899. break;
  900. case Object :: Type_SURF:
  901. NotSupportedObjectType(obj,"Surface");
  902. break;
  903. case Object :: Type_FONT:
  904. NotSupportedObjectType(obj,"Font");
  905. break;
  906. case Object :: Type_MBALL:
  907. NotSupportedObjectType(obj,"MetaBall");
  908. break;
  909. case Object :: Type_WAVE:
  910. NotSupportedObjectType(obj,"Wave");
  911. break;
  912. case Object :: Type_LATTICE:
  913. NotSupportedObjectType(obj,"Lattice");
  914. break;
  915. // invalid or unknown type
  916. default:
  917. break;
  918. }
  919. }
  920. for(unsigned int x = 0; x < 4; ++x) {
  921. for(unsigned int y = 0; y < 4; ++y) {
  922. node->mTransformation[y][x] = obj->obmat[x][y];
  923. }
  924. }
  925. aiMatrix4x4 m = parentTransform;
  926. m = m.Inverse();
  927. node->mTransformation = m*node->mTransformation;
  928. if (children.size()) {
  929. node->mNumChildren = static_cast<unsigned int>(children.size());
  930. aiNode** nd = node->mChildren = new aiNode*[node->mNumChildren]();
  931. for_each (const Object* nobj,children) {
  932. *nd = ConvertNode(in,nobj,conv_data,node->mTransformation * parentTransform);
  933. (*nd++)->mParent = node;
  934. }
  935. }
  936. // apply modifiers
  937. modifier_cache->ApplyModifiers(*node,conv_data,in,*obj);
  938. return node.dismiss();
  939. }
  940. #endif