FBXExporter.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, 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. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_FBX_EXPORTER
  35. #include "FBXExporter.h"
  36. #include "FBXExportNode.h"
  37. #include "FBXExportProperty.h"
  38. #include "FBXCommon.h"
  39. #include "FBXUtil.h"
  40. #include <assimp/version.h> // aiGetVersion
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/Exporter.hpp>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/Logger.hpp>
  45. #include <assimp/StreamWriter.h> // StreamWriterLE
  46. #include <assimp/Exceptional.h> // DeadlyExportError
  47. #include <assimp/material.h> // aiTextureType
  48. #include <assimp/scene.h>
  49. #include <assimp/mesh.h>
  50. // Header files, standard library.
  51. #include <array>
  52. #include <ctime> // localtime, tm_*
  53. #include <map>
  54. #include <memory> // shared_ptr
  55. #include <numeric>
  56. #include <set>
  57. #include <sstream> // stringstream
  58. #include <string>
  59. #include <unordered_set>
  60. #include <utility>
  61. #include <vector>
  62. #include <cmath>
  63. // RESOURCES:
  64. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  65. // https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  66. using namespace Assimp;
  67. using namespace Assimp::FBX;
  68. // some constants that we'll use for writing metadata
  69. namespace Assimp {
  70. namespace FBX {
  71. const std::string EXPORT_VERSION_STR = "7.5.0";
  72. const uint32_t EXPORT_VERSION_INT = 7500; // 7.5 == 2016+
  73. // FBX files have some hashed values that depend on the creation time field,
  74. // but for now we don't actually know how to generate these.
  75. // what we can do is set them to a known-working version.
  76. // this is the data that Blender uses in their FBX export process.
  77. const std::string GENERIC_CTIME = "1970-01-01 10:00:00:000";
  78. const std::string GENERIC_FILEID =
  79. "\x28\xb3\x2a\xeb\xb6\x24\xcc\xc2\xbf\xc8\xb0\x2a\xa9\x2b\xfc\xf1";
  80. const std::string GENERIC_FOOTID =
  81. "\xfa\xbc\xab\x09\xd0\xc8\xd4\x66\xb1\x76\xfb\x83\x1c\xf7\x26\x7e";
  82. const std::string FOOT_MAGIC =
  83. "\xf8\x5a\x8c\x6a\xde\xf5\xd9\x7e\xec\xe9\x0c\xe3\x75\x8f\x29\x0b";
  84. const std::string COMMENT_UNDERLINE =
  85. ";------------------------------------------------------------------";
  86. }
  87. // ---------------------------------------------------------------------
  88. // Worker function for exporting a scene to binary FBX.
  89. // Prototyped and registered in Exporter.cpp
  90. void ExportSceneFBX (
  91. const char* pFile,
  92. IOSystem* pIOSystem,
  93. const aiScene* pScene,
  94. const ExportProperties* pProperties
  95. ){
  96. // initialize the exporter
  97. FBXExporter exporter(pScene, pProperties);
  98. // perform binary export
  99. exporter.ExportBinary(pFile, pIOSystem);
  100. }
  101. // ---------------------------------------------------------------------
  102. // Worker function for exporting a scene to ASCII FBX.
  103. // Prototyped and registered in Exporter.cpp
  104. void ExportSceneFBXA (
  105. const char* pFile,
  106. IOSystem* pIOSystem,
  107. const aiScene* pScene,
  108. const ExportProperties* pProperties
  109. ){
  110. // initialize the exporter
  111. FBXExporter exporter(pScene, pProperties);
  112. // perform ascii export
  113. exporter.ExportAscii(pFile, pIOSystem);
  114. }
  115. } // end of namespace Assimp
  116. FBXExporter::FBXExporter ( const aiScene* pScene, const ExportProperties* pProperties )
  117. : binary(false)
  118. , mScene(pScene)
  119. , mProperties(pProperties)
  120. , outfile()
  121. , connections()
  122. , mesh_uids()
  123. , material_uids()
  124. , node_uids() {
  125. // will probably need to determine UIDs, connections, etc here.
  126. // basically anything that needs to be known
  127. // before we start writing sections to the stream.
  128. }
  129. void FBXExporter::ExportBinary (
  130. const char* pFile,
  131. IOSystem* pIOSystem
  132. ){
  133. // remember that we're exporting in binary mode
  134. binary = true;
  135. // we're not currently using these preferences,
  136. // but clang will cry about it if we never touch it.
  137. // TODO: some of these might be relevant to export
  138. (void)mProperties;
  139. // open the indicated file for writing (in binary mode)
  140. outfile.reset(pIOSystem->Open(pFile,"wb"));
  141. if (!outfile) {
  142. throw DeadlyExportError(
  143. "could not open output .fbx file: " + std::string(pFile)
  144. );
  145. }
  146. // first a binary-specific file header
  147. WriteBinaryHeader();
  148. // the rest of the file is in node entries.
  149. // we have to serialize each entry before we write to the output,
  150. // as the first thing we write is the byte offset of the _next_ entry.
  151. // Either that or we can skip back to write the offset when we finish.
  152. WriteAllNodes();
  153. // finally we have a binary footer to the file
  154. WriteBinaryFooter();
  155. // explicitly release file pointer,
  156. // so we don't have to rely on class destruction.
  157. outfile.reset();
  158. }
  159. void FBXExporter::ExportAscii (
  160. const char* pFile,
  161. IOSystem* pIOSystem
  162. ){
  163. // remember that we're exporting in ascii mode
  164. binary = false;
  165. // open the indicated file for writing in text mode
  166. outfile.reset(pIOSystem->Open(pFile,"wt"));
  167. if (!outfile) {
  168. throw DeadlyExportError(
  169. "could not open output .fbx file: " + std::string(pFile)
  170. );
  171. }
  172. // write the ascii header
  173. WriteAsciiHeader();
  174. // write all the sections
  175. WriteAllNodes();
  176. // make sure the file ends with a newline.
  177. // note: if the file is opened in text mode,
  178. // this should do the right cross-platform thing.
  179. outfile->Write("\n", 1, 1);
  180. // explicitly release file pointer,
  181. // so we don't have to rely on class destruction.
  182. outfile.reset();
  183. }
  184. void FBXExporter::WriteAsciiHeader()
  185. {
  186. // basically just a comment at the top of the file
  187. std::stringstream head;
  188. head << "; FBX " << EXPORT_VERSION_STR << " project file\n";
  189. head << "; Created by the Open Asset Import Library (Assimp)\n";
  190. head << "; http://assimp.org\n";
  191. head << "; -------------------------------------------------\n";
  192. const std::string ascii_header = head.str();
  193. outfile->Write(ascii_header.c_str(), ascii_header.size(), 1);
  194. }
  195. void FBXExporter::WriteAsciiSectionHeader(const std::string& title)
  196. {
  197. StreamWriterLE outstream(outfile);
  198. std::stringstream s;
  199. s << "\n\n; " << title << '\n';
  200. s << FBX::COMMENT_UNDERLINE << "\n";
  201. outstream.PutString(s.str());
  202. }
  203. void FBXExporter::WriteBinaryHeader()
  204. {
  205. // first a specific sequence of 23 bytes, always the same
  206. const char binary_header[24] = "Kaydara FBX Binary\x20\x20\x00\x1a\x00";
  207. outfile->Write(binary_header, 1, 23);
  208. // then FBX version number, "multiplied" by 1000, as little-endian uint32.
  209. // so 7.3 becomes 7300 == 0x841C0000, 7.4 becomes 7400 == 0xE81C0000, etc
  210. {
  211. StreamWriterLE outstream(outfile);
  212. outstream.PutU4(EXPORT_VERSION_INT);
  213. } // StreamWriter destructor writes the data to the file
  214. // after this the node data starts immediately
  215. // (probably with the FBXHEaderExtension node)
  216. }
  217. void FBXExporter::WriteBinaryFooter()
  218. {
  219. outfile->Write(NULL_RECORD, NumNullRecords, 1);
  220. outfile->Write(GENERIC_FOOTID.c_str(), GENERIC_FOOTID.size(), 1);
  221. // here some padding is added for alignment to 16 bytes.
  222. // if already aligned, the full 16 bytes is added.
  223. size_t pos = outfile->Tell();
  224. size_t pad = 16 - (pos % 16);
  225. for (size_t i = 0; i < pad; ++i) {
  226. outfile->Write("\x00", 1, 1);
  227. }
  228. // not sure what this is, but it seems to always be 0 in modern files
  229. for (size_t i = 0; i < 4; ++i) {
  230. outfile->Write("\x00", 1, 1);
  231. }
  232. // now the file version again
  233. {
  234. StreamWriterLE outstream(outfile);
  235. outstream.PutU4(EXPORT_VERSION_INT);
  236. } // StreamWriter destructor writes the data to the file
  237. // and finally some binary footer added to all files
  238. for (size_t i = 0; i < 120; ++i) {
  239. outfile->Write("\x00", 1, 1);
  240. }
  241. outfile->Write(FOOT_MAGIC.c_str(), FOOT_MAGIC.size(), 1);
  242. }
  243. void FBXExporter::WriteAllNodes ()
  244. {
  245. // header
  246. // (and fileid, creation time, creator, if binary)
  247. WriteHeaderExtension();
  248. // global settings
  249. WriteGlobalSettings();
  250. // documents
  251. WriteDocuments();
  252. // references
  253. WriteReferences();
  254. // definitions
  255. WriteDefinitions();
  256. // objects
  257. WriteObjects();
  258. // connections
  259. WriteConnections();
  260. // WriteTakes? (deprecated since at least 2015 (fbx 7.4))
  261. }
  262. //FBXHeaderExtension top-level node
  263. void FBXExporter::WriteHeaderExtension ()
  264. {
  265. if (!binary) {
  266. // no title, follows directly from the top comment
  267. }
  268. FBX::Node n("FBXHeaderExtension");
  269. StreamWriterLE outstream(outfile);
  270. int indent = 0;
  271. // begin node
  272. n.Begin(outstream, binary, indent);
  273. // write properties
  274. // (none)
  275. // finish properties
  276. n.EndProperties(outstream, binary, indent, 0);
  277. // begin children
  278. n.BeginChildren(outstream, binary, indent);
  279. indent = 1;
  280. // write child nodes
  281. FBX::Node::WritePropertyNode(
  282. "FBXHeaderVersion", int32_t(1003), outstream, binary, indent
  283. );
  284. FBX::Node::WritePropertyNode(
  285. "FBXVersion", int32_t(EXPORT_VERSION_INT), outstream, binary, indent
  286. );
  287. if (binary) {
  288. FBX::Node::WritePropertyNode(
  289. "EncryptionType", int32_t(0), outstream, binary, indent
  290. );
  291. }
  292. FBX::Node CreationTimeStamp("CreationTimeStamp");
  293. time_t rawtime;
  294. time(&rawtime);
  295. struct tm * now = localtime(&rawtime);
  296. CreationTimeStamp.AddChild("Version", int32_t(1000));
  297. CreationTimeStamp.AddChild("Year", int32_t(now->tm_year + 1900));
  298. CreationTimeStamp.AddChild("Month", int32_t(now->tm_mon + 1));
  299. CreationTimeStamp.AddChild("Day", int32_t(now->tm_mday));
  300. CreationTimeStamp.AddChild("Hour", int32_t(now->tm_hour));
  301. CreationTimeStamp.AddChild("Minute", int32_t(now->tm_min));
  302. CreationTimeStamp.AddChild("Second", int32_t(now->tm_sec));
  303. CreationTimeStamp.AddChild("Millisecond", int32_t(0));
  304. CreationTimeStamp.Dump(outstream, binary, indent);
  305. std::stringstream creator;
  306. creator << "Open Asset Import Library (Assimp) " << aiGetVersionMajor()
  307. << "." << aiGetVersionMinor() << "." << aiGetVersionRevision();
  308. FBX::Node::WritePropertyNode(
  309. "Creator", creator.str(), outstream, binary, indent
  310. );
  311. indent = 0;
  312. // finish node
  313. n.End(outstream, binary, indent, true);
  314. // that's it for FBXHeaderExtension...
  315. if (!binary) { return; }
  316. // but binary files also need top-level FileID, CreationTime, Creator:
  317. std::vector<uint8_t> raw(GENERIC_FILEID.size());
  318. for (size_t i = 0; i < GENERIC_FILEID.size(); ++i) {
  319. raw[i] = uint8_t(GENERIC_FILEID[i]);
  320. }
  321. FBX::Node::WritePropertyNode(
  322. "FileId", std::move(raw), outstream, binary, indent
  323. );
  324. FBX::Node::WritePropertyNode(
  325. "CreationTime", GENERIC_CTIME, outstream, binary, indent
  326. );
  327. FBX::Node::WritePropertyNode(
  328. "Creator", creator.str(), outstream, binary, indent
  329. );
  330. }
  331. // WriteGlobalSettings helpers
  332. void WritePropInt(const aiScene* scene, FBX::Node& p, const std::string& key, int defaultValue)
  333. {
  334. int value;
  335. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  336. p.AddP70int(key, value);
  337. } else {
  338. p.AddP70int(key, defaultValue);
  339. }
  340. }
  341. void WritePropDouble(const aiScene* scene, FBX::Node& p, const std::string& key, double defaultValue)
  342. {
  343. double value;
  344. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  345. p.AddP70double(key, value);
  346. } else {
  347. // fallback lookup float instead
  348. float floatValue;
  349. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, floatValue)) {
  350. p.AddP70double(key, (double)floatValue);
  351. } else {
  352. p.AddP70double(key, defaultValue);
  353. }
  354. }
  355. }
  356. void WritePropEnum(const aiScene* scene, FBX::Node& p, const std::string& key, int defaultValue)
  357. {
  358. int value;
  359. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  360. p.AddP70enum(key, value);
  361. } else {
  362. p.AddP70enum(key, defaultValue);
  363. }
  364. }
  365. void WritePropColor(const aiScene* scene, FBX::Node& p, const std::string& key, const aiVector3D& defaultValue)
  366. {
  367. aiVector3D value;
  368. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  369. // ai_real can be float or double, cast to avoid warnings
  370. p.AddP70color(key, (double)value.x, (double)value.y, (double)value.z);
  371. } else {
  372. p.AddP70color(key, (double)defaultValue.x, (double)defaultValue.y, (double)defaultValue.z);
  373. }
  374. }
  375. void WritePropString(const aiScene* scene, FBX::Node& p, const std::string& key, const std::string& defaultValue)
  376. {
  377. aiString value; // MetaData doesn't hold std::string
  378. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  379. p.AddP70string(key, value.C_Str());
  380. } else {
  381. p.AddP70string(key, defaultValue);
  382. }
  383. }
  384. void FBXExporter::WriteGlobalSettings () {
  385. FBX::Node gs("GlobalSettings");
  386. gs.AddChild("Version", int32_t(1000));
  387. FBX::Node p("Properties70");
  388. WritePropInt(mScene, p, "UpAxis", 1);
  389. WritePropInt(mScene, p, "UpAxisSign", 1);
  390. WritePropInt(mScene, p, "FrontAxis", 2);
  391. WritePropInt(mScene, p, "FrontAxisSign", 1);
  392. WritePropInt(mScene, p, "CoordAxis", 0);
  393. WritePropInt(mScene, p, "CoordAxisSign", 1);
  394. WritePropInt(mScene, p, "OriginalUpAxis", 1);
  395. WritePropInt(mScene, p, "OriginalUpAxisSign", 1);
  396. WritePropDouble(mScene, p, "UnitScaleFactor", 1.0);
  397. WritePropDouble(mScene, p, "OriginalUnitScaleFactor", 1.0);
  398. WritePropColor(mScene, p, "AmbientColor", aiVector3D((ai_real)0.0, (ai_real)0.0, (ai_real)0.0));
  399. WritePropString(mScene, p,"DefaultCamera", "Producer Perspective");
  400. WritePropEnum(mScene, p, "TimeMode", 11);
  401. WritePropEnum(mScene, p, "TimeProtocol", 2);
  402. WritePropEnum(mScene, p, "SnapOnFrameMode", 0);
  403. p.AddP70time("TimeSpanStart", 0); // TODO: animation support
  404. p.AddP70time("TimeSpanStop", FBX::SECOND); // TODO: animation support
  405. WritePropDouble(mScene, p, "CustomFrameRate", -1.0);
  406. p.AddP70("TimeMarker", "Compound", "", ""); // not sure what this is
  407. WritePropInt(mScene, p, "CurrentTimeMarker", -1);
  408. gs.AddChild(p);
  409. gs.Dump(outfile, binary, 0);
  410. }
  411. void FBXExporter::WriteDocuments() {
  412. if (!binary) {
  413. WriteAsciiSectionHeader("Documents Description");
  414. }
  415. // not sure what the use of multiple documents would be,
  416. // or whether any end-application supports it
  417. FBX::Node docs("Documents");
  418. docs.AddChild("Count", int32_t(1));
  419. FBX::Node doc("Document");
  420. // generate uid
  421. int64_t uid = generate_uid();
  422. doc.AddProperties(uid, "", "Scene");
  423. FBX::Node p("Properties70");
  424. p.AddP70("SourceObject", "object", "", ""); // what is this even for?
  425. p.AddP70string("ActiveAnimStackName", ""); // should do this properly?
  426. doc.AddChild(p);
  427. // UID for root node in scene hierarchy.
  428. // always set to 0 in the case of a single document.
  429. // not sure what happens if more than one document exists,
  430. // but that won't matter to us as we're exporting a single scene.
  431. doc.AddChild("RootNode", int64_t(0));
  432. docs.AddChild(doc);
  433. docs.Dump(outfile, binary, 0);
  434. }
  435. void FBXExporter::WriteReferences() {
  436. if (!binary) {
  437. WriteAsciiSectionHeader("Document References");
  438. }
  439. // always empty for now.
  440. // not really sure what this is for.
  441. FBX::Node n("References");
  442. n.force_has_children = true;
  443. n.Dump(outfile, binary, 0);
  444. }
  445. // ---------------------------------------------------------------
  446. // some internal helper functions used for writing the definitions
  447. // (before any actual data is written)
  448. // ---------------------------------------------------------------
  449. size_t count_nodes(const aiNode* n, const aiNode* root) {
  450. size_t count;
  451. if (n == root) {
  452. count = n->mNumMeshes; // (not counting root node)
  453. } else if (n->mNumMeshes > 1) {
  454. count = n->mNumMeshes + 1;
  455. } else {
  456. count = 1;
  457. }
  458. for (size_t i = 0; i < n->mNumChildren; ++i) {
  459. count += count_nodes(n->mChildren[i], root);
  460. }
  461. return count;
  462. }
  463. static bool has_phong_mat(const aiScene* scene) {
  464. // just search for any material with a shininess exponent
  465. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  466. aiMaterial* mat = scene->mMaterials[i];
  467. float shininess = 0;
  468. mat->Get(AI_MATKEY_SHININESS, shininess);
  469. if (shininess > 0) {
  470. return true;
  471. }
  472. }
  473. return false;
  474. }
  475. static size_t count_images(const aiScene* scene) {
  476. std::unordered_set<std::string> images;
  477. aiString texpath;
  478. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  479. aiMaterial *mat = scene->mMaterials[i];
  480. for (size_t tt = aiTextureType_DIFFUSE; tt < aiTextureType_UNKNOWN; ++tt) {
  481. const aiTextureType textype = static_cast<aiTextureType>(tt);
  482. const size_t texcount = mat->GetTextureCount(textype);
  483. for (unsigned int j = 0; j < texcount; ++j) {
  484. mat->GetTexture(textype, j, &texpath);
  485. images.insert(std::string(texpath.C_Str()));
  486. }
  487. }
  488. }
  489. return images.size();
  490. }
  491. static size_t count_textures(const aiScene* scene) {
  492. size_t count = 0;
  493. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  494. aiMaterial* mat = scene->mMaterials[i];
  495. for (
  496. size_t tt = aiTextureType_DIFFUSE;
  497. tt < aiTextureType_UNKNOWN;
  498. ++tt
  499. ){
  500. // TODO: handle layered textures
  501. if (mat->GetTextureCount(static_cast<aiTextureType>(tt)) > 0) {
  502. count += 1;
  503. }
  504. }
  505. }
  506. return count;
  507. }
  508. static size_t count_deformers(const aiScene* scene) {
  509. size_t count = 0;
  510. for (size_t i = 0; i < scene->mNumMeshes; ++i) {
  511. const size_t n = scene->mMeshes[i]->mNumBones;
  512. if (n) {
  513. // 1 main deformer, 1 subdeformer per bone
  514. count += n + 1;
  515. }
  516. }
  517. return count;
  518. }
  519. void FBXExporter::WriteDefinitions () {
  520. // basically this is just bookkeeping:
  521. // determining how many of each type of object there are
  522. // and specifying the base properties to use when otherwise unspecified.
  523. // ascii section header
  524. if (!binary) {
  525. WriteAsciiSectionHeader("Object definitions");
  526. }
  527. // we need to count the objects
  528. int32_t count;
  529. int32_t total_count = 0;
  530. // and store them
  531. std::vector<FBX::Node> object_nodes;
  532. FBX::Node n, pt, p;
  533. // GlobalSettings
  534. // this seems to always be here in Maya exports
  535. n = FBX::Node("ObjectType", "GlobalSettings");
  536. count = 1;
  537. n.AddChild("Count", count);
  538. object_nodes.push_back(n);
  539. total_count += count;
  540. // AnimationStack / FbxAnimStack
  541. // this seems to always be here in Maya exports,
  542. // but no harm seems to come of leaving it out.
  543. count = mScene->mNumAnimations;
  544. if (count) {
  545. n = FBX::Node("ObjectType", "AnimationStack");
  546. n.AddChild("Count", count);
  547. pt = FBX::Node("PropertyTemplate", "FbxAnimStack");
  548. p = FBX::Node("Properties70");
  549. p.AddP70string("Description", "");
  550. p.AddP70time("LocalStart", 0);
  551. p.AddP70time("LocalStop", 0);
  552. p.AddP70time("ReferenceStart", 0);
  553. p.AddP70time("ReferenceStop", 0);
  554. pt.AddChild(p);
  555. n.AddChild(pt);
  556. object_nodes.push_back(n);
  557. total_count += count;
  558. }
  559. // AnimationLayer / FbxAnimLayer
  560. // this seems to always be here in Maya exports,
  561. // but no harm seems to come of leaving it out.
  562. // Assimp doesn't support animation layers,
  563. // so there will be one per aiAnimation
  564. count = mScene->mNumAnimations;
  565. if (count) {
  566. n = FBX::Node("ObjectType", "AnimationLayer");
  567. n.AddChild("Count", count);
  568. pt = FBX::Node("PropertyTemplate", "FBXAnimLayer");
  569. p = FBX::Node("Properties70");
  570. p.AddP70("Weight", "Number", "", "A", double(100));
  571. p.AddP70bool("Mute", false);
  572. p.AddP70bool("Solo", false);
  573. p.AddP70bool("Lock", false);
  574. p.AddP70color("Color", 0.8, 0.8, 0.8);
  575. p.AddP70("BlendMode", "enum", "", "", int32_t(0));
  576. p.AddP70("RotationAccumulationMode", "enum", "", "", int32_t(0));
  577. p.AddP70("ScaleAccumulationMode", "enum", "", "", int32_t(0));
  578. p.AddP70("BlendModeBypass", "ULongLong", "", "", int64_t(0));
  579. pt.AddChild(p);
  580. n.AddChild(pt);
  581. object_nodes.push_back(n);
  582. total_count += count;
  583. }
  584. // NodeAttribute
  585. // this is completely absurd.
  586. // there can only be one "NodeAttribute" template,
  587. // but FbxSkeleton, FbxCamera, FbxLight all are "NodeAttributes".
  588. // so if only one exists we should set the template for that,
  589. // otherwise... we just pick one :/.
  590. // the others have to set all their properties every instance,
  591. // because there's no template.
  592. count = 1; // TODO: select properly
  593. if (count) {
  594. // FbxSkeleton
  595. n = FBX::Node("ObjectType", "NodeAttribute");
  596. n.AddChild("Count", count);
  597. pt = FBX::Node("PropertyTemplate", "FbxSkeleton");
  598. p = FBX::Node("Properties70");
  599. p.AddP70color("Color", 0.8, 0.8, 0.8);
  600. p.AddP70double("Size", 33.333333333333);
  601. p.AddP70("LimbLength", "double", "Number", "H", double(1));
  602. // note: not sure what the "H" flag is for - hidden?
  603. pt.AddChild(p);
  604. n.AddChild(pt);
  605. object_nodes.push_back(n);
  606. total_count += count;
  607. }
  608. // Model / FbxNode
  609. // <~~ node hierarchy
  610. count = int32_t(count_nodes(mScene->mRootNode, mScene->mRootNode));
  611. if (count) {
  612. n = FBX::Node("ObjectType", "Model");
  613. n.AddChild("Count", count);
  614. pt = FBX::Node("PropertyTemplate", "FbxNode");
  615. p = FBX::Node("Properties70");
  616. p.AddP70enum("QuaternionInterpolate", 0);
  617. p.AddP70vector("RotationOffset", 0.0, 0.0, 0.0);
  618. p.AddP70vector("RotationPivot", 0.0, 0.0, 0.0);
  619. p.AddP70vector("ScalingOffset", 0.0, 0.0, 0.0);
  620. p.AddP70vector("ScalingPivot", 0.0, 0.0, 0.0);
  621. p.AddP70bool("TranslationActive", false);
  622. p.AddP70vector("TranslationMin", 0.0, 0.0, 0.0);
  623. p.AddP70vector("TranslationMax", 0.0, 0.0, 0.0);
  624. p.AddP70bool("TranslationMinX", false);
  625. p.AddP70bool("TranslationMinY", false);
  626. p.AddP70bool("TranslationMinZ", false);
  627. p.AddP70bool("TranslationMaxX", false);
  628. p.AddP70bool("TranslationMaxY", false);
  629. p.AddP70bool("TranslationMaxZ", false);
  630. p.AddP70enum("RotationOrder", 0);
  631. p.AddP70bool("RotationSpaceForLimitOnly", false);
  632. p.AddP70double("RotationStiffnessX", 0.0);
  633. p.AddP70double("RotationStiffnessY", 0.0);
  634. p.AddP70double("RotationStiffnessZ", 0.0);
  635. p.AddP70double("AxisLen", 10.0);
  636. p.AddP70vector("PreRotation", 0.0, 0.0, 0.0);
  637. p.AddP70vector("PostRotation", 0.0, 0.0, 0.0);
  638. p.AddP70bool("RotationActive", false);
  639. p.AddP70vector("RotationMin", 0.0, 0.0, 0.0);
  640. p.AddP70vector("RotationMax", 0.0, 0.0, 0.0);
  641. p.AddP70bool("RotationMinX", false);
  642. p.AddP70bool("RotationMinY", false);
  643. p.AddP70bool("RotationMinZ", false);
  644. p.AddP70bool("RotationMaxX", false);
  645. p.AddP70bool("RotationMaxY", false);
  646. p.AddP70bool("RotationMaxZ", false);
  647. p.AddP70enum("InheritType", 0);
  648. p.AddP70bool("ScalingActive", false);
  649. p.AddP70vector("ScalingMin", 0.0, 0.0, 0.0);
  650. p.AddP70vector("ScalingMax", 1.0, 1.0, 1.0);
  651. p.AddP70bool("ScalingMinX", false);
  652. p.AddP70bool("ScalingMinY", false);
  653. p.AddP70bool("ScalingMinZ", false);
  654. p.AddP70bool("ScalingMaxX", false);
  655. p.AddP70bool("ScalingMaxY", false);
  656. p.AddP70bool("ScalingMaxZ", false);
  657. p.AddP70vector("GeometricTranslation", 0.0, 0.0, 0.0);
  658. p.AddP70vector("GeometricRotation", 0.0, 0.0, 0.0);
  659. p.AddP70vector("GeometricScaling", 1.0, 1.0, 1.0);
  660. p.AddP70double("MinDampRangeX", 0.0);
  661. p.AddP70double("MinDampRangeY", 0.0);
  662. p.AddP70double("MinDampRangeZ", 0.0);
  663. p.AddP70double("MaxDampRangeX", 0.0);
  664. p.AddP70double("MaxDampRangeY", 0.0);
  665. p.AddP70double("MaxDampRangeZ", 0.0);
  666. p.AddP70double("MinDampStrengthX", 0.0);
  667. p.AddP70double("MinDampStrengthY", 0.0);
  668. p.AddP70double("MinDampStrengthZ", 0.0);
  669. p.AddP70double("MaxDampStrengthX", 0.0);
  670. p.AddP70double("MaxDampStrengthY", 0.0);
  671. p.AddP70double("MaxDampStrengthZ", 0.0);
  672. p.AddP70double("PreferedAngleX", 0.0);
  673. p.AddP70double("PreferedAngleY", 0.0);
  674. p.AddP70double("PreferedAngleZ", 0.0);
  675. p.AddP70("LookAtProperty", "object", "", "");
  676. p.AddP70("UpVectorProperty", "object", "", "");
  677. p.AddP70bool("Show", true);
  678. p.AddP70bool("NegativePercentShapeSupport", true);
  679. p.AddP70int("DefaultAttributeIndex", -1);
  680. p.AddP70bool("Freeze", false);
  681. p.AddP70bool("LODBox", false);
  682. p.AddP70(
  683. "Lcl Translation", "Lcl Translation", "", "A",
  684. double(0), double(0), double(0)
  685. );
  686. p.AddP70(
  687. "Lcl Rotation", "Lcl Rotation", "", "A",
  688. double(0), double(0), double(0)
  689. );
  690. p.AddP70(
  691. "Lcl Scaling", "Lcl Scaling", "", "A",
  692. double(1), double(1), double(1)
  693. );
  694. p.AddP70("Visibility", "Visibility", "", "A", double(1));
  695. p.AddP70(
  696. "Visibility Inheritance", "Visibility Inheritance", "", "",
  697. int32_t(1)
  698. );
  699. pt.AddChild(p);
  700. n.AddChild(pt);
  701. object_nodes.push_back(n);
  702. total_count += count;
  703. }
  704. // Geometry / FbxMesh
  705. // <~~ aiMesh
  706. count = mScene->mNumMeshes;
  707. // Blendshapes are considered Geometry
  708. int32_t bsDeformerCount=0;
  709. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  710. aiMesh* m = mScene->mMeshes[mi];
  711. if (m->mNumAnimMeshes > 0) {
  712. count+=m->mNumAnimMeshes;
  713. bsDeformerCount+=m->mNumAnimMeshes; // One deformer per blendshape
  714. bsDeformerCount++; // Plus one master blendshape deformer
  715. }
  716. }
  717. if (count) {
  718. n = FBX::Node("ObjectType", "Geometry");
  719. n.AddChild("Count", count);
  720. pt = FBX::Node("PropertyTemplate", "FbxMesh");
  721. p = FBX::Node("Properties70");
  722. p.AddP70color("Color", 0, 0, 0);
  723. p.AddP70vector("BBoxMin", 0, 0, 0);
  724. p.AddP70vector("BBoxMax", 0, 0, 0);
  725. p.AddP70bool("Primary Visibility", true);
  726. p.AddP70bool("Casts Shadows", true);
  727. p.AddP70bool("Receive Shadows", true);
  728. pt.AddChild(p);
  729. n.AddChild(pt);
  730. object_nodes.push_back(n);
  731. total_count += count;
  732. }
  733. // Material / FbxSurfacePhong, FbxSurfaceLambert, FbxSurfaceMaterial
  734. // <~~ aiMaterial
  735. // basically if there's any phong material this is defined as phong,
  736. // and otherwise lambert.
  737. // More complex materials cause a bare-bones FbxSurfaceMaterial definition
  738. // and are treated specially, as they're not really supported by FBX.
  739. // TODO: support Maya's Stingray PBS material
  740. count = mScene->mNumMaterials;
  741. if (count) {
  742. bool has_phong = has_phong_mat(mScene);
  743. n = FBX::Node("ObjectType", "Material");
  744. n.AddChild("Count", count);
  745. pt = FBX::Node("PropertyTemplate");
  746. if (has_phong) {
  747. pt.AddProperty("FbxSurfacePhong");
  748. } else {
  749. pt.AddProperty("FbxSurfaceLambert");
  750. }
  751. p = FBX::Node("Properties70");
  752. if (has_phong) {
  753. p.AddP70string("ShadingModel", "Phong");
  754. } else {
  755. p.AddP70string("ShadingModel", "Lambert");
  756. }
  757. p.AddP70bool("MultiLayer", false);
  758. p.AddP70colorA("EmissiveColor", 0.0, 0.0, 0.0);
  759. p.AddP70numberA("EmissiveFactor", 1.0);
  760. p.AddP70colorA("AmbientColor", 0.2, 0.2, 0.2);
  761. p.AddP70numberA("AmbientFactor", 1.0);
  762. p.AddP70colorA("DiffuseColor", 0.8, 0.8, 0.8);
  763. p.AddP70numberA("DiffuseFactor", 1.0);
  764. p.AddP70vector("Bump", 0.0, 0.0, 0.0);
  765. p.AddP70vector("NormalMap", 0.0, 0.0, 0.0);
  766. p.AddP70double("BumpFactor", 1.0);
  767. p.AddP70colorA("TransparentColor", 0.0, 0.0, 0.0);
  768. p.AddP70numberA("TransparencyFactor", 0.0);
  769. p.AddP70color("DisplacementColor", 0.0, 0.0, 0.0);
  770. p.AddP70double("DisplacementFactor", 1.0);
  771. p.AddP70color("VectorDisplacementColor", 0.0, 0.0, 0.0);
  772. p.AddP70double("VectorDisplacementFactor", 1.0);
  773. if (has_phong) {
  774. p.AddP70colorA("SpecularColor", 0.2, 0.2, 0.2);
  775. p.AddP70numberA("SpecularFactor", 1.0);
  776. p.AddP70numberA("ShininessExponent", 20.0);
  777. p.AddP70colorA("ReflectionColor", 0.0, 0.0, 0.0);
  778. p.AddP70numberA("ReflectionFactor", 1.0);
  779. }
  780. pt.AddChild(p);
  781. n.AddChild(pt);
  782. object_nodes.push_back(n);
  783. total_count += count;
  784. }
  785. // Video / FbxVideo
  786. // one for each image file.
  787. count = int32_t(count_images(mScene));
  788. if (count) {
  789. n = FBX::Node("ObjectType", "Video");
  790. n.AddChild("Count", count);
  791. pt = FBX::Node("PropertyTemplate", "FbxVideo");
  792. p = FBX::Node("Properties70");
  793. p.AddP70bool("ImageSequence", false);
  794. p.AddP70int("ImageSequenceOffset", 0);
  795. p.AddP70double("FrameRate", 0.0);
  796. p.AddP70int("LastFrame", 0);
  797. p.AddP70int("Width", 0);
  798. p.AddP70int("Height", 0);
  799. p.AddP70("Path", "KString", "XRefUrl", "", "");
  800. p.AddP70int("StartFrame", 0);
  801. p.AddP70int("StopFrame", 0);
  802. p.AddP70double("PlaySpeed", 0.0);
  803. p.AddP70time("Offset", 0);
  804. p.AddP70enum("InterlaceMode", 0);
  805. p.AddP70bool("FreeRunning", false);
  806. p.AddP70bool("Loop", false);
  807. p.AddP70enum("AccessMode", 0);
  808. pt.AddChild(p);
  809. n.AddChild(pt);
  810. object_nodes.push_back(n);
  811. total_count += count;
  812. }
  813. // Texture / FbxFileTexture
  814. // <~~ aiTexture
  815. count = int32_t(count_textures(mScene));
  816. if (count) {
  817. n = FBX::Node("ObjectType", "Texture");
  818. n.AddChild("Count", count);
  819. pt = FBX::Node("PropertyTemplate", "FbxFileTexture");
  820. p = FBX::Node("Properties70");
  821. p.AddP70enum("TextureTypeUse", 0);
  822. p.AddP70numberA("Texture alpha", 1.0);
  823. p.AddP70enum("CurrentMappingType", 0);
  824. p.AddP70enum("WrapModeU", 0);
  825. p.AddP70enum("WrapModeV", 0);
  826. p.AddP70bool("UVSwap", false);
  827. p.AddP70bool("PremultiplyAlpha", true);
  828. p.AddP70vectorA("Translation", 0.0, 0.0, 0.0);
  829. p.AddP70vectorA("Rotation", 0.0, 0.0, 0.0);
  830. p.AddP70vectorA("Scaling", 1.0, 1.0, 1.0);
  831. p.AddP70vector("TextureRotationPivot", 0.0, 0.0, 0.0);
  832. p.AddP70vector("TextureScalingPivot", 0.0, 0.0, 0.0);
  833. p.AddP70enum("CurrentTextureBlendMode", 1);
  834. p.AddP70string("UVSet", "default");
  835. p.AddP70bool("UseMaterial", false);
  836. p.AddP70bool("UseMipMap", false);
  837. pt.AddChild(p);
  838. n.AddChild(pt);
  839. object_nodes.push_back(n);
  840. total_count += count;
  841. }
  842. // AnimationCurveNode / FbxAnimCurveNode
  843. count = mScene->mNumAnimations * 3;
  844. if (count) {
  845. n = FBX::Node("ObjectType", "AnimationCurveNode");
  846. n.AddChild("Count", count);
  847. pt = FBX::Node("PropertyTemplate", "FbxAnimCurveNode");
  848. p = FBX::Node("Properties70");
  849. p.AddP70("d", "Compound", "", "");
  850. pt.AddChild(p);
  851. n.AddChild(pt);
  852. object_nodes.push_back(n);
  853. total_count += count;
  854. }
  855. // AnimationCurve / FbxAnimCurve
  856. count = mScene->mNumAnimations * 9;
  857. if (count) {
  858. n = FBX::Node("ObjectType", "AnimationCurve");
  859. n.AddChild("Count", count);
  860. object_nodes.push_back(n);
  861. total_count += count;
  862. }
  863. // Pose
  864. count = 0;
  865. for (size_t i = 0; i < mScene->mNumMeshes; ++i) {
  866. aiMesh* mesh = mScene->mMeshes[i];
  867. if (mesh->HasBones()) { ++count; }
  868. }
  869. if (count) {
  870. n = FBX::Node("ObjectType", "Pose");
  871. n.AddChild("Count", count);
  872. object_nodes.push_back(n);
  873. total_count += count;
  874. }
  875. // Deformer
  876. count = int32_t(count_deformers(mScene))+bsDeformerCount;
  877. if (count) {
  878. n = FBX::Node("ObjectType", "Deformer");
  879. n.AddChild("Count", count);
  880. object_nodes.push_back(n);
  881. total_count += count;
  882. }
  883. // (template)
  884. count = 0;
  885. if (count) {
  886. n = FBX::Node("ObjectType", "");
  887. n.AddChild("Count", count);
  888. pt = FBX::Node("PropertyTemplate", "");
  889. p = FBX::Node("Properties70");
  890. pt.AddChild(p);
  891. n.AddChild(pt);
  892. object_nodes.push_back(n);
  893. total_count += count;
  894. }
  895. // now write it all
  896. FBX::Node defs("Definitions");
  897. defs.AddChild("Version", int32_t(100));
  898. defs.AddChild("Count", int32_t(total_count));
  899. for (auto &on : object_nodes) {
  900. defs.AddChild(on);
  901. }
  902. defs.Dump(outfile, binary, 0);
  903. }
  904. // -------------------------------------------------------------------
  905. // some internal helper functions used for writing the objects section
  906. // (which holds the actual data)
  907. // -------------------------------------------------------------------
  908. static aiNode* get_node_for_mesh(unsigned int meshIndex, aiNode* node) {
  909. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  910. if (node->mMeshes[i] == meshIndex) {
  911. return node;
  912. }
  913. }
  914. for (size_t i = 0; i < node->mNumChildren; ++i) {
  915. aiNode* ret = get_node_for_mesh(meshIndex, node->mChildren[i]);
  916. if (ret) { return ret; }
  917. }
  918. return nullptr;
  919. }
  920. aiMatrix4x4 get_world_transform(const aiNode* node, const aiScene* scene) {
  921. std::vector<const aiNode*> node_chain;
  922. while (node != scene->mRootNode && node != nullptr) {
  923. node_chain.push_back(node);
  924. node = node->mParent;
  925. }
  926. aiMatrix4x4 transform;
  927. for (auto n = node_chain.rbegin(); n != node_chain.rend(); ++n) {
  928. transform *= (*n)->mTransformation;
  929. }
  930. return transform;
  931. }
  932. inline int64_t to_ktime(double ticks, const aiAnimation* anim) {
  933. if (FP_ZERO == std::fpclassify(anim->mTicksPerSecond)) {
  934. return static_cast<int64_t>(ticks * FBX::SECOND);
  935. }
  936. // Defensive: handle zero or near-zero mTicksPerSecond
  937. double tps = anim->mTicksPerSecond;
  938. double timeVal;
  939. if (FP_ZERO == std::fpclassify(tps)) {
  940. timeVal = ticks;
  941. } else {
  942. timeVal = ticks / tps;
  943. }
  944. // Clamp to prevent overflow
  945. const double kMax = static_cast<double>(INT64_MAX) / static_cast<double>(FBX::SECOND);
  946. const double kMin = static_cast<double>(INT64_MIN) / static_cast<double>(FBX::SECOND);
  947. if (timeVal > kMax) {
  948. return INT64_MAX;
  949. }
  950. if (timeVal < kMin) {
  951. return INT64_MIN;
  952. }
  953. return static_cast<int64_t>((ticks / anim->mTicksPerSecond) * FBX::SECOND);
  954. }
  955. inline int64_t to_ktime(double time) {
  956. // Clamp to prevent overflow
  957. const double kMax = static_cast<double>(INT64_MAX) / static_cast<double>(FBX::SECOND);
  958. const double kMin = static_cast<double>(INT64_MIN) / static_cast<double>(FBX::SECOND);
  959. if (time > kMax) {
  960. return INT64_MAX;
  961. }
  962. if (time < kMin) {
  963. return INT64_MIN;
  964. }
  965. return static_cast<int64_t>(time * FBX::SECOND);
  966. }
  967. void FBXExporter::WriteObjects () {
  968. if (!binary) {
  969. WriteAsciiSectionHeader("Object properties");
  970. }
  971. // numbers should match those given in definitions! make sure to check
  972. StreamWriterLE outstream(outfile);
  973. FBX::Node object_node("Objects");
  974. int indent = 0;
  975. object_node.Begin(outstream, binary, indent);
  976. object_node.EndProperties(outstream, binary, indent);
  977. object_node.BeginChildren(outstream, binary, indent);
  978. bool bJoinIdenticalVertices = mProperties->GetPropertyBool("bJoinIdenticalVertices", true);
  979. // save vertex_indices as it is needed later
  980. std::vector<std::vector<int32_t>> vVertexIndice(mScene->mNumMeshes);
  981. std::vector<uint32_t> uniq_v_before_mi;
  982. const auto bTransparencyFactorReferencedToOpacity = mProperties->GetPropertyBool(AI_CONFIG_EXPORT_FBX_TRANSPARENCY_FACTOR_REFER_TO_OPACITY, false);
  983. // geometry (aiMesh)
  984. mesh_uids.clear();
  985. indent = 1;
  986. std::function<void(const aiNode*)> visit_node_geo = [&](const aiNode *node) {
  987. if (node->mNumMeshes == 0) {
  988. for (uint32_t ni = 0; ni < node->mNumChildren; ni++) {
  989. visit_node_geo(node->mChildren[ni]);
  990. }
  991. return;
  992. }
  993. // start the node record
  994. FBX::Node n("Geometry");
  995. int64_t uid = generate_uid();
  996. mesh_uids[node] = uid;
  997. n.AddProperty(uid);
  998. n.AddProperty(FBX::SEPARATOR + "Geometry");
  999. n.AddProperty("Mesh");
  1000. n.Begin(outstream, binary, indent);
  1001. n.DumpProperties(outstream, binary, indent);
  1002. n.EndProperties(outstream, binary, indent);
  1003. n.BeginChildren(outstream, binary, indent);
  1004. // output vertex data - each vertex should be unique (probably)
  1005. std::vector<double> flattened_vertices;
  1006. // index of original vertex in vertex data vector
  1007. std::vector<int32_t> vertex_indices;
  1008. std::vector<double> normal_data;
  1009. std::vector<double> color_data;
  1010. std::vector<int32_t> polygon_data;
  1011. std::vector<std::vector<double>> uv_data;
  1012. std::vector<std::vector<int32_t>> uv_indices;
  1013. indent = 2;
  1014. for (uint32_t n_mi = 0; n_mi < node->mNumMeshes; n_mi++) {
  1015. const auto mi = node->mMeshes[n_mi];
  1016. const aiMesh *m = mScene->mMeshes[mi];
  1017. size_t v_offset = vertex_indices.size();
  1018. size_t uniq_v_before = flattened_vertices.size() / 3;
  1019. // map of vertex value to its index in the data vector
  1020. std::map<aiVector3D,size_t> index_by_vertex_value;
  1021. if (bJoinIdenticalVertices) {
  1022. int32_t index = 0;
  1023. for (size_t vi = 0; vi < m->mNumVertices; ++vi) {
  1024. aiVector3D vtx = m->mVertices[vi];
  1025. auto elem = index_by_vertex_value.find(vtx);
  1026. if (elem == index_by_vertex_value.end()) {
  1027. vertex_indices.push_back(index);
  1028. index_by_vertex_value[vtx] = index;
  1029. flattened_vertices.insert(flattened_vertices.end(), { vtx.x, vtx.y, vtx.z });
  1030. ++index;
  1031. } else {
  1032. vertex_indices.push_back(int32_t(elem->second));
  1033. }
  1034. }
  1035. } else { // do not join vertex, respect the export flag
  1036. vertex_indices.resize(v_offset + m->mNumVertices);
  1037. std::iota(vertex_indices.begin() + v_offset, vertex_indices.end(), 0);
  1038. for(unsigned int v = 0; v < m->mNumVertices; ++ v) {
  1039. aiVector3D vtx = m->mVertices[v];
  1040. flattened_vertices.insert(flattened_vertices.end(), {vtx.x, vtx.y, vtx.z});
  1041. }
  1042. }
  1043. vVertexIndice[mi].insert(
  1044. // TODO test whether this can be end or not
  1045. vVertexIndice[mi].end(),
  1046. vertex_indices.begin() + v_offset,
  1047. vertex_indices.end()
  1048. );
  1049. // here could be edges but they're insane.
  1050. // it's optional anyway, so let's ignore it.
  1051. // output polygon data as a flattened array of vertex indices.
  1052. // the last vertex index of each polygon is negated and - 1
  1053. for (size_t fi = 0; fi < m->mNumFaces; fi++) {
  1054. const aiFace &f = m->mFaces[fi];
  1055. if (f.mNumIndices == 0) continue;
  1056. size_t pvi = 0;
  1057. for (; pvi < f.mNumIndices - 1; pvi++) {
  1058. polygon_data.push_back(
  1059. static_cast<int32_t>(uniq_v_before + vertex_indices[v_offset + f.mIndices[pvi]])
  1060. );
  1061. }
  1062. polygon_data.push_back(
  1063. static_cast<int32_t>(-1 ^ (uniq_v_before + vertex_indices[v_offset+f.mIndices[pvi]]))
  1064. );
  1065. }
  1066. uniq_v_before_mi.push_back(static_cast<uint32_t>(uniq_v_before));
  1067. if (m->HasNormals()) {
  1068. normal_data.reserve(3 * polygon_data.size());
  1069. for (size_t fi = 0; fi < m->mNumFaces; fi++) {
  1070. const aiFace & f = m->mFaces[fi];
  1071. for (size_t pvi = 0; pvi < f.mNumIndices; pvi++) {
  1072. const aiVector3D &curN = m->mNormals[f.mIndices[pvi]];
  1073. normal_data.insert(normal_data.end(), { curN.x, curN.y, curN.z });
  1074. }
  1075. }
  1076. }
  1077. const int32_t colorChannelIndex = 0;
  1078. if (m->HasVertexColors(colorChannelIndex)) {
  1079. color_data.reserve(4 * polygon_data.size());
  1080. for (size_t fi = 0; fi < m->mNumFaces; fi++) {
  1081. const aiFace &f = m->mFaces[fi];
  1082. for (size_t pvi = 0; pvi < f.mNumIndices; pvi++) {
  1083. const aiColor4D &c = m->mColors[colorChannelIndex][f.mIndices[pvi]];
  1084. color_data.insert(color_data.end(), { c.r, c.g, c.b, c.a });
  1085. }
  1086. }
  1087. }
  1088. const auto num_uv = static_cast<size_t>(m->GetNumUVChannels());
  1089. uv_indices.resize(std::max(num_uv, uv_indices.size()));
  1090. uv_data.resize(std::max(num_uv, uv_data.size()));
  1091. std::map<aiVector3D, int32_t> index_by_uv;
  1092. // uvs, if any
  1093. for (size_t uvi = 0; uvi < m->GetNumUVChannels(); uvi++) {
  1094. const auto nc = m->mNumUVComponents[uvi];
  1095. if (nc > 2) {
  1096. // FBX only supports 2-channel UV maps...
  1097. // or at least i'm not sure how to indicate a different number
  1098. std::stringstream err;
  1099. err << "Only 2-channel UV maps supported by FBX,";
  1100. err << " but mesh " << mi;
  1101. if (m->mName.length) {
  1102. err << " (" << m->mName.C_Str() << ")";
  1103. }
  1104. err << " UV map " << uvi;
  1105. err << " has " << m->mNumUVComponents[uvi];
  1106. err << " components! Data will be preserved,";
  1107. err << " but may be incorrectly interpreted on load.";
  1108. ASSIMP_LOG_WARN(err.str());
  1109. }
  1110. int32_t index = static_cast<int32_t>(uv_data[uvi].size()) / nc;
  1111. for (size_t fi = 0; fi < m->mNumFaces; fi++) {
  1112. const aiFace &f = m->mFaces[fi];
  1113. for (size_t pvi = 0; pvi < f.mNumIndices; pvi++) {
  1114. const aiVector3D &curUv = m->mTextureCoords[uvi][f.mIndices[pvi]];
  1115. auto elem = index_by_uv.find(curUv);
  1116. if (elem == index_by_uv.end()) {
  1117. index_by_uv[curUv] = index;
  1118. uv_indices[uvi].push_back(index);
  1119. for (uint32_t x = 0; x < nc; ++x) {
  1120. uv_data[uvi].push_back(curUv[x]);
  1121. }
  1122. ++index;
  1123. } else {
  1124. uv_indices[uvi].push_back(elem->second);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. FBX::Node::WritePropertyNode("Vertices", flattened_vertices, outstream, binary, indent);
  1131. FBX::Node::WritePropertyNode("PolygonVertexIndex", polygon_data, outstream, binary, indent);
  1132. FBX::Node::WritePropertyNode("GeometryVersion", int32_t(124), outstream, binary, indent);
  1133. if (!normal_data.empty()) {
  1134. FBX::Node normals("LayerElementNormal", int32_t(0));
  1135. normals.Begin(outstream, binary, indent);
  1136. normals.DumpProperties(outstream, binary, indent);
  1137. normals.EndProperties(outstream, binary, indent);
  1138. normals.BeginChildren(outstream, binary, indent);
  1139. indent = 3;
  1140. FBX::Node::WritePropertyNode("Version", int32_t(101), outstream, binary, indent);
  1141. FBX::Node::WritePropertyNode("Name", "", outstream, binary, indent);
  1142. FBX::Node::WritePropertyNode("MappingInformationType", "ByPolygonVertex", outstream, binary, indent);
  1143. FBX::Node::WritePropertyNode("ReferenceInformationType", "Direct", outstream, binary, indent);
  1144. FBX::Node::WritePropertyNode("Normals", normal_data, outstream, binary, indent);
  1145. // note: version 102 has a NormalsW also... not sure what it is,
  1146. // so stick with version 101 for now.
  1147. indent = 2;
  1148. normals.End(outstream, binary, indent, true);
  1149. }
  1150. if (!color_data.empty()) {
  1151. const auto colorChannelIndex = 0;
  1152. FBX::Node vertexcolors("LayerElementColor", int32_t(colorChannelIndex));
  1153. vertexcolors.Begin(outstream, binary, indent);
  1154. vertexcolors.DumpProperties(outstream, binary, indent);
  1155. vertexcolors.EndProperties(outstream, binary, indent);
  1156. vertexcolors.BeginChildren(outstream, binary, indent);
  1157. indent = 3;
  1158. FBX::Node::WritePropertyNode("Version", int32_t(101), outstream, binary, indent);
  1159. char layerName[8];
  1160. snprintf(layerName, sizeof(layerName), "COLOR_%d", colorChannelIndex);
  1161. FBX::Node::WritePropertyNode("Name", (const char *)layerName, outstream, binary, indent);
  1162. FBX::Node::WritePropertyNode("MappingInformationType", "ByPolygonVertex", outstream, binary, indent);
  1163. FBX::Node::WritePropertyNode("ReferenceInformationType", "Direct", outstream, binary, indent);
  1164. FBX::Node::WritePropertyNode("Colors", color_data, outstream, binary, indent);
  1165. indent = 2;
  1166. vertexcolors.End(outstream, binary, indent, true);
  1167. }
  1168. for (uint32_t uvi = 0; uvi < uv_data.size(); uvi++) {
  1169. FBX::Node uv("LayerElementUV", int32_t(uvi));
  1170. uv.Begin(outstream, binary, indent);
  1171. uv.DumpProperties(outstream, binary, indent);
  1172. uv.EndProperties(outstream, binary, indent);
  1173. uv.BeginChildren(outstream, binary, indent);
  1174. indent = 3;
  1175. FBX::Node::WritePropertyNode("Version", int32_t(101), outstream, binary, indent);
  1176. FBX::Node::WritePropertyNode("Name", "", outstream, binary, indent);
  1177. FBX::Node::WritePropertyNode("MappingInformationType", "ByPolygonVertex", outstream, binary, indent);
  1178. FBX::Node::WritePropertyNode("ReferenceInformationType", "IndexToDirect", outstream, binary, indent);
  1179. FBX::Node::WritePropertyNode("UV", uv_data[uvi], outstream, binary, indent);
  1180. FBX::Node::WritePropertyNode("UVIndex", uv_indices[uvi], outstream, binary, indent);
  1181. indent = 2;
  1182. uv.End(outstream, binary, indent, true);
  1183. }
  1184. // When merging multiple meshes, we instead use by polygon so the correct material is
  1185. // assigned to each face. Previously, this LayerElementMaterial always had 0 since it
  1186. // assumed there was 1 material for each node for all meshes.
  1187. FBX::Node mat("LayerElementMaterial", int32_t(0));
  1188. mat.AddChild("Version", int32_t(101));
  1189. mat.AddChild("Name", "");
  1190. if (node->mNumMeshes == 1) {
  1191. mat.AddChild("MappingInformationType", "AllSame");
  1192. mat.AddChild("ReferenceInformationType", "IndexToDirect");
  1193. std::vector<int32_t> mat_indices = {0};
  1194. mat.AddChild("Materials", mat_indices);
  1195. } else {
  1196. mat.AddChild("MappingInformationType", "ByPolygon");
  1197. mat.AddChild("ReferenceInformationType", "IndexToDirect");
  1198. std::vector<int32_t> mat_indices;
  1199. for (uint32_t n_mi = 0; n_mi < node->mNumMeshes; n_mi++) {
  1200. const auto mi = node->mMeshes[n_mi];
  1201. const auto *const m = mScene->mMeshes[mi];
  1202. for (size_t fi = 0; fi < m->mNumFaces; fi++) {
  1203. mat_indices.push_back(n_mi);
  1204. }
  1205. }
  1206. mat.AddChild("Materials", mat_indices);
  1207. }
  1208. mat.Dump(outstream, binary, indent);
  1209. // finally we have the layer specifications,
  1210. // which select the normals / UV set / etc to use.
  1211. // TODO: handle multiple uv sets correctly?
  1212. FBX::Node layer("Layer", int32_t(0));
  1213. layer.AddChild("Version", int32_t(100));
  1214. FBX::Node le;
  1215. if (!normal_data.empty()) {
  1216. le = FBX::Node("LayerElement");
  1217. le.AddChild("Type", "LayerElementNormal");
  1218. le.AddChild("TypedIndex", int32_t(0));
  1219. layer.AddChild(le);
  1220. }
  1221. if (!color_data.empty()) {
  1222. le = FBX::Node("LayerElement");
  1223. le.AddChild("Type", "LayerElementColor");
  1224. le.AddChild("TypedIndex", int32_t(0));
  1225. layer.AddChild(le);
  1226. }
  1227. le = FBX::Node("LayerElement");
  1228. le.AddChild("Type", "LayerElementMaterial");
  1229. le.AddChild("TypedIndex", int32_t(0));
  1230. layer.AddChild(le);
  1231. le = FBX::Node("LayerElement");
  1232. le.AddChild("Type", "LayerElementUV");
  1233. le.AddChild("TypedIndex", int32_t(0));
  1234. layer.AddChild(le);
  1235. layer.Dump(outstream, binary, indent);
  1236. for(unsigned int lr = 1; lr < uv_data.size(); ++ lr) {
  1237. FBX::Node layerExtra("Layer", int32_t(lr));
  1238. layerExtra.AddChild("Version", int32_t(100));
  1239. FBX::Node leExtra("LayerElement");
  1240. leExtra.AddChild("Type", "LayerElementUV");
  1241. leExtra.AddChild("TypedIndex", int32_t(lr));
  1242. layerExtra.AddChild(leExtra);
  1243. layerExtra.Dump(outstream, binary, indent);
  1244. }
  1245. // finish the node record
  1246. indent = 1;
  1247. n.End(outstream, binary, indent, true);
  1248. for (uint32_t ni = 0; ni < node->mNumChildren; ni++) {
  1249. visit_node_geo(node->mChildren[ni]);
  1250. }
  1251. return;
  1252. };
  1253. visit_node_geo(mScene->mRootNode);
  1254. // aiMaterial
  1255. material_uids.clear();
  1256. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1257. // it's all about this material
  1258. aiMaterial* m = mScene->mMaterials[i];
  1259. // these are used to receive material data
  1260. ai_real f; aiColor3D c;
  1261. // start the node record
  1262. FBX::Node n("Material");
  1263. int64_t uid = generate_uid();
  1264. material_uids.push_back(uid);
  1265. n.AddProperty(uid);
  1266. aiString name;
  1267. m->Get(AI_MATKEY_NAME, name);
  1268. n.AddProperty(name.C_Str() + FBX::SEPARATOR + "Material");
  1269. n.AddProperty("");
  1270. n.AddChild("Version", int32_t(102));
  1271. f = 0;
  1272. m->Get(AI_MATKEY_SHININESS, f);
  1273. bool phong = (f > 0);
  1274. if (phong) {
  1275. n.AddChild("ShadingModel", "phong");
  1276. } else {
  1277. n.AddChild("ShadingModel", "lambert");
  1278. }
  1279. n.AddChild("MultiLayer", int32_t(0));
  1280. FBX::Node p("Properties70");
  1281. // materials exported using the FBX SDK have two sets of fields.
  1282. // there are the properties specified in the PropertyTemplate,
  1283. // which are those supported by the modernFBX SDK,
  1284. // and an extra set of properties with simpler names.
  1285. // The extra properties are a legacy material system from pre-2009.
  1286. //
  1287. // In the modern system, each property has "color" and "factor".
  1288. // Generally the interpretation of these seems to be
  1289. // that the colour is multiplied by the factor before use,
  1290. // but this is not always clear-cut.
  1291. //
  1292. // Usually assimp only stores the colour,
  1293. // so we can just leave the factors at the default "1.0".
  1294. // first we can export the "standard" properties
  1295. if (m->Get(AI_MATKEY_COLOR_AMBIENT, c) == aiReturn_SUCCESS) {
  1296. p.AddP70colorA("AmbientColor", c.r, c.g, c.b);
  1297. //p.AddP70numberA("AmbientFactor", 1.0);
  1298. }
  1299. if (m->Get(AI_MATKEY_COLOR_DIFFUSE, c) == aiReturn_SUCCESS) {
  1300. p.AddP70colorA("DiffuseColor", c.r, c.g, c.b);
  1301. //p.AddP70numberA("DiffuseFactor", 1.0);
  1302. }
  1303. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1304. // "TransparentColor" / "TransparencyFactor"...
  1305. // thanks FBX, for your insightful interpretation of consistency
  1306. p.AddP70colorA("TransparentColor", c.r, c.g, c.b);
  1307. if (!bTransparencyFactorReferencedToOpacity) {
  1308. // TransparencyFactor defaults to 0.0, so set it to 1.0.
  1309. // note: Maya always sets this to 1.0,
  1310. // so we can't use it sensibly as "Opacity".
  1311. // In stead we rely on the legacy "Opacity" value, below.
  1312. // Blender also relies on "Opacity" not "TransparencyFactor",
  1313. // probably for a similar reason.
  1314. p.AddP70numberA("TransparencyFactor", 1.0);
  1315. }
  1316. }
  1317. if (bTransparencyFactorReferencedToOpacity) {
  1318. if (m->Get(AI_MATKEY_OPACITY, f) == aiReturn_SUCCESS) {
  1319. p.AddP70numberA("TransparencyFactor", 1.0 - f);
  1320. }
  1321. }
  1322. if (m->Get(AI_MATKEY_COLOR_REFLECTIVE, c) == aiReturn_SUCCESS) {
  1323. p.AddP70colorA("ReflectionColor", c.r, c.g, c.b);
  1324. }
  1325. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1326. p.AddP70numberA("ReflectionFactor", f);
  1327. }
  1328. if (phong) {
  1329. if (m->Get(AI_MATKEY_COLOR_SPECULAR, c) == aiReturn_SUCCESS) {
  1330. p.AddP70colorA("SpecularColor", c.r, c.g, c.b);
  1331. }
  1332. if (m->Get(AI_MATKEY_SHININESS_STRENGTH, f) == aiReturn_SUCCESS) {
  1333. p.AddP70numberA("ShininessFactor", f);
  1334. }
  1335. if (m->Get(AI_MATKEY_SHININESS, f) == aiReturn_SUCCESS) {
  1336. p.AddP70numberA("ShininessExponent", f);
  1337. }
  1338. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1339. p.AddP70numberA("ReflectionFactor", f);
  1340. }
  1341. }
  1342. // Now the legacy system.
  1343. // For safety let's include it.
  1344. // thrse values don't exist in the property template,
  1345. // and usually are completely ignored when loading.
  1346. // One notable exception is the "Opacity" property,
  1347. // which Blender uses as (1.0 - alpha).
  1348. c.r = 0.0f; c.g = 0.0f; c.b = 0.0f;
  1349. m->Get(AI_MATKEY_COLOR_EMISSIVE, c);
  1350. p.AddP70vector("Emissive", c.r, c.g, c.b);
  1351. c.r = 0.2f; c.g = 0.2f; c.b = 0.2f;
  1352. m->Get(AI_MATKEY_COLOR_AMBIENT, c);
  1353. p.AddP70vector("Ambient", c.r, c.g, c.b);
  1354. c.r = 0.8f; c.g = 0.8f; c.b = 0.8f;
  1355. m->Get(AI_MATKEY_COLOR_DIFFUSE, c);
  1356. p.AddP70vector("Diffuse", c.r, c.g, c.b);
  1357. // The FBX SDK determines "Opacity" from transparency colour (RGB)
  1358. // and factor (F) as: O = (1.0 - F * ((R + G + B) / 3)).
  1359. // However we actually have an opacity value,
  1360. // so we should take it from AI_MATKEY_OPACITY if possible.
  1361. // It might make more sense to use TransparencyFactor,
  1362. // but Blender actually loads "Opacity" correctly, so let's use it.
  1363. f = 1.0f;
  1364. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1365. f = 1.0f - ((c.r + c.g + c.b) / 3.0f);
  1366. }
  1367. m->Get(AI_MATKEY_OPACITY, f);
  1368. p.AddP70double("Opacity", f);
  1369. if (phong) {
  1370. // specular color is multiplied by shininess_strength
  1371. c.r = 0.2f; c.g = 0.2f; c.b = 0.2f;
  1372. m->Get(AI_MATKEY_COLOR_SPECULAR, c);
  1373. f = 1.0f;
  1374. m->Get(AI_MATKEY_SHININESS_STRENGTH, f);
  1375. p.AddP70vector("Specular", f*c.r, f*c.g, f*c.b);
  1376. f = 20.0f;
  1377. m->Get(AI_MATKEY_SHININESS, f);
  1378. p.AddP70double("Shininess", f);
  1379. // Legacy "Reflectivity" is F*F*((R+G+B)/3),
  1380. // where F is the proportion of light reflected (AKA reflectivity),
  1381. // and RGB is the reflective colour of the material.
  1382. // No idea why, but we might as well set it the same way.
  1383. f = 0.0f;
  1384. m->Get(AI_MATKEY_REFLECTIVITY, f);
  1385. c.r = 1.0f, c.g = 1.0f, c.b = 1.0f;
  1386. m->Get(AI_MATKEY_COLOR_REFLECTIVE, c);
  1387. p.AddP70double("Reflectivity", f*f*((c.r+c.g+c.b)/3.0));
  1388. }
  1389. n.AddChild(p);
  1390. n.Dump(outstream, binary, indent);
  1391. }
  1392. // we need to look up all the images we're using,
  1393. // so we can generate uids, and eliminate duplicates.
  1394. std::map<std::string, int64_t> uid_by_image;
  1395. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1396. aiString texpath;
  1397. aiMaterial* mat = mScene->mMaterials[i];
  1398. for (
  1399. size_t tt = aiTextureType_DIFFUSE;
  1400. tt < aiTextureType_UNKNOWN;
  1401. ++tt
  1402. ){
  1403. const aiTextureType textype = static_cast<aiTextureType>(tt);
  1404. const size_t texcount = mat->GetTextureCount(textype);
  1405. for (size_t j = 0; j < texcount; ++j) {
  1406. mat->GetTexture(textype, (unsigned int)j, &texpath);
  1407. const std::string texstring = texpath.C_Str();
  1408. auto elem = uid_by_image.find(texstring);
  1409. if (elem == uid_by_image.end()) {
  1410. uid_by_image[texstring] = generate_uid();
  1411. }
  1412. }
  1413. }
  1414. }
  1415. std::map<std::string, std::string> tpath_by_image;
  1416. // FbxVideo - stores images used by textures.
  1417. for (const auto &it : uid_by_image) {
  1418. FBX::Node n("Video");
  1419. const int64_t& uid = it.second;
  1420. const std::string name = ""; // TODO: ... name???
  1421. n.AddProperties(uid, name + FBX::SEPARATOR + "Video", "Clip");
  1422. n.AddChild("Type", "Clip");
  1423. FBX::Node p("Properties70");
  1424. // TODO: get full path... relative path... etc... ugh...
  1425. // for now just use the same path for everything,
  1426. // and hopefully one of them will work out.
  1427. std::string path = it.first;
  1428. // try get embedded texture
  1429. const aiTexture* embedded_texture = mScene->GetEmbeddedTexture(it.first.c_str());
  1430. if (embedded_texture != nullptr) {
  1431. // change the path (use original filename, if available. If name is empty, concatenate texture index with file extension)
  1432. std::stringstream newPath;
  1433. if (embedded_texture->mFilename.length > 0) {
  1434. newPath << embedded_texture->mFilename.C_Str();
  1435. // If newPath doesn't end in an extension, add extension from embedded_texture->achFormatHint
  1436. std::string np = newPath.str();
  1437. size_t dot_pos = np.find_last_of('.');
  1438. if (dot_pos == std::string::npos || dot_pos < np.find_last_of("/\\")) {
  1439. // No extension found, add one
  1440. newPath << "." << embedded_texture->achFormatHint;
  1441. }
  1442. } else if (embedded_texture->achFormatHint[0]) {
  1443. int texture_index = std::stoi(path.substr(1, path.size() - 1));
  1444. newPath << texture_index << "." << embedded_texture->achFormatHint;
  1445. }
  1446. auto elem = tpath_by_image.find(path);
  1447. if (elem == tpath_by_image.end()) {
  1448. tpath_by_image[path] = newPath.str();
  1449. }
  1450. path = newPath.str();
  1451. // embed the texture
  1452. size_t texture_size = static_cast<size_t>(embedded_texture->mWidth * std::max(embedded_texture->mHeight, 1u));
  1453. if (binary) {
  1454. // embed texture as binary data
  1455. std::vector<uint8_t> tex_data;
  1456. tex_data.resize(texture_size);
  1457. memcpy(&tex_data[0], (char*)embedded_texture->pcData, texture_size);
  1458. n.AddChild("Content", tex_data);
  1459. } else {
  1460. // embed texture in base64 encoding
  1461. std::string encoded_texture = FBX::Util::EncodeBase64((char*)embedded_texture->pcData, texture_size);
  1462. n.AddChild("Content", encoded_texture);
  1463. }
  1464. }
  1465. p.AddP70("Path", "KString", "XRefUrl", "", path);
  1466. n.AddChild(p);
  1467. n.AddChild("UseMipMap", int32_t(0));
  1468. n.AddChild("Filename", path);
  1469. n.AddChild("RelativeFilename", path);
  1470. n.Dump(outstream, binary, indent);
  1471. }
  1472. // Textures
  1473. // referenced by material_index/texture_type pairs.
  1474. std::map<std::pair<size_t,size_t>,int64_t> texture_uids;
  1475. const std::map<aiTextureType,std::string> prop_name_by_tt = {
  1476. {aiTextureType_DIFFUSE, "DiffuseColor"},
  1477. {aiTextureType_SPECULAR, "SpecularColor"},
  1478. {aiTextureType_AMBIENT, "AmbientColor"},
  1479. {aiTextureType_EMISSIVE, "EmissiveColor"},
  1480. {aiTextureType_HEIGHT, "Bump"},
  1481. {aiTextureType_NORMALS, "NormalMap"},
  1482. {aiTextureType_SHININESS, "ShininessExponent"},
  1483. {aiTextureType_OPACITY, "TransparentColor"},
  1484. {aiTextureType_DISPLACEMENT, "DisplacementColor"},
  1485. //{aiTextureType_LIGHTMAP, "???"},
  1486. {aiTextureType_REFLECTION, "ReflectionColor"}
  1487. //{aiTextureType_UNKNOWN, ""}
  1488. };
  1489. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1490. // textures are attached to materials
  1491. aiMaterial* mat = mScene->mMaterials[i];
  1492. int64_t material_uid = material_uids[i];
  1493. for (
  1494. size_t j = aiTextureType_DIFFUSE;
  1495. j < aiTextureType_UNKNOWN;
  1496. ++j
  1497. ) {
  1498. const aiTextureType tt = static_cast<aiTextureType>(j);
  1499. size_t n = mat->GetTextureCount(tt);
  1500. if (n < 1) { // no texture of this type
  1501. continue;
  1502. }
  1503. if (n > 1) {
  1504. // TODO: multilayer textures
  1505. std::stringstream err;
  1506. err << "Multilayer textures not supported (for now),";
  1507. err << " skipping texture type " << j;
  1508. err << " of material " << i;
  1509. ASSIMP_LOG_WARN(err.str());
  1510. }
  1511. // get image path for this (single-image) texture
  1512. aiString tpath;
  1513. if (mat->GetTexture(tt, 0, &tpath) != aiReturn_SUCCESS) {
  1514. std::stringstream err;
  1515. err << "Failed to get texture 0 for texture of type " << tt;
  1516. err << " on material " << i;
  1517. err << ", however GetTextureCount returned 1.";
  1518. throw DeadlyExportError(err.str());
  1519. }
  1520. const std::string texture_path(tpath.C_Str());
  1521. // get connected image uid
  1522. auto elem = uid_by_image.find(texture_path);
  1523. if (elem == uid_by_image.end()) {
  1524. // this should never happen
  1525. std::stringstream err;
  1526. err << "Failed to find video element for texture with path";
  1527. err << " \"" << texture_path << "\"";
  1528. err << ", type " << j << ", material " << i;
  1529. throw DeadlyExportError(err.str());
  1530. }
  1531. const int64_t image_uid = elem->second;
  1532. // get the name of the material property to connect to
  1533. auto elem2 = prop_name_by_tt.find(tt);
  1534. if (elem2 == prop_name_by_tt.end()) {
  1535. // don't know how to handle this type of texture,
  1536. // so skip it.
  1537. std::stringstream err;
  1538. err << "Not sure how to handle texture of type " << j;
  1539. err << " on material " << i;
  1540. err << ", skipping...";
  1541. ASSIMP_LOG_WARN(err.str());
  1542. continue;
  1543. }
  1544. const std::string& prop_name = elem2->second;
  1545. // generate a uid for this texture
  1546. const int64_t texture_uid = generate_uid();
  1547. // link the texture to the material
  1548. connections.emplace_back(
  1549. "C", "OP", texture_uid, material_uid, prop_name
  1550. );
  1551. // link the image data to the texture
  1552. connections.emplace_back("C", "OO", image_uid, texture_uid);
  1553. aiUVTransform trafo;
  1554. unsigned int max = sizeof(aiUVTransform);
  1555. aiGetMaterialFloatArray(mat, AI_MATKEY_UVTRANSFORM(aiTextureType_DIFFUSE, 0), (ai_real *)&trafo, &max);
  1556. auto tp_elem = tpath_by_image.find(texture_path);
  1557. std::string tfile_path = texture_path;
  1558. if (tp_elem != tpath_by_image.end()) {
  1559. tfile_path = tp_elem->second;
  1560. } else {
  1561. std::stringstream err;
  1562. err << "Texture path not found for texure " << texture_path;
  1563. err << " on material " << i;
  1564. ASSIMP_LOG_WARN(err.str());
  1565. }
  1566. // now write the actual texture node
  1567. FBX::Node tnode("Texture");
  1568. // TODO: some way to determine texture name?
  1569. const std::string texture_name = "" + FBX::SEPARATOR + "Texture";
  1570. tnode.AddProperties(texture_uid, texture_name, "");
  1571. // there really doesn't seem to be a better type than this:
  1572. tnode.AddChild("Type", "TextureVideoClip");
  1573. tnode.AddChild("Version", int32_t(202));
  1574. tnode.AddChild("TextureName", texture_name);
  1575. FBX::Node p("Properties70");
  1576. p.AddP70vectorA("Translation", trafo.mTranslation[0], trafo.mTranslation[1], 0.0);
  1577. p.AddP70vectorA("Rotation", 0, 0, trafo.mRotation);
  1578. p.AddP70vectorA("Scaling", trafo.mScaling[0], trafo.mScaling[1], 0.0);
  1579. p.AddP70enum("CurrentTextureBlendMode", 0); // TODO: verify
  1580. //p.AddP70string("UVSet", ""); // TODO: how should this work?
  1581. p.AddP70bool("UseMaterial", true);
  1582. tnode.AddChild(p);
  1583. // can't easily determine which texture path will be correct,
  1584. // so just store what we have in every field.
  1585. // these being incorrect is a common problem with FBX anyway.
  1586. tnode.AddChild("FileName", tp_elem->second);
  1587. tnode.AddChild("RelativeFilename", tp_elem->second);
  1588. tnode.AddChild("ModelUVTranslation", double(0.0), double(0.0));
  1589. tnode.AddChild("ModelUVScaling", double(1.0), double(1.0));
  1590. tnode.AddChild("Texture_Alpha_Source", "None");
  1591. tnode.AddChild(
  1592. "Cropping", int32_t(0), int32_t(0), int32_t(0), int32_t(0)
  1593. );
  1594. tnode.Dump(outstream, binary, indent);
  1595. }
  1596. }
  1597. // Blendshapes, if any
  1598. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1599. const aiMesh* m = mScene->mMeshes[mi];
  1600. if (m->mNumAnimMeshes == 0) {
  1601. continue;
  1602. }
  1603. // make a deformer for this mesh
  1604. int64_t deformer_uid = generate_uid();
  1605. FBX::Node dnode("Deformer");
  1606. dnode.AddProperties(deformer_uid, m->mName.data + FBX::SEPARATOR + "Blendshapes", "BlendShape");
  1607. dnode.AddChild("Version", int32_t(101));
  1608. dnode.Dump(outstream, binary, indent);
  1609. // connect it
  1610. const auto node = get_node_for_mesh((unsigned int)mi, mScene->mRootNode);
  1611. connections.emplace_back("C", "OO", deformer_uid, mesh_uids[node]);
  1612. std::vector<int32_t> vertex_indices = vVertexIndice[mi];
  1613. for (unsigned int am = 0; am < m->mNumAnimMeshes; ++am) {
  1614. aiAnimMesh *pAnimMesh = m->mAnimMeshes[am];
  1615. std::string blendshape_name = pAnimMesh->mName.data;
  1616. // start the node record
  1617. FBX::Node bsnode("Geometry");
  1618. int64_t blendshape_uid = generate_uid();
  1619. blendshape_uids.push_back(blendshape_uid);
  1620. bsnode.AddProperty(blendshape_uid);
  1621. bsnode.AddProperty(blendshape_name + FBX::SEPARATOR + "Geometry");
  1622. bsnode.AddProperty("Shape");
  1623. bsnode.AddChild("Version", int32_t(100));
  1624. bsnode.Begin(outstream, binary, indent);
  1625. bsnode.DumpProperties(outstream, binary, indent);
  1626. bsnode.EndProperties(outstream, binary, indent);
  1627. bsnode.BeginChildren(outstream, binary, indent);
  1628. indent++;
  1629. if (pAnimMesh->HasPositions()) {
  1630. std::vector<int32_t>shape_indices;
  1631. std::vector<float>pPositionDiff;
  1632. std::vector<float>pNormalDiff;
  1633. for (unsigned int vt = 0; vt < vertex_indices.size(); ++vt) {
  1634. aiVector3D pDiff = (pAnimMesh->mVertices[vertex_indices[vt]] - m->mVertices[vertex_indices[vt]]);
  1635. shape_indices.push_back(vertex_indices[vt]);
  1636. pPositionDiff.push_back(pDiff[0]);
  1637. pPositionDiff.push_back(pDiff[1]);
  1638. pPositionDiff.push_back(pDiff[2]);
  1639. if (pAnimMesh->HasNormals()) {
  1640. aiVector3D nDiff = (pAnimMesh->mNormals[vertex_indices[vt]] - m->mNormals[vertex_indices[vt]]);
  1641. pNormalDiff.push_back(nDiff[0]);
  1642. pNormalDiff.push_back(nDiff[1]);
  1643. pNormalDiff.push_back(nDiff[2]);
  1644. } else {
  1645. pNormalDiff.push_back(0.0);
  1646. pNormalDiff.push_back(0.0);
  1647. pNormalDiff.push_back(0.0);
  1648. }
  1649. }
  1650. FBX::Node::WritePropertyNode(
  1651. "Indexes", shape_indices, outstream, binary, indent
  1652. );
  1653. FBX::Node::WritePropertyNode(
  1654. "Vertices", pPositionDiff, outstream, binary, indent
  1655. );
  1656. if (pNormalDiff.size()>0) {
  1657. FBX::Node::WritePropertyNode(
  1658. "Normals", pNormalDiff, outstream, binary, indent
  1659. );
  1660. }
  1661. }
  1662. indent--;
  1663. bsnode.End(outstream, binary, indent, true);
  1664. // Add blendshape Channel Deformer
  1665. FBX::Node sdnode("Deformer");
  1666. const int64_t blendchannel_uid = generate_uid();
  1667. sdnode.AddProperties(
  1668. blendchannel_uid, blendshape_name + FBX::SEPARATOR + "SubDeformer", "BlendShapeChannel"
  1669. );
  1670. sdnode.AddChild("Version", int32_t(100));
  1671. sdnode.AddChild("DeformPercent", float(0.0));
  1672. FBX::Node p("Properties70");
  1673. p.AddP70numberA("DeformPercent", 0.0);
  1674. sdnode.AddChild(p);
  1675. // TODO: Normally just one weight per channel, adding stub for later development
  1676. std::vector<double>fFullWeights;
  1677. fFullWeights.push_back(100.);
  1678. sdnode.AddChild("FullWeights", fFullWeights);
  1679. sdnode.Dump(outstream, binary, indent);
  1680. connections.emplace_back("C", "OO", blendchannel_uid, deformer_uid);
  1681. connections.emplace_back("C", "OO", blendshape_uid, blendchannel_uid);
  1682. }
  1683. }
  1684. // bones.
  1685. //
  1686. // output structure:
  1687. // subset of node hierarchy that are "skeleton",
  1688. // i.e. do not have meshes but only bones.
  1689. // but.. i'm not sure how anyone could guarantee that...
  1690. //
  1691. // input...
  1692. // well, for each mesh it has "bones",
  1693. // and the bone names correspond to nodes.
  1694. // of course we also need the parent nodes,
  1695. // as they give some of the transform........
  1696. //
  1697. // well. we can assume a sane input, i suppose.
  1698. //
  1699. // so input is the bone node hierarchy,
  1700. // with an extra thing for the transformation of the MESH in BONE space.
  1701. //
  1702. // output is a set of bone nodes,
  1703. // a "bindpose" which indicates the default local transform of all bones,
  1704. // and a set of "deformers".
  1705. // each deformer is parented to a mesh geometry,
  1706. // and has one or more "subdeformer"s as children.
  1707. // each subdeformer has one bone node as a child,
  1708. // and represents the influence of that bone on the grandparent mesh.
  1709. // the subdeformer has a list of indices, and weights,
  1710. // with indices specifying vertex indices,
  1711. // and weights specifying the corresponding influence of this bone.
  1712. // it also has Transform and TransformLink elements,
  1713. // specifying the transform of the MESH in BONE space,
  1714. // and the transformation of the BONE in WORLD space,
  1715. // likely in the bindpose.
  1716. //
  1717. // the input bone structure is different but similar,
  1718. // storing the number of weights for this bone,
  1719. // and an array of (vertex index, weight) pairs.
  1720. //
  1721. // one sticky point is that the number of vertices may not match,
  1722. // because assimp splits vertices by normal, uv, etc.
  1723. // first we should mark the skeleton for each mesh.
  1724. // the skeleton must include not only the aiBones,
  1725. // but also all their parent nodes.
  1726. // anything that affects the position of any bone node must be included.
  1727. // note that we want to preserve input order as much as possible here.
  1728. // previously, sorting by name lead to consistent output across systems, but was not
  1729. // suitable for downstream consumption by some applications.
  1730. std::vector<std::vector<const aiNode*>> skeleton_by_mesh(mScene->mNumMeshes);
  1731. // at the same time we can build a list of all the skeleton nodes,
  1732. // which will be used later to mark them as type "limbNode".
  1733. std::unordered_set<const aiNode*> limbnodes;
  1734. //actual bone nodes in fbx, without parenting-up
  1735. std::vector<std::string> allBoneNames;
  1736. for(unsigned int m = 0; m < mScene->mNumMeshes; ++ m) {
  1737. aiMesh* pMesh = mScene->mMeshes[m];
  1738. for(unsigned int b = 0; b < pMesh->mNumBones; ++ b)
  1739. allBoneNames.push_back(pMesh->mBones[b]->mName.data);
  1740. }
  1741. aiMatrix4x4 mxTransIdentity;
  1742. // and a map of nodes by bone name, as finding them is annoying.
  1743. std::map<std::string,aiNode*> node_by_bone;
  1744. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1745. const aiMesh* m = mScene->mMeshes[mi];
  1746. std::vector<const aiNode*> skeleton;
  1747. for (size_t bi =0; bi < m->mNumBones; ++bi) {
  1748. const aiBone* b = m->mBones[bi];
  1749. const std::string name(b->mName.C_Str());
  1750. auto elem = node_by_bone.find(name);
  1751. aiNode* n;
  1752. if (elem != node_by_bone.end()) {
  1753. n = elem->second;
  1754. } else {
  1755. n = mScene->mRootNode->FindNode(b->mName);
  1756. if (!n) {
  1757. // this should never happen
  1758. std::stringstream err;
  1759. err << "Failed to find node for bone: \"" << name << "\"";
  1760. throw DeadlyExportError(err.str());
  1761. }
  1762. node_by_bone[name] = n;
  1763. limbnodes.insert(n);
  1764. }
  1765. skeleton.push_back(n);
  1766. // mark all parent nodes as skeleton as well,
  1767. // up until we find the root node,
  1768. // or else the node containing the mesh,
  1769. // or else the parent of a node containing the mesh.
  1770. for (
  1771. const aiNode* parent = n->mParent;
  1772. parent && parent != mScene->mRootNode;
  1773. parent = parent->mParent
  1774. ) {
  1775. // if we've already done this node we can skip it all
  1776. if (std::find(skeleton.begin(), skeleton.end(), parent) != skeleton.end()) {
  1777. break;
  1778. }
  1779. // ignore fbx transform nodes as these will be collapsed later
  1780. // TODO: cache this by aiNode*
  1781. const std::string node_name(parent->mName.C_Str());
  1782. if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) {
  1783. continue;
  1784. }
  1785. //not a bone in scene && no effect in transform
  1786. if (std::find(allBoneNames.begin(), allBoneNames.end(), node_name) == allBoneNames.end()
  1787. && parent->mTransformation == mxTransIdentity) {
  1788. continue;
  1789. }
  1790. // otherwise check if this is the root of the skeleton
  1791. bool end = false;
  1792. // is the mesh part of this node?
  1793. for (size_t i = 0; i < parent->mNumMeshes && !end; ++i) {
  1794. end |= parent->mMeshes[i] == mi;
  1795. }
  1796. // is the mesh in one of the children of this node?
  1797. for (size_t j = 0; j < parent->mNumChildren && !end; ++j) {
  1798. aiNode* child = parent->mChildren[j];
  1799. for (size_t i = 0; i < child->mNumMeshes && !end; ++i) {
  1800. end |= child->mMeshes[i] == mi;
  1801. }
  1802. }
  1803. // if it was the skeleton root we can finish here
  1804. if (end) { break; }
  1805. }
  1806. }
  1807. skeleton_by_mesh[mi] = skeleton;
  1808. }
  1809. // we'll need the uids for the bone nodes, so generate them now
  1810. for (size_t i = 0; i < mScene->mNumMeshes; ++i) {
  1811. auto &s = skeleton_by_mesh[i];
  1812. for (const aiNode* n : s) {
  1813. if (node_uids.find(n) == node_uids.end()) {
  1814. node_uids[n] = generate_uid();
  1815. }
  1816. }
  1817. }
  1818. // now, for each aiMesh, we need to export a deformer,
  1819. // and for each aiBone a subdeformer,
  1820. // which should have all the skinning info.
  1821. // these will need to be connected properly to the mesh,
  1822. // and we can do that all now.
  1823. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1824. const aiMesh* m = mScene->mMeshes[mi];
  1825. if (!m->HasBones()) {
  1826. continue;
  1827. }
  1828. const aiNode *mesh_node = get_node_for_mesh((uint32_t)mi, mScene->mRootNode);
  1829. // make a deformer for this mesh
  1830. int64_t deformer_uid = generate_uid();
  1831. FBX::Node dnode("Deformer");
  1832. dnode.AddProperties(deformer_uid, FBX::SEPARATOR + "Deformer", "Skin");
  1833. dnode.AddChild("Version", int32_t(101));
  1834. // "acuracy"... this is not a typo....
  1835. dnode.AddChild("Link_DeformAcuracy", double(50));
  1836. dnode.AddChild("SkinningType", "Linear"); // TODO: other modes?
  1837. dnode.Dump(outstream, binary, indent);
  1838. // connect it
  1839. connections.emplace_back("C", "OO", deformer_uid, mesh_uids[mesh_node]);
  1840. // TODO, FIXME: this won't work if anything is not in the bind pose.
  1841. // for now if such a situation is detected, we throw an exception.
  1842. std::set<const aiBone*> not_in_bind_pose;
  1843. std::set<const aiNode*> no_offset_matrix;
  1844. // first get this mesh's position in world space,
  1845. // as we'll need it for each subdeformer.
  1846. //
  1847. // ...of course taking the position of the MESH doesn't make sense,
  1848. // as it can be instanced to many nodes.
  1849. // All we can do is assume no instancing,
  1850. // and take the first node we find that contains the mesh.
  1851. aiMatrix4x4 mesh_xform = get_world_transform(mesh_node, mScene);
  1852. // now make a subdeformer for each bone in the skeleton
  1853. const auto & skeleton= skeleton_by_mesh[mi];
  1854. for (const aiNode* bone_node : skeleton) {
  1855. // if there's a bone for this node, find it
  1856. const aiBone* b = nullptr;
  1857. for (size_t bi = 0; bi < m->mNumBones; ++bi) {
  1858. // TODO: this probably should index by something else
  1859. const std::string name(m->mBones[bi]->mName.C_Str());
  1860. if (node_by_bone[name] == bone_node) {
  1861. b = m->mBones[bi];
  1862. break;
  1863. }
  1864. }
  1865. if (!b) {
  1866. no_offset_matrix.insert(bone_node);
  1867. }
  1868. // start the subdeformer node
  1869. const int64_t subdeformer_uid = generate_uid();
  1870. FBX::Node sdnode("Deformer");
  1871. sdnode.AddProperties(
  1872. subdeformer_uid, FBX::SEPARATOR + "SubDeformer", "Cluster"
  1873. );
  1874. sdnode.AddChild("Version", int32_t(100));
  1875. sdnode.AddChild("UserData", "", "");
  1876. // add indices and weights, if any
  1877. if (b) {
  1878. std::set<int32_t> setWeightedVertex;
  1879. std::vector<int32_t> subdef_indices;
  1880. std::vector<double> subdef_weights;
  1881. int32_t last_index = -1;
  1882. for (size_t wi = 0; wi < b->mNumWeights; ++wi) {
  1883. if (b->mWeights[wi].mVertexId >= vVertexIndice[mi].size()) {
  1884. ASSIMP_LOG_ERROR("UNREAL: Skipping vertex index to prevent buffer overflow.");
  1885. continue;
  1886. }
  1887. int32_t vi = vVertexIndice[mi][b->mWeights[wi].mVertexId]
  1888. + uniq_v_before_mi[mi];
  1889. bool bIsWeightedAlready = (setWeightedVertex.find(vi) != setWeightedVertex.end());
  1890. if (vi == last_index || bIsWeightedAlready) {
  1891. // only for vertices we exported to fbx
  1892. // TODO, FIXME: this assumes identically-located vertices
  1893. // will always deform in the same way.
  1894. // as assimp doesn't store a separate list of "positions",
  1895. // there's not much that can be done about this
  1896. // other than assuming that identical position means
  1897. // identical vertex.
  1898. continue;
  1899. }
  1900. setWeightedVertex.insert(vi);
  1901. subdef_indices.push_back(vi);
  1902. subdef_weights.push_back(b->mWeights[wi].mWeight);
  1903. last_index = vi;
  1904. }
  1905. // yes, "indexes"
  1906. sdnode.AddChild("Indexes", subdef_indices);
  1907. sdnode.AddChild("Weights", subdef_weights);
  1908. }
  1909. // transform is the transform of the mesh, but in bone space.
  1910. // if the skeleton is in the bind pose,
  1911. // we can take the inverse of the world-space bone transform
  1912. // and multiply by the world-space transform of the mesh.
  1913. aiMatrix4x4 bone_xform = get_world_transform(bone_node, mScene);
  1914. aiMatrix4x4 inverse_bone_xform = bone_xform;
  1915. inverse_bone_xform.Inverse();
  1916. aiMatrix4x4 tr = inverse_bone_xform * mesh_xform;
  1917. sdnode.AddChild("Transform", tr);
  1918. sdnode.AddChild("TransformLink", bone_xform);
  1919. // note: this means we ALWAYS rely on the mesh node transform
  1920. // being unchanged from the time the skeleton was bound.
  1921. // there's not really any way around this at the moment.
  1922. // done
  1923. sdnode.Dump(outstream, binary, indent);
  1924. // lastly, connect to the parent deformer
  1925. connections.emplace_back(
  1926. "C", "OO", subdeformer_uid, deformer_uid
  1927. );
  1928. // we also need to connect the limb node to the subdeformer.
  1929. connections.emplace_back(
  1930. "C", "OO", node_uids[bone_node], subdeformer_uid
  1931. );
  1932. }
  1933. // if we cannot create a valid FBX file, simply die.
  1934. // this will both prevent unnecessary bug reports,
  1935. // and tell the user what they can do to fix the situation
  1936. // (i.e. export their model in the bind pose).
  1937. if (no_offset_matrix.size() && not_in_bind_pose.size()) {
  1938. std::stringstream err;
  1939. err << "Not enough information to construct bind pose";
  1940. err << " for mesh " << mi << "!";
  1941. err << " Transform matrix for bone \"";
  1942. err << (*not_in_bind_pose.begin())->mName.C_Str() << "\"";
  1943. if (not_in_bind_pose.size() > 1) {
  1944. err << " (and " << not_in_bind_pose.size() - 1 << " more)";
  1945. }
  1946. err << " does not match mOffsetMatrix,";
  1947. err << " and node \"";
  1948. err << (*no_offset_matrix.begin())->mName.C_Str() << "\"";
  1949. if (no_offset_matrix.size() > 1) {
  1950. err << " (and " << no_offset_matrix.size() - 1 << " more)";
  1951. }
  1952. err << " has no offset matrix to rely on.";
  1953. err << " Please ensure bones are in the bind pose to export.";
  1954. throw DeadlyExportError(err.str());
  1955. }
  1956. }
  1957. // BindPose
  1958. //
  1959. // This is a legacy system, which should be unnecessary.
  1960. //
  1961. // Somehow including it slows file loading by the official FBX SDK,
  1962. // and as it can reconstruct it from the deformers anyway,
  1963. // this is not currently included.
  1964. //
  1965. // The code is kept here in case it's useful in the future,
  1966. // but it's pretty much a hack anyway,
  1967. // as assimp doesn't store bindpose information for full skeletons.
  1968. //
  1969. /*for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1970. aiMesh* mesh = mScene->mMeshes[mi];
  1971. if (! mesh->HasBones()) { continue; }
  1972. int64_t bindpose_uid = generate_uid();
  1973. FBX::Node bpnode("Pose");
  1974. bpnode.AddProperty(bindpose_uid);
  1975. // note: this uid is never linked or connected to anything.
  1976. bpnode.AddProperty(FBX::SEPARATOR + "Pose"); // blank name
  1977. bpnode.AddProperty("BindPose");
  1978. bpnode.AddChild("Type", "BindPose");
  1979. bpnode.AddChild("Version", int32_t(100));
  1980. aiNode* mesh_node = get_node_for_mesh(mi, mScene->mRootNode);
  1981. // next get the whole skeleton for this mesh.
  1982. // we need it all to define the bindpose section.
  1983. // the FBX SDK will complain if it's missing,
  1984. // and also if parents of used bones don't have a subdeformer.
  1985. // order shouldn't matter.
  1986. std::set<aiNode*> skeleton;
  1987. for (size_t bi = 0; bi < mesh->mNumBones; ++bi) {
  1988. // bone node should have already been indexed
  1989. const aiBone* b = mesh->mBones[bi];
  1990. const std::string bone_name(b->mName.C_Str());
  1991. aiNode* parent = node_by_bone[bone_name];
  1992. // insert all nodes down to the root or mesh node
  1993. while (
  1994. parent
  1995. && parent != mScene->mRootNode
  1996. && parent != mesh_node
  1997. ) {
  1998. skeleton.insert(parent);
  1999. parent = parent->mParent;
  2000. }
  2001. }
  2002. // number of pose nodes. includes one for the mesh itself.
  2003. bpnode.AddChild("NbPoseNodes", int32_t(1 + skeleton.size()));
  2004. // the first pose node is always the mesh itself
  2005. FBX::Node pose("PoseNode");
  2006. pose.AddChild("Node", mesh_uids[mi]);
  2007. aiMatrix4x4 mesh_node_xform = get_world_transform(mesh_node, mScene);
  2008. pose.AddChild("Matrix", mesh_node_xform);
  2009. bpnode.AddChild(pose);
  2010. for (aiNode* bonenode : skeleton) {
  2011. // does this node have a uid yet?
  2012. int64_t node_uid;
  2013. auto node_uid_iter = node_uids.find(bonenode);
  2014. if (node_uid_iter != node_uids.end()) {
  2015. node_uid = node_uid_iter->second;
  2016. } else {
  2017. node_uid = generate_uid();
  2018. node_uids[bonenode] = node_uid;
  2019. }
  2020. // make a pose thingy
  2021. pose = FBX::Node("PoseNode");
  2022. pose.AddChild("Node", node_uid);
  2023. aiMatrix4x4 node_xform = get_world_transform(bonenode, mScene);
  2024. pose.AddChild("Matrix", node_xform);
  2025. bpnode.AddChild(pose);
  2026. }
  2027. // now write it
  2028. bpnode.Dump(outstream, binary, indent);
  2029. }*/
  2030. // lights
  2031. indent = 1;
  2032. lights_uids.clear();
  2033. for (size_t li = 0; li < mScene->mNumLights; ++li) {
  2034. aiLight* l = mScene->mLights[li];
  2035. int64_t uid = generate_uid();
  2036. const std::string lightNodeAttributeName = l->mName.C_Str() + FBX::SEPARATOR + "NodeAttribute";
  2037. FBX::Node lna("NodeAttribute");
  2038. lna.AddProperties(uid, lightNodeAttributeName, "Light");
  2039. FBX::Node lnap("Properties70");
  2040. // Light color.
  2041. lnap.AddP70colorA("Color", l->mColorDiffuse.r, l->mColorDiffuse.g, l->mColorDiffuse.b);
  2042. // TODO Assimp light description is quite concise and do not handle light intensity.
  2043. // Default value to 1000W.
  2044. lnap.AddP70numberA("Intensity", 1000);
  2045. // FBXLight::EType conversion
  2046. switch (l->mType) {
  2047. case aiLightSource_POINT:
  2048. lnap.AddP70enum("LightType", 0);
  2049. break;
  2050. case aiLightSource_DIRECTIONAL:
  2051. lnap.AddP70enum("LightType", 1);
  2052. break;
  2053. case aiLightSource_SPOT:
  2054. lnap.AddP70enum("LightType", 2);
  2055. lnap.AddP70numberA("InnerAngle", AI_RAD_TO_DEG(l->mAngleInnerCone));
  2056. lnap.AddP70numberA("OuterAngle", AI_RAD_TO_DEG(l->mAngleOuterCone));
  2057. break;
  2058. // TODO Assimp do not handle 'area' nor 'volume' lights, but FBX does.
  2059. /*case aiLightSource_AREA:
  2060. lnap.AddP70enum("LightType", 3);
  2061. lnap.AddP70enum("AreaLightShape", 0); // 0=Rectangle, 1=Sphere
  2062. break;
  2063. case aiLightSource_VOLUME:
  2064. lnap.AddP70enum("LightType", 4);
  2065. break;*/
  2066. default:
  2067. break;
  2068. }
  2069. // Did not understood how to configure the decay so disabling attenuation.
  2070. lnap.AddP70enum("DecayType", 0);
  2071. // Dump to FBX stream
  2072. lna.AddChild(lnap);
  2073. lna.AddChild("TypeFlags", FBX::FBXExportProperty("Light"));
  2074. lna.AddChild("GeometryVersion", FBX::FBXExportProperty(int32_t(124)));
  2075. lna.Dump(outstream, binary, indent);
  2076. // Store name and uid (will be used later when parsing scene nodes)
  2077. lights_uids[l->mName.C_Str()] = uid;
  2078. }
  2079. // TODO: cameras
  2080. // write nodes (i.e. model hierarchy)
  2081. // start at root node
  2082. WriteModelNodes(
  2083. outstream, mScene->mRootNode, 0, limbnodes
  2084. );
  2085. // animations
  2086. //
  2087. // in FBX there are:
  2088. // * AnimationStack - corresponds to an aiAnimation
  2089. // * AnimationLayer - a combinable animation component
  2090. // * AnimationCurveNode - links the property to be animated
  2091. // * AnimationCurve - defines animation data for a single property value
  2092. //
  2093. // the CurveNode also provides the default value for a property,
  2094. // such as the X, Y, Z coordinates for animatable translation.
  2095. //
  2096. // the Curve only specifies values for one component of the property,
  2097. // so there will be a separate AnimationCurve for X, Y, and Z.
  2098. //
  2099. // Assimp has:
  2100. // * aiAnimation - basically corresponds to an AnimationStack
  2101. // * aiNodeAnim - defines all animation for one aiNode
  2102. // * aiVectorKey/aiQuatKey - define the keyframe data for T/R/S
  2103. //
  2104. // assimp has no equivalent for AnimationLayer,
  2105. // and these are flattened on FBX import.
  2106. // we can assume there will be one per AnimationStack.
  2107. //
  2108. // the aiNodeAnim contains all animation data for a single aiNode,
  2109. // which will correspond to three AnimationCurveNode's:
  2110. // one each for translation, rotation and scale.
  2111. // The data for each of these will be put in 9 AnimationCurve's,
  2112. // T.X, T.Y, T.Z, R.X, R.Y, R.Z, etc.
  2113. // AnimationStack / aiAnimation
  2114. std::vector<int64_t> animation_stack_uids(mScene->mNumAnimations);
  2115. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2116. int64_t animstack_uid = generate_uid();
  2117. animation_stack_uids[ai] = animstack_uid;
  2118. const aiAnimation* anim = mScene->mAnimations[ai];
  2119. FBX::Node asnode("AnimationStack");
  2120. std::string name = anim->mName.C_Str() + FBX::SEPARATOR + "AnimStack";
  2121. asnode.AddProperties(animstack_uid, name, "");
  2122. FBX::Node p("Properties70");
  2123. p.AddP70time("LocalStart", 0); // assimp doesn't store this
  2124. p.AddP70time("LocalStop", to_ktime(anim->mDuration, anim));
  2125. p.AddP70time("ReferenceStart", 0);
  2126. p.AddP70time("ReferenceStop", to_ktime(anim->mDuration, anim));
  2127. asnode.AddChild(p);
  2128. // this node absurdly always pretends it has children
  2129. // (in this case it does, but just in case...)
  2130. asnode.force_has_children = true;
  2131. asnode.Dump(outstream, binary, indent);
  2132. // note: animation stacks are not connected to anything
  2133. }
  2134. // AnimationLayer - one per aiAnimation
  2135. std::vector<int64_t> animation_layer_uids(mScene->mNumAnimations);
  2136. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2137. int64_t animlayer_uid = generate_uid();
  2138. animation_layer_uids[ai] = animlayer_uid;
  2139. FBX::Node alnode("AnimationLayer");
  2140. alnode.AddProperties(animlayer_uid, FBX::SEPARATOR + "AnimLayer", "");
  2141. // this node absurdly always pretends it has children
  2142. alnode.force_has_children = true;
  2143. alnode.Dump(outstream, binary, indent);
  2144. // connect to the relevant animstack
  2145. connections.emplace_back(
  2146. "C", "OO", animlayer_uid, animation_stack_uids[ai]
  2147. );
  2148. }
  2149. // AnimCurveNode - three per aiNodeAnim
  2150. std::vector<std::vector<std::array<int64_t,3>>> curve_node_uids;
  2151. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2152. const aiAnimation* anim = mScene->mAnimations[ai];
  2153. const int64_t layer_uid = animation_layer_uids[ai];
  2154. std::vector<std::array<int64_t,3>> nodeanim_uids;
  2155. for (size_t nai = 0; nai < anim->mNumChannels; ++nai) {
  2156. const aiNodeAnim* na = anim->mChannels[nai];
  2157. // get the corresponding aiNode
  2158. const aiNode* node = mScene->mRootNode->FindNode(na->mNodeName);
  2159. // and its transform
  2160. const aiMatrix4x4 node_xfm = get_world_transform(node, mScene);
  2161. aiVector3D T, R, S;
  2162. node_xfm.Decompose(S, R, T);
  2163. // AnimationCurveNode uids
  2164. std::array<int64_t,3> ids;
  2165. ids[0] = generate_uid(); // T
  2166. ids[1] = generate_uid(); // R
  2167. ids[2] = generate_uid(); // S
  2168. // translation
  2169. WriteAnimationCurveNode(outstream,
  2170. ids[0], "T", T, "Lcl Translation",
  2171. layer_uid, node_uids[node]
  2172. );
  2173. // rotation
  2174. WriteAnimationCurveNode(outstream,
  2175. ids[1], "R", R, "Lcl Rotation",
  2176. layer_uid, node_uids[node]
  2177. );
  2178. // scale
  2179. WriteAnimationCurveNode(outstream,
  2180. ids[2], "S", S, "Lcl Scale",
  2181. layer_uid, node_uids[node]
  2182. );
  2183. // store the uids for later use
  2184. nodeanim_uids.push_back(ids);
  2185. }
  2186. curve_node_uids.push_back(nodeanim_uids);
  2187. }
  2188. // AnimCurve - defines actual keyframe data.
  2189. // there's a separate curve for every component of every vector,
  2190. // for example a transform curvenode will have separate X/Y/Z AnimCurve's
  2191. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2192. const aiAnimation* anim = mScene->mAnimations[ai];
  2193. for (size_t nai = 0; nai < anim->mNumChannels; ++nai) {
  2194. const aiNodeAnim* na = anim->mChannels[nai];
  2195. // get the corresponding aiNode
  2196. const aiNode* node = mScene->mRootNode->FindNode(na->mNodeName);
  2197. // and its transform
  2198. const aiMatrix4x4 node_xfm = get_world_transform(node, mScene);
  2199. aiVector3D T, R, S;
  2200. node_xfm.Decompose(S, R, T);
  2201. const std::array<int64_t,3>& ids = curve_node_uids[ai][nai];
  2202. std::vector<int64_t> times;
  2203. std::vector<float> xval, yval, zval;
  2204. // position/translation
  2205. for (size_t ki = 0; ki < na->mNumPositionKeys; ++ki) {
  2206. const aiVectorKey& k = na->mPositionKeys[ki];
  2207. times.push_back(to_ktime(k.mTime, anim));
  2208. xval.push_back(k.mValue.x);
  2209. yval.push_back(k.mValue.y);
  2210. zval.push_back(k.mValue.z);
  2211. }
  2212. // one curve each for X, Y, Z
  2213. WriteAnimationCurve(outstream, T.x, times, xval, ids[0], "d|X");
  2214. WriteAnimationCurve(outstream, T.y, times, yval, ids[0], "d|Y");
  2215. WriteAnimationCurve(outstream, T.z, times, zval, ids[0], "d|Z");
  2216. // rotation
  2217. times.clear(); xval.clear(); yval.clear(); zval.clear();
  2218. for (size_t ki = 0; ki < na->mNumRotationKeys; ++ki) {
  2219. const aiQuatKey& k = na->mRotationKeys[ki];
  2220. times.push_back(to_ktime(k.mTime, anim));
  2221. // TODO: aiQuaternion method to convert to Euler...
  2222. aiMatrix4x4 m(k.mValue.GetMatrix());
  2223. aiVector3D qs, qr, qt;
  2224. m.Decompose(qs, qr, qt);
  2225. qr = AI_RAD_TO_DEG(qr);
  2226. xval.push_back(qr.x);
  2227. yval.push_back(qr.y);
  2228. zval.push_back(qr.z);
  2229. }
  2230. WriteAnimationCurve(outstream, R.x, times, xval, ids[1], "d|X");
  2231. WriteAnimationCurve(outstream, R.y, times, yval, ids[1], "d|Y");
  2232. WriteAnimationCurve(outstream, R.z, times, zval, ids[1], "d|Z");
  2233. // scaling/scale
  2234. times.clear(); xval.clear(); yval.clear(); zval.clear();
  2235. for (size_t ki = 0; ki < na->mNumScalingKeys; ++ki) {
  2236. const aiVectorKey& k = na->mScalingKeys[ki];
  2237. times.push_back(to_ktime(k.mTime, anim));
  2238. xval.push_back(k.mValue.x);
  2239. yval.push_back(k.mValue.y);
  2240. zval.push_back(k.mValue.z);
  2241. }
  2242. WriteAnimationCurve(outstream, S.x, times, xval, ids[2], "d|X");
  2243. WriteAnimationCurve(outstream, S.y, times, yval, ids[2], "d|Y");
  2244. WriteAnimationCurve(outstream, S.z, times, zval, ids[2], "d|Z");
  2245. }
  2246. }
  2247. indent = 0;
  2248. object_node.End(outstream, binary, indent, true);
  2249. }
  2250. // convenience map of magic node name strings to FBX properties,
  2251. // including the expected type of transform.
  2252. const std::map<std::string,std::pair<std::string,char>> transform_types = {
  2253. {"Translation", {"Lcl Translation", 't'}},
  2254. {"RotationOffset", {"RotationOffset", 't'}},
  2255. {"RotationPivot", {"RotationPivot", 't'}},
  2256. {"PreRotation", {"PreRotation", 'r'}},
  2257. {"Rotation", {"Lcl Rotation", 'r'}},
  2258. {"PostRotation", {"PostRotation", 'r'}},
  2259. {"RotationPivotInverse", {"RotationPivotInverse", 'i'}},
  2260. {"ScalingOffset", {"ScalingOffset", 't'}},
  2261. {"ScalingPivot", {"ScalingPivot", 't'}},
  2262. {"Scaling", {"Lcl Scaling", 's'}},
  2263. {"ScalingPivotInverse", {"ScalingPivotInverse", 'i'}},
  2264. {"GeometricScaling", {"GeometricScaling", 's'}},
  2265. {"GeometricRotation", {"GeometricRotation", 'r'}},
  2266. {"GeometricTranslation", {"GeometricTranslation", 't'}},
  2267. {"GeometricTranslationInverse", {"GeometricTranslationInverse", 'i'}},
  2268. {"GeometricRotationInverse", {"GeometricRotationInverse", 'i'}},
  2269. {"GeometricScalingInverse", {"GeometricScalingInverse", 'i'}}
  2270. };
  2271. //add metadata to fbx property
  2272. void add_meta(FBX::Node& fbx_node, const aiNode* node){
  2273. if(node->mMetaData == nullptr) return;
  2274. aiMetadata* meta = node->mMetaData;
  2275. for (unsigned int i = 0; i < meta->mNumProperties; ++i) {
  2276. aiString key = meta->mKeys[i];
  2277. aiMetadataEntry* entry = &meta->mValues[i];
  2278. switch (entry->mType) {
  2279. case AI_BOOL:{
  2280. bool val = *static_cast<bool *>(entry->mData);
  2281. fbx_node.AddP70bool(key.C_Str(), val);
  2282. break;
  2283. }
  2284. case AI_INT32:{
  2285. int32_t val = *static_cast<int32_t *>(entry->mData);
  2286. fbx_node.AddP70int(key.C_Str(), val);
  2287. break;
  2288. }
  2289. case AI_UINT64:{
  2290. //use string to add uint64
  2291. uint64_t val = *static_cast<uint64_t *>(entry->mData);
  2292. fbx_node.AddP70string(key.C_Str(), std::to_string(val).c_str());
  2293. break;
  2294. }
  2295. case AI_FLOAT:{
  2296. float val = *static_cast<float *>(entry->mData);
  2297. fbx_node.AddP70double(key.C_Str(), val);
  2298. break;
  2299. }
  2300. case AI_DOUBLE:{
  2301. double val = *static_cast<double *>(entry->mData);
  2302. fbx_node.AddP70double(key.C_Str(), val);
  2303. break;
  2304. }
  2305. case AI_AISTRING:{
  2306. aiString val = *static_cast<aiString *>(entry->mData);
  2307. fbx_node.AddP70string(key.C_Str(), val.C_Str());
  2308. break;
  2309. }
  2310. case AI_AIMETADATA: {
  2311. //ignore
  2312. break;
  2313. }
  2314. default:
  2315. break;
  2316. }
  2317. }
  2318. }
  2319. // write a single model node to the stream
  2320. void FBXExporter::WriteModelNode(
  2321. StreamWriterLE& outstream,
  2322. bool,
  2323. const aiNode* node,
  2324. int64_t node_uid,
  2325. const std::string& type,
  2326. const std::vector<std::pair<std::string,aiVector3D>>& transform_chain,
  2327. TransformInheritance inherit_type
  2328. ){
  2329. const aiVector3D zero = {0, 0, 0};
  2330. const aiVector3D one = {1, 1, 1};
  2331. FBX::Node m("Model");
  2332. std::string name = node->mName.C_Str() + FBX::SEPARATOR + "Model";
  2333. m.AddProperties(node_uid, std::move(name), type);
  2334. m.AddChild("Version", int32_t(232));
  2335. FBX::Node p("Properties70");
  2336. p.AddP70bool("RotationActive", true);
  2337. p.AddP70int("DefaultAttributeIndex", 0);
  2338. p.AddP70enum("InheritType", inherit_type);
  2339. if (transform_chain.empty()) {
  2340. // decompose 4x4 transform matrix into TRS
  2341. aiVector3D t, r, s;
  2342. node->mTransformation.Decompose(s, r, t);
  2343. if (t != zero) {
  2344. p.AddP70(
  2345. "Lcl Translation", "Lcl Translation", "", "A",
  2346. double(t.x), double(t.y), double(t.z)
  2347. );
  2348. }
  2349. if (r != zero) {
  2350. r = AI_RAD_TO_DEG(r);
  2351. p.AddP70(
  2352. "Lcl Rotation", "Lcl Rotation", "", "A",
  2353. double(r.x), double(r.y), double(r.z)
  2354. );
  2355. }
  2356. if (s != one) {
  2357. p.AddP70(
  2358. "Lcl Scaling", "Lcl Scaling", "", "A",
  2359. double(s.x), double(s.y), double(s.z)
  2360. );
  2361. }
  2362. } else {
  2363. // apply the transformation chain.
  2364. // these transformation elements are created when importing FBX,
  2365. // which has a complex transformation hierarchy for each node.
  2366. // as such we can bake the hierarchy back into the node on export.
  2367. for (auto &item : transform_chain) {
  2368. auto elem = transform_types.find(item.first);
  2369. if (elem == transform_types.end()) {
  2370. // then this is a bug
  2371. std::stringstream err;
  2372. err << "unrecognized FBX transformation type: ";
  2373. err << item.first;
  2374. throw DeadlyExportError(err.str());
  2375. }
  2376. const std::string &cur_name = elem->second.first;
  2377. const aiVector3D &v = item.second;
  2378. if (cur_name.compare(0, 4, "Lcl ") == 0) {
  2379. // special handling for animatable properties
  2380. p.AddP70( cur_name, cur_name, "", "A", double(v.x), double(v.y), double(v.z) );
  2381. } else {
  2382. p.AddP70vector(cur_name, v.x, v.y, v.z);
  2383. }
  2384. }
  2385. }
  2386. add_meta(p, node);
  2387. m.AddChild(p);
  2388. // not sure what these are for,
  2389. // but they seem to be omnipresent
  2390. m.AddChild("Shading", FBXExportProperty(true));
  2391. m.AddChild("Culling", FBXExportProperty("CullingOff"));
  2392. m.Dump(outstream, binary, 1);
  2393. }
  2394. // wrapper for WriteModelNodes to create and pass a blank transform chain
  2395. void FBXExporter::WriteModelNodes(
  2396. StreamWriterLE& s,
  2397. const aiNode* node,
  2398. int64_t parent_uid,
  2399. const std::unordered_set<const aiNode*>& limbnodes
  2400. ) {
  2401. std::vector<std::pair<std::string,aiVector3D>> chain;
  2402. WriteModelNodes(s, node, parent_uid, limbnodes, chain);
  2403. }
  2404. void FBXExporter::WriteModelNodes(
  2405. StreamWriterLE& outstream,
  2406. const aiNode* node,
  2407. int64_t parent_uid,
  2408. const std::unordered_set<const aiNode*>& limbnodes,
  2409. std::vector<std::pair<std::string,aiVector3D>>& transform_chain
  2410. ) {
  2411. // first collapse any expanded transformation chains created by FBX import.
  2412. std::string node_name(node->mName.C_Str());
  2413. if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) {
  2414. auto pos = node_name.find(MAGIC_NODE_TAG) + MAGIC_NODE_TAG.size() + 1;
  2415. std::string type_name = node_name.substr(pos);
  2416. auto elem = transform_types.find(type_name);
  2417. if (elem == transform_types.end()) {
  2418. // then this is a bug and should be fixed
  2419. std::stringstream err;
  2420. err << "unrecognized FBX transformation node";
  2421. err << " of type " << type_name << " in node " << node_name;
  2422. throw DeadlyExportError(err.str());
  2423. }
  2424. aiVector3D t, r, s;
  2425. node->mTransformation.Decompose(s, r, t);
  2426. switch (elem->second.second) {
  2427. case 'i': // inverse
  2428. // we don't need to worry about the inverse matrices
  2429. break;
  2430. case 't': // translation
  2431. transform_chain.emplace_back(elem->first, t);
  2432. break;
  2433. case 'r': // rotation
  2434. transform_chain.emplace_back(elem->first, AI_RAD_TO_DEG(r));
  2435. break;
  2436. case 's': // scale
  2437. transform_chain.emplace_back(elem->first, s);
  2438. break;
  2439. default:
  2440. // this should never happen
  2441. std::stringstream err;
  2442. err << "unrecognized FBX transformation type code: ";
  2443. err << elem->second.second;
  2444. throw DeadlyExportError(err.str());
  2445. }
  2446. // now continue on to any child nodes
  2447. for (unsigned i = 0; i < node->mNumChildren; ++i) {
  2448. WriteModelNodes(
  2449. outstream,
  2450. node->mChildren[i],
  2451. parent_uid,
  2452. limbnodes,
  2453. transform_chain
  2454. );
  2455. }
  2456. return;
  2457. }
  2458. int64_t node_uid = 0;
  2459. // generate uid and connect to parent, if not the root node,
  2460. if (node != mScene->mRootNode) {
  2461. auto elem = node_uids.find(node);
  2462. if (elem != node_uids.end()) {
  2463. node_uid = elem->second;
  2464. } else {
  2465. node_uid = generate_uid();
  2466. node_uids[node] = node_uid;
  2467. }
  2468. connections.emplace_back("C", "OO", node_uid, parent_uid);
  2469. }
  2470. // what type of node is this?
  2471. if (node == mScene->mRootNode) {
  2472. // handled later
  2473. } else if (node->mNumMeshes == 1) {
  2474. // connect to child mesh, which should have been written previously
  2475. // TODO double check this line
  2476. connections.emplace_back("C", "OO", mesh_uids[node], node_uid);
  2477. // also connect to the material for the child mesh
  2478. connections.emplace_back(
  2479. "C", "OO",
  2480. material_uids[mScene->mMeshes[node->mMeshes[0]]->mMaterialIndex],
  2481. node_uid
  2482. );
  2483. // write model node
  2484. WriteModelNode(
  2485. outstream, binary, node, node_uid, "Mesh", transform_chain
  2486. );
  2487. } else if (limbnodes.count(node)) {
  2488. WriteModelNode(
  2489. outstream, binary, node, node_uid, "LimbNode", transform_chain
  2490. );
  2491. // we also need to write a nodeattribute to mark it as a skeleton
  2492. int64_t node_attribute_uid = generate_uid();
  2493. FBX::Node na("NodeAttribute");
  2494. na.AddProperties(
  2495. node_attribute_uid, FBX::SEPARATOR + "NodeAttribute", "LimbNode"
  2496. );
  2497. na.AddChild("TypeFlags", FBXExportProperty("Skeleton"));
  2498. na.Dump(outstream, binary, 1);
  2499. // and connect them
  2500. connections.emplace_back("C", "OO", node_attribute_uid, node_uid);
  2501. } else if (node->mNumMeshes >= 1) {
  2502. connections.emplace_back("C", "OO", mesh_uids[node], node_uid);
  2503. for (size_t i = 0; i < node->mNumMeshes; i++) {
  2504. connections.emplace_back(
  2505. "C", "OO",
  2506. material_uids[mScene->mMeshes[node->mMeshes[i]]->mMaterialIndex],
  2507. node_uid
  2508. );
  2509. }
  2510. WriteModelNode(outstream, binary, node, node_uid, "Mesh", transform_chain);
  2511. } else {
  2512. const auto& lightIt = lights_uids.find(node->mName.C_Str());
  2513. if(lightIt != lights_uids.end()) {
  2514. // Node has a light connected to it.
  2515. WriteModelNode(
  2516. outstream, binary, node, node_uid, "Light", transform_chain
  2517. );
  2518. connections.emplace_back("C", "OO", lightIt->second, node_uid);
  2519. } else {
  2520. // generate a null node so we can add children to it
  2521. WriteModelNode(
  2522. outstream, binary, node, node_uid, "Null", transform_chain
  2523. );
  2524. }
  2525. }
  2526. if (node == mScene->mRootNode && node->mNumMeshes > 0) {
  2527. int64_t new_node_uid = generate_uid();
  2528. connections.emplace_back("C", "OO", new_node_uid, node_uid);
  2529. connections.emplace_back("C", "OO", mesh_uids[node], new_node_uid);
  2530. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  2531. connections.emplace_back(
  2532. "C", "OO",
  2533. material_uids[mScene->mMeshes[node->mMeshes[i]]->mMaterialIndex],
  2534. new_node_uid
  2535. );
  2536. }
  2537. aiNode new_node;
  2538. new_node.mName = mScene->mMeshes[0]->mName;
  2539. WriteModelNode(outstream, binary, &new_node, new_node_uid, "Mesh", {});
  2540. }
  2541. // now recurse into children
  2542. for (size_t i = 0; i < node->mNumChildren; ++i) {
  2543. WriteModelNodes(
  2544. outstream, node->mChildren[i], node_uid, limbnodes
  2545. );
  2546. }
  2547. }
  2548. void FBXExporter::WriteAnimationCurveNode(
  2549. StreamWriterLE &outstream,
  2550. int64_t uid,
  2551. const std::string &name, // "T", "R", or "S"
  2552. aiVector3D default_value,
  2553. const std::string &property_name, // "Lcl Translation" etc
  2554. int64_t layer_uid,
  2555. int64_t node_uid) {
  2556. FBX::Node n("AnimationCurveNode");
  2557. n.AddProperties(uid, name + FBX::SEPARATOR + "AnimCurveNode", "");
  2558. FBX::Node p("Properties70");
  2559. p.AddP70numberA("d|X", default_value.x);
  2560. p.AddP70numberA("d|Y", default_value.y);
  2561. p.AddP70numberA("d|Z", default_value.z);
  2562. n.AddChild(p);
  2563. n.Dump(outstream, binary, 1);
  2564. // connect to layer
  2565. this->connections.emplace_back("C", "OO", uid, layer_uid);
  2566. // connect to bone
  2567. this->connections.emplace_back("C", "OP", uid, node_uid, property_name);
  2568. }
  2569. void FBXExporter::WriteAnimationCurve(
  2570. StreamWriterLE& outstream,
  2571. double default_value,
  2572. const std::vector<int64_t>& times,
  2573. const std::vector<float>& values,
  2574. int64_t curvenode_uid,
  2575. const std::string& property_link // "d|X", "d|Y", etc
  2576. ) {
  2577. FBX::Node n("AnimationCurve");
  2578. int64_t curve_uid = generate_uid();
  2579. n.AddProperties(curve_uid, FBX::SEPARATOR + "AnimCurve", "");
  2580. n.AddChild("Default", default_value);
  2581. n.AddChild("KeyVer", int32_t(4009));
  2582. n.AddChild("KeyTime", times);
  2583. n.AddChild("KeyValueFloat", values);
  2584. // TODO: keyattr flags and data (STUB for now)
  2585. n.AddChild("KeyAttrFlags", std::vector<int32_t>{0});
  2586. n.AddChild("KeyAttrDataFloat", std::vector<float>{0,0,0,0});
  2587. n.AddChild(
  2588. "KeyAttrRefCount",
  2589. std::vector<int32_t>{static_cast<int32_t>(times.size())}
  2590. );
  2591. n.Dump(outstream, binary, 1);
  2592. this->connections.emplace_back(
  2593. "C", "OP", curve_uid, curvenode_uid, property_link
  2594. );
  2595. }
  2596. void FBXExporter::WriteConnections ()
  2597. {
  2598. // we should have completed the connection graph already,
  2599. // so basically just dump it here
  2600. if (!binary) {
  2601. WriteAsciiSectionHeader("Object connections");
  2602. }
  2603. // TODO: comments with names in the ascii version
  2604. FBX::Node conn("Connections");
  2605. StreamWriterLE outstream(outfile);
  2606. conn.Begin(outstream, binary, 0);
  2607. conn.BeginChildren(outstream, binary, 0);
  2608. for (auto &n : connections) {
  2609. n.Dump(outstream, binary, 1);
  2610. }
  2611. conn.End(outstream, binary, 0, !connections.empty());
  2612. connections.clear();
  2613. }
  2614. #endif // ASSIMP_BUILD_NO_FBX_EXPORTER
  2615. #endif // ASSIMP_BUILD_NO_EXPORT