BlenderLoader.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, 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. //#define ASSIMP_BUILD_NO_COMPRESSED_BLEND
  37. // Uncomment this to disable support for (gzip)compressed .BLEND files
  38. #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
  39. #include "BlenderIntermediate.h"
  40. #include "BlenderModifier.h"
  41. #include "BlenderBMesh.h"
  42. #include "BlenderCustomData.h"
  43. #include <assimp/StringUtils.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/importerdesc.h>
  46. #include <assimp/StringComparison.h>
  47. #include <assimp/StreamReader.h>
  48. #include <assimp/MemoryIOWrapper.h>
  49. #include <cctype>
  50. // zlib is needed for compressed blend files
  51. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  52. # ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  53. # include <zlib.h>
  54. # else
  55. # include "../contrib/zlib/zlib.h"
  56. # endif
  57. #endif
  58. namespace Assimp {
  59. template<> const char* LogFunctions<BlenderImporter>::Prefix()
  60. {
  61. static auto prefix = "BLEND: ";
  62. return prefix;
  63. }
  64. }
  65. using namespace Assimp;
  66. using namespace Assimp::Blender;
  67. using namespace Assimp::Formatter;
  68. static const aiImporterDesc blenderDesc = {
  69. "Blender 3D Importer \nhttp://www.blender3d.org",
  70. "",
  71. "",
  72. "No animation support yet",
  73. aiImporterFlags_SupportBinaryFlavour,
  74. 0,
  75. 0,
  76. 2,
  77. 50,
  78. "blend"
  79. };
  80. // ------------------------------------------------------------------------------------------------
  81. // Constructor to be privately used by Importer
  82. BlenderImporter::BlenderImporter()
  83. : modifier_cache(new BlenderModifierShowcase()) {
  84. // empty
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Destructor, private as well
  88. BlenderImporter::~BlenderImporter()
  89. {
  90. delete modifier_cache;
  91. }
  92. static const char* Tokens[] = { "BLENDER" };
  93. static const char* TokensForSearch[] = { "blender" };
  94. // ------------------------------------------------------------------------------------------------
  95. // Returns whether the class can handle the format of the given file.
  96. bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  97. {
  98. const std::string& extension = GetExtension(pFile);
  99. if (extension == "blend") {
  100. return true;
  101. }
  102. else if ((!extension.length() || checkSig) && pIOHandler) {
  103. // note: this won't catch compressed files
  104. return SearchFileHeaderForToken(pIOHandler,pFile, TokensForSearch,1);
  105. }
  106. return false;
  107. }
  108. // ------------------------------------------------------------------------------------------------
  109. // List all extensions handled by this loader
  110. void BlenderImporter::GetExtensionList(std::set<std::string>& app)
  111. {
  112. app.insert("blend");
  113. }
  114. // ------------------------------------------------------------------------------------------------
  115. // Loader registry entry
  116. const aiImporterDesc* BlenderImporter::GetInfo () const
  117. {
  118. return &blenderDesc;
  119. }
  120. // ------------------------------------------------------------------------------------------------
  121. // Setup configuration properties for the loader
  122. void BlenderImporter::SetupProperties(const Importer* /*pImp*/)
  123. {
  124. // nothing to be done for the moment
  125. }
  126. // ------------------------------------------------------------------------------------------------
  127. // Imports the given file into the given scene structure.
  128. void BlenderImporter::InternReadFile( const std::string& pFile,
  129. aiScene* pScene, IOSystem* pIOHandler)
  130. {
  131. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  132. std::vector<Bytef> uncompressed;
  133. #endif
  134. FileDatabase file;
  135. std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb"));
  136. if (!stream) {
  137. ThrowException("Could not open file for reading");
  138. }
  139. char magic[8] = {0};
  140. stream->Read(magic,7,1);
  141. if (strcmp(magic, Tokens[0] )) {
  142. // Check for presence of the gzip header. If yes, assume it is a
  143. // compressed blend file and try uncompressing it, else fail. This is to
  144. // avoid uncompressing random files which our loader might end up with.
  145. #ifdef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  146. ThrowException("BLENDER magic bytes are missing, is this file compressed (Assimp was built without decompression support)?");
  147. #else
  148. if (magic[0] != 0x1f || static_cast<uint8_t>(magic[1]) != 0x8b) {
  149. ThrowException("BLENDER magic bytes are missing, couldn't find GZIP header either");
  150. }
  151. LogDebug("Found no BLENDER magic word but a GZIP header, might be a compressed file");
  152. if (magic[2] != 8) {
  153. ThrowException("Unsupported GZIP compression method");
  154. }
  155. // http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
  156. stream->Seek(0L,aiOrigin_SET);
  157. std::shared_ptr<StreamReaderLE> reader = std::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
  158. // build a zlib stream
  159. z_stream zstream;
  160. zstream.opaque = Z_NULL;
  161. zstream.zalloc = Z_NULL;
  162. zstream.zfree = Z_NULL;
  163. zstream.data_type = Z_BINARY;
  164. // http://hewgill.com/journal/entries/349-how-to-decompress-gzip-stream-with-zlib
  165. inflateInit2(&zstream, 16+MAX_WBITS);
  166. zstream.next_in = reinterpret_cast<Bytef*>( reader->GetPtr() );
  167. zstream.avail_in = reader->GetRemainingSize();
  168. size_t total = 0l;
  169. // TODO: be smarter about this, decompress directly into heap buffer
  170. // and decompress the data .... do 1k chunks in the hope that we won't kill the stack
  171. #define MYBLOCK 1024
  172. Bytef block[MYBLOCK];
  173. int ret;
  174. do {
  175. zstream.avail_out = MYBLOCK;
  176. zstream.next_out = block;
  177. ret = inflate(&zstream, Z_NO_FLUSH);
  178. if (ret != Z_STREAM_END && ret != Z_OK) {
  179. ThrowException("Failure decompressing this file using gzip, seemingly it is NOT a compressed .BLEND file");
  180. }
  181. const size_t have = MYBLOCK - zstream.avail_out;
  182. total += have;
  183. uncompressed.resize(total);
  184. memcpy(uncompressed.data() + total - have,block,have);
  185. }
  186. while (ret != Z_STREAM_END);
  187. // terminate zlib
  188. inflateEnd(&zstream);
  189. // replace the input stream with a memory stream
  190. stream.reset(new MemoryIOStream(reinterpret_cast<uint8_t*>(uncompressed.data()),total));
  191. // .. and retry
  192. stream->Read(magic,7,1);
  193. if (strcmp(magic,"BLENDER")) {
  194. ThrowException("Found no BLENDER magic word in decompressed GZIP file");
  195. }
  196. #endif
  197. }
  198. file.i64bit = (stream->Read(magic,1,1),magic[0]=='-');
  199. file.little = (stream->Read(magic,1,1),magic[0]=='v');
  200. stream->Read(magic,3,1);
  201. magic[3] = '\0';
  202. LogInfo((format(),"Blender version is ",magic[0],".",magic+1,
  203. " (64bit: ",file.i64bit?"true":"false",
  204. ", little endian: ",file.little?"true":"false",")"
  205. ));
  206. ParseBlendFile(file,stream);
  207. Scene scene;
  208. ExtractScene(scene,file);
  209. ConvertBlendFile(pScene,scene,file);
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. void BlenderImporter::ParseBlendFile(FileDatabase& out, std::shared_ptr<IOStream> stream)
  213. {
  214. out.reader = std::shared_ptr<StreamReaderAny>(new StreamReaderAny(stream,out.little));
  215. DNAParser dna_reader(out);
  216. const DNA* dna = NULL;
  217. out.entries.reserve(128); { // even small BLEND files tend to consist of many file blocks
  218. SectionParser parser(*out.reader.get(),out.i64bit);
  219. // first parse the file in search for the DNA and insert all other sections into the database
  220. while ((parser.Next(),1)) {
  221. const FileBlockHead& head = parser.GetCurrent();
  222. if (head.id == "ENDB") {
  223. break; // only valid end of the file
  224. }
  225. else if (head.id == "DNA1") {
  226. dna_reader.Parse();
  227. dna = &dna_reader.GetDNA();
  228. continue;
  229. }
  230. out.entries.push_back(head);
  231. }
  232. }
  233. if (!dna) {
  234. ThrowException("SDNA not found");
  235. }
  236. std::sort(out.entries.begin(),out.entries.end());
  237. }
  238. // ------------------------------------------------------------------------------------------------
  239. void BlenderImporter::ExtractScene(Scene& out, const FileDatabase& file)
  240. {
  241. const FileBlockHead* block = NULL;
  242. std::map<std::string,size_t>::const_iterator it = file.dna.indices.find("Scene");
  243. if (it == file.dna.indices.end()) {
  244. ThrowException("There is no `Scene` structure record");
  245. }
  246. const Structure& ss = file.dna.structures[(*it).second];
  247. // we need a scene somewhere to start with.
  248. for(const FileBlockHead& bl :file.entries) {
  249. // Fix: using the DNA index is more reliable to locate scenes
  250. //if (bl.id == "SC") {
  251. if (bl.dna_index == (*it).second) {
  252. block = &bl;
  253. break;
  254. }
  255. }
  256. if (!block) {
  257. ThrowException("There is not a single `Scene` record to load");
  258. }
  259. file.reader->SetCurrentPos(block->start);
  260. ss.Convert(out,file);
  261. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  262. ASSIMP_LOG_INFO_F(
  263. "(Stats) Fields read: " ,file.stats().fields_read,
  264. ", pointers resolved: " ,file.stats().pointers_resolved,
  265. ", cache hits: " ,file.stats().cache_hits,
  266. ", cached objects: " ,file.stats().cached_objects
  267. );
  268. #endif
  269. }
  270. // ------------------------------------------------------------------------------------------------
  271. void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileDatabase& file)
  272. {
  273. ConversionData conv(file);
  274. // FIXME it must be possible to take the hierarchy directly from
  275. // the file. This is terrible. Here, we're first looking for
  276. // all objects which don't have parent objects at all -
  277. std::deque<const Object*> no_parents;
  278. for (std::shared_ptr<Base> cur = std::static_pointer_cast<Base> ( in.base.first ); cur; cur = cur->next) {
  279. if (cur->object) {
  280. if(!cur->object->parent) {
  281. no_parents.push_back(cur->object.get());
  282. } else {
  283. conv.objects.insert( cur->object.get() );
  284. }
  285. }
  286. }
  287. for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
  288. if (cur->object) {
  289. if(cur->object->parent) {
  290. conv.objects.insert(cur->object.get());
  291. }
  292. }
  293. }
  294. if (no_parents.empty()) {
  295. ThrowException("Expected at least one object with no parent");
  296. }
  297. aiNode* root = out->mRootNode = new aiNode("<BlenderRoot>");
  298. root->mNumChildren = static_cast<unsigned int>(no_parents.size());
  299. root->mChildren = new aiNode*[root->mNumChildren]();
  300. for (unsigned int i = 0; i < root->mNumChildren; ++i) {
  301. root->mChildren[i] = ConvertNode(in, no_parents[i], conv, aiMatrix4x4());
  302. root->mChildren[i]->mParent = root;
  303. }
  304. BuildMaterials(conv);
  305. if (conv.meshes->size()) {
  306. out->mMeshes = new aiMesh*[out->mNumMeshes = static_cast<unsigned int>( conv.meshes->size() )];
  307. std::copy(conv.meshes->begin(),conv.meshes->end(),out->mMeshes);
  308. conv.meshes.dismiss();
  309. }
  310. if (conv.lights->size()) {
  311. out->mLights = new aiLight*[out->mNumLights = static_cast<unsigned int>( conv.lights->size() )];
  312. std::copy(conv.lights->begin(),conv.lights->end(),out->mLights);
  313. conv.lights.dismiss();
  314. }
  315. if (conv.cameras->size()) {
  316. out->mCameras = new aiCamera*[out->mNumCameras = static_cast<unsigned int>( conv.cameras->size() )];
  317. std::copy(conv.cameras->begin(),conv.cameras->end(),out->mCameras);
  318. conv.cameras.dismiss();
  319. }
  320. if (conv.materials->size()) {
  321. out->mMaterials = new aiMaterial*[out->mNumMaterials = static_cast<unsigned int>( conv.materials->size() )];
  322. std::copy(conv.materials->begin(),conv.materials->end(),out->mMaterials);
  323. conv.materials.dismiss();
  324. }
  325. if (conv.textures->size()) {
  326. out->mTextures = new aiTexture*[out->mNumTextures = static_cast<unsigned int>( conv.textures->size() )];
  327. std::copy(conv.textures->begin(),conv.textures->end(),out->mTextures);
  328. conv.textures.dismiss();
  329. }
  330. // acknowledge that the scene might come out incomplete
  331. // by Assimp's definition of `complete`: blender scenes
  332. // can consist of thousands of cameras or lights with
  333. // not a single mesh between them.
  334. if (!out->mNumMeshes) {
  335. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  336. }
  337. }
  338. // ------------------------------------------------------------------------------------------------
  339. void BlenderImporter::ResolveImage(aiMaterial* out, const Material* mat, const MTex* tex, const Image* img, ConversionData& conv_data)
  340. {
  341. (void)mat; (void)tex; (void)conv_data;
  342. aiString name;
  343. // check if the file contents are bundled with the BLEND file
  344. if (img->packedfile) {
  345. name.data[0] = '*';
  346. name.length = 1+ ASSIMP_itoa10(name.data+1,static_cast<unsigned int>(MAXLEN-1), static_cast<int32_t>(conv_data.textures->size()));
  347. conv_data.textures->push_back(new aiTexture());
  348. aiTexture* tex = conv_data.textures->back();
  349. // usually 'img->name' will be the original file name of the embedded textures,
  350. // so we can extract the file extension from it.
  351. const size_t nlen = strlen( img->name );
  352. const char* s = img->name+nlen, *e = s;
  353. while ( s >= img->name && *s != '.' ) {
  354. --s;
  355. }
  356. tex->achFormatHint[0] = s+1>e ? '\0' : ::tolower( s[1] );
  357. tex->achFormatHint[1] = s+2>e ? '\0' : ::tolower( s[2] );
  358. tex->achFormatHint[2] = s+3>e ? '\0' : ::tolower( s[3] );
  359. tex->achFormatHint[3] = '\0';
  360. // tex->mHeight = 0;
  361. tex->mWidth = img->packedfile->size;
  362. uint8_t* ch = new uint8_t[tex->mWidth];
  363. conv_data.db.reader->SetCurrentPos(static_cast<size_t>( img->packedfile->data->val));
  364. conv_data.db.reader->CopyAndAdvance(ch,tex->mWidth);
  365. tex->pcData = reinterpret_cast<aiTexel*>(ch);
  366. LogInfo("Reading embedded texture, original file was "+std::string(img->name));
  367. } else {
  368. name = aiString( img->name );
  369. }
  370. aiTextureType texture_type = aiTextureType_UNKNOWN;
  371. MTex::MapType map_type = tex->mapto;
  372. if (map_type & MTex::MapType_COL)
  373. texture_type = aiTextureType_DIFFUSE;
  374. else if (map_type & MTex::MapType_NORM) {
  375. if (tex->tex->imaflag & Tex::ImageFlags_NORMALMAP) {
  376. texture_type = aiTextureType_NORMALS;
  377. }
  378. else {
  379. texture_type = aiTextureType_HEIGHT;
  380. }
  381. out->AddProperty(&tex->norfac,1,AI_MATKEY_BUMPSCALING);
  382. }
  383. else if (map_type & MTex::MapType_COLSPEC)
  384. texture_type = aiTextureType_SPECULAR;
  385. else if (map_type & MTex::MapType_COLMIR)
  386. texture_type = aiTextureType_REFLECTION;
  387. //else if (map_type & MTex::MapType_REF)
  388. else if (map_type & MTex::MapType_SPEC)
  389. texture_type = aiTextureType_SHININESS;
  390. else if (map_type & MTex::MapType_EMIT)
  391. texture_type = aiTextureType_EMISSIVE;
  392. //else if (map_type & MTex::MapType_ALPHA)
  393. //else if (map_type & MTex::MapType_HAR)
  394. //else if (map_type & MTex::MapType_RAYMIRR)
  395. //else if (map_type & MTex::MapType_TRANSLU)
  396. else if (map_type & MTex::MapType_AMB)
  397. texture_type = aiTextureType_AMBIENT;
  398. else if (map_type & MTex::MapType_DISPLACE)
  399. texture_type = aiTextureType_DISPLACEMENT;
  400. //else if (map_type & MTex::MapType_WARP)
  401. out->AddProperty(&name,AI_MATKEY_TEXTURE(texture_type,
  402. conv_data.next_texture[texture_type]++));
  403. }
  404. // ------------------------------------------------------------------------------------------------
  405. void BlenderImporter::AddSentinelTexture(aiMaterial* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  406. {
  407. (void)mat; (void)tex; (void)conv_data;
  408. aiString name;
  409. name.length = ai_snprintf(name.data, MAXLEN, "Procedural,num=%i,type=%s",conv_data.sentinel_cnt++,
  410. GetTextureTypeDisplayString(tex->tex->type)
  411. );
  412. out->AddProperty(&name,AI_MATKEY_TEXTURE_DIFFUSE(
  413. conv_data.next_texture[aiTextureType_DIFFUSE]++)
  414. );
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. void BlenderImporter::ResolveTexture(aiMaterial* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  418. {
  419. const Tex* rtex = tex->tex.get();
  420. if(!rtex || !rtex->type) {
  421. return;
  422. }
  423. // We can't support most of the texture types because they're mostly procedural.
  424. // These are substituted by a dummy texture.
  425. const char* dispnam = "";
  426. switch( rtex->type )
  427. {
  428. // these are listed in blender's UI
  429. case Tex::Type_CLOUDS :
  430. case Tex::Type_WOOD :
  431. case Tex::Type_MARBLE :
  432. case Tex::Type_MAGIC :
  433. case Tex::Type_BLEND :
  434. case Tex::Type_STUCCI :
  435. case Tex::Type_NOISE :
  436. case Tex::Type_PLUGIN :
  437. case Tex::Type_MUSGRAVE :
  438. case Tex::Type_VORONOI :
  439. case Tex::Type_DISTNOISE :
  440. case Tex::Type_ENVMAP :
  441. // these do no appear in the UI, why?
  442. case Tex::Type_POINTDENSITY :
  443. case Tex::Type_VOXELDATA :
  444. LogWarn(std::string("Encountered a texture with an unsupported type: ")+dispnam);
  445. AddSentinelTexture(out, mat, tex, conv_data);
  446. break;
  447. case Tex::Type_IMAGE :
  448. if (!rtex->ima) {
  449. LogError("A texture claims to be an Image, but no image reference is given");
  450. break;
  451. }
  452. ResolveImage(out, mat, tex, rtex->ima.get(),conv_data);
  453. break;
  454. default:
  455. ai_assert(false);
  456. };
  457. }
  458. // ------------------------------------------------------------------------------------------------
  459. void BlenderImporter::BuildDefaultMaterial(Blender::ConversionData& conv_data)
  460. {
  461. // add a default material if necessary
  462. unsigned int index = static_cast<unsigned int>( -1 );
  463. for( aiMesh* mesh : conv_data.meshes.get() ) {
  464. if (mesh->mMaterialIndex == static_cast<unsigned int>( -1 )) {
  465. if (index == static_cast<unsigned int>( -1 )) {
  466. // Setup a default material.
  467. std::shared_ptr<Material> p(new Material());
  468. ai_assert(::strlen(AI_DEFAULT_MATERIAL_NAME) < sizeof(p->id.name)-2);
  469. strcpy( p->id.name+2, AI_DEFAULT_MATERIAL_NAME );
  470. // Note: MSVC11 does not zero-initialize Material here, although it should.
  471. // Thus all relevant fields should be explicitly initialized. We cannot add
  472. // a default constructor to Material since the DNA codegen does not support
  473. // parsing it.
  474. p->r = p->g = p->b = 0.6f;
  475. p->specr = p->specg = p->specb = 0.6f;
  476. p->ambr = p->ambg = p->ambb = 0.0f;
  477. p->mirr = p->mirg = p->mirb = 0.0f;
  478. p->emit = 0.f;
  479. p->alpha = 0.f;
  480. p->har = 0;
  481. index = static_cast<unsigned int>( conv_data.materials_raw.size() );
  482. conv_data.materials_raw.push_back(p);
  483. LogInfo("Adding default material");
  484. }
  485. mesh->mMaterialIndex = index;
  486. }
  487. }
  488. }
  489. void BlenderImporter::AddBlendParams(aiMaterial* result, const Material* source)
  490. {
  491. aiColor3D diffuseColor(source->r, source->g, source->b);
  492. result->AddProperty(&diffuseColor, 1, "$mat.blend.diffuse.color", 0, 0);
  493. float diffuseIntensity = source->ref;
  494. result->AddProperty(&diffuseIntensity, 1, "$mat.blend.diffuse.intensity", 0, 0);
  495. int diffuseShader = source->diff_shader;
  496. result->AddProperty(&diffuseShader, 1, "$mat.blend.diffuse.shader", 0, 0);
  497. int diffuseRamp = 0;
  498. result->AddProperty(&diffuseRamp, 1, "$mat.blend.diffuse.ramp", 0, 0);
  499. aiColor3D specularColor(source->specr, source->specg, source->specb);
  500. result->AddProperty(&specularColor, 1, "$mat.blend.specular.color", 0, 0);
  501. float specularIntensity = source->spec;
  502. result->AddProperty(&specularIntensity, 1, "$mat.blend.specular.intensity", 0, 0);
  503. int specularShader = source->spec_shader;
  504. result->AddProperty(&specularShader, 1, "$mat.blend.specular.shader", 0, 0);
  505. int specularRamp = 0;
  506. result->AddProperty(&specularRamp, 1, "$mat.blend.specular.ramp", 0, 0);
  507. int specularHardness = source->har;
  508. result->AddProperty(&specularHardness, 1, "$mat.blend.specular.hardness", 0, 0);
  509. int transparencyUse = source->mode & MA_TRANSPARENCY ? 1 : 0;
  510. result->AddProperty(&transparencyUse, 1, "$mat.blend.transparency.use", 0, 0);
  511. int transparencyMethod = source->mode & MA_RAYTRANSP ? 2 : (source->mode & MA_ZTRANSP ? 1 : 0);
  512. result->AddProperty(&transparencyMethod, 1, "$mat.blend.transparency.method", 0, 0);
  513. float transparencyAlpha = source->alpha;
  514. result->AddProperty(&transparencyAlpha, 1, "$mat.blend.transparency.alpha", 0, 0);
  515. float transparencySpecular = source->spectra;
  516. result->AddProperty(&transparencySpecular, 1, "$mat.blend.transparency.specular", 0, 0);
  517. float transparencyFresnel = source->fresnel_tra;
  518. result->AddProperty(&transparencyFresnel, 1, "$mat.blend.transparency.fresnel", 0, 0);
  519. float transparencyBlend = source->fresnel_tra_i;
  520. result->AddProperty(&transparencyBlend, 1, "$mat.blend.transparency.blend", 0, 0);
  521. float transparencyIor = source->ang;
  522. result->AddProperty(&transparencyIor, 1, "$mat.blend.transparency.ior", 0, 0);
  523. float transparencyFilter = source->filter;
  524. result->AddProperty(&transparencyFilter, 1, "$mat.blend.transparency.filter", 0, 0);
  525. float transparencyFalloff = source->tx_falloff;
  526. result->AddProperty(&transparencyFalloff, 1, "$mat.blend.transparency.falloff", 0, 0);
  527. float transparencyLimit = source->tx_limit;
  528. result->AddProperty(&transparencyLimit, 1, "$mat.blend.transparency.limit", 0, 0);
  529. int transparencyDepth = source->ray_depth_tra;
  530. result->AddProperty(&transparencyDepth, 1, "$mat.blend.transparency.depth", 0, 0);
  531. float transparencyGlossAmount = source->gloss_tra;
  532. result->AddProperty(&transparencyGlossAmount, 1, "$mat.blend.transparency.glossAmount", 0, 0);
  533. float transparencyGlossThreshold = source->adapt_thresh_tra;
  534. result->AddProperty(&transparencyGlossThreshold, 1, "$mat.blend.transparency.glossThreshold", 0, 0);
  535. int transparencyGlossSamples = source->samp_gloss_tra;
  536. result->AddProperty(&transparencyGlossSamples, 1, "$mat.blend.transparency.glossSamples", 0, 0);
  537. int mirrorUse = source->mode & MA_RAYMIRROR ? 1 : 0;
  538. result->AddProperty(&mirrorUse, 1, "$mat.blend.mirror.use", 0, 0);
  539. float mirrorReflectivity = source->ray_mirror;
  540. result->AddProperty(&mirrorReflectivity, 1, "$mat.blend.mirror.reflectivity", 0, 0);
  541. aiColor3D mirrorColor(source->mirr, source->mirg, source->mirb);
  542. result->AddProperty(&mirrorColor, 1, "$mat.blend.mirror.color", 0, 0);
  543. float mirrorFresnel = source->fresnel_mir;
  544. result->AddProperty(&mirrorFresnel, 1, "$mat.blend.mirror.fresnel", 0, 0);
  545. float mirrorBlend = source->fresnel_mir_i;
  546. result->AddProperty(&mirrorBlend, 1, "$mat.blend.mirror.blend", 0, 0);
  547. int mirrorDepth = source->ray_depth;
  548. result->AddProperty(&mirrorDepth, 1, "$mat.blend.mirror.depth", 0, 0);
  549. float mirrorMaxDist = source->dist_mir;
  550. result->AddProperty(&mirrorMaxDist, 1, "$mat.blend.mirror.maxDist", 0, 0);
  551. int mirrorFadeTo = source->fadeto_mir;
  552. result->AddProperty(&mirrorFadeTo, 1, "$mat.blend.mirror.fadeTo", 0, 0);
  553. float mirrorGlossAmount = source->gloss_mir;
  554. result->AddProperty(&mirrorGlossAmount, 1, "$mat.blend.mirror.glossAmount", 0, 0);
  555. float mirrorGlossThreshold = source->adapt_thresh_mir;
  556. result->AddProperty(&mirrorGlossThreshold, 1, "$mat.blend.mirror.glossThreshold", 0, 0);
  557. int mirrorGlossSamples = source->samp_gloss_mir;
  558. result->AddProperty(&mirrorGlossSamples, 1, "$mat.blend.mirror.glossSamples", 0, 0);
  559. float mirrorGlossAnisotropic = source->aniso_gloss_mir;
  560. result->AddProperty(&mirrorGlossAnisotropic, 1, "$mat.blend.mirror.glossAnisotropic", 0, 0);
  561. }
  562. void BlenderImporter::BuildMaterials(ConversionData& conv_data)
  563. {
  564. conv_data.materials->reserve(conv_data.materials_raw.size());
  565. BuildDefaultMaterial(conv_data);
  566. for(std::shared_ptr<Material> mat : conv_data.materials_raw) {
  567. // reset per material global counters
  568. for (size_t i = 0; i < sizeof(conv_data.next_texture)/sizeof(conv_data.next_texture[0]);++i) {
  569. conv_data.next_texture[i] = 0 ;
  570. }
  571. aiMaterial* mout = new aiMaterial();
  572. conv_data.materials->push_back(mout);
  573. // For any new material field handled here, the default material above must be updated with an appropriate default value.
  574. // set material name
  575. aiString name = aiString(mat->id.name+2); // skip over the name prefix 'MA'
  576. mout->AddProperty(&name,AI_MATKEY_NAME);
  577. // basic material colors
  578. aiColor3D col(mat->r,mat->g,mat->b);
  579. if (mat->r || mat->g || mat->b ) {
  580. // Usually, zero diffuse color means no diffuse color at all in the equation.
  581. // So we omit this member to express this intent.
  582. mout->AddProperty(&col,1,AI_MATKEY_COLOR_DIFFUSE);
  583. if (mat->emit) {
  584. aiColor3D emit_col(mat->emit * mat->r, mat->emit * mat->g, mat->emit * mat->b) ;
  585. mout->AddProperty(&emit_col, 1, AI_MATKEY_COLOR_EMISSIVE) ;
  586. }
  587. }
  588. col = aiColor3D(mat->specr,mat->specg,mat->specb);
  589. mout->AddProperty(&col,1,AI_MATKEY_COLOR_SPECULAR);
  590. // is hardness/shininess set?
  591. if( mat->har ) {
  592. const float har = mat->har;
  593. mout->AddProperty(&har,1,AI_MATKEY_SHININESS);
  594. }
  595. col = aiColor3D(mat->ambr,mat->ambg,mat->ambb);
  596. mout->AddProperty(&col,1,AI_MATKEY_COLOR_AMBIENT);
  597. // is mirror enabled?
  598. if( mat->mode & MA_RAYMIRROR ) {
  599. const float ray_mirror = mat->ray_mirror;
  600. mout->AddProperty(&ray_mirror,1,AI_MATKEY_REFLECTIVITY);
  601. }
  602. col = aiColor3D(mat->mirr,mat->mirg,mat->mirb);
  603. mout->AddProperty(&col,1,AI_MATKEY_COLOR_REFLECTIVE);
  604. for(size_t i = 0; i < sizeof(mat->mtex) / sizeof(mat->mtex[0]); ++i) {
  605. if (!mat->mtex[i]) {
  606. continue;
  607. }
  608. ResolveTexture(mout,mat.get(),mat->mtex[i].get(),conv_data);
  609. }
  610. AddBlendParams(mout, mat.get());
  611. }
  612. }
  613. // ------------------------------------------------------------------------------------------------
  614. void BlenderImporter::CheckActualType(const ElemBase* dt, const char* check)
  615. {
  616. ai_assert(dt);
  617. if (strcmp(dt->dna_type,check)) {
  618. ThrowException((format(),
  619. "Expected object at ",std::hex,dt," to be of type `",check,
  620. "`, but it claims to be a `",dt->dna_type,"`instead"
  621. ));
  622. }
  623. }
  624. // ------------------------------------------------------------------------------------------------
  625. void BlenderImporter::NotSupportedObjectType(const Object* obj, const char* type)
  626. {
  627. LogWarn((format(), "Object `",obj->id.name,"` - type is unsupported: `",type, "`, skipping" ));
  628. }
  629. // ------------------------------------------------------------------------------------------------
  630. void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, const Mesh* mesh,
  631. ConversionData& conv_data, TempArray<std::vector,aiMesh>& temp
  632. )
  633. {
  634. // TODO: Resolve various problems with BMesh triangulation before re-enabling.
  635. // See issues #400, #373, #318 #315 and #132.
  636. #if defined(TODO_FIX_BMESH_CONVERSION)
  637. BlenderBMeshConverter BMeshConverter( mesh );
  638. if ( BMeshConverter.ContainsBMesh( ) )
  639. {
  640. mesh = BMeshConverter.TriangulateBMesh( );
  641. }
  642. #endif
  643. typedef std::pair<const int,size_t> MyPair;
  644. if ((!mesh->totface && !mesh->totloop) || !mesh->totvert) {
  645. return;
  646. }
  647. // some sanity checks
  648. if (static_cast<size_t> ( mesh->totface ) > mesh->mface.size() ){
  649. ThrowException("Number of faces is larger than the corresponding array");
  650. }
  651. if (static_cast<size_t> ( mesh->totvert ) > mesh->mvert.size()) {
  652. ThrowException("Number of vertices is larger than the corresponding array");
  653. }
  654. if (static_cast<size_t> ( mesh->totloop ) > mesh->mloop.size()) {
  655. ThrowException("Number of vertices is larger than the corresponding array");
  656. }
  657. // collect per-submesh numbers
  658. std::map<int,size_t> per_mat;
  659. std::map<int,size_t> per_mat_verts;
  660. for (int i = 0; i < mesh->totface; ++i) {
  661. const MFace& mf = mesh->mface[i];
  662. per_mat[ mf.mat_nr ]++;
  663. per_mat_verts[ mf.mat_nr ] += mf.v4?4:3;
  664. }
  665. for (int i = 0; i < mesh->totpoly; ++i) {
  666. const MPoly& mp = mesh->mpoly[i];
  667. per_mat[ mp.mat_nr ]++;
  668. per_mat_verts[ mp.mat_nr ] += mp.totloop;
  669. }
  670. // ... and allocate the corresponding meshes
  671. const size_t old = temp->size();
  672. temp->reserve(temp->size() + per_mat.size());
  673. std::map<size_t,size_t> mat_num_to_mesh_idx;
  674. for(MyPair& it : per_mat) {
  675. mat_num_to_mesh_idx[it.first] = temp->size();
  676. temp->push_back(new aiMesh());
  677. aiMesh* out = temp->back();
  678. out->mVertices = new aiVector3D[per_mat_verts[it.first]];
  679. out->mNormals = new aiVector3D[per_mat_verts[it.first]];
  680. //out->mNumFaces = 0
  681. //out->mNumVertices = 0
  682. out->mFaces = new aiFace[it.second]();
  683. // all sub-meshes created from this mesh are named equally. this allows
  684. // curious users to recover the original adjacency.
  685. out->mName = aiString(mesh->id.name+2);
  686. // skip over the name prefix 'ME'
  687. // resolve the material reference and add this material to the set of
  688. // output materials. The (temporary) material index is the index
  689. // of the material entry within the list of resolved materials.
  690. if (mesh->mat) {
  691. if (static_cast<size_t> ( it.first ) >= mesh->mat.size() ) {
  692. ThrowException("Material index is out of range");
  693. }
  694. std::shared_ptr<Material> mat = mesh->mat[it.first];
  695. const std::deque< std::shared_ptr<Material> >::iterator has = std::find(
  696. conv_data.materials_raw.begin(),
  697. conv_data.materials_raw.end(),mat
  698. );
  699. if (has != conv_data.materials_raw.end()) {
  700. out->mMaterialIndex = static_cast<unsigned int>( std::distance(conv_data.materials_raw.begin(),has));
  701. }
  702. else {
  703. out->mMaterialIndex = static_cast<unsigned int>( conv_data.materials_raw.size() );
  704. conv_data.materials_raw.push_back(mat);
  705. }
  706. }
  707. else out->mMaterialIndex = static_cast<unsigned int>( -1 );
  708. }
  709. for (int i = 0; i < mesh->totface; ++i) {
  710. const MFace& mf = mesh->mface[i];
  711. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mf.mat_nr ] ];
  712. aiFace& f = out->mFaces[out->mNumFaces++];
  713. f.mIndices = new unsigned int[ f.mNumIndices = mf.v4?4:3 ];
  714. aiVector3D* vo = out->mVertices + out->mNumVertices;
  715. aiVector3D* vn = out->mNormals + out->mNumVertices;
  716. // XXX we can't fold this easily, because we are restricted
  717. // to the member names from the BLEND file (v1,v2,v3,v4)
  718. // which are assigned by the genblenddna.py script and
  719. // cannot be changed without breaking the entire
  720. // import process.
  721. if (mf.v1 >= mesh->totvert) {
  722. ThrowException("Vertex index v1 out of range");
  723. }
  724. const MVert* v = &mesh->mvert[mf.v1];
  725. vo->x = v->co[0];
  726. vo->y = v->co[1];
  727. vo->z = v->co[2];
  728. vn->x = v->no[0];
  729. vn->y = v->no[1];
  730. vn->z = v->no[2];
  731. f.mIndices[0] = out->mNumVertices++;
  732. ++vo;
  733. ++vn;
  734. // if (f.mNumIndices >= 2) {
  735. if (mf.v2 >= mesh->totvert) {
  736. ThrowException("Vertex index v2 out of range");
  737. }
  738. v = &mesh->mvert[mf.v2];
  739. vo->x = v->co[0];
  740. vo->y = v->co[1];
  741. vo->z = v->co[2];
  742. vn->x = v->no[0];
  743. vn->y = v->no[1];
  744. vn->z = v->no[2];
  745. f.mIndices[1] = out->mNumVertices++;
  746. ++vo;
  747. ++vn;
  748. if (mf.v3 >= mesh->totvert) {
  749. ThrowException("Vertex index v3 out of range");
  750. }
  751. // if (f.mNumIndices >= 3) {
  752. v = &mesh->mvert[mf.v3];
  753. vo->x = v->co[0];
  754. vo->y = v->co[1];
  755. vo->z = v->co[2];
  756. vn->x = v->no[0];
  757. vn->y = v->no[1];
  758. vn->z = v->no[2];
  759. f.mIndices[2] = out->mNumVertices++;
  760. ++vo;
  761. ++vn;
  762. if (mf.v4 >= mesh->totvert) {
  763. ThrowException("Vertex index v4 out of range");
  764. }
  765. // if (f.mNumIndices >= 4) {
  766. if (mf.v4) {
  767. v = &mesh->mvert[mf.v4];
  768. vo->x = v->co[0];
  769. vo->y = v->co[1];
  770. vo->z = v->co[2];
  771. vn->x = v->no[0];
  772. vn->y = v->no[1];
  773. vn->z = v->no[2];
  774. f.mIndices[3] = out->mNumVertices++;
  775. ++vo;
  776. ++vn;
  777. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  778. }
  779. else out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  780. // }
  781. // }
  782. // }
  783. }
  784. for (int i = 0; i < mesh->totpoly; ++i) {
  785. const MPoly& mf = mesh->mpoly[i];
  786. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mf.mat_nr ] ];
  787. aiFace& f = out->mFaces[out->mNumFaces++];
  788. f.mIndices = new unsigned int[ f.mNumIndices = mf.totloop ];
  789. aiVector3D* vo = out->mVertices + out->mNumVertices;
  790. aiVector3D* vn = out->mNormals + out->mNumVertices;
  791. // XXX we can't fold this easily, because we are restricted
  792. // to the member names from the BLEND file (v1,v2,v3,v4)
  793. // which are assigned by the genblenddna.py script and
  794. // cannot be changed without breaking the entire
  795. // import process.
  796. for (int j = 0;j < mf.totloop; ++j)
  797. {
  798. const MLoop& loop = mesh->mloop[mf.loopstart + j];
  799. if (loop.v >= mesh->totvert) {
  800. ThrowException("Vertex index out of range");
  801. }
  802. const MVert& v = mesh->mvert[loop.v];
  803. vo->x = v.co[0];
  804. vo->y = v.co[1];
  805. vo->z = v.co[2];
  806. vn->x = v.no[0];
  807. vn->y = v.no[1];
  808. vn->z = v.no[2];
  809. f.mIndices[j] = out->mNumVertices++;
  810. ++vo;
  811. ++vn;
  812. }
  813. if (mf.totloop == 3)
  814. {
  815. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  816. }
  817. else
  818. {
  819. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  820. }
  821. }
  822. // TODO should we create the TextureUVMapping map in Convert<Material> to prevent redundant processing?
  823. // create texture <-> uvname mapping for all materials
  824. // key is texture number, value is data *
  825. typedef std::map<uint32_t, const MLoopUV *> TextureUVMapping;
  826. // key is material number, value is the TextureUVMapping for the material
  827. typedef std::map<uint32_t, TextureUVMapping> MaterialTextureUVMappings;
  828. MaterialTextureUVMappings matTexUvMappings;
  829. const uint32_t maxMat = static_cast<const uint32_t>(mesh->mat.size());
  830. for (uint32_t m = 0; m < maxMat; ++m) {
  831. // get material by index
  832. const std::shared_ptr<Material> pMat = mesh->mat[m];
  833. TextureUVMapping texuv;
  834. const uint32_t maxTex = sizeof(pMat->mtex) / sizeof(pMat->mtex[0]);
  835. for (uint32_t t = 0; t < maxTex; ++t) {
  836. if (pMat->mtex[t] && pMat->mtex[t]->uvname[0]) {
  837. // get the CustomData layer for given uvname and correct type
  838. const ElemBase *pLoop = getCustomDataLayerData(mesh->ldata, CD_MLOOPUV, pMat->mtex[t]->uvname);
  839. if (pLoop) {
  840. texuv.insert(std::make_pair(t, dynamic_cast<const MLoopUV *>(pLoop)));
  841. }
  842. }
  843. }
  844. if (texuv.size()) {
  845. matTexUvMappings.insert(std::make_pair(m, texuv));
  846. }
  847. }
  848. // collect texture coordinates, they're stored in a separate per-face buffer
  849. if (mesh->mtface || mesh->mloopuv) {
  850. if (mesh->totface > static_cast<int> ( mesh->mtface.size())) {
  851. ThrowException("Number of UV faces is larger than the corresponding UV face array (#1)");
  852. }
  853. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  854. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  855. const auto itMatTexUvMapping = matTexUvMappings.find((*it)->mMaterialIndex);
  856. if (itMatTexUvMapping == matTexUvMappings.end()) {
  857. // default behaviour like before
  858. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  859. }
  860. else {
  861. // create texture coords for every mapped tex
  862. for (uint32_t i = 0; i < itMatTexUvMapping->second.size(); ++i) {
  863. (*it)->mTextureCoords[i] = new aiVector3D[(*it)->mNumVertices];
  864. }
  865. }
  866. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  867. }
  868. for (int i = 0; i < mesh->totface; ++i) {
  869. const MTFace* v = &mesh->mtface[i];
  870. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  871. const aiFace& f = out->mFaces[out->mNumFaces++];
  872. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  873. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  874. vo->x = v->uv[i][0];
  875. vo->y = v->uv[i][1];
  876. }
  877. }
  878. for (int i = 0; i < mesh->totpoly; ++i) {
  879. const MPoly& v = mesh->mpoly[i];
  880. aiMesh* const out = temp[ mat_num_to_mesh_idx[ v.mat_nr ] ];
  881. const aiFace& f = out->mFaces[out->mNumFaces++];
  882. const auto itMatTexUvMapping = matTexUvMappings.find(v.mat_nr);
  883. if (itMatTexUvMapping == matTexUvMappings.end()) {
  884. // old behavior
  885. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  886. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  887. const MLoopUV& uv = mesh->mloopuv[v.loopstart + j];
  888. vo->x = uv.uv[0];
  889. vo->y = uv.uv[1];
  890. }
  891. }
  892. else {
  893. // create textureCoords for every mapped tex
  894. for (uint32_t m = 0; m < itMatTexUvMapping->second.size(); ++m) {
  895. const MLoopUV *tm = itMatTexUvMapping->second[m];
  896. aiVector3D* vo = &out->mTextureCoords[m][out->mNumVertices];
  897. uint32_t j = 0;
  898. for (; j < f.mNumIndices; ++j, ++vo) {
  899. const MLoopUV& uv = tm[v.loopstart + j];
  900. vo->x = uv.uv[0];
  901. vo->y = uv.uv[1];
  902. }
  903. // only update written mNumVertices in last loop
  904. // TODO why must the numVertices be incremented here?
  905. if (m == itMatTexUvMapping->second.size() - 1) {
  906. out->mNumVertices += j;
  907. }
  908. }
  909. }
  910. }
  911. }
  912. // collect texture coordinates, old-style (marked as deprecated in current blender sources)
  913. if (mesh->tface) {
  914. if (mesh->totface > static_cast<int> ( mesh->tface.size())) {
  915. ThrowException("Number of faces is larger than the corresponding UV face array (#2)");
  916. }
  917. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  918. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  919. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  920. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  921. }
  922. for (int i = 0; i < mesh->totface; ++i) {
  923. const TFace* v = &mesh->tface[i];
  924. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  925. const aiFace& f = out->mFaces[out->mNumFaces++];
  926. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  927. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  928. vo->x = v->uv[i][0];
  929. vo->y = v->uv[i][1];
  930. }
  931. }
  932. }
  933. // collect vertex colors, stored separately as well
  934. if (mesh->mcol || mesh->mloopcol) {
  935. if (mesh->totface > static_cast<int> ( (mesh->mcol.size()/4)) ) {
  936. ThrowException("Number of faces is larger than the corresponding color face array");
  937. }
  938. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  939. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  940. (*it)->mColors[0] = new aiColor4D[(*it)->mNumVertices];
  941. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  942. }
  943. for (int i = 0; i < mesh->totface; ++i) {
  944. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  945. const aiFace& f = out->mFaces[out->mNumFaces++];
  946. aiColor4D* vo = &out->mColors[0][out->mNumVertices];
  947. for (unsigned int n = 0; n < f.mNumIndices; ++n, ++vo,++out->mNumVertices) {
  948. const MCol* col = &mesh->mcol[(i<<2)+n];
  949. vo->r = col->r;
  950. vo->g = col->g;
  951. vo->b = col->b;
  952. vo->a = col->a;
  953. }
  954. for (unsigned int n = f.mNumIndices; n < 4; ++n);
  955. }
  956. for (int i = 0; i < mesh->totpoly; ++i) {
  957. const MPoly& v = mesh->mpoly[i];
  958. aiMesh* const out = temp[ mat_num_to_mesh_idx[ v.mat_nr ] ];
  959. const aiFace& f = out->mFaces[out->mNumFaces++];
  960. aiColor4D* vo = &out->mColors[0][out->mNumVertices];
  961. const ai_real scaleZeroToOne = 1.f/255.f;
  962. for (unsigned int j = 0; j < f.mNumIndices; ++j,++vo,++out->mNumVertices) {
  963. const MLoopCol& col = mesh->mloopcol[v.loopstart + j];
  964. vo->r = ai_real(col.r) * scaleZeroToOne;
  965. vo->g = ai_real(col.g) * scaleZeroToOne;
  966. vo->b = ai_real(col.b) * scaleZeroToOne;
  967. vo->a = ai_real(col.a) * scaleZeroToOne;
  968. }
  969. }
  970. }
  971. return;
  972. }
  973. // ------------------------------------------------------------------------------------------------
  974. aiCamera* BlenderImporter::ConvertCamera(const Scene& /*in*/, const Object* obj, const Camera* cam, ConversionData& /*conv_data*/)
  975. {
  976. std::unique_ptr<aiCamera> out(new aiCamera());
  977. out->mName = obj->id.name+2;
  978. out->mPosition = aiVector3D(0.f, 0.f, 0.f);
  979. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  980. out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  981. if (cam->sensor_x && cam->lens) {
  982. out->mHorizontalFOV = 2.f * std::atan2(cam->sensor_x, 2.f * cam->lens);
  983. }
  984. out->mClipPlaneNear = cam->clipsta;
  985. out->mClipPlaneFar = cam->clipend;
  986. return out.release();
  987. }
  988. // ------------------------------------------------------------------------------------------------
  989. aiLight* BlenderImporter::ConvertLight(const Scene& /*in*/, const Object* obj, const Lamp* lamp, ConversionData& /*conv_data*/)
  990. {
  991. std::unique_ptr<aiLight> out(new aiLight());
  992. out->mName = obj->id.name+2;
  993. switch (lamp->type)
  994. {
  995. case Lamp::Type_Local:
  996. out->mType = aiLightSource_POINT;
  997. break;
  998. case Lamp::Type_Spot:
  999. out->mType = aiLightSource_SPOT;
  1000. // blender orients directional lights as facing toward -z
  1001. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  1002. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  1003. out->mAngleInnerCone = lamp->spotsize * (1.0f - lamp->spotblend);
  1004. out->mAngleOuterCone = lamp->spotsize;
  1005. break;
  1006. case Lamp::Type_Sun:
  1007. out->mType = aiLightSource_DIRECTIONAL;
  1008. // blender orients directional lights as facing toward -z
  1009. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  1010. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  1011. break;
  1012. case Lamp::Type_Area:
  1013. out->mType = aiLightSource_AREA;
  1014. if (lamp->area_shape == 0) {
  1015. out->mSize = aiVector2D(lamp->area_size, lamp->area_size);
  1016. }
  1017. else {
  1018. out->mSize = aiVector2D(lamp->area_size, lamp->area_sizey);
  1019. }
  1020. // blender orients directional lights as facing toward -z
  1021. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  1022. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  1023. break;
  1024. default:
  1025. break;
  1026. }
  1027. out->mColorAmbient = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  1028. out->mColorSpecular = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  1029. out->mColorDiffuse = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  1030. // If default values are supplied, compute the coefficients from light's max distance
  1031. // Read this: https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/
  1032. //
  1033. if (lamp->constant_coefficient == 1.0f && lamp->linear_coefficient == 0.0f && lamp->quadratic_coefficient == 0.0f && lamp->dist > 0.0f)
  1034. {
  1035. out->mAttenuationConstant = 1.0f;
  1036. out->mAttenuationLinear = 2.0f / lamp->dist;
  1037. out->mAttenuationQuadratic = 1.0f / (lamp->dist * lamp->dist);
  1038. }
  1039. else
  1040. {
  1041. out->mAttenuationConstant = lamp->constant_coefficient;
  1042. out->mAttenuationLinear = lamp->linear_coefficient;
  1043. out->mAttenuationQuadratic = lamp->quadratic_coefficient;
  1044. }
  1045. return out.release();
  1046. }
  1047. // ------------------------------------------------------------------------------------------------
  1048. aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, ConversionData& conv_data, const aiMatrix4x4& parentTransform)
  1049. {
  1050. std::deque<const Object*> children;
  1051. for(ObjectSet::iterator it = conv_data.objects.begin(); it != conv_data.objects.end() ;) {
  1052. const Object* object = *it;
  1053. if (object->parent == obj) {
  1054. children.push_back(object);
  1055. conv_data.objects.erase(it++);
  1056. continue;
  1057. }
  1058. ++it;
  1059. }
  1060. std::unique_ptr<aiNode> node(new aiNode(obj->id.name+2)); // skip over the name prefix 'OB'
  1061. if (obj->data) {
  1062. switch (obj->type)
  1063. {
  1064. case Object :: Type_EMPTY:
  1065. break; // do nothing
  1066. // supported object types
  1067. case Object :: Type_MESH: {
  1068. const size_t old = conv_data.meshes->size();
  1069. CheckActualType(obj->data.get(),"Mesh");
  1070. ConvertMesh(in,obj,static_cast<const Mesh*>(obj->data.get()),conv_data,conv_data.meshes);
  1071. if (conv_data.meshes->size() > old) {
  1072. node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size()-old)];
  1073. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  1074. node->mMeshes[i] = static_cast<unsigned int>(i + old);
  1075. }
  1076. }}
  1077. break;
  1078. case Object :: Type_LAMP: {
  1079. CheckActualType(obj->data.get(),"Lamp");
  1080. aiLight* mesh = ConvertLight(in,obj,static_cast<const Lamp*>(
  1081. obj->data.get()),conv_data);
  1082. if (mesh) {
  1083. conv_data.lights->push_back(mesh);
  1084. }}
  1085. break;
  1086. case Object :: Type_CAMERA: {
  1087. CheckActualType(obj->data.get(),"Camera");
  1088. aiCamera* mesh = ConvertCamera(in,obj,static_cast<const Camera*>(
  1089. obj->data.get()),conv_data);
  1090. if (mesh) {
  1091. conv_data.cameras->push_back(mesh);
  1092. }}
  1093. break;
  1094. // unsupported object types / log, but do not break
  1095. case Object :: Type_CURVE:
  1096. NotSupportedObjectType(obj,"Curve");
  1097. break;
  1098. case Object :: Type_SURF:
  1099. NotSupportedObjectType(obj,"Surface");
  1100. break;
  1101. case Object :: Type_FONT:
  1102. NotSupportedObjectType(obj,"Font");
  1103. break;
  1104. case Object :: Type_MBALL:
  1105. NotSupportedObjectType(obj,"MetaBall");
  1106. break;
  1107. case Object :: Type_WAVE:
  1108. NotSupportedObjectType(obj,"Wave");
  1109. break;
  1110. case Object :: Type_LATTICE:
  1111. NotSupportedObjectType(obj,"Lattice");
  1112. break;
  1113. // invalid or unknown type
  1114. default:
  1115. break;
  1116. }
  1117. }
  1118. for(unsigned int x = 0; x < 4; ++x) {
  1119. for(unsigned int y = 0; y < 4; ++y) {
  1120. node->mTransformation[y][x] = obj->obmat[x][y];
  1121. }
  1122. }
  1123. aiMatrix4x4 m = parentTransform;
  1124. m = m.Inverse();
  1125. node->mTransformation = m*node->mTransformation;
  1126. if (children.size()) {
  1127. node->mNumChildren = static_cast<unsigned int>(children.size());
  1128. aiNode** nd = node->mChildren = new aiNode*[node->mNumChildren]();
  1129. for (const Object* nobj :children) {
  1130. *nd = ConvertNode(in,nobj,conv_data,node->mTransformation * parentTransform);
  1131. (*nd++)->mParent = node.get();
  1132. }
  1133. }
  1134. // apply modifiers
  1135. modifier_cache->ApplyModifiers(*node,conv_data,in,*obj);
  1136. return node.release();
  1137. }
  1138. #endif // ASSIMP_BUILD_NO_BLEND_IMPORTER