AssetImporter.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/Context.h>
  4. #include <Urho3D/Core/ProcessUtils.h>
  5. #include <Urho3D/Core/StringUtils.h>
  6. #include <Urho3D/Core/WorkQueue.h>
  7. #include <Urho3D/Graphics/AnimatedModel.h>
  8. #include <Urho3D/Graphics/Animation.h>
  9. #include <Urho3D/Graphics/DebugRenderer.h>
  10. #include <Urho3D/Graphics/Geometry.h>
  11. #include <Urho3D/Graphics/Graphics.h>
  12. #include <Urho3D/Graphics/Light.h>
  13. #include <Urho3D/Graphics/Material.h>
  14. #include <Urho3D/Graphics/Octree.h>
  15. #include <Urho3D/Graphics/Zone.h>
  16. #include <Urho3D/GraphicsAPI/IndexBuffer.h>
  17. #include <Urho3D/GraphicsAPI/VertexBuffer.h>
  18. #include <Urho3D/IO/File.h>
  19. #include <Urho3D/IO/FileSystem.h>
  20. #ifdef URHO3D_PHYSICS
  21. #include <Urho3D/Physics/PhysicsWorld.h>
  22. #endif
  23. #include <Urho3D/Resource/ResourceCache.h>
  24. #include <Urho3D/Resource/XMLFile.h>
  25. #include <Urho3D/Scene/Scene.h>
  26. #ifdef WIN32
  27. #include <Urho3D/Engine/WinWrapped.h>
  28. #endif
  29. #include <assimp/config.h>
  30. #include <assimp/cimport.h>
  31. #include <assimp/scene.h>
  32. #include <assimp/postprocess.h>
  33. #include <assimp/DefaultLogger.hpp>
  34. #include <Urho3D/DebugNew.h>
  35. using namespace Urho3D;
  36. struct OutModel
  37. {
  38. String outName_;
  39. aiNode* rootNode_{};
  40. HashSet<unsigned> meshIndices_;
  41. Vector<aiMesh*> meshes_;
  42. Vector<aiNode*> meshNodes_;
  43. Vector<aiNode*> bones_;
  44. Vector<aiNode*> pivotlessBones_;
  45. Vector<aiAnimation*> animations_;
  46. Vector<float> boneRadii_;
  47. Vector<BoundingBox> boneHitboxes_;
  48. aiNode* rootBone_{};
  49. unsigned totalVertices_{};
  50. unsigned totalIndices_{};
  51. };
  52. struct OutScene
  53. {
  54. String outName_;
  55. aiNode* rootNode_{};
  56. Vector<OutModel> models_;
  57. Vector<aiNode*> nodes_;
  58. Vector<unsigned> nodeModelIndices_;
  59. };
  60. // FBX transform chain
  61. enum TransformationComp
  62. {
  63. TransformationComp_Translation = 0,
  64. TransformationComp_RotationOffset,
  65. TransformationComp_RotationPivot,
  66. TransformationComp_PreRotation,
  67. TransformationComp_Rotation,
  68. TransformationComp_PostRotation,
  69. TransformationComp_RotationPivotInverse,
  70. TransformationComp_ScalingOffset,
  71. TransformationComp_ScalingPivot,
  72. TransformationComp_Scaling,
  73. // Not checking these
  74. // They are typically flushed out in the fbxconverter, but there
  75. // might be cases where they're not, hence, leaving them.
  76. #ifdef EXT_TRANSFORMATION_CHECK
  77. TransformationComp_ScalingPivotInverse,
  78. TransformationComp_GeometricTranslation,
  79. TransformationComp_GeometricRotation,
  80. TransformationComp_GeometricScaling,
  81. #endif
  82. TransformationComp_MAXIMUM
  83. };
  84. const char *transformSuffix[TransformationComp_MAXIMUM] =
  85. {
  86. "Translation", // TransformationComp_Translation = 0,
  87. "RotationOffset", // TransformationComp_RotationOffset,
  88. "RotationPivot", // TransformationComp_RotationPivot,
  89. "PreRotation", // TransformationComp_PreRotation,
  90. "Rotation", // TransformationComp_Rotation,
  91. "PostRotation", // TransformationComp_PostRotation,
  92. "RotationPivotInverse", // TransformationComp_RotationPivotInverse,
  93. "ScalingOffset", // TransformationComp_ScalingOffset,
  94. "ScalingPivot", // TransformationComp_ScalingPivot,
  95. "Scaling", // TransformationComp_Scaling,
  96. #ifdef EXT_TRANSFORMATION_CHECK
  97. "ScalingPivotInverse", // TransformationComp_ScalingPivotInverse,
  98. "GeometricTranslation", // TransformationComp_GeometricTranslation,
  99. "GeometricRotation", // TransformationComp_GeometricRotation,
  100. "GeometricScaling", // TransformationComp_GeometricScaling,
  101. #endif
  102. };
  103. static const unsigned MAX_CHANNELS = 4;
  104. SharedPtr<Context> context_(new Context());
  105. const aiScene* scene_ = nullptr;
  106. aiNode* rootNode_ = nullptr;
  107. String inputName_;
  108. String resourcePath_;
  109. String outPath_;
  110. String outName_;
  111. bool useSubdirs_ = true;
  112. bool localIDs_ = false;
  113. bool saveBinary_ = false;
  114. bool saveJson_ = false;
  115. bool createZone_ = true;
  116. bool noAnimations_ = false;
  117. bool noHierarchy_ = false;
  118. bool noMaterials_ = false;
  119. bool noTextures_ = false;
  120. bool noMaterialDiffuseColor_ = false;
  121. bool noEmptyNodes_ = false;
  122. bool saveMaterialList_ = false;
  123. bool includeNonSkinningBones_ = false;
  124. bool verboseLog_ = false;
  125. bool emissiveAO_ = false;
  126. bool noOverwriteMaterial_ = false;
  127. bool noOverwriteTexture_ = false;
  128. bool noOverwriteNewerTexture_ = false;
  129. bool checkUniqueModel_ = true;
  130. bool moveToBindPose_ = false;
  131. unsigned maxBones_ = 64;
  132. Vector<String> nonSkinningBoneIncludes_;
  133. Vector<String> nonSkinningBoneExcludes_;
  134. HashSet<aiAnimation*> allAnimations_;
  135. Vector<aiAnimation*> sceneAnimations_;
  136. float defaultTicksPerSecond_ = 4800.0f;
  137. // For subset animation import usage
  138. float importStartTime_ = 0.0f;
  139. float importEndTime_ = 0.0f;
  140. bool suppressFbxPivotNodes_ = true;
  141. int main(int argc, char** argv);
  142. void Run(const Vector<String>& arguments);
  143. void DumpNodes(aiNode* rootNode, unsigned level);
  144. void ExportModel(const String& outName, bool animationOnly);
  145. void ExportAnimation(const String& outName, bool animationOnly);
  146. void CollectMeshes(OutModel& model, aiNode* node);
  147. void CollectBones(OutModel& model, bool animationOnly = false);
  148. void CollectBonesFinal(Vector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  149. void MoveToBindPose(OutModel& model, aiNode* current);
  150. void CollectAnimations(OutModel* model = nullptr);
  151. void BuildBoneCollisionInfo(OutModel& model);
  152. void BuildAndSaveModel(OutModel& model);
  153. void BuildAndSaveAnimations(OutModel* model = nullptr);
  154. void ExportScene(const String& outName, bool asPrefab);
  155. void CollectSceneModels(OutScene& scene, aiNode* node);
  156. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  157. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  158. void BuildAndSaveScene(OutScene& scene, bool asPrefab);
  159. void ExportMaterials(HashSet<String>& usedTextures);
  160. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  161. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  162. void CombineLods(const Vector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  163. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*>>& dest, aiNode* node);
  164. unsigned GetMeshIndex(aiMesh* mesh);
  165. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  166. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  167. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  168. void GetBlendData(OutModel& model, aiMesh* mesh, aiNode* meshNode, Vector<i32>& boneMappings, Vector<Vector<unsigned char>>&
  169. blendIndices, Vector<Vector<float>>& blendWeights);
  170. String GetMeshMaterialName(aiMesh* mesh);
  171. String GetMaterialTextureName(const String& nameIn);
  172. String GenerateMaterialName(aiMaterial* material);
  173. String GenerateTextureName(unsigned texIndex);
  174. unsigned GetNumValidFaces(aiMesh* mesh);
  175. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  176. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  177. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, bool isSkinned, BoundingBox& box,
  178. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<Vector<unsigned char>>& blendIndices,
  179. Vector<Vector<float>>& blendWeights);
  180. Vector<VertexElement> GetVertexElements(aiMesh* mesh, bool isSkinned);
  181. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  182. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  183. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  184. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  185. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  186. String FromAIString(const aiString& str);
  187. Vector3 ToVector3(const aiVector3D& vec);
  188. Vector2 ToVector2(const aiVector2D& vec);
  189. Quaternion ToQuaternion(const aiQuaternion& quat);
  190. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat);
  191. aiMatrix4x4 ToAIMatrix4x4(const Matrix3x4& mat);
  192. String SanitateAssetName(const String& name);
  193. unsigned GetPivotlessBoneIndex(OutModel& model, const String& boneName);
  194. void ExtrapolatePivotlessAnimation(OutModel* model);
  195. void CollectSceneNodesAsBones(OutModel &model, aiNode* rootNode);
  196. int main(int argc, char** argv)
  197. {
  198. Vector<String> arguments;
  199. #ifdef WIN32
  200. arguments = ParseArguments(GetCommandLineW());
  201. #else
  202. arguments = ParseArguments(argc, argv);
  203. #endif
  204. Run(arguments);
  205. return 0;
  206. }
  207. void Run(const Vector<String>& arguments)
  208. {
  209. if (arguments.Size() < 2)
  210. {
  211. ErrorExit(
  212. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  213. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  214. "Commands:\n"
  215. "model Output a model\n"
  216. "anim Output animation(s)\n"
  217. "scene Output a scene\n"
  218. "node Output a node and its children (prefab)\n"
  219. "dump Dump scene node structure. No output file is generated\n"
  220. "lod Combine several Urho3D models as LOD levels of the output model\n"
  221. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  222. "\n"
  223. "Options:\n"
  224. "-b Save scene in binary format, default format is XML\n"
  225. "-j Save scene in JSON format, default format is XML\n"
  226. "-h Generate hard instead of smooth normals if input has no normals\n"
  227. "-i Use local ID's for scene nodes\n"
  228. "-l Output a material list file for models\n"
  229. "-na Do not output animations\n"
  230. "-nm Do not output materials\n"
  231. "-nt Do not output material textures\n"
  232. "-nc Do not use material diffuse color value, instead output white\n"
  233. "-nh Do not save full node hierarchy (scene mode only)\n"
  234. "-ns Do not create subdirectories for resources\n"
  235. "-nz Do not create a zone and a directional light (scene mode only)\n"
  236. "-nf Do not fix infacing normals\n"
  237. "-ne Do not save empty nodes (scene mode only)\n"
  238. "-mb <x> Maximum number of bones per submesh. Default 64\n"
  239. "-p <path> Set path for scene resources. Default is output file path\n"
  240. "-r <name> Use the named scene node as root node\n"
  241. "-f <freq> Animation tick frequency to use if unspecified. Default 4800\n"
  242. "-o Optimize redundant submeshes. Loses scene hierarchy and animations\n"
  243. "-s <filter> Include non-skinning bones in the model's skeleton. Can be given a\n"
  244. " case-insensitive semicolon separated filter list. Bone is included\n"
  245. " if its name contains any of the filters. Prefix filter with minus\n"
  246. " sign to use as an exclude. For example -s \"Bip01;-Dummy;-Helper\"\n"
  247. "-t Generate tangents\n"
  248. "-v Enable verbose Assimp library logging\n"
  249. "-eao Interpret material emissive texture as ambient occlusion\n"
  250. "-cm Check and do not overwrite if material exists\n"
  251. "-ct Check and do not overwrite if texture exists\n"
  252. "-ctn Check and do not overwrite if texture has newer timestamp\n"
  253. "-am Export all meshes even if identical (scene mode only)\n"
  254. "-bp Move bones to bind pose before saving model\n"
  255. "-split <start> <end> (animation model only)\n"
  256. " Split animation, will only import from start frame to end frame\n"
  257. "-np Do not suppress $fbx pivot nodes (FBX files only)\n"
  258. );
  259. }
  260. context_->RegisterSubsystem(new FileSystem(context_));
  261. context_->RegisterSubsystem(new ResourceCache(context_));
  262. context_->RegisterSubsystem(new WorkQueue(context_));
  263. RegisterSceneLibrary(context_);
  264. RegisterGraphicsLibrary(context_);
  265. #ifdef URHO3D_PHYSICS
  266. RegisterPhysicsLibrary(context_);
  267. #endif
  268. String command = arguments[0].ToLower();
  269. String rootNodeName;
  270. unsigned flags =
  271. aiProcess_ConvertToLeftHanded |
  272. aiProcess_JoinIdenticalVertices |
  273. aiProcess_Triangulate |
  274. aiProcess_GenSmoothNormals |
  275. aiProcess_LimitBoneWeights |
  276. aiProcess_ImproveCacheLocality |
  277. aiProcess_RemoveRedundantMaterials |
  278. aiProcess_FixInfacingNormals |
  279. aiProcess_FindInvalidData |
  280. aiProcess_GenUVCoords |
  281. aiProcess_FindInstances |
  282. aiProcess_OptimizeMeshes;
  283. for (unsigned i = 2; i < arguments.Size(); ++i)
  284. {
  285. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  286. {
  287. String argument = arguments[i].Substring(1).ToLower();
  288. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  289. if (argument == "b")
  290. saveBinary_ = true;
  291. else if(argument == "j")
  292. saveJson_ = true;
  293. else if (argument == "h")
  294. {
  295. flags &= ~aiProcess_GenSmoothNormals;
  296. flags |= aiProcess_GenNormals;
  297. }
  298. else if (argument == "i")
  299. localIDs_ = true;
  300. else if (argument == "l")
  301. saveMaterialList_ = true;
  302. else if (argument == "t")
  303. flags |= aiProcess_CalcTangentSpace;
  304. else if (argument == "o")
  305. flags |= aiProcess_PreTransformVertices;
  306. else if (argument.Length() == 2 && argument[0] == 'n')
  307. {
  308. switch (tolower(argument[1]))
  309. {
  310. case 'a':
  311. noAnimations_ = true;
  312. break;
  313. case 'c':
  314. noMaterialDiffuseColor_ = true;
  315. break;
  316. case 'm':
  317. noMaterials_ = true;
  318. break;
  319. case 'h':
  320. noHierarchy_ = true;
  321. break;
  322. case 'e':
  323. noEmptyNodes_ = true;
  324. break;
  325. case 's':
  326. useSubdirs_ = false;
  327. break;
  328. case 't':
  329. noTextures_ = true;
  330. break;
  331. case 'z':
  332. createZone_ = false;
  333. break;
  334. case 'f':
  335. flags &= ~aiProcess_FixInfacingNormals;
  336. break;
  337. case 'p':
  338. suppressFbxPivotNodes_ = false;
  339. break;
  340. }
  341. }
  342. else if (argument == "mb" && !value.Empty())
  343. {
  344. maxBones_ = ToU32(value);
  345. if (maxBones_ < 1)
  346. maxBones_ = 1;
  347. ++i;
  348. }
  349. else if (argument == "p" && !value.Empty())
  350. {
  351. resourcePath_ = AddTrailingSlash(value);
  352. ++i;
  353. }
  354. else if (argument == "r" && !value.Empty())
  355. {
  356. rootNodeName = value;
  357. ++i;
  358. }
  359. else if (argument == "f" && !value.Empty())
  360. {
  361. defaultTicksPerSecond_ = ToFloat(value);
  362. ++i;
  363. }
  364. else if (argument == "s")
  365. {
  366. includeNonSkinningBones_ = true;
  367. if (value.Length() && (value[0] != '-' || value.Length() > 3))
  368. {
  369. Vector<String> filters = value.Split(';');
  370. for (unsigned i = 0; i < filters.Size(); ++i)
  371. {
  372. if (filters[i][0] == '-')
  373. nonSkinningBoneExcludes_.Push(filters[i].Substring(1));
  374. else
  375. nonSkinningBoneIncludes_.Push(filters[i]);
  376. }
  377. }
  378. }
  379. else if (argument == "v")
  380. verboseLog_ = true;
  381. else if (argument == "eao")
  382. emissiveAO_ = true;
  383. else if (argument == "cm")
  384. noOverwriteMaterial_ = true;
  385. else if (argument == "ct")
  386. noOverwriteTexture_ = true;
  387. else if (argument == "ctn")
  388. noOverwriteNewerTexture_ = true;
  389. else if (argument == "am")
  390. checkUniqueModel_ = false;
  391. else if (argument == "bp")
  392. moveToBindPose_ = true;
  393. else if (argument == "split")
  394. {
  395. String value2 = i + 2 < arguments.Size() ? arguments[i + 2] : String::EMPTY;
  396. if (value.Length() && value2.Length() && (value[0] != '-') && (value2[0] != '-'))
  397. {
  398. importStartTime_ = ToFloat(value);
  399. importEndTime_ = ToFloat(value2);
  400. }
  401. }
  402. }
  403. }
  404. if (command == "model" || command == "scene" || command == "anim" || command == "node" || command == "dump")
  405. {
  406. String inFile = arguments[1];
  407. String outFile;
  408. if (arguments.Size() > 2 && arguments[2][0] != '-')
  409. outFile = GetInternalPath(arguments[2]);
  410. inputName_ = GetFileName(inFile);
  411. outName_ = outFile;
  412. outPath_ = GetPath(outFile);
  413. if (resourcePath_.Empty())
  414. {
  415. resourcePath_ = outPath_;
  416. // If output file already has the Models/ path (model mode), do not take it into the resource path
  417. if (command == "model")
  418. {
  419. if (resourcePath_.EndsWith("Models/", false))
  420. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  421. }
  422. if (resourcePath_.Empty())
  423. resourcePath_ = "./";
  424. }
  425. resourcePath_ = AddTrailingSlash(resourcePath_);
  426. if (command != "dump" && outFile.Empty())
  427. ErrorExit("No output file defined");
  428. if (verboseLog_)
  429. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  430. PrintLine("Reading file " + inFile);
  431. if (!inFile.EndsWith(".fbx", false))
  432. suppressFbxPivotNodes_ = false;
  433. // Only do this for the "model" command. "anim" command extrapolates animation from the original bone definition
  434. if (suppressFbxPivotNodes_ && command == "model")
  435. {
  436. PrintLine("Suppressing $fbx nodes");
  437. aiPropertyStore *aiprops = aiCreatePropertyStore();
  438. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS, 1); //default = true;
  439. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ALL_MATERIALS, 0); //default = false;
  440. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_MATERIALS, 1); //default = true;
  441. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_CAMERAS, 1); //default = true;
  442. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_LIGHTS, 1); //default = true;
  443. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ANIMATIONS, 1); //default = true;
  444. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_STRICT_MODE, 0); //default = false;
  445. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, 0); //**false, default = true;
  446. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, 1);//default = true;
  447. scene_ = aiImportFileExWithProperties(GetNativePath(inFile).CString(), flags, nullptr, aiprops);
  448. // prevent processing animation suppression, both cannot work simultaneously
  449. suppressFbxPivotNodes_ = false;
  450. }
  451. else
  452. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  453. if (!scene_)
  454. ErrorExit("Could not open or parse input file " + inFile + ": " + String(aiGetErrorString()));
  455. if (verboseLog_)
  456. Assimp::DefaultLogger::kill();
  457. rootNode_ = scene_->mRootNode;
  458. if (!rootNodeName.Empty())
  459. {
  460. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  461. if (!rootNode_)
  462. ErrorExit("Could not find scene node " + rootNodeName);
  463. }
  464. if (command == "dump")
  465. {
  466. DumpNodes(rootNode_, 0);
  467. return;
  468. }
  469. if (command == "model")
  470. ExportModel(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  471. if (command == "anim")
  472. {
  473. noMaterials_ = true;
  474. ExportAnimation(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  475. }
  476. if (command == "scene" || command == "node")
  477. {
  478. bool asPrefab = command == "node";
  479. // Saving as prefab requires the hierarchy, especially the root node
  480. if (asPrefab)
  481. noHierarchy_ = false;
  482. ExportScene(outFile, asPrefab);
  483. }
  484. if (!noMaterials_)
  485. {
  486. HashSet<String> usedTextures;
  487. ExportMaterials(usedTextures);
  488. if (!noTextures_)
  489. CopyTextures(usedTextures, GetPath(inFile));
  490. }
  491. }
  492. else if (command == "lod")
  493. {
  494. Vector<float> lodDistances;
  495. Vector<String> modelNames;
  496. String outFile;
  497. unsigned numLodArguments = 0;
  498. for (unsigned i = 1; i < arguments.Size(); ++i)
  499. {
  500. if (arguments[i][0] == '-')
  501. break;
  502. ++numLodArguments;
  503. }
  504. if (numLodArguments < 4)
  505. ErrorExit("Must define at least 2 LOD levels");
  506. if (!(numLodArguments & 1u))
  507. ErrorExit("No output file defined");
  508. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  509. {
  510. if (i == numLodArguments)
  511. outFile = GetInternalPath(arguments[i]);
  512. else
  513. {
  514. if (i & 1u)
  515. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  516. else
  517. modelNames.Push(GetInternalPath(arguments[i]));
  518. }
  519. }
  520. if (lodDistances[0] != 0.0f)
  521. {
  522. PrintLine("Warning: first LOD distance forced to 0");
  523. lodDistances[0] = 0.0f;
  524. }
  525. CombineLods(lodDistances, modelNames, outFile);
  526. }
  527. else
  528. ErrorExit("Unrecognized command " + command);
  529. }
  530. void DumpNodes(aiNode* rootNode, unsigned level)
  531. {
  532. if (!rootNode)
  533. return;
  534. String indent(' ', level * 2);
  535. Vector3 pos, scale;
  536. Quaternion rot;
  537. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  538. GetPosRotScale(transform, pos, rot, scale);
  539. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  540. if (rootNode->mNumMeshes == 1)
  541. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  542. if (rootNode->mNumMeshes > 1)
  543. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  544. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  545. DumpNodes(rootNode->mChildren[i], level + 1);
  546. }
  547. void ExportModel(const String& outName, bool animationOnly)
  548. {
  549. if (outName.Empty())
  550. ErrorExit("No output file defined");
  551. OutModel model;
  552. model.rootNode_ = rootNode_;
  553. model.outName_ = outName;
  554. CollectMeshes(model, model.rootNode_);
  555. CollectBones(model, animationOnly);
  556. BuildBoneCollisionInfo(model);
  557. BuildAndSaveModel(model);
  558. if (!noAnimations_)
  559. {
  560. CollectAnimations(&model);
  561. BuildAndSaveAnimations(&model);
  562. // Save scene-global animations
  563. CollectAnimations();
  564. BuildAndSaveAnimations();
  565. }
  566. }
  567. void ExportAnimation(const String& outName, bool animationOnly)
  568. {
  569. if (outName.Empty())
  570. ErrorExit("No output file defined");
  571. OutModel model;
  572. model.rootNode_ = rootNode_;
  573. model.outName_ = outName;
  574. CollectMeshes(model, model.rootNode_);
  575. CollectBones(model, animationOnly);
  576. BuildBoneCollisionInfo(model);
  577. // BuildAndSaveModel(model);
  578. if (!noAnimations_)
  579. {
  580. // Most fbx animation files contain only a skeleton and no skinned mesh.
  581. // Assume the scene node contains the model's bone definition and,
  582. // transfer the info to the model.
  583. if (suppressFbxPivotNodes_ && model.bones_.Size() == 0)
  584. CollectSceneNodesAsBones(model, rootNode_);
  585. CollectAnimations(&model);
  586. BuildAndSaveAnimations(&model);
  587. // Save scene-global animations
  588. CollectAnimations();
  589. BuildAndSaveAnimations();
  590. }
  591. }
  592. void CollectMeshes(OutModel& model, aiNode* node)
  593. {
  594. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  595. {
  596. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  597. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  598. {
  599. if (mesh == model.meshes_[j])
  600. {
  601. PrintLine("Warning: same mesh found multiple times");
  602. break;
  603. }
  604. }
  605. model.meshIndices_.Insert(node->mMeshes[i]);
  606. model.meshes_.Push(mesh);
  607. model.meshNodes_.Push(node);
  608. model.totalVertices_ += mesh->mNumVertices;
  609. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  610. }
  611. for (unsigned i = 0; i < node->mNumChildren; ++i)
  612. CollectMeshes(model, node->mChildren[i]);
  613. }
  614. void CollectBones(OutModel& model, bool animationOnly)
  615. {
  616. HashSet<aiNode*> necessary;
  617. HashSet<aiNode*> rootNodes;
  618. bool haveSkinnedMeshes = false;
  619. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  620. {
  621. if (model.meshes_[i]->HasBones())
  622. {
  623. haveSkinnedMeshes = true;
  624. break;
  625. }
  626. }
  627. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  628. {
  629. aiMesh* mesh = model.meshes_[i];
  630. aiNode* meshNode = model.meshNodes_[i];
  631. aiNode* meshParentNode = meshNode->mParent;
  632. aiNode* rootNode = nullptr;
  633. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  634. {
  635. aiBone* bone = mesh->mBones[j];
  636. String boneName(FromAIString(bone->mName));
  637. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  638. if (!boneNode)
  639. ErrorExit("Could not find scene node for bone " + boneName);
  640. necessary.Insert(boneNode);
  641. rootNode = boneNode;
  642. for (;;)
  643. {
  644. boneNode = boneNode->mParent;
  645. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  646. break;
  647. rootNode = boneNode;
  648. necessary.Insert(boneNode);
  649. }
  650. if (rootNodes.Find(rootNode) == rootNodes.End())
  651. rootNodes.Insert(rootNode);
  652. }
  653. // When model is partially skinned, include the attachment nodes of the rigid meshes in the skeleton
  654. if (haveSkinnedMeshes && !mesh->mNumBones)
  655. {
  656. aiNode* boneNode = meshNode;
  657. necessary.Insert(boneNode);
  658. rootNode = boneNode;
  659. for (;;)
  660. {
  661. boneNode = boneNode->mParent;
  662. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  663. break;
  664. rootNode = boneNode;
  665. necessary.Insert(boneNode);
  666. }
  667. if (rootNodes.Find(rootNode) == rootNodes.End())
  668. rootNodes.Insert(rootNode);
  669. }
  670. }
  671. // If we find multiple root nodes, try to remedy by going back in the parent chain and finding a common parent
  672. if (rootNodes.Size() > 1)
  673. {
  674. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  675. {
  676. aiNode* commonParent = (*i);
  677. while (commonParent)
  678. {
  679. unsigned found = 0;
  680. for (HashSet<aiNode*>::Iterator j = rootNodes.Begin(); j != rootNodes.End(); ++j)
  681. {
  682. if (i == j)
  683. continue;
  684. aiNode* parent = *j;
  685. while (parent)
  686. {
  687. if (parent == commonParent)
  688. {
  689. ++found;
  690. break;
  691. }
  692. parent = parent->mParent;
  693. }
  694. }
  695. if (found >= rootNodes.Size() - 1)
  696. {
  697. PrintLine("Multiple roots initially found, using new root node " + FromAIString(commonParent->mName));
  698. rootNodes.Clear();
  699. rootNodes.Insert(commonParent);
  700. necessary.Insert(commonParent);
  701. break;
  702. }
  703. commonParent = commonParent->mParent;
  704. }
  705. if (rootNodes.Size() == 1)
  706. break; // Succeeded
  707. }
  708. if (rootNodes.Size() > 1)
  709. ErrorExit("Skeleton with multiple root nodes found, not supported");
  710. }
  711. if (rootNodes.Empty())
  712. return;
  713. model.rootBone_ = *rootNodes.Begin();
  714. // Move the model to bind pose now if requested
  715. if (moveToBindPose_)
  716. {
  717. PrintLine("Moving bones to bind pose");
  718. MoveToBindPose(model, model.rootBone_);
  719. }
  720. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  721. // Initialize the bone collision info
  722. model.boneRadii_.Resize(model.bones_.Size());
  723. model.boneHitboxes_.Resize(model.bones_.Size());
  724. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  725. {
  726. model.boneRadii_[i] = 0.0f;
  727. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  728. }
  729. }
  730. void MoveToBindPose(OutModel& model, aiNode* current)
  731. {
  732. String nodeName(FromAIString(current->mName));
  733. Matrix3x4 bindWorldTransform = GetOffsetMatrix(model, nodeName).Inverse();
  734. // Skip if we get an identity offset matrix (bone lookup failed)
  735. if (!bindWorldTransform.Equals(Matrix3x4::IDENTITY))
  736. {
  737. if (current->mParent && current != model.rootNode_)
  738. {
  739. aiMatrix4x4 parentWorldTransform = GetDerivedTransform(current->mParent, model.rootNode_, true);
  740. Matrix3x4 parentInverse = ToMatrix3x4(parentWorldTransform).Inverse();
  741. current->mTransformation = ToAIMatrix4x4(parentInverse * bindWorldTransform);
  742. }
  743. else
  744. current->mTransformation = ToAIMatrix4x4(bindWorldTransform);
  745. }
  746. for (unsigned i = 0; i < current->mNumChildren; ++i)
  747. MoveToBindPose(model, current->mChildren[i]);
  748. }
  749. void CollectBonesFinal(Vector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  750. {
  751. bool includeBone = necessary.Find(node) != necessary.End();
  752. String boneName = FromAIString(node->mName);
  753. // Check include/exclude filters for non-skinned bones
  754. if (!includeBone && includeNonSkinningBones_)
  755. {
  756. // If no includes specified, include by default but check for excludes
  757. if (nonSkinningBoneIncludes_.Empty())
  758. includeBone = true;
  759. // Check against includes/excludes
  760. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  761. {
  762. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  763. {
  764. includeBone = true;
  765. break;
  766. }
  767. }
  768. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  769. {
  770. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  771. {
  772. includeBone = false;
  773. break;
  774. }
  775. }
  776. if (includeBone)
  777. PrintLine("Including non-skinning bone " + boneName);
  778. }
  779. if (includeBone)
  780. dest.Push(node);
  781. for (unsigned i = 0; i < node->mNumChildren; ++i)
  782. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  783. }
  784. void CollectAnimations(OutModel* model)
  785. {
  786. const aiScene* scene = scene_;
  787. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  788. {
  789. aiAnimation* anim = scene->mAnimations[i];
  790. if (allAnimations_.Contains(anim))
  791. continue;
  792. if (model)
  793. {
  794. bool modelBoneFound = false;
  795. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  796. {
  797. aiNodeAnim* channel = anim->mChannels[j];
  798. String channelName = FromAIString(channel->mNodeName);
  799. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  800. {
  801. modelBoneFound = true;
  802. break;
  803. }
  804. }
  805. if (modelBoneFound)
  806. {
  807. model->animations_.Push(anim);
  808. allAnimations_.Insert(anim);
  809. }
  810. }
  811. else
  812. {
  813. sceneAnimations_.Push(anim);
  814. allAnimations_.Insert(anim);
  815. }
  816. }
  817. /// \todo Vertex morphs are ignored for now
  818. }
  819. void BuildBoneCollisionInfo(OutModel& model)
  820. {
  821. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  822. {
  823. aiMesh* mesh = model.meshes_[i];
  824. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  825. {
  826. aiBone* bone = mesh->mBones[j];
  827. String boneName = FromAIString(bone->mName);
  828. unsigned boneIndex = GetBoneIndex(model, boneName);
  829. if (boneIndex == M_MAX_UNSIGNED)
  830. continue;
  831. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  832. {
  833. float weight = bone->mWeights[k].mWeight;
  834. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  835. if (weight > 0.33f)
  836. {
  837. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  838. Vector3 vertex = ToVector3(vertexBoneSpace);
  839. float radius = vertex.Length();
  840. if (radius > model.boneRadii_[boneIndex])
  841. model.boneRadii_[boneIndex] = radius;
  842. model.boneHitboxes_[boneIndex].Merge(vertex);
  843. }
  844. }
  845. }
  846. }
  847. }
  848. void BuildAndSaveModel(OutModel& model)
  849. {
  850. if (!model.rootNode_)
  851. {
  852. PrintLine("Null root node for model, skipping model save");
  853. return;
  854. }
  855. String rootNodeName = FromAIString(model.rootNode_->mName);
  856. if (!model.meshes_.Size())
  857. {
  858. PrintLine("No geometries found starting from node " + rootNodeName + ", skipping model save");
  859. return;
  860. }
  861. PrintLine("Writing model " + rootNodeName);
  862. SharedPtr<Model> outModel(new Model(context_));
  863. Vector<Vector<i32>> allBoneMappings;
  864. BoundingBox box;
  865. unsigned numValidGeometries = 0;
  866. bool combineBuffers = true;
  867. // Check if buffers can be combined (same vertex elements, under 65535 vertices)
  868. Vector<VertexElement> elements = GetVertexElements(model.meshes_[0], model.bones_.Size() > 0);
  869. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  870. {
  871. if (GetNumValidFaces(model.meshes_[i]))
  872. {
  873. ++numValidGeometries;
  874. if (i > 0 && GetVertexElements(model.meshes_[i], model.bones_.Size() > 0) != elements)
  875. combineBuffers = false;
  876. }
  877. }
  878. // Check if keeping separate buffers allows to avoid 32-bit indices
  879. if (combineBuffers && model.totalVertices_ > 65535)
  880. {
  881. bool allUnder65k = true;
  882. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  883. {
  884. if (GetNumValidFaces(model.meshes_[i]))
  885. {
  886. if (model.meshes_[i]->mNumVertices > 65535)
  887. allUnder65k = false;
  888. }
  889. }
  890. if (allUnder65k == true)
  891. combineBuffers = false;
  892. }
  893. SharedPtr<IndexBuffer> ib;
  894. SharedPtr<VertexBuffer> vb;
  895. Vector<SharedPtr<VertexBuffer>> vbVector;
  896. Vector<SharedPtr<IndexBuffer>> ibVector;
  897. unsigned startVertexOffset = 0;
  898. unsigned startIndexOffset = 0;
  899. unsigned destGeomIndex = 0;
  900. bool isSkinned = model.bones_.Size() > 0;
  901. outModel->SetNumGeometries(numValidGeometries);
  902. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  903. {
  904. aiMesh* mesh = model.meshes_[i];
  905. Vector<VertexElement> elements = GetVertexElements(mesh, isSkinned);
  906. unsigned validFaces = GetNumValidFaces(mesh);
  907. if (!validFaces)
  908. continue;
  909. bool largeIndices;
  910. if (combineBuffers)
  911. largeIndices = model.totalIndices_ > 65535;
  912. else
  913. largeIndices = mesh->mNumVertices > 65535;
  914. // Create new buffers if necessary
  915. if (!combineBuffers || vbVector.Empty())
  916. {
  917. vb = new VertexBuffer(context_);
  918. ib = new IndexBuffer(context_);
  919. if (combineBuffers)
  920. {
  921. ib->SetSize(model.totalIndices_, largeIndices);
  922. vb->SetSize(model.totalVertices_, elements);
  923. }
  924. else
  925. {
  926. ib->SetSize(validFaces * 3, largeIndices);
  927. vb->SetSize(mesh->mNumVertices, elements);
  928. }
  929. vbVector.Push(vb);
  930. ibVector.Push(ib);
  931. startVertexOffset = 0;
  932. startIndexOffset = 0;
  933. }
  934. // Get the world transform of the mesh for baking into the vertices
  935. Matrix3x4 vertexTransform;
  936. Matrix3 normalTransform;
  937. Vector3 pos, scale;
  938. Quaternion rot;
  939. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  940. vertexTransform = Matrix3x4(pos, rot, scale);
  941. normalTransform = rot.RotationMatrix();
  942. SharedPtr<Geometry> geom(new Geometry(context_));
  943. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  944. String(validFaces * 3) + " indices");
  945. if (model.bones_.Size() > 0 && !mesh->HasBones())
  946. PrintLine("Warning: model has bones but geometry " + String(i) + " has no skinning information");
  947. byte* vertexData = vb->GetShadowData();
  948. byte* indexData = ib->GetShadowData();
  949. // Build the index data
  950. if (!largeIndices)
  951. {
  952. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  953. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  954. WriteShortIndices(dest, mesh, j, startVertexOffset);
  955. }
  956. else
  957. {
  958. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  959. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  960. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  961. }
  962. // Build the vertex data
  963. // If there are bones, get blend data
  964. Vector<Vector<unsigned char>> blendIndices;
  965. Vector<Vector<float>> blendWeights;
  966. Vector<i32> boneMappings;
  967. if (model.bones_.Size())
  968. GetBlendData(model, mesh, model.meshNodes_[i], boneMappings, blendIndices, blendWeights);
  969. auto* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  970. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  971. WriteVertex(dest, mesh, j, isSkinned, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  972. // Calculate the geometry center
  973. Vector3 center = Vector3::ZERO;
  974. if (validFaces)
  975. {
  976. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  977. {
  978. if (mesh->mFaces[j].mNumIndices == 3)
  979. {
  980. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  981. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  982. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  983. }
  984. }
  985. center /= (float)validFaces * 3;
  986. }
  987. // Define the geometry
  988. geom->SetIndexBuffer(ib);
  989. geom->SetVertexBuffer(0, vb);
  990. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  991. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  992. outModel->SetGeometry(destGeomIndex, 0, geom);
  993. outModel->SetGeometryCenter(destGeomIndex, center);
  994. if (model.bones_.Size() > maxBones_)
  995. allBoneMappings.Push(boneMappings);
  996. startVertexOffset += mesh->mNumVertices;
  997. startIndexOffset += validFaces * 3;
  998. ++destGeomIndex;
  999. }
  1000. // Define the model buffers and bounding box
  1001. Vector<i32> emptyMorphRange;
  1002. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1003. outModel->SetIndexBuffers(ibVector);
  1004. outModel->SetBoundingBox(box);
  1005. // Build skeleton if necessary
  1006. if (model.bones_.Size() && model.rootBone_)
  1007. {
  1008. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  1009. FromAIString(model.rootBone_->mName));
  1010. Skeleton skeleton;
  1011. Vector<Bone>& bones = skeleton.GetModifiableBones();
  1012. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1013. {
  1014. aiNode* boneNode = model.bones_[i];
  1015. String boneName(FromAIString(boneNode->mName));
  1016. Bone newBone;
  1017. newBone.name_ = boneName;
  1018. aiMatrix4x4 transform = boneNode->mTransformation;
  1019. // Make the root bone transform relative to the model's root node, if it is not already
  1020. // (in case there are nodes between that are not accounted for otherwise)
  1021. if (boneNode == model.rootBone_)
  1022. transform = GetDerivedTransform(boneNode, model.rootNode_, false);
  1023. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  1024. // Get offset information if exists
  1025. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  1026. newBone.radius_ = model.boneRadii_[i];
  1027. newBone.boundingBox_ = model.boneHitboxes_[i];
  1028. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  1029. newBone.parentIndex_ = i;
  1030. bones.Push(newBone);
  1031. }
  1032. // Set the bone hierarchy
  1033. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  1034. {
  1035. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  1036. for (unsigned j = 0; j < bones.Size(); ++j)
  1037. {
  1038. if (bones[j].name_ == parentName)
  1039. {
  1040. bones[i].parentIndex_ = j;
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. outModel->SetSkeleton(skeleton);
  1046. if (model.bones_.Size() > maxBones_)
  1047. outModel->SetGeometryBoneMappings(allBoneMappings);
  1048. }
  1049. File outFile(context_);
  1050. if (!outFile.Open(model.outName_, FILE_WRITE))
  1051. ErrorExit("Could not open output file " + model.outName_);
  1052. outModel->Save(outFile);
  1053. // If exporting materials, also save material list for use by the editor
  1054. if (!noMaterials_ && saveMaterialList_)
  1055. {
  1056. String materialListName = ReplaceExtension(model.outName_, ".txt");
  1057. File listFile(context_);
  1058. if (listFile.Open(materialListName, FILE_WRITE))
  1059. {
  1060. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1061. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  1062. }
  1063. else
  1064. PrintLine("Warning: could not write material list file " + materialListName);
  1065. }
  1066. }
  1067. void BuildAndSaveAnimations(OutModel* model)
  1068. {
  1069. // extrapolate anim
  1070. ExtrapolatePivotlessAnimation(model);
  1071. // build and save anim
  1072. const Vector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  1073. for (unsigned i = 0; i < animations.Size(); ++i)
  1074. {
  1075. aiAnimation* anim = animations[i];
  1076. auto duration = (float)anim->mDuration;
  1077. String animName = FromAIString(anim->mName);
  1078. String animOutName;
  1079. float thisImportEndTime = importEndTime_;
  1080. float thisImportStartTime = importStartTime_;
  1081. // If no animation split specified, set the end time to duration
  1082. if (thisImportEndTime == 0.0f)
  1083. thisImportEndTime = duration;
  1084. if (animName.Empty())
  1085. animName = "Anim" + String(i + 1);
  1086. if (model)
  1087. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  1088. else
  1089. animOutName = outPath_ + GetFileName(outName_) + "_" + SanitateAssetName(animName) + ".ani";
  1090. auto ticksPerSecond = (float)anim->mTicksPerSecond;
  1091. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  1092. if (ticksPerSecond < M_EPSILON)
  1093. ticksPerSecond = defaultTicksPerSecond_;
  1094. float tickConversion = 1.0f / ticksPerSecond;
  1095. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  1096. // to start from zero
  1097. float startTime = duration;
  1098. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  1099. {
  1100. aiNodeAnim* channel = anim->mChannels[j];
  1101. if (channel->mNumPositionKeys > 0)
  1102. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  1103. if (channel->mNumRotationKeys > 0)
  1104. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  1105. if (channel->mNumScalingKeys > 0)
  1106. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  1107. }
  1108. if (startTime > thisImportStartTime)
  1109. thisImportStartTime = startTime;
  1110. duration = thisImportEndTime - thisImportStartTime;
  1111. SharedPtr<Animation> outAnim(new Animation(context_));
  1112. outAnim->SetAnimationName(animName);
  1113. outAnim->SetLength(duration * tickConversion);
  1114. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  1115. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  1116. {
  1117. aiNodeAnim* channel = anim->mChannels[j];
  1118. String channelName = FromAIString(channel->mNodeName);
  1119. aiNode* boneNode = nullptr;
  1120. if (model)
  1121. {
  1122. unsigned boneIndex;
  1123. i32 pos = channelName.Find("_$AssimpFbx$");
  1124. if (!suppressFbxPivotNodes_ || pos == String::NPOS)
  1125. {
  1126. boneIndex = GetBoneIndex(*model, channelName);
  1127. if (boneIndex == M_MAX_UNSIGNED)
  1128. {
  1129. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  1130. outAnim->RemoveTrack(channelName);
  1131. continue;
  1132. }
  1133. boneNode = model->bones_[boneIndex];
  1134. }
  1135. else
  1136. {
  1137. channelName = channelName.Substring(0, pos);
  1138. // every first $fbx animation channel for a bone will consolidate other $fbx animation to a single channel
  1139. // skip subsequent $fbx animation channel for the same bone
  1140. if (outAnim->GetTrack(channelName) != nullptr)
  1141. continue;
  1142. boneIndex = GetPivotlessBoneIndex(*model, channelName);
  1143. if (boneIndex == M_MAX_UNSIGNED)
  1144. {
  1145. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  1146. outAnim->RemoveTrack(channelName);
  1147. continue;
  1148. }
  1149. boneNode = model->pivotlessBones_[boneIndex];
  1150. }
  1151. }
  1152. else
  1153. {
  1154. boneNode = GetNode(channelName, scene_->mRootNode);
  1155. if (!boneNode)
  1156. {
  1157. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  1158. outAnim->RemoveTrack(channelName);
  1159. continue;
  1160. }
  1161. }
  1162. // To export single frame animation, check if first key frame is identical to bone transformation
  1163. aiVector3D bonePos, boneScale;
  1164. aiQuaternion boneRot;
  1165. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  1166. bool posEqual = true;
  1167. bool scaleEqual = true;
  1168. bool rotEqual = true;
  1169. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  1170. posEqual = false;
  1171. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  1172. scaleEqual = false;
  1173. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  1174. rotEqual = false;
  1175. AnimationTrack* track = outAnim->CreateTrack(channelName);
  1176. // Check which channels are used
  1177. track->channelMask_ = AnimationChannels::None;
  1178. if (channel->mNumPositionKeys > 1 || !posEqual)
  1179. track->channelMask_ |= AnimationChannels::Position;
  1180. if (channel->mNumRotationKeys > 1 || !rotEqual)
  1181. track->channelMask_ |= AnimationChannels::Rotation;
  1182. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  1183. track->channelMask_ |= AnimationChannels::Scale;
  1184. // Check for redundant identity scale in all keyframes and remove in that case
  1185. if (!!(track->channelMask_ & AnimationChannels::Scale))
  1186. {
  1187. bool redundantScale = true;
  1188. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  1189. {
  1190. float SCALE_EPSILON = 0.000001f;
  1191. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  1192. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  1193. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  1194. {
  1195. redundantScale = false;
  1196. break;
  1197. }
  1198. }
  1199. if (redundantScale)
  1200. track->channelMask_ &= ~AnimationChannels::Scale;
  1201. }
  1202. if (!track->channelMask_)
  1203. {
  1204. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  1205. outAnim->RemoveTrack(channelName);
  1206. continue;
  1207. }
  1208. // Currently only same amount of keyframes is supported
  1209. // Note: should also check the times of individual keyframes for match
  1210. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  1211. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  1212. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  1213. {
  1214. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  1215. outAnim->RemoveTrack(channelName);
  1216. continue;
  1217. }
  1218. unsigned keyFrames = channel->mNumPositionKeys;
  1219. if (channel->mNumRotationKeys > keyFrames)
  1220. keyFrames = channel->mNumRotationKeys;
  1221. if (channel->mNumScalingKeys > keyFrames)
  1222. keyFrames = channel->mNumScalingKeys;
  1223. for (unsigned k = 0; k < keyFrames; ++k)
  1224. {
  1225. AnimationKeyFrame kf;
  1226. kf.time_ = 0.0f;
  1227. kf.position_ = Vector3::ZERO;
  1228. kf.rotation_ = Quaternion::IDENTITY;
  1229. kf.scale_ = Vector3::ONE;
  1230. // Get time for the keyframe. Adjust with animation's start time
  1231. if (!!(track->channelMask_ & AnimationChannels::Position) && k < channel->mNumPositionKeys)
  1232. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime);
  1233. else if (!!(track->channelMask_ & AnimationChannels::Rotation) && k < channel->mNumRotationKeys)
  1234. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime);
  1235. else if (!!(track->channelMask_ & AnimationChannels::Scale) && k < channel->mNumScalingKeys)
  1236. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime);
  1237. // Make sure time stays positive
  1238. kf.time_ = Max(kf.time_, 0.0f);
  1239. // Start with the bone's base transform
  1240. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  1241. aiVector3D pos, scale;
  1242. aiQuaternion rot;
  1243. boneTransform.Decompose(scale, rot, pos);
  1244. // Then apply the active channels
  1245. if (!!(track->channelMask_ & AnimationChannels::Position) && k < channel->mNumPositionKeys)
  1246. pos = channel->mPositionKeys[k].mValue;
  1247. if (!!(track->channelMask_ & AnimationChannels::Rotation) && k < channel->mNumRotationKeys)
  1248. rot = channel->mRotationKeys[k].mValue;
  1249. if (!!(track->channelMask_ & AnimationChannels::Scale) && k < channel->mNumScalingKeys)
  1250. scale = channel->mScalingKeys[k].mValue;
  1251. // If root bone, transform with nodes in between model root node (if any)
  1252. if (model && boneNode == model->rootBone_)
  1253. {
  1254. aiMatrix4x4 transMat, scaleMat, rotMat;
  1255. aiMatrix4x4::Translation(pos, transMat);
  1256. aiMatrix4x4::Scaling(scale, scaleMat);
  1257. rotMat = aiMatrix4x4(rot.GetMatrix());
  1258. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1259. aiMatrix4x4 tformOld = tform;
  1260. tform = GetDerivedTransform(tform, boneNode, model->rootNode_, false);
  1261. // Do not decompose if did not actually change
  1262. if (tform != tformOld)
  1263. tform.Decompose(scale, rot, pos);
  1264. }
  1265. if (!!(track->channelMask_ & AnimationChannels::Position))
  1266. kf.position_ = ToVector3(pos);
  1267. if (!!(track->channelMask_ & AnimationChannels::Rotation))
  1268. kf.rotation_ = ToQuaternion(rot);
  1269. if (!!(track->channelMask_ & AnimationChannels::Scale))
  1270. kf.scale_ = ToVector3(scale);
  1271. if (kf.time_ >= thisImportStartTime && kf.time_ <= thisImportEndTime)
  1272. {
  1273. kf.time_ = (kf.time_ - thisImportStartTime) * tickConversion;
  1274. track->keyFrames_.Push(kf);
  1275. }
  1276. }
  1277. }
  1278. File outFile(context_);
  1279. if (!outFile.Open(animOutName, FILE_WRITE))
  1280. ErrorExit("Could not open output file " + animOutName);
  1281. outAnim->Save(outFile);
  1282. }
  1283. }
  1284. void ExportScene(const String& outName, bool asPrefab)
  1285. {
  1286. OutScene outScene;
  1287. outScene.outName_ = outName;
  1288. outScene.rootNode_ = rootNode_;
  1289. if (useSubdirs_)
  1290. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  1291. CollectSceneModels(outScene, rootNode_);
  1292. // Save models, their material lists and animations
  1293. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  1294. BuildAndSaveModel(outScene.models_[i]);
  1295. // Save scene-global animations
  1296. if (!noAnimations_)
  1297. {
  1298. CollectAnimations();
  1299. BuildAndSaveAnimations();
  1300. }
  1301. // Save scene
  1302. BuildAndSaveScene(outScene, asPrefab);
  1303. }
  1304. void CollectSceneModels(OutScene& scene, aiNode* node)
  1305. {
  1306. Vector<Pair<aiNode*, aiMesh*>> meshes;
  1307. GetMeshesUnderNode(meshes, node);
  1308. if (meshes.Size())
  1309. {
  1310. OutModel model;
  1311. model.rootNode_ = node;
  1312. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  1313. for (unsigned i = 0; i < meshes.Size(); ++i)
  1314. {
  1315. aiMesh* mesh = meshes[i].second_;
  1316. unsigned meshIndex = GetMeshIndex(mesh);
  1317. model.meshIndices_.Insert(meshIndex);
  1318. model.meshes_.Push(mesh);
  1319. model.meshNodes_.Push(meshes[i].first_);
  1320. model.totalVertices_ += mesh->mNumVertices;
  1321. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  1322. }
  1323. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  1324. bool unique = true;
  1325. if (checkUniqueModel_)
  1326. {
  1327. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  1328. {
  1329. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  1330. {
  1331. PrintLine("Added node " + FromAIString(node->mName));
  1332. scene.nodes_.Push(node);
  1333. scene.nodeModelIndices_.Push(i);
  1334. unique = false;
  1335. break;
  1336. }
  1337. }
  1338. }
  1339. if (unique)
  1340. {
  1341. PrintLine("Added model " + model.outName_);
  1342. PrintLine("Added node " + FromAIString(node->mName));
  1343. CollectBones(model);
  1344. BuildBoneCollisionInfo(model);
  1345. if (!noAnimations_)
  1346. {
  1347. CollectAnimations(&model);
  1348. BuildAndSaveAnimations(&model);
  1349. }
  1350. scene.models_.Push(model);
  1351. scene.nodes_.Push(node);
  1352. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  1353. }
  1354. }
  1355. for (unsigned i = 0; i < node->mNumChildren; ++i)
  1356. CollectSceneModels(scene, node->mChildren[i]);
  1357. }
  1358. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1359. {
  1360. CreateSceneNode(scene, srcNode, nodeMapping);
  1361. for (unsigned i = 0; i < srcNode->mNumChildren; ++i)
  1362. CreateHierarchy(scene, srcNode->mChildren[i], nodeMapping);
  1363. }
  1364. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1365. {
  1366. if (nodeMapping.Contains(srcNode))
  1367. return nodeMapping[srcNode];
  1368. // Flatten hierarchy if requested
  1369. if (noHierarchy_)
  1370. {
  1371. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1372. Vector3 pos, scale;
  1373. Quaternion rot;
  1374. GetPosRotScale(GetDerivedTransform(srcNode, rootNode_), pos, rot, scale);
  1375. outNode->SetTransform(pos, rot, scale);
  1376. nodeMapping[srcNode] = outNode;
  1377. return outNode;
  1378. }
  1379. if (srcNode == rootNode_ || !srcNode->mParent)
  1380. {
  1381. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1382. Vector3 pos, scale;
  1383. Quaternion rot;
  1384. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1385. outNode->SetTransform(pos, rot, scale);
  1386. nodeMapping[srcNode] = outNode;
  1387. return outNode;
  1388. }
  1389. else
  1390. {
  1391. // Ensure the existence of the parent chain as in the original file
  1392. if (!nodeMapping.Contains(srcNode->mParent))
  1393. CreateSceneNode(scene, srcNode->mParent, nodeMapping);
  1394. Node* parent = nodeMapping[srcNode->mParent];
  1395. Node* outNode = parent->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1396. Vector3 pos, scale;
  1397. Quaternion rot;
  1398. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1399. outNode->SetTransform(pos, rot, scale);
  1400. nodeMapping[srcNode] = outNode;
  1401. return outNode;
  1402. }
  1403. }
  1404. void BuildAndSaveScene(OutScene& scene, bool asPrefab)
  1405. {
  1406. if (!asPrefab)
  1407. PrintLine("Writing scene");
  1408. else
  1409. PrintLine("Writing node hierarchy");
  1410. SharedPtr<Scene> outScene(new Scene(context_));
  1411. if (!asPrefab)
  1412. {
  1413. #ifdef URHO3D_PHYSICS
  1414. /// \todo Make the physics properties configurable
  1415. outScene->CreateComponent<PhysicsWorld>();
  1416. #endif
  1417. /// \todo Make the octree properties configurable, or detect from the scene contents
  1418. outScene->CreateComponent<Octree>();
  1419. outScene->CreateComponent<DebugRenderer>();
  1420. if (createZone_)
  1421. {
  1422. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  1423. auto* zone = zoneNode->CreateComponent<Zone>();
  1424. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  1425. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  1426. // Create default light only if scene does not define them
  1427. if (!scene_->HasLights())
  1428. {
  1429. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  1430. auto* light = lightNode->CreateComponent<Light>();
  1431. light->SetLightType(LIGHT_DIRECTIONAL);
  1432. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  1433. }
  1434. }
  1435. }
  1436. auto* cache = context_->GetSubsystem<ResourceCache>();
  1437. HashMap<aiNode*, Node*> nodeMapping;
  1438. Node* outRootNode = nullptr;
  1439. if (asPrefab)
  1440. outRootNode = CreateSceneNode(outScene, rootNode_, nodeMapping);
  1441. else
  1442. {
  1443. // If not saving as a prefab, associate the root node with the scene first to prevent unnecessary creation of a root
  1444. // However do not do that if the root node does not have an identity matrix, or itself contains a model
  1445. // (models at the Urho scene root are not preferable)
  1446. if (ToMatrix3x4(rootNode_->mTransformation).Equals(Matrix3x4::IDENTITY) && !scene.nodes_.Contains(rootNode_))
  1447. nodeMapping[rootNode_] = outScene;
  1448. }
  1449. // If is allowed to export empty nodes, export the full Assimp node hierarchy first
  1450. if (!noHierarchy_ && !noEmptyNodes_)
  1451. CreateHierarchy(outScene, rootNode_, nodeMapping);
  1452. // Create geometry nodes
  1453. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  1454. {
  1455. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  1456. Node* modelNode = CreateSceneNode(outScene, scene.nodes_[i], nodeMapping);
  1457. auto* staticModel =
  1458. static_cast<StaticModel*>(
  1459. model.bones_.Empty() ? modelNode->CreateComponent<StaticModel>() : modelNode->CreateComponent<AnimatedModel>());
  1460. // Create a dummy model so that the reference can be stored
  1461. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  1462. if (!cache->Exists(modelName))
  1463. {
  1464. auto* dummyModel = new Model(context_);
  1465. dummyModel->SetName(modelName);
  1466. dummyModel->SetNumGeometries(model.meshes_.Size());
  1467. cache->AddManualResource(dummyModel);
  1468. }
  1469. staticModel->SetModel(cache->GetResource<Model>(modelName));
  1470. // Set materials if they are known
  1471. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1472. {
  1473. String matName = GetMeshMaterialName(model.meshes_[j]);
  1474. // Create a dummy material so that the reference can be stored
  1475. if (!cache->Exists(matName))
  1476. {
  1477. auto* dummyMat = new Material(context_);
  1478. dummyMat->SetName(matName);
  1479. cache->AddManualResource(dummyMat);
  1480. }
  1481. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1482. }
  1483. }
  1484. // Create lights
  1485. if (!asPrefab)
  1486. {
  1487. for (unsigned i = 0; i < scene_->mNumLights; ++i)
  1488. {
  1489. aiLight* light = scene_->mLights[i];
  1490. aiNode* lightNode = GetNode(FromAIString(light->mName), rootNode_, true);
  1491. if (!lightNode)
  1492. continue;
  1493. Node* outNode = CreateSceneNode(outScene, lightNode, nodeMapping);
  1494. Vector3 lightAdjustPosition = ToVector3(light->mPosition);
  1495. Vector3 lightAdjustDirection = ToVector3(light->mDirection);
  1496. // If light is not aligned at the scene node, an adjustment node needs to be created
  1497. if (!lightAdjustPosition.Equals(Vector3::ZERO) || (light->mType != aiLightSource_POINT &&
  1498. !lightAdjustDirection.Equals(Vector3::FORWARD)))
  1499. {
  1500. outNode = outNode->CreateChild("LightAdjust");
  1501. outNode->SetPosition(lightAdjustPosition);
  1502. outNode->SetDirection(lightAdjustDirection);
  1503. }
  1504. auto* outLight = outNode->CreateComponent<Light>();
  1505. outLight->SetColor(Color(light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b));
  1506. switch (light->mType)
  1507. {
  1508. case aiLightSource_DIRECTIONAL:
  1509. outLight->SetLightType(LIGHT_DIRECTIONAL);
  1510. break;
  1511. case aiLightSource_SPOT:
  1512. outLight->SetLightType(LIGHT_SPOT);
  1513. outLight->SetFov(light->mAngleOuterCone * 0.5f * M_RADTODEG);
  1514. break;
  1515. case aiLightSource_POINT:
  1516. outLight->SetLightType(LIGHT_POINT);
  1517. break;
  1518. default:
  1519. break;
  1520. }
  1521. // Calculate range from attenuation parameters so that light intensity has been reduced to 10% at that distance
  1522. if (light->mType != aiLightSource_DIRECTIONAL)
  1523. {
  1524. float a = light->mAttenuationQuadratic;
  1525. float b = light->mAttenuationLinear;
  1526. float c = -10.0f;
  1527. if (!Equals(a, 0.0f))
  1528. {
  1529. float root1 = (-b + sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1530. float root2 = (-b - sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1531. outLight->SetRange(Max(root1, root2));
  1532. }
  1533. else if (!Equals(b, 0.0f))
  1534. outLight->SetRange(-c / b);
  1535. }
  1536. }
  1537. }
  1538. File file(context_);
  1539. if (!file.Open(scene.outName_, FILE_WRITE))
  1540. ErrorExit("Could not open output file " + scene.outName_);
  1541. if (!asPrefab)
  1542. {
  1543. if (saveBinary_)
  1544. outScene->Save(file);
  1545. else if (saveJson_)
  1546. outScene->SaveJSON(file);
  1547. else
  1548. outScene->SaveXML(file);
  1549. }
  1550. else
  1551. {
  1552. if (saveBinary_)
  1553. outRootNode->Save(file);
  1554. else if (saveJson_)
  1555. outRootNode->SaveJSON(file);
  1556. else
  1557. outRootNode->SaveXML(file);
  1558. }
  1559. }
  1560. void ExportMaterials(HashSet<String>& usedTextures)
  1561. {
  1562. if (useSubdirs_)
  1563. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1564. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1565. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1566. }
  1567. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1568. {
  1569. aiString matNameStr;
  1570. material->Get(AI_MATKEY_NAME, matNameStr);
  1571. String matName = SanitateAssetName(FromAIString(matNameStr));
  1572. if (matName.Trimmed().Empty())
  1573. matName = GenerateMaterialName(material);
  1574. // Do not actually create a material instance, but instead craft an xml file manually
  1575. XMLFile outMaterial(context_);
  1576. XMLElement materialElem = outMaterial.CreateRoot("material");
  1577. String diffuseTexName;
  1578. String normalTexName;
  1579. String specularTexName;
  1580. String lightmapTexName;
  1581. String emissiveTexName;
  1582. Color diffuseColor = Color::WHITE;
  1583. Color specularColor;
  1584. Color emissiveColor = Color::BLACK;
  1585. bool hasAlpha = false;
  1586. bool twoSided = false;
  1587. float specPower = 1.0f;
  1588. aiString stringVal;
  1589. float floatVal;
  1590. int intVal;
  1591. aiColor3D colorVal;
  1592. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1593. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1594. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1595. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1596. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1597. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1598. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1599. lightmapTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1600. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1601. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1602. if (!noMaterialDiffuseColor_)
  1603. {
  1604. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1605. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1606. }
  1607. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1608. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1609. if (!emissiveAO_)
  1610. {
  1611. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1612. emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1613. }
  1614. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1615. {
  1616. /// \hack New Assimp behavior - some materials may return 0 opacity, which is invisible.
  1617. /// Revert to full opacity in that case
  1618. if (floatVal < M_EPSILON)
  1619. floatVal = 1.0f;
  1620. if (floatVal < 1.0f)
  1621. hasAlpha = true;
  1622. diffuseColor.a_ = floatVal;
  1623. }
  1624. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1625. specPower = floatVal;
  1626. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1627. twoSided = (intVal != 0);
  1628. String techniqueName = "Techniques/NoTexture";
  1629. if (!diffuseTexName.Empty())
  1630. {
  1631. techniqueName = "Techniques/Diff";
  1632. if (!normalTexName.Empty())
  1633. techniqueName += "Normal";
  1634. if (!specularTexName.Empty())
  1635. techniqueName += "Spec";
  1636. // For now lightmap does not coexist with normal & specular
  1637. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1638. techniqueName += "LightMap";
  1639. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1640. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1641. }
  1642. if (hasAlpha)
  1643. techniqueName += "Alpha";
  1644. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1645. techniqueElem.SetString("name", techniqueName + ".xml");
  1646. if (!diffuseTexName.Empty())
  1647. {
  1648. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1649. diffuseElem.SetString("unit", "diffuse");
  1650. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1651. usedTextures.Insert(diffuseTexName);
  1652. }
  1653. if (!normalTexName.Empty())
  1654. {
  1655. XMLElement normalElem = materialElem.CreateChild("texture");
  1656. normalElem.SetString("unit", "normal");
  1657. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1658. usedTextures.Insert(normalTexName);
  1659. }
  1660. if (!specularTexName.Empty())
  1661. {
  1662. XMLElement specularElem = materialElem.CreateChild("texture");
  1663. specularElem.SetString("unit", "specular");
  1664. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1665. usedTextures.Insert(specularTexName);
  1666. }
  1667. if (!lightmapTexName.Empty())
  1668. {
  1669. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1670. lightmapElem.SetString("unit", "emissive");
  1671. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1672. usedTextures.Insert(lightmapTexName);
  1673. }
  1674. if (!emissiveTexName.Empty())
  1675. {
  1676. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1677. emissiveElem.SetString("unit", "emissive");
  1678. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1679. usedTextures.Insert(emissiveTexName);
  1680. }
  1681. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1682. diffuseColorElem.SetString("name", "MatDiffColor");
  1683. diffuseColorElem.SetColor("value", diffuseColor);
  1684. XMLElement specularElem = materialElem.CreateChild("parameter");
  1685. specularElem.SetString("name", "MatSpecColor");
  1686. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1687. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1688. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1689. emissiveColorElem.SetColor("value", emissiveColor);
  1690. if (twoSided)
  1691. {
  1692. XMLElement cullElem = materialElem.CreateChild("cull");
  1693. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1694. cullElem.SetString("value", "none");
  1695. shadowCullElem.SetString("value", "none");
  1696. }
  1697. auto* fileSystem = context_->GetSubsystem<FileSystem>();
  1698. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1699. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1700. {
  1701. PrintLine("Skipping save of existing material " + matName);
  1702. return;
  1703. }
  1704. PrintLine("Writing material " + matName);
  1705. File outFile(context_);
  1706. if (!outFile.Open(outFileName, FILE_WRITE))
  1707. ErrorExit("Could not open output file " + outFileName);
  1708. outMaterial.Save(outFile);
  1709. }
  1710. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1711. {
  1712. auto* fileSystem = context_->GetSubsystem<FileSystem>();
  1713. if (useSubdirs_)
  1714. fileSystem->CreateDir(resourcePath_ + "Textures");
  1715. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1716. {
  1717. // Handle assimp embedded textures
  1718. if (i->Length() && i->At(0) == '*')
  1719. {
  1720. unsigned texIndex = ToI32(i->Substring(1));
  1721. if (texIndex >= scene_->mNumTextures)
  1722. PrintLine("Skipping out of range texture index " + String(texIndex));
  1723. else
  1724. {
  1725. aiTexture* tex = scene_->mTextures[texIndex];
  1726. String fullDestName = resourcePath_ + GenerateTextureName(texIndex);
  1727. bool destExists = fileSystem->FileExists(fullDestName);
  1728. if (destExists && noOverwriteTexture_)
  1729. {
  1730. PrintLine("Skipping copy of existing embedded texture " + GetFileNameAndExtension(fullDestName));
  1731. continue;
  1732. }
  1733. // Encoded texture
  1734. if (!tex->mHeight)
  1735. {
  1736. PrintLine("Saving embedded texture " + GetFileNameAndExtension(fullDestName));
  1737. File dest(context_, fullDestName, FILE_WRITE);
  1738. dest.Write((const void*)tex->pcData, tex->mWidth);
  1739. }
  1740. // RGBA8 texture
  1741. else
  1742. {
  1743. PrintLine("Saving embedded RGBA texture " + GetFileNameAndExtension(fullDestName));
  1744. Image image(context_);
  1745. image.SetSize(tex->mWidth, tex->mHeight, 4);
  1746. memcpy(image.GetData(), (const void*)tex->pcData, (size_t)tex->mWidth * tex->mHeight * 4);
  1747. image.SavePNG(fullDestName);
  1748. }
  1749. }
  1750. }
  1751. else
  1752. {
  1753. String fullSourceName = sourcePath + *i;
  1754. String fullDestName = resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i;
  1755. if (!fileSystem->FileExists(fullSourceName))
  1756. {
  1757. PrintLine("Skipping copy of nonexisting material texture " + *i);
  1758. continue;
  1759. }
  1760. {
  1761. File test(context_, fullSourceName);
  1762. if (!test.GetSize())
  1763. {
  1764. PrintLine("Skipping copy of zero-size material texture " + *i);
  1765. continue;
  1766. }
  1767. }
  1768. bool destExists = fileSystem->FileExists(fullDestName);
  1769. if (destExists && noOverwriteTexture_)
  1770. {
  1771. PrintLine("Skipping copy of existing texture " + *i);
  1772. continue;
  1773. }
  1774. if (destExists && noOverwriteNewerTexture_ && fileSystem->GetLastModifiedTime(fullDestName) >
  1775. fileSystem->GetLastModifiedTime(fullSourceName))
  1776. {
  1777. PrintLine("Skipping copying of material texture " + *i + ", destination is newer");
  1778. continue;
  1779. }
  1780. PrintLine("Copying material texture " + *i);
  1781. fileSystem->Copy(fullSourceName, fullDestName);
  1782. }
  1783. }
  1784. }
  1785. void CombineLods(const Vector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1786. {
  1787. // Load models
  1788. Vector<SharedPtr<Model>> srcModels;
  1789. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1790. {
  1791. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1792. File srcFile(context_);
  1793. srcFile.Open(modelNames[i]);
  1794. SharedPtr<Model> srcModel(new Model(context_));
  1795. if (!srcModel->Load(srcFile))
  1796. ErrorExit("Could not load input model " + modelNames[i]);
  1797. srcModels.Push(srcModel);
  1798. }
  1799. // Check that none of the models already has LOD levels
  1800. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1801. {
  1802. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1803. {
  1804. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1805. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1806. }
  1807. }
  1808. // Check for number of geometries (need to have same amount for now)
  1809. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1810. {
  1811. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1812. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1813. }
  1814. // If there are bones, check for compatibility (need to have exact match for now)
  1815. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1816. {
  1817. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1818. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1819. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1820. {
  1821. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1822. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1823. }
  1824. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1825. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1826. }
  1827. Vector<SharedPtr<VertexBuffer>> vbVector;
  1828. Vector<SharedPtr<IndexBuffer>> ibVector;
  1829. Vector<i32> emptyMorphRange;
  1830. // Create the final model
  1831. SharedPtr<Model> outModel(new Model(context_));
  1832. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1833. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1834. {
  1835. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1836. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1837. {
  1838. Geometry* geometry = srcModels[j]->GetGeometry(i, 0);
  1839. geometry->SetLodDistance(lodDistances[j]);
  1840. outModel->SetGeometry(i, j, geometry);
  1841. for (unsigned k = 0; k < geometry->GetNumVertexBuffers(); ++k)
  1842. {
  1843. SharedPtr<VertexBuffer> vb(geometry->GetVertexBuffer(k));
  1844. if (!vbVector.Contains(vb))
  1845. vbVector.Push(vb);
  1846. }
  1847. SharedPtr<IndexBuffer> ib(geometry->GetIndexBuffer());
  1848. if (!ibVector.Contains(ib))
  1849. ibVector.Push(ib);
  1850. }
  1851. }
  1852. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1853. outModel->SetIndexBuffers(ibVector);
  1854. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1855. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1856. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1857. /// \todo Vertex morphs are ignored for now
  1858. // Save the final model
  1859. PrintLine("Writing output model");
  1860. File outFile(context_);
  1861. if (!outFile.Open(outName, FILE_WRITE))
  1862. ErrorExit("Could not open output file " + outName);
  1863. outModel->Save(outFile);
  1864. }
  1865. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*>>& dest, aiNode* node)
  1866. {
  1867. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1868. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1869. }
  1870. unsigned GetMeshIndex(aiMesh* mesh)
  1871. {
  1872. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1873. {
  1874. if (scene_->mMeshes[i] == mesh)
  1875. return i;
  1876. }
  1877. return M_MAX_UNSIGNED;
  1878. }
  1879. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1880. {
  1881. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1882. {
  1883. if (boneName == model.bones_[i]->mName.data)
  1884. return i;
  1885. }
  1886. return M_MAX_UNSIGNED;
  1887. }
  1888. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1889. {
  1890. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1891. {
  1892. aiMesh* mesh = model.meshes_[i];
  1893. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1894. {
  1895. aiBone* bone = mesh->mBones[j];
  1896. if (boneName == bone->mName.data)
  1897. return bone;
  1898. }
  1899. }
  1900. return nullptr;
  1901. }
  1902. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1903. {
  1904. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1905. {
  1906. aiMesh* mesh = model.meshes_[i];
  1907. aiNode* node = model.meshNodes_[i];
  1908. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1909. {
  1910. aiBone* bone = mesh->mBones[j];
  1911. if (boneName == bone->mName.data)
  1912. {
  1913. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1914. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1915. nodeDerivedInverse.Inverse();
  1916. offset *= nodeDerivedInverse;
  1917. return ToMatrix3x4(offset);
  1918. }
  1919. }
  1920. }
  1921. // Fallback for rigid skinning for which actual offset matrix information doesn't exist
  1922. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1923. {
  1924. aiMesh* mesh = model.meshes_[i];
  1925. aiNode* node = model.meshNodes_[i];
  1926. if (!mesh->HasBones() && boneName == node->mName.data)
  1927. {
  1928. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1929. nodeDerivedInverse.Inverse();
  1930. return ToMatrix3x4(nodeDerivedInverse);
  1931. }
  1932. }
  1933. return Matrix3x4::IDENTITY;
  1934. }
  1935. void GetBlendData(OutModel& model, aiMesh* mesh, aiNode* meshNode, Vector<i32>& boneMappings, Vector<Vector<unsigned char>>&
  1936. blendIndices, Vector<Vector<float>>& blendWeights)
  1937. {
  1938. blendIndices.Resize(mesh->mNumVertices);
  1939. blendWeights.Resize(mesh->mNumVertices);
  1940. boneMappings.Clear();
  1941. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1942. if (model.bones_.Size() > maxBones_)
  1943. {
  1944. if (mesh->mNumBones > maxBones_)
  1945. {
  1946. ErrorExit(
  1947. "Geometry (submesh) has over " + String(maxBones_) + " bone influences. Try splitting to more submeshes\n"
  1948. "that each stay at " + String(maxBones_) + " bones or below."
  1949. );
  1950. }
  1951. if (mesh->mNumBones > 0)
  1952. {
  1953. boneMappings.Resize(mesh->mNumBones);
  1954. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1955. {
  1956. aiBone* bone = mesh->mBones[i];
  1957. String boneName = FromAIString(bone->mName);
  1958. unsigned globalIndex = GetBoneIndex(model, boneName);
  1959. if (globalIndex == M_MAX_UNSIGNED)
  1960. ErrorExit("Bone " + boneName + " not found");
  1961. boneMappings[i] = globalIndex;
  1962. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1963. {
  1964. unsigned vertex = bone->mWeights[j].mVertexId;
  1965. blendIndices[vertex].Push(i);
  1966. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1967. }
  1968. }
  1969. }
  1970. else
  1971. {
  1972. // If mesh does not have skinning information, implement rigid skinning so that it stays compatible with AnimatedModel
  1973. String boneName = FromAIString(meshNode->mName);
  1974. unsigned globalIndex = GetBoneIndex(model, boneName);
  1975. if (globalIndex == M_MAX_UNSIGNED)
  1976. PrintLine("Warning: bone " + boneName + " not found, skipping rigid skinning");
  1977. else
  1978. {
  1979. boneMappings.Push(globalIndex);
  1980. for (unsigned i = 0; i < mesh->mNumVertices; ++i)
  1981. {
  1982. blendIndices[i].Push(0);
  1983. blendWeights[i].Push(1.0f);
  1984. }
  1985. }
  1986. }
  1987. }
  1988. else
  1989. {
  1990. if (mesh->mNumBones > 0)
  1991. {
  1992. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1993. {
  1994. aiBone* bone = mesh->mBones[i];
  1995. String boneName = FromAIString(bone->mName);
  1996. unsigned globalIndex = GetBoneIndex(model, boneName);
  1997. if (globalIndex == M_MAX_UNSIGNED)
  1998. ErrorExit("Bone " + boneName + " not found");
  1999. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  2000. {
  2001. unsigned vertex = bone->mWeights[j].mVertexId;
  2002. blendIndices[vertex].Push(globalIndex);
  2003. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  2004. }
  2005. }
  2006. }
  2007. else
  2008. {
  2009. String boneName = FromAIString(meshNode->mName);
  2010. unsigned globalIndex = GetBoneIndex(model, boneName);
  2011. if (globalIndex == M_MAX_UNSIGNED)
  2012. PrintLine("Warning: bone " + boneName + " not found, skipping rigid skinning");
  2013. else
  2014. {
  2015. for (unsigned i = 0; i < mesh->mNumVertices; ++i)
  2016. {
  2017. blendIndices[i].Push(globalIndex);
  2018. blendWeights[i].Push(1.0f);
  2019. }
  2020. }
  2021. }
  2022. }
  2023. // Normalize weights now if necessary, also remove too many influences
  2024. for (unsigned i = 0; i < blendWeights.Size(); ++i)
  2025. {
  2026. if (blendWeights[i].Size() > 4)
  2027. {
  2028. PrintLine("Warning: more than 4 bone influences in vertex " + String(i));
  2029. while (blendWeights[i].Size() > 4)
  2030. {
  2031. unsigned lowestIndex = 0;
  2032. float lowest = M_INFINITY;
  2033. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2034. {
  2035. if (blendWeights[i][j] < lowest)
  2036. {
  2037. lowest = blendWeights[i][j];
  2038. lowestIndex = j;
  2039. }
  2040. }
  2041. blendWeights[i].Erase(lowestIndex);
  2042. blendIndices[i].Erase(lowestIndex);
  2043. }
  2044. }
  2045. float sum = 0.0f;
  2046. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2047. sum += blendWeights[i][j];
  2048. if (sum != 1.0f && sum != 0.0f)
  2049. {
  2050. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2051. blendWeights[i][j] /= sum;
  2052. }
  2053. }
  2054. }
  2055. String GetMeshMaterialName(aiMesh* mesh)
  2056. {
  2057. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  2058. aiString matNameStr;
  2059. material->Get(AI_MATKEY_NAME, matNameStr);
  2060. String matName = SanitateAssetName(FromAIString(matNameStr));
  2061. if (matName.Trimmed().Empty())
  2062. matName = GenerateMaterialName(material);
  2063. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  2064. }
  2065. String GenerateMaterialName(aiMaterial* material)
  2066. {
  2067. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  2068. {
  2069. if (scene_->mMaterials[i] == material)
  2070. return inputName_ + "_Material" + String(i);
  2071. }
  2072. // Should not go here
  2073. return String::EMPTY;
  2074. }
  2075. String GetMaterialTextureName(const String& nameIn)
  2076. {
  2077. // Detect assimp embedded texture
  2078. if (nameIn.Length() && nameIn[0] == '*')
  2079. return GenerateTextureName(ToI32(nameIn.Substring(1)));
  2080. else
  2081. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  2082. }
  2083. String GenerateTextureName(unsigned texIndex)
  2084. {
  2085. if (texIndex < scene_->mNumTextures)
  2086. {
  2087. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  2088. aiTexture* tex = scene_->mTextures[texIndex];
  2089. if (!tex->mHeight)
  2090. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  2091. else
  2092. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  2093. }
  2094. // Should not go here
  2095. return String::EMPTY;
  2096. }
  2097. unsigned GetNumValidFaces(aiMesh* mesh)
  2098. {
  2099. unsigned ret = 0;
  2100. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  2101. {
  2102. if (mesh->mFaces[j].mNumIndices == 3)
  2103. ++ret;
  2104. }
  2105. return ret;
  2106. }
  2107. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  2108. {
  2109. if (mesh->mFaces[index].mNumIndices == 3)
  2110. {
  2111. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  2112. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  2113. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  2114. }
  2115. }
  2116. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  2117. {
  2118. if (mesh->mFaces[index].mNumIndices == 3)
  2119. {
  2120. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  2121. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  2122. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  2123. }
  2124. }
  2125. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, bool isSkinned, BoundingBox& box,
  2126. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<Vector<unsigned char>>& blendIndices,
  2127. Vector<Vector<float>>& blendWeights)
  2128. {
  2129. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  2130. box.Merge(vertex);
  2131. *dest++ = vertex.x_;
  2132. *dest++ = vertex.y_;
  2133. *dest++ = vertex.z_;
  2134. if (mesh->HasNormals())
  2135. {
  2136. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  2137. *dest++ = normal.x_;
  2138. *dest++ = normal.y_;
  2139. *dest++ = normal.z_;
  2140. }
  2141. for (unsigned i = 0; i < mesh->GetNumColorChannels() && i < MAX_CHANNELS; ++i)
  2142. {
  2143. *((unsigned*)dest) = Color(mesh->mColors[i][index].r, mesh->mColors[i][index].g, mesh->mColors[i][index].b,
  2144. mesh->mColors[i][index].a).ToU32();
  2145. ++dest;
  2146. }
  2147. for (unsigned i = 0; i < mesh->GetNumUVChannels() && i < MAX_CHANNELS; ++i)
  2148. {
  2149. Vector3 texCoord = ToVector3(mesh->mTextureCoords[i][index]);
  2150. *dest++ = texCoord.x_;
  2151. *dest++ = texCoord.y_;
  2152. }
  2153. if (mesh->HasTangentsAndBitangents())
  2154. {
  2155. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  2156. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  2157. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  2158. // Check handedness
  2159. float w = 1.0f;
  2160. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  2161. w = -1.0f;
  2162. *dest++ = tangent.x_;
  2163. *dest++ = tangent.y_;
  2164. *dest++ = tangent.z_;
  2165. *dest++ = w;
  2166. }
  2167. if (isSkinned)
  2168. {
  2169. for (unsigned i = 0; i < 4; ++i)
  2170. {
  2171. if (i < blendWeights[index].Size())
  2172. *dest++ = blendWeights[index][i];
  2173. else
  2174. *dest++ = 0.0f;
  2175. }
  2176. auto* destBytes = (unsigned char*)dest;
  2177. ++dest;
  2178. for (unsigned i = 0; i < 4; ++i)
  2179. {
  2180. if (i < blendIndices[index].Size())
  2181. *destBytes++ = blendIndices[index][i];
  2182. else
  2183. *destBytes++ = 0;
  2184. }
  2185. }
  2186. }
  2187. Vector<VertexElement> GetVertexElements(aiMesh* mesh, bool isSkinned)
  2188. {
  2189. Vector<VertexElement> ret;
  2190. // Position must always be first and of type Vector3 for raycasts to work
  2191. ret.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION));
  2192. if (mesh->HasNormals())
  2193. ret.Push(VertexElement(TYPE_VECTOR3, SEM_NORMAL));
  2194. for (unsigned i = 0; i < mesh->GetNumColorChannels() && i < MAX_CHANNELS; ++i)
  2195. ret.Push(VertexElement(TYPE_UBYTE4_NORM, SEM_COLOR, i));
  2196. /// \todo Assimp mesh structure can specify 3D UV-coords. How to determine the difference? For now always treated as 2D.
  2197. for (unsigned i = 0; i < mesh->GetNumUVChannels() && i < MAX_CHANNELS; ++i)
  2198. ret.Push(VertexElement(TYPE_VECTOR2, SEM_TEXCOORD, i));
  2199. if (mesh->HasTangentsAndBitangents())
  2200. ret.Push(VertexElement(TYPE_VECTOR4, SEM_TANGENT));
  2201. if (isSkinned)
  2202. {
  2203. ret.Push(VertexElement(TYPE_VECTOR4, SEM_BLENDWEIGHTS));
  2204. ret.Push(VertexElement(TYPE_UBYTE4, SEM_BLENDINDICES));
  2205. }
  2206. return ret;
  2207. }
  2208. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  2209. {
  2210. if (!rootNode)
  2211. return nullptr;
  2212. if (!name.Compare(rootNode->mName.data, caseSensitive))
  2213. return rootNode;
  2214. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  2215. {
  2216. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  2217. if (found)
  2218. return found;
  2219. }
  2220. return nullptr;
  2221. }
  2222. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive)
  2223. {
  2224. return GetDerivedTransform(node->mTransformation, node, rootNode, rootInclusive);
  2225. }
  2226. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive)
  2227. {
  2228. // If basenode is defined, go only up to it in the parent chain
  2229. while (node && node != rootNode)
  2230. {
  2231. node = node->mParent;
  2232. if (!rootInclusive && node == rootNode)
  2233. break;
  2234. if (node)
  2235. transform = node->mTransformation * transform;
  2236. }
  2237. return transform;
  2238. }
  2239. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  2240. {
  2241. if (meshNode == modelRootNode)
  2242. return {};
  2243. else
  2244. return GetDerivedTransform(meshNode, modelRootNode);
  2245. }
  2246. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  2247. {
  2248. aiVector3D aiPos;
  2249. aiQuaternion aiRot;
  2250. aiVector3D aiScale;
  2251. transform.Decompose(aiScale, aiRot, aiPos);
  2252. pos = ToVector3(aiPos);
  2253. rot = ToQuaternion(aiRot);
  2254. scale = ToVector3(aiScale);
  2255. }
  2256. String FromAIString(const aiString& str)
  2257. {
  2258. return String(str.data);
  2259. }
  2260. Vector3 ToVector3(const aiVector3D& vec)
  2261. {
  2262. return Vector3(vec.x, vec.y, vec.z);
  2263. }
  2264. Vector2 ToVector2(const aiVector2D& vec)
  2265. {
  2266. return Vector2(vec.x, vec.y);
  2267. }
  2268. Quaternion ToQuaternion(const aiQuaternion& quat)
  2269. {
  2270. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  2271. }
  2272. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat)
  2273. {
  2274. Matrix3x4 ret;
  2275. memcpy(&ret.m00_, &mat.a1, sizeof(Matrix3x4));
  2276. return ret;
  2277. }
  2278. aiMatrix4x4 ToAIMatrix4x4(const Matrix3x4& mat)
  2279. {
  2280. aiMatrix4x4 ret;
  2281. memcpy(&ret.a1, &mat.m00_, sizeof(Matrix3x4));
  2282. return ret;
  2283. }
  2284. String SanitateAssetName(const String& name)
  2285. {
  2286. String fixedName = name;
  2287. fixedName.Replace("<", "");
  2288. fixedName.Replace(">", "");
  2289. fixedName.Replace("?", "");
  2290. fixedName.Replace("*", "");
  2291. fixedName.Replace(":", "");
  2292. fixedName.Replace("\"", "");
  2293. fixedName.Replace("/", "");
  2294. fixedName.Replace("\\", "");
  2295. fixedName.Replace("|", "");
  2296. return fixedName;
  2297. }
  2298. unsigned GetPivotlessBoneIndex(OutModel& model, const String& boneName)
  2299. {
  2300. for (unsigned i = 0; i < model.pivotlessBones_.Size(); ++i)
  2301. {
  2302. if (boneName == model.pivotlessBones_[i]->mName.data)
  2303. return i;
  2304. }
  2305. return M_MAX_UNSIGNED;
  2306. }
  2307. void FillChainTransforms(OutModel &model, aiMatrix4x4 *chain, const String& mainBoneName)
  2308. {
  2309. for (unsigned j = 0; j < TransformationComp_MAXIMUM; ++j)
  2310. {
  2311. String transfBoneName = mainBoneName + "_$AssimpFbx$_" + String(transformSuffix[j]);
  2312. for (unsigned k = 0; k < model.bones_.Size(); ++k)
  2313. {
  2314. String boneName = String(model.bones_[k]->mName.data);
  2315. if (boneName == transfBoneName)
  2316. {
  2317. chain[j] = model.bones_[k]->mTransformation;
  2318. break;
  2319. }
  2320. }
  2321. }
  2322. }
  2323. void ExpandAnimatedChannelKeys(aiAnimation* anim, unsigned mainChannel, const int *channelIndices)
  2324. {
  2325. aiNodeAnim* channel = anim->mChannels[mainChannel];
  2326. unsigned int poskeyFrames = channel->mNumPositionKeys;
  2327. unsigned int rotkeyFrames = channel->mNumRotationKeys;
  2328. unsigned int scalekeyFrames = channel->mNumScalingKeys;
  2329. // Get max key frames
  2330. for (unsigned i = 0; i < TransformationComp_MAXIMUM; ++i)
  2331. {
  2332. if (channelIndices[i] != -1 && channelIndices[i] != mainChannel)
  2333. {
  2334. aiNodeAnim* channel2 = anim->mChannels[channelIndices[i]];
  2335. if (channel2->mNumPositionKeys > poskeyFrames)
  2336. poskeyFrames = channel2->mNumPositionKeys;
  2337. if (channel2->mNumRotationKeys > rotkeyFrames)
  2338. rotkeyFrames = channel2->mNumRotationKeys;
  2339. if (channel2->mNumScalingKeys > scalekeyFrames)
  2340. scalekeyFrames = channel2->mNumScalingKeys;
  2341. }
  2342. }
  2343. // Resize and init vector key array
  2344. if (poskeyFrames > channel->mNumPositionKeys)
  2345. {
  2346. auto* newKeys = new aiVectorKey[poskeyFrames];
  2347. for (unsigned i = 0; i < poskeyFrames; ++i)
  2348. {
  2349. if (i < channel->mNumPositionKeys )
  2350. newKeys[i] = aiVectorKey(channel->mPositionKeys[i].mTime, channel->mPositionKeys[i].mValue);
  2351. else
  2352. newKeys[i].mValue = aiVector3D(0.0f, 0.0f, 0.0f);
  2353. }
  2354. delete[] channel->mPositionKeys;
  2355. channel->mPositionKeys = newKeys;
  2356. channel->mNumPositionKeys = poskeyFrames;
  2357. }
  2358. if (rotkeyFrames > channel->mNumRotationKeys)
  2359. {
  2360. auto* newKeys = new aiQuatKey[rotkeyFrames];
  2361. for (unsigned i = 0; i < rotkeyFrames; ++i)
  2362. {
  2363. if (i < channel->mNumRotationKeys)
  2364. newKeys[i] = aiQuatKey(channel->mRotationKeys[i].mTime, channel->mRotationKeys[i].mValue);
  2365. else
  2366. newKeys[i].mValue = aiQuaternion();
  2367. }
  2368. delete[] channel->mRotationKeys;
  2369. channel->mRotationKeys = newKeys;
  2370. channel->mNumRotationKeys = rotkeyFrames;
  2371. }
  2372. if (scalekeyFrames > channel->mNumScalingKeys)
  2373. {
  2374. auto* newKeys = new aiVectorKey[scalekeyFrames];
  2375. for (unsigned i = 0; i < scalekeyFrames; ++i)
  2376. {
  2377. if ( i < channel->mNumScalingKeys)
  2378. newKeys[i] = aiVectorKey(channel->mScalingKeys[i].mTime, channel->mScalingKeys[i].mValue);
  2379. else
  2380. newKeys[i].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2381. }
  2382. delete[] channel->mScalingKeys;
  2383. channel->mScalingKeys = newKeys;
  2384. channel->mNumScalingKeys = scalekeyFrames;
  2385. }
  2386. }
  2387. void InitAnimatedChainTransformIndices(aiAnimation* anim, unsigned mainChannel, const String& mainBoneName, int *channelIndices)
  2388. {
  2389. int numTransforms = 0;
  2390. for (unsigned j = 0; j < TransformationComp_MAXIMUM; ++j)
  2391. {
  2392. String transfBoneName = mainBoneName + "_$AssimpFbx$_" + String(transformSuffix[j]);
  2393. channelIndices[j] = -1;
  2394. for (unsigned k = 0; k < anim->mNumChannels; ++k)
  2395. {
  2396. aiNodeAnim* channel = anim->mChannels[k];
  2397. String channelName = FromAIString(channel->mNodeName);
  2398. if (channelName == transfBoneName)
  2399. {
  2400. ++numTransforms;
  2401. channelIndices[j] = k;
  2402. break;
  2403. }
  2404. }
  2405. }
  2406. // resize animated channel key size
  2407. if (numTransforms > 1)
  2408. ExpandAnimatedChannelKeys(anim, mainChannel, channelIndices);
  2409. }
  2410. void CreatePivotlessFbxBoneStruct(OutModel &model)
  2411. {
  2412. // Init
  2413. model.pivotlessBones_.Clear();
  2414. aiMatrix4x4 chains[TransformationComp_MAXIMUM];
  2415. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  2416. {
  2417. String mainBoneName = String(model.bones_[i]->mName.data);
  2418. // Skip $fbx nodes
  2419. if (mainBoneName.Find("$AssimpFbx$") != String::NPOS)
  2420. continue;
  2421. std::fill_n(chains, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  2422. FillChainTransforms(model, &chains[0], mainBoneName);
  2423. // Calculate chained transform
  2424. aiMatrix4x4 finalTransform;
  2425. for (const auto& chain : chains)
  2426. finalTransform = finalTransform * chain;
  2427. // New bone node
  2428. auto*pnode = new aiNode;
  2429. pnode->mName = model.bones_[i]->mName;
  2430. pnode->mTransformation = finalTransform * model.bones_[i]->mTransformation;
  2431. model.pivotlessBones_.Push(pnode);
  2432. }
  2433. }
  2434. void ExtrapolatePivotlessAnimation(OutModel* model)
  2435. {
  2436. if (suppressFbxPivotNodes_ && model)
  2437. {
  2438. PrintLine("Suppressing $fbx nodes");
  2439. // Construct new bone structure from suppressed $fbx pivot nodes
  2440. CreatePivotlessFbxBoneStruct(*model);
  2441. // Extrapolate anim
  2442. const Vector<aiAnimation *> &animations = model->animations_;
  2443. for (unsigned i = 0; i < animations.Size(); ++i)
  2444. {
  2445. aiAnimation* anim = animations[i];
  2446. Vector<String> mainBoneCompleteList;
  2447. mainBoneCompleteList.Clear();
  2448. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  2449. {
  2450. aiNodeAnim* channel = anim->mChannels[j];
  2451. String channelName = FromAIString(channel->mNodeName);
  2452. i32 pos = channelName.Find("_$AssimpFbx$");
  2453. if (pos != String::NPOS)
  2454. {
  2455. // Every first $fbx animation channel for a bone will consolidate other $fbx animation to a single channel
  2456. // skip subsequent $fbx animation channel for the same bone
  2457. String mainBoneName = channelName.Substring(0, pos);
  2458. if (mainBoneCompleteList.Find(mainBoneName) != mainBoneCompleteList.End())
  2459. continue;
  2460. mainBoneCompleteList.Push(mainBoneName);
  2461. unsigned boneIdx = GetBoneIndex(*model, mainBoneName);
  2462. // This condition exists if a geometry, not a bone, has a key animation
  2463. if (boneIdx == M_MAX_UNSIGNED)
  2464. continue;
  2465. // Init chain indices and fill transforms
  2466. aiMatrix4x4 mainboneTransform = model->bones_[boneIdx]->mTransformation;
  2467. aiMatrix4x4 chain[TransformationComp_MAXIMUM];
  2468. int channelIndices[TransformationComp_MAXIMUM];
  2469. InitAnimatedChainTransformIndices(anim, j, mainBoneName, &channelIndices[0]);
  2470. std::fill_n(chain, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  2471. FillChainTransforms(*model, &chain[0], mainBoneName);
  2472. unsigned keyFrames = channel->mNumPositionKeys;
  2473. if (channel->mNumRotationKeys > keyFrames)
  2474. keyFrames = channel->mNumRotationKeys;
  2475. if (channel->mNumScalingKeys > keyFrames)
  2476. keyFrames = channel->mNumScalingKeys;
  2477. for (unsigned k = 0; k < keyFrames; ++k)
  2478. {
  2479. double frameTime = 0.0;
  2480. aiMatrix4x4 finalTransform;
  2481. // Chain transform animated values
  2482. for (unsigned l = 0; l < TransformationComp_MAXIMUM; ++l)
  2483. {
  2484. // It's either the chain transform or animation channel transform
  2485. if (channelIndices[l] != -1)
  2486. {
  2487. aiMatrix4x4 animtform, tempMat;
  2488. aiNodeAnim* animchannel = anim->mChannels[channelIndices[l]];
  2489. if (k < animchannel->mNumPositionKeys)
  2490. {
  2491. aiMatrix4x4::Translation(animchannel->mPositionKeys[k].mValue, tempMat);
  2492. animtform = animtform * tempMat;
  2493. frameTime = Max(animchannel->mPositionKeys[k].mTime, frameTime);
  2494. }
  2495. if (k < animchannel->mNumRotationKeys)
  2496. {
  2497. tempMat = aiMatrix4x4(animchannel->mRotationKeys[k].mValue.GetMatrix());
  2498. animtform = animtform * tempMat;
  2499. frameTime = Max(animchannel->mRotationKeys[k].mTime, frameTime);
  2500. }
  2501. if (k < animchannel->mNumScalingKeys)
  2502. {
  2503. aiMatrix4x4::Scaling(animchannel->mScalingKeys[k].mValue, tempMat);
  2504. animtform = animtform * tempMat;
  2505. frameTime = Max(animchannel->mScalingKeys[k].mTime, frameTime);
  2506. }
  2507. finalTransform = finalTransform * animtform;
  2508. }
  2509. else
  2510. finalTransform = finalTransform * chain[l];
  2511. }
  2512. aiVector3D animPos, animScale;
  2513. aiQuaternion animRot;
  2514. finalTransform = finalTransform * mainboneTransform;
  2515. finalTransform.Decompose(animScale, animRot, animPos);
  2516. // New values
  2517. if (k < channel->mNumPositionKeys)
  2518. {
  2519. channel->mPositionKeys[k].mValue = animPos;
  2520. channel->mPositionKeys[k].mTime = frameTime;
  2521. }
  2522. if (k < channel->mNumRotationKeys)
  2523. {
  2524. channel->mRotationKeys[k].mValue = animRot;
  2525. channel->mRotationKeys[k].mTime = frameTime;
  2526. }
  2527. if (k < channel->mNumScalingKeys)
  2528. {
  2529. channel->mScalingKeys[k].mValue = animScale;
  2530. channel->mScalingKeys[k].mTime = frameTime;
  2531. }
  2532. }
  2533. }
  2534. }
  2535. }
  2536. }
  2537. }
  2538. void CollectSceneNodesAsBones(OutModel &model, aiNode* rootNode)
  2539. {
  2540. if (!rootNode)
  2541. return;
  2542. model.bones_.Push(rootNode);
  2543. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  2544. {
  2545. CollectSceneNodesAsBones(model, rootNode->mChildren[i]);
  2546. }
  2547. }