ColladaExporter.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER
  35. #include "ColladaExporter.h"
  36. #include <assimp/Bitmap.h>
  37. #include <assimp/commonMetaData.h>
  38. #include <assimp/MathFunctions.h>
  39. #include <assimp/fast_atof.h>
  40. #include <assimp/SceneCombiner.h>
  41. #include <assimp/StringUtils.h>
  42. #include <assimp/XMLTools.h>
  43. #include <assimp/DefaultIOSystem.h>
  44. #include <assimp/IOSystem.hpp>
  45. #include <assimp/Exporter.hpp>
  46. #include <assimp/scene.h>
  47. #include <assimp/Exceptional.h>
  48. #include <memory>
  49. #include <ctime>
  50. #include <set>
  51. #include <vector>
  52. #include <iostream>
  53. using namespace Assimp;
  54. namespace Assimp {
  55. // ------------------------------------------------------------------------------------------------
  56. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  57. void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) {
  58. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  59. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  60. // invoke the exporter
  61. ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file);
  62. if (iDoTheExportThing.mOutput.fail()) {
  63. throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
  64. }
  65. // we're still here - export successfully completed. Write result to the given IOSYstem
  66. std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  67. if(outfile == NULL) {
  68. throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
  69. }
  70. // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
  71. outfile->Write( iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()),1);
  72. }
  73. } // end of namespace Assimp
  74. // ------------------------------------------------------------------------------------------------
  75. // Encodes a string into a valid XML ID using the xsd:ID schema qualifications.
  76. static const std::string XMLIDEncode(const std::string& name) {
  77. const char XML_ID_CHARS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.";
  78. const unsigned int XML_ID_CHARS_COUNT = sizeof(XML_ID_CHARS) / sizeof(char);
  79. if (name.length() == 0) {
  80. return name;
  81. }
  82. std::stringstream idEncoded;
  83. // xsd:ID must start with letter or underscore
  84. if (!((name[0] >= 'A' && name[0] <= 'z') || name[0] == '_')) {
  85. idEncoded << '_';
  86. }
  87. for (std::string::const_iterator it = name.begin(); it != name.end(); ++it) {
  88. // xsd:ID can only contain letters, digits, underscores, hyphens and periods
  89. if (strchr(XML_ID_CHARS, *it) != nullptr) {
  90. idEncoded << *it;
  91. } else {
  92. // Select placeholder character based on invalid character to prevent name collisions
  93. idEncoded << XML_ID_CHARS[(*it) % XML_ID_CHARS_COUNT];
  94. }
  95. }
  96. return idEncoded.str();
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Constructor for a specific scene to export
  100. ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file)
  101. : mIOSystem(pIOSystem)
  102. , mPath(path)
  103. , mFile(file) {
  104. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  105. mOutput.imbue( std::locale("C") );
  106. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  107. mScene = pScene;
  108. mSceneOwned = false;
  109. // set up strings
  110. endstr = "\n";
  111. // start writing the file
  112. WriteFile();
  113. }
  114. // ------------------------------------------------------------------------------------------------
  115. // Destructor
  116. ColladaExporter::~ColladaExporter() {
  117. if ( mSceneOwned ) {
  118. delete mScene;
  119. }
  120. }
  121. // ------------------------------------------------------------------------------------------------
  122. // Starts writing the contents
  123. void ColladaExporter::WriteFile() {
  124. // write the DTD
  125. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  126. // COLLADA element start
  127. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  128. PushTag();
  129. WriteTextures();
  130. WriteHeader();
  131. WriteCamerasLibrary();
  132. WriteLightsLibrary();
  133. WriteMaterials();
  134. WriteGeometryLibrary();
  135. WriteControllerLibrary();
  136. WriteSceneLibrary();
  137. // customized, Writes the animation library
  138. WriteAnimationsLibrary();
  139. // useless Collada fu at the end, just in case we haven't had enough indirections, yet.
  140. mOutput << startstr << "<scene>" << endstr;
  141. PushTag();
  142. mOutput << startstr << "<instance_visual_scene url=\"#" + XMLIDEncode(mScene->mRootNode->mName.C_Str()) + "\" />" << endstr;
  143. PopTag();
  144. mOutput << startstr << "</scene>" << endstr;
  145. PopTag();
  146. mOutput << "</COLLADA>" << endstr;
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Writes the asset header
  150. void ColladaExporter::WriteHeader() {
  151. static const ai_real epsilon = Math::getEpsilon<ai_real>();
  152. static const aiQuaternion x_rot(aiMatrix3x3(
  153. 0, -1, 0,
  154. 1, 0, 0,
  155. 0, 0, 1));
  156. static const aiQuaternion y_rot(aiMatrix3x3(
  157. 1, 0, 0,
  158. 0, 1, 0,
  159. 0, 0, 1));
  160. static const aiQuaternion z_rot(aiMatrix3x3(
  161. 1, 0, 0,
  162. 0, 0, 1,
  163. 0, -1, 0));
  164. static const unsigned int date_nb_chars = 20;
  165. char date_str[date_nb_chars];
  166. std::time_t date = std::time(NULL);
  167. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  168. aiVector3D scaling;
  169. aiQuaternion rotation;
  170. aiVector3D position;
  171. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  172. rotation.Normalize();
  173. bool add_root_node = false;
  174. ai_real scale = 1.0;
  175. if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  176. scale = (ai_real) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
  177. } else {
  178. add_root_node = true;
  179. }
  180. std::string up_axis = "Y_UP";
  181. if(rotation.Equal(x_rot, epsilon)) {
  182. up_axis = "X_UP";
  183. } else if(rotation.Equal(y_rot, epsilon)) {
  184. up_axis = "Y_UP";
  185. } else if(rotation.Equal(z_rot, epsilon)) {
  186. up_axis = "Z_UP";
  187. } else {
  188. add_root_node = true;
  189. }
  190. if(! position.Equal(aiVector3D(0, 0, 0))) {
  191. add_root_node = true;
  192. }
  193. if(mScene->mRootNode->mNumChildren == 0) {
  194. add_root_node = true;
  195. }
  196. if(add_root_node) {
  197. aiScene* scene;
  198. SceneCombiner::CopyScene(&scene, mScene);
  199. aiNode* root = new aiNode("Scene");
  200. root->mNumChildren = 1;
  201. root->mChildren = new aiNode*[root->mNumChildren];
  202. root->mChildren[0] = scene->mRootNode;
  203. scene->mRootNode->mParent = root;
  204. scene->mRootNode = root;
  205. mScene = scene;
  206. mSceneOwned = true;
  207. up_axis = "Y_UP";
  208. scale = 1.0;
  209. }
  210. mOutput << startstr << "<asset>" << endstr;
  211. PushTag();
  212. mOutput << startstr << "<contributor>" << endstr;
  213. PushTag();
  214. // If no Scene metadata, use root node metadata
  215. aiMetadata* meta = mScene->mMetaData;
  216. if (nullptr == meta) {
  217. meta = mScene->mRootNode->mMetaData;
  218. }
  219. aiString value;
  220. if (!meta || !meta->Get("Author", value)) {
  221. mOutput << startstr << "<author>" << "Assimp" << "</author>" << endstr;
  222. } else {
  223. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  224. }
  225. if (nullptr == meta || !meta->Get(AI_METADATA_SOURCE_GENERATOR, value)) {
  226. mOutput << startstr << "<authoring_tool>" << "Assimp Exporter" << "</authoring_tool>" << endstr;
  227. } else {
  228. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  229. }
  230. if (meta) {
  231. if (meta->Get("Comments", value)) {
  232. mOutput << startstr << "<comments>" << XMLEscape(value.C_Str()) << "</comments>" << endstr;
  233. }
  234. if (meta->Get(AI_METADATA_SOURCE_COPYRIGHT, value)) {
  235. mOutput << startstr << "<copyright>" << XMLEscape(value.C_Str()) << "</copyright>" << endstr;
  236. }
  237. if (meta->Get("SourceData", value)) {
  238. mOutput << startstr << "<source_data>" << XMLEscape(value.C_Str()) << "</source_data>" << endstr;
  239. }
  240. }
  241. PopTag();
  242. mOutput << startstr << "</contributor>" << endstr;
  243. if (nullptr == meta || !meta->Get("Created", value)) {
  244. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  245. } else {
  246. mOutput << startstr << "<created>" << XMLEscape(value.C_Str()) << "</created>" << endstr;
  247. }
  248. // Modified date is always the date saved
  249. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  250. if (meta) {
  251. if (meta->Get("Keywords", value)) {
  252. mOutput << startstr << "<keywords>" << XMLEscape(value.C_Str()) << "</keywords>" << endstr;
  253. }
  254. if (meta->Get("Revision", value)) {
  255. mOutput << startstr << "<revision>" << XMLEscape(value.C_Str()) << "</revision>" << endstr;
  256. }
  257. if (meta->Get("Subject", value)) {
  258. mOutput << startstr << "<subject>" << XMLEscape(value.C_Str()) << "</subject>" << endstr;
  259. }
  260. if (meta->Get("Title", value)) {
  261. mOutput << startstr << "<title>" << XMLEscape(value.C_Str()) << "</title>" << endstr;
  262. }
  263. }
  264. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  265. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  266. PopTag();
  267. mOutput << startstr << "</asset>" << endstr;
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. // Write the embedded textures
  271. void ColladaExporter::WriteTextures() {
  272. static const unsigned int buffer_size = 1024;
  273. char str[buffer_size];
  274. if (mScene->HasTextures()) {
  275. for(unsigned int i = 0; i < mScene->mNumTextures; i++) {
  276. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  277. // so we just write the textures in the current directory.
  278. aiTexture* texture = mScene->mTextures[i];
  279. if ( nullptr == texture ) {
  280. continue;
  281. }
  282. ASSIMP_itoa10(str, buffer_size, i + 1);
  283. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
  284. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb"));
  285. if(outfile == NULL) {
  286. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  287. }
  288. if(texture->mHeight == 0) {
  289. outfile->Write((void*) texture->pcData, texture->mWidth, 1);
  290. } else {
  291. Bitmap::Save(texture, outfile.get());
  292. }
  293. outfile->Flush();
  294. textures.insert(std::make_pair(i, name));
  295. }
  296. }
  297. }
  298. // ------------------------------------------------------------------------------------------------
  299. // Write the embedded textures
  300. void ColladaExporter::WriteCamerasLibrary() {
  301. if(mScene->HasCameras()) {
  302. mOutput << startstr << "<library_cameras>" << endstr;
  303. PushTag();
  304. for( size_t a = 0; a < mScene->mNumCameras; ++a)
  305. WriteCamera( a);
  306. PopTag();
  307. mOutput << startstr << "</library_cameras>" << endstr;
  308. }
  309. }
  310. void ColladaExporter::WriteCamera(size_t pIndex){
  311. const aiCamera *cam = mScene->mCameras[pIndex];
  312. const std::string cameraName = XMLEscape(cam->mName.C_Str());
  313. const std::string cameraId = XMLIDEncode(cam->mName.C_Str());
  314. mOutput << startstr << "<camera id=\"" << cameraId << "-camera\" name=\"" << cameraName << "\" >" << endstr;
  315. PushTag();
  316. mOutput << startstr << "<optics>" << endstr;
  317. PushTag();
  318. mOutput << startstr << "<technique_common>" << endstr;
  319. PushTag();
  320. //assimp doesn't support the import of orthographic cameras! se we write
  321. //always perspective
  322. mOutput << startstr << "<perspective>" << endstr;
  323. PushTag();
  324. mOutput << startstr << "<xfov sid=\"xfov\">"<<
  325. AI_RAD_TO_DEG(cam->mHorizontalFOV)
  326. <<"</xfov>" << endstr;
  327. mOutput << startstr << "<aspect_ratio>"
  328. << cam->mAspect
  329. << "</aspect_ratio>" << endstr;
  330. mOutput << startstr << "<znear sid=\"znear\">"
  331. << cam->mClipPlaneNear
  332. << "</znear>" << endstr;
  333. mOutput << startstr << "<zfar sid=\"zfar\">"
  334. << cam->mClipPlaneFar
  335. << "</zfar>" << endstr;
  336. PopTag();
  337. mOutput << startstr << "</perspective>" << endstr;
  338. PopTag();
  339. mOutput << startstr << "</technique_common>" << endstr;
  340. PopTag();
  341. mOutput << startstr << "</optics>" << endstr;
  342. PopTag();
  343. mOutput << startstr << "</camera>" << endstr;
  344. }
  345. // ------------------------------------------------------------------------------------------------
  346. // Write the embedded textures
  347. void ColladaExporter::WriteLightsLibrary() {
  348. if(mScene->HasLights()) {
  349. mOutput << startstr << "<library_lights>" << endstr;
  350. PushTag();
  351. for( size_t a = 0; a < mScene->mNumLights; ++a)
  352. WriteLight( a);
  353. PopTag();
  354. mOutput << startstr << "</library_lights>" << endstr;
  355. }
  356. }
  357. void ColladaExporter::WriteLight(size_t pIndex){
  358. const aiLight *light = mScene->mLights[pIndex];
  359. const std::string lightName = XMLEscape(light->mName.C_Str());
  360. const std::string lightId = XMLIDEncode(light->mName.C_Str());
  361. mOutput << startstr << "<light id=\"" << lightId << "-light\" name=\""
  362. << lightName << "\" >" << endstr;
  363. PushTag();
  364. mOutput << startstr << "<technique_common>" << endstr;
  365. PushTag();
  366. switch(light->mType){
  367. case aiLightSource_AMBIENT:
  368. WriteAmbienttLight(light);
  369. break;
  370. case aiLightSource_DIRECTIONAL:
  371. WriteDirectionalLight(light);
  372. break;
  373. case aiLightSource_POINT:
  374. WritePointLight(light);
  375. break;
  376. case aiLightSource_SPOT:
  377. WriteSpotLight(light);
  378. break;
  379. case aiLightSource_AREA:
  380. case aiLightSource_UNDEFINED:
  381. case _aiLightSource_Force32Bit:
  382. break;
  383. }
  384. PopTag();
  385. mOutput << startstr << "</technique_common>" << endstr;
  386. PopTag();
  387. mOutput << startstr << "</light>" << endstr;
  388. }
  389. void ColladaExporter::WritePointLight(const aiLight *const light){
  390. const aiColor3D &color= light->mColorDiffuse;
  391. mOutput << startstr << "<point>" << endstr;
  392. PushTag();
  393. mOutput << startstr << "<color sid=\"color\">"
  394. << color.r<<" "<<color.g<<" "<<color.b
  395. <<"</color>" << endstr;
  396. mOutput << startstr << "<constant_attenuation>"
  397. << light->mAttenuationConstant
  398. <<"</constant_attenuation>" << endstr;
  399. mOutput << startstr << "<linear_attenuation>"
  400. << light->mAttenuationLinear
  401. <<"</linear_attenuation>" << endstr;
  402. mOutput << startstr << "<quadratic_attenuation>"
  403. << light->mAttenuationQuadratic
  404. <<"</quadratic_attenuation>" << endstr;
  405. PopTag();
  406. mOutput << startstr << "</point>" << endstr;
  407. }
  408. void ColladaExporter::WriteDirectionalLight(const aiLight *const light){
  409. const aiColor3D &color= light->mColorDiffuse;
  410. mOutput << startstr << "<directional>" << endstr;
  411. PushTag();
  412. mOutput << startstr << "<color sid=\"color\">"
  413. << color.r<<" "<<color.g<<" "<<color.b
  414. <<"</color>" << endstr;
  415. PopTag();
  416. mOutput << startstr << "</directional>" << endstr;
  417. }
  418. void ColladaExporter::WriteSpotLight(const aiLight *const light){
  419. const aiColor3D &color= light->mColorDiffuse;
  420. mOutput << startstr << "<spot>" << endstr;
  421. PushTag();
  422. mOutput << startstr << "<color sid=\"color\">"
  423. << color.r<<" "<<color.g<<" "<<color.b
  424. <<"</color>" << endstr;
  425. mOutput << startstr << "<constant_attenuation>"
  426. << light->mAttenuationConstant
  427. <<"</constant_attenuation>" << endstr;
  428. mOutput << startstr << "<linear_attenuation>"
  429. << light->mAttenuationLinear
  430. <<"</linear_attenuation>" << endstr;
  431. mOutput << startstr << "<quadratic_attenuation>"
  432. << light->mAttenuationQuadratic
  433. <<"</quadratic_attenuation>" << endstr;
  434. const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
  435. mOutput << startstr <<"<falloff_angle sid=\"fall_off_angle\">"
  436. << fallOffAngle
  437. <<"</falloff_angle>" << endstr;
  438. double temp = light->mAngleOuterCone-light->mAngleInnerCone;
  439. temp = std::cos(temp);
  440. temp = std::log(temp)/std::log(0.1);
  441. temp = 1/temp;
  442. mOutput << startstr << "<falloff_exponent sid=\"fall_off_exponent\">"
  443. << temp
  444. <<"</falloff_exponent>" << endstr;
  445. PopTag();
  446. mOutput << startstr << "</spot>" << endstr;
  447. }
  448. void ColladaExporter::WriteAmbienttLight(const aiLight *const light){
  449. const aiColor3D &color= light->mColorAmbient;
  450. mOutput << startstr << "<ambient>" << endstr;
  451. PushTag();
  452. mOutput << startstr << "<color sid=\"color\">"
  453. << color.r<<" "<<color.g<<" "<<color.b
  454. <<"</color>" << endstr;
  455. PopTag();
  456. mOutput << startstr << "</ambient>" << endstr;
  457. }
  458. // ------------------------------------------------------------------------------------------------
  459. // Reads a single surface entry from the given material keys
  460. void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat,
  461. aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex) {
  462. if( pSrcMat->GetTextureCount( pTexture) > 0 ) {
  463. aiString texfile;
  464. unsigned int uvChannel = 0;
  465. pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel);
  466. std::string index_str(texfile.C_Str());
  467. if(index_str.size() != 0 && index_str[0] == '*') {
  468. unsigned int index;
  469. index_str = index_str.substr(1, std::string::npos);
  470. try {
  471. index = (unsigned int) strtoul10_64(index_str.c_str());
  472. } catch(std::exception& error) {
  473. throw DeadlyExportError(error.what());
  474. }
  475. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  476. if(name != textures.end()) {
  477. poSurface.texture = name->second;
  478. } else {
  479. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  480. }
  481. } else {
  482. poSurface.texture = texfile.C_Str();
  483. }
  484. poSurface.channel = uvChannel;
  485. poSurface.exist = true;
  486. } else {
  487. if( pKey )
  488. poSurface.exist = pSrcMat->Get( pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
  489. }
  490. }
  491. static bool isalnum_C(char c) {
  492. return ( nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c) );
  493. }
  494. // ------------------------------------------------------------------------------------------------
  495. // Writes an image entry for the given surface
  496. void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd) {
  497. if( !pSurface.texture.empty() )
  498. {
  499. mOutput << startstr << "<image id=\"" << XMLIDEncode(pNameAdd) << "\">" << endstr;
  500. PushTag();
  501. mOutput << startstr << "<init_from>";
  502. // URL encode image file name first, then XML encode on top
  503. std::stringstream imageUrlEncoded;
  504. for( std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it )
  505. {
  506. if( isalnum_C( (unsigned char) *it) || *it == ':' || *it == '_' || *it == '-' || *it == '.' || *it == '/' || *it == '\\' )
  507. imageUrlEncoded << *it;
  508. else
  509. imageUrlEncoded << '%' << std::hex << size_t( (unsigned char) *it) << std::dec;
  510. }
  511. mOutput << XMLEscape(imageUrlEncoded.str());
  512. mOutput << "</init_from>" << endstr;
  513. PopTag();
  514. mOutput << startstr << "</image>" << endstr;
  515. }
  516. }
  517. // ------------------------------------------------------------------------------------------------
  518. // Writes a color-or-texture entry into an effect definition
  519. void ColladaExporter::WriteTextureColorEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pImageName)
  520. {
  521. if(pSurface.exist) {
  522. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  523. PushTag();
  524. if( pSurface.texture.empty() )
  525. {
  526. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  527. }
  528. else
  529. {
  530. mOutput << startstr << "<texture texture=\"" << XMLIDEncode(pImageName) << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  531. }
  532. PopTag();
  533. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  534. }
  535. }
  536. // ------------------------------------------------------------------------------------------------
  537. // Writes the two parameters necessary for referencing a texture in an effect entry
  538. void ColladaExporter::WriteTextureParamEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pMatName)
  539. {
  540. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  541. if( !pSurface.texture.empty() )
  542. {
  543. mOutput << startstr << "<newparam sid=\"" << XMLIDEncode(pMatName) << "-" << pTypeName << "-surface\">" << endstr;
  544. PushTag();
  545. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  546. PushTag();
  547. mOutput << startstr << "<init_from>" << XMLIDEncode(pMatName) << "-" << pTypeName << "-image</init_from>" << endstr;
  548. PopTag();
  549. mOutput << startstr << "</surface>" << endstr;
  550. PopTag();
  551. mOutput << startstr << "</newparam>" << endstr;
  552. mOutput << startstr << "<newparam sid=\"" << XMLIDEncode(pMatName) << "-" << pTypeName << "-sampler\">" << endstr;
  553. PushTag();
  554. mOutput << startstr << "<sampler2D>" << endstr;
  555. PushTag();
  556. mOutput << startstr << "<source>" << XMLIDEncode(pMatName) << "-" << pTypeName << "-surface</source>" << endstr;
  557. PopTag();
  558. mOutput << startstr << "</sampler2D>" << endstr;
  559. PopTag();
  560. mOutput << startstr << "</newparam>" << endstr;
  561. }
  562. }
  563. // ------------------------------------------------------------------------------------------------
  564. // Writes a scalar property
  565. void ColladaExporter::WriteFloatEntry( const Property& pProperty, const std::string& pTypeName)
  566. {
  567. if(pProperty.exist) {
  568. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  569. PushTag();
  570. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  571. PopTag();
  572. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  573. }
  574. }
  575. // ------------------------------------------------------------------------------------------------
  576. // Writes the material setup
  577. void ColladaExporter::WriteMaterials()
  578. {
  579. materials.resize( mScene->mNumMaterials);
  580. /// collect all materials from the scene
  581. size_t numTextures = 0;
  582. for( size_t a = 0; a < mScene->mNumMaterials; ++a )
  583. {
  584. const aiMaterial* mat = mScene->mMaterials[a];
  585. aiString name;
  586. if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) {
  587. name = "mat";
  588. materials[a].name = std::string( "m") + to_string(a) + name.C_Str();
  589. } else {
  590. // try to use the material's name if no other material has already taken it, else append #
  591. std::string testName = name.C_Str();
  592. size_t materialCountWithThisName = 0;
  593. for( size_t i = 0; i < a; i ++ ) {
  594. if( materials[i].name == testName ) {
  595. materialCountWithThisName ++;
  596. }
  597. }
  598. if( materialCountWithThisName == 0 ) {
  599. materials[a].name = name.C_Str();
  600. } else {
  601. materials[a].name = std::string(name.C_Str()) + to_string(materialCountWithThisName);
  602. }
  603. }
  604. aiShadingMode shading = aiShadingMode_Flat;
  605. materials[a].shading_model = "phong";
  606. if(mat->Get( AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  607. if(shading == aiShadingMode_Phong) {
  608. materials[a].shading_model = "phong";
  609. } else if(shading == aiShadingMode_Blinn) {
  610. materials[a].shading_model = "blinn";
  611. } else if(shading == aiShadingMode_NoShading) {
  612. materials[a].shading_model = "constant";
  613. } else if(shading == aiShadingMode_Gouraud) {
  614. materials[a].shading_model = "lambert";
  615. }
  616. }
  617. ReadMaterialSurface( materials[a].ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  618. if( !materials[a].ambient.texture.empty() ) numTextures++;
  619. ReadMaterialSurface( materials[a].diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  620. if( !materials[a].diffuse.texture.empty() ) numTextures++;
  621. ReadMaterialSurface( materials[a].specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  622. if( !materials[a].specular.texture.empty() ) numTextures++;
  623. ReadMaterialSurface( materials[a].emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  624. if( !materials[a].emissive.texture.empty() ) numTextures++;
  625. ReadMaterialSurface( materials[a].reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE);
  626. if( !materials[a].reflective.texture.empty() ) numTextures++;
  627. ReadMaterialSurface( materials[a].transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT);
  628. if( !materials[a].transparent.texture.empty() ) numTextures++;
  629. ReadMaterialSurface( materials[a].normal, mat, aiTextureType_NORMALS, NULL, 0, 0);
  630. if( !materials[a].normal.texture.empty() ) numTextures++;
  631. materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
  632. materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
  633. materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  634. }
  635. // output textures if present
  636. if( numTextures > 0 )
  637. {
  638. mOutput << startstr << "<library_images>" << endstr;
  639. PushTag();
  640. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  641. {
  642. const Material& mat = *it;
  643. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  644. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  645. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  646. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  647. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  648. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  649. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  650. }
  651. PopTag();
  652. mOutput << startstr << "</library_images>" << endstr;
  653. }
  654. // output effects - those are the actual carriers of information
  655. if( !materials.empty() )
  656. {
  657. mOutput << startstr << "<library_effects>" << endstr;
  658. PushTag();
  659. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  660. {
  661. const Material& mat = *it;
  662. // this is so ridiculous it must be right
  663. mOutput << startstr << "<effect id=\"" << XMLIDEncode(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  664. PushTag();
  665. mOutput << startstr << "<profile_COMMON>" << endstr;
  666. PushTag();
  667. // write sampler- and surface params for the texture entries
  668. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  669. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  670. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  671. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  672. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  673. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  674. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  675. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  676. PushTag();
  677. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  678. PushTag();
  679. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  680. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  681. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  682. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  683. WriteFloatEntry(mat.shininess, "shininess");
  684. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  685. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  686. WriteFloatEntry(mat.transparency, "transparency");
  687. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  688. if(! mat.normal.texture.empty()) {
  689. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  690. }
  691. PopTag();
  692. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  693. PopTag();
  694. mOutput << startstr << "</technique>" << endstr;
  695. PopTag();
  696. mOutput << startstr << "</profile_COMMON>" << endstr;
  697. PopTag();
  698. mOutput << startstr << "</effect>" << endstr;
  699. }
  700. PopTag();
  701. mOutput << startstr << "</library_effects>" << endstr;
  702. // write materials - they're just effect references
  703. mOutput << startstr << "<library_materials>" << endstr;
  704. PushTag();
  705. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  706. {
  707. const Material& mat = *it;
  708. mOutput << startstr << "<material id=\"" << XMLIDEncode(mat.name) << "\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  709. PushTag();
  710. mOutput << startstr << "<instance_effect url=\"#" << XMLIDEncode(mat.name) << "-fx\"/>" << endstr;
  711. PopTag();
  712. mOutput << startstr << "</material>" << endstr;
  713. }
  714. PopTag();
  715. mOutput << startstr << "</library_materials>" << endstr;
  716. }
  717. }
  718. // ------------------------------------------------------------------------------------------------
  719. // Writes the controller library
  720. void ColladaExporter::WriteControllerLibrary()
  721. {
  722. mOutput << startstr << "<library_controllers>" << endstr;
  723. PushTag();
  724. for( size_t a = 0; a < mScene->mNumMeshes; ++a) {
  725. WriteController( a);
  726. }
  727. PopTag();
  728. mOutput << startstr << "</library_controllers>" << endstr;
  729. }
  730. // ------------------------------------------------------------------------------------------------
  731. // Writes a skin controller of the given mesh
  732. void ColladaExporter::WriteController( size_t pIndex)
  733. {
  734. const aiMesh* mesh = mScene->mMeshes[pIndex];
  735. const std::string idstr = mesh->mName.length == 0 ? GetMeshId(pIndex) : mesh->mName.C_Str();
  736. const std::string idstrEscaped = XMLIDEncode(idstr);
  737. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  738. return;
  739. if ( mesh->mNumBones == 0 )
  740. return;
  741. mOutput << startstr << "<controller id=\"" << idstrEscaped << "-skin\" ";
  742. mOutput << "name=\"skinCluster" << pIndex << "\">"<< endstr;
  743. PushTag();
  744. mOutput << startstr << "<skin source=\"#" << idstrEscaped << "\">" << endstr;
  745. PushTag();
  746. // bind pose matrix
  747. mOutput << startstr << "<bind_shape_matrix>" << endstr;
  748. PushTag();
  749. // I think it is identity in general cases.
  750. aiMatrix4x4 mat;
  751. mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
  752. mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
  753. mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
  754. mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
  755. PopTag();
  756. mOutput << startstr << "</bind_shape_matrix>" << endstr;
  757. mOutput << startstr << "<source id=\"" << idstrEscaped << "-skin-joints\" name=\"" << idstrEscaped << "-skin-joints\">" << endstr;
  758. PushTag();
  759. mOutput << startstr << "<Name_array id=\"" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
  760. for( size_t i = 0; i < mesh->mNumBones; ++i )
  761. mOutput << XMLIDEncode(mesh->mBones[i]->mName.C_Str()) << " ";
  762. mOutput << "</Name_array>" << endstr;
  763. mOutput << startstr << "<technique_common>" << endstr;
  764. PushTag();
  765. mOutput << startstr << "<accessor source=\"#" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
  766. PushTag();
  767. mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
  768. PopTag();
  769. mOutput << startstr << "</accessor>" << endstr;
  770. PopTag();
  771. mOutput << startstr << "</technique_common>" << endstr;
  772. PopTag();
  773. mOutput << startstr << "</source>" << endstr;
  774. std::vector<ai_real> bind_poses;
  775. bind_poses.reserve(mesh->mNumBones * 16);
  776. for(unsigned int i = 0; i < mesh->mNumBones; ++i)
  777. for( unsigned int j = 0; j < 4; ++j)
  778. bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
  779. WriteFloatArray( idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real*) bind_poses.data(), bind_poses.size() / 16);
  780. bind_poses.clear();
  781. std::vector<ai_real> skin_weights;
  782. skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
  783. for( size_t i = 0; i < mesh->mNumBones; ++i)
  784. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  785. skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
  786. WriteFloatArray( idstr + "-skin-weights", FloatType_Weight, (const ai_real*) skin_weights.data(), skin_weights.size());
  787. skin_weights.clear();
  788. mOutput << startstr << "<joints>" << endstr;
  789. PushTag();
  790. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\"></input>" << endstr;
  791. mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstrEscaped << "-skin-bind_poses\"></input>" << endstr;
  792. PopTag();
  793. mOutput << startstr << "</joints>" << endstr;
  794. mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
  795. PushTag();
  796. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\" offset=\"0\"></input>" << endstr;
  797. mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstrEscaped << "-skin-weights\" offset=\"1\"></input>" << endstr;
  798. mOutput << startstr << "<vcount>";
  799. std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
  800. for( size_t i = 0; i < mesh->mNumBones; ++i)
  801. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  802. ++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
  803. for( size_t i = 0; i < mesh->mNumVertices; ++i)
  804. mOutput << num_influences[i] << " ";
  805. mOutput << "</vcount>" << endstr;
  806. mOutput << startstr << "<v>";
  807. ai_uint joint_weight_indices_length = 0;
  808. std::vector<ai_uint> accum_influences;
  809. accum_influences.reserve(num_influences.size());
  810. for( size_t i = 0; i < num_influences.size(); ++i)
  811. {
  812. accum_influences.push_back(joint_weight_indices_length);
  813. joint_weight_indices_length += num_influences[i];
  814. }
  815. ai_uint weight_index = 0;
  816. std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
  817. for( unsigned int i = 0; i < mesh->mNumBones; ++i)
  818. for( unsigned j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  819. {
  820. unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
  821. for( ai_uint k = 0; k < num_influences[vId]; ++k)
  822. {
  823. if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1)
  824. {
  825. joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
  826. joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
  827. break;
  828. }
  829. }
  830. ++weight_index;
  831. }
  832. for( size_t i = 0; i < joint_weight_indices.size(); ++i)
  833. mOutput << joint_weight_indices[i] << " ";
  834. num_influences.clear();
  835. accum_influences.clear();
  836. joint_weight_indices.clear();
  837. mOutput << "</v>" << endstr;
  838. PopTag();
  839. mOutput << startstr << "</vertex_weights>" << endstr;
  840. PopTag();
  841. mOutput << startstr << "</skin>" << endstr;
  842. PopTag();
  843. mOutput << startstr << "</controller>" << endstr;
  844. }
  845. // ------------------------------------------------------------------------------------------------
  846. // Writes the geometry library
  847. void ColladaExporter::WriteGeometryLibrary()
  848. {
  849. mOutput << startstr << "<library_geometries>" << endstr;
  850. PushTag();
  851. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  852. WriteGeometry( a);
  853. PopTag();
  854. mOutput << startstr << "</library_geometries>" << endstr;
  855. }
  856. // ------------------------------------------------------------------------------------------------
  857. // Writes the given mesh
  858. void ColladaExporter::WriteGeometry( size_t pIndex)
  859. {
  860. const aiMesh* mesh = mScene->mMeshes[pIndex];
  861. const std::string idstr = mesh->mName.length == 0 ? GetMeshId(pIndex) : mesh->mName.C_Str();
  862. const std::string geometryName = XMLEscape(idstr);
  863. const std::string geometryId = XMLIDEncode(idstr);
  864. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  865. return;
  866. // opening tag
  867. mOutput << startstr << "<geometry id=\"" << geometryId << "\" name=\"" << geometryName << "\" >" << endstr;
  868. PushTag();
  869. mOutput << startstr << "<mesh>" << endstr;
  870. PushTag();
  871. // Positions
  872. WriteFloatArray( idstr + "-positions", FloatType_Vector, (ai_real*) mesh->mVertices, mesh->mNumVertices);
  873. // Normals, if any
  874. if( mesh->HasNormals() )
  875. WriteFloatArray( idstr + "-normals", FloatType_Vector, (ai_real*) mesh->mNormals, mesh->mNumVertices);
  876. // texture coords
  877. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  878. {
  879. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  880. {
  881. WriteFloatArray( idstr + "-tex" + to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  882. (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
  883. }
  884. }
  885. // vertex colors
  886. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  887. {
  888. if( mesh->HasVertexColors(static_cast<unsigned int>(a)) )
  889. WriteFloatArray( idstr + "-color" + to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
  890. }
  891. // assemble vertex structure
  892. // Only write input for POSITION since we will write other as shared inputs in polygon definition
  893. mOutput << startstr << "<vertices id=\"" << geometryId << "-vertices" << "\">" << endstr;
  894. PushTag();
  895. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << geometryId << "-positions\" />" << endstr;
  896. PopTag();
  897. mOutput << startstr << "</vertices>" << endstr;
  898. // count the number of lines, triangles and polygon meshes
  899. int countLines = 0;
  900. int countPoly = 0;
  901. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  902. {
  903. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  904. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  905. }
  906. // lines
  907. if (countLines)
  908. {
  909. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  910. PushTag();
  911. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  912. if( mesh->HasNormals() )
  913. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  914. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  915. {
  916. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  917. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  918. }
  919. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  920. {
  921. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  922. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  923. }
  924. mOutput << startstr << "<p>";
  925. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  926. {
  927. const aiFace& face = mesh->mFaces[a];
  928. if (face.mNumIndices != 2) continue;
  929. for( size_t b = 0; b < face.mNumIndices; ++b )
  930. mOutput << face.mIndices[b] << " ";
  931. }
  932. mOutput << "</p>" << endstr;
  933. PopTag();
  934. mOutput << startstr << "</lines>" << endstr;
  935. }
  936. // triangle - don't use it, because compatibility problems
  937. // polygons
  938. if (countPoly)
  939. {
  940. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  941. PushTag();
  942. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  943. if( mesh->HasNormals() )
  944. mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  945. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  946. {
  947. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  948. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  949. }
  950. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  951. {
  952. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  953. mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  954. }
  955. mOutput << startstr << "<vcount>";
  956. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  957. {
  958. if (mesh->mFaces[a].mNumIndices < 3) continue;
  959. mOutput << mesh->mFaces[a].mNumIndices << " ";
  960. }
  961. mOutput << "</vcount>" << endstr;
  962. mOutput << startstr << "<p>";
  963. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  964. {
  965. const aiFace& face = mesh->mFaces[a];
  966. if (face.mNumIndices < 3) continue;
  967. for( size_t b = 0; b < face.mNumIndices; ++b )
  968. mOutput << face.mIndices[b] << " ";
  969. }
  970. mOutput << "</p>" << endstr;
  971. PopTag();
  972. mOutput << startstr << "</polylist>" << endstr;
  973. }
  974. // closing tags
  975. PopTag();
  976. mOutput << startstr << "</mesh>" << endstr;
  977. PopTag();
  978. mOutput << startstr << "</geometry>" << endstr;
  979. }
  980. // ------------------------------------------------------------------------------------------------
  981. // Writes a float array of the given type
  982. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount)
  983. {
  984. size_t floatsPerElement = 0;
  985. switch( pType )
  986. {
  987. case FloatType_Vector: floatsPerElement = 3; break;
  988. case FloatType_TexCoord2: floatsPerElement = 2; break;
  989. case FloatType_TexCoord3: floatsPerElement = 3; break;
  990. case FloatType_Color: floatsPerElement = 3; break;
  991. case FloatType_Mat4x4: floatsPerElement = 16; break;
  992. case FloatType_Weight: floatsPerElement = 1; break;
  993. case FloatType_Time: floatsPerElement = 1; break;
  994. default:
  995. return;
  996. }
  997. std::string arrayId = XMLIDEncode(pIdString) + "-array";
  998. mOutput << startstr << "<source id=\"" << XMLIDEncode(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  999. PushTag();
  1000. // source array
  1001. mOutput << startstr << "<float_array id=\"" << arrayId << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  1002. PushTag();
  1003. if( pType == FloatType_TexCoord2 )
  1004. {
  1005. for( size_t a = 0; a < pElementCount; ++a )
  1006. {
  1007. mOutput << pData[a*3+0] << " ";
  1008. mOutput << pData[a*3+1] << " ";
  1009. }
  1010. }
  1011. else if( pType == FloatType_Color )
  1012. {
  1013. for( size_t a = 0; a < pElementCount; ++a )
  1014. {
  1015. mOutput << pData[a*4+0] << " ";
  1016. mOutput << pData[a*4+1] << " ";
  1017. mOutput << pData[a*4+2] << " ";
  1018. }
  1019. }
  1020. else
  1021. {
  1022. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  1023. mOutput << pData[a] << " ";
  1024. }
  1025. mOutput << "</float_array>" << endstr;
  1026. PopTag();
  1027. // the usual Collada fun. Let's bloat it even more!
  1028. mOutput << startstr << "<technique_common>" << endstr;
  1029. PushTag();
  1030. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  1031. PushTag();
  1032. switch( pType )
  1033. {
  1034. case FloatType_Vector:
  1035. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  1036. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  1037. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  1038. break;
  1039. case FloatType_TexCoord2:
  1040. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  1041. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  1042. break;
  1043. case FloatType_TexCoord3:
  1044. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  1045. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  1046. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  1047. break;
  1048. case FloatType_Color:
  1049. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  1050. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  1051. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  1052. break;
  1053. case FloatType_Mat4x4:
  1054. mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
  1055. break;
  1056. case FloatType_Weight:
  1057. mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
  1058. break;
  1059. // customized, add animation related
  1060. case FloatType_Time:
  1061. mOutput << startstr << "<param name=\"TIME\" type=\"float\" />" << endstr;
  1062. break;
  1063. }
  1064. PopTag();
  1065. mOutput << startstr << "</accessor>" << endstr;
  1066. PopTag();
  1067. mOutput << startstr << "</technique_common>" << endstr;
  1068. PopTag();
  1069. mOutput << startstr << "</source>" << endstr;
  1070. }
  1071. // ------------------------------------------------------------------------------------------------
  1072. // Writes the scene library
  1073. void ColladaExporter::WriteSceneLibrary()
  1074. {
  1075. const std::string sceneName = XMLEscape(mScene->mRootNode->mName.C_Str());
  1076. const std::string sceneId = XMLIDEncode(mScene->mRootNode->mName.C_Str());
  1077. mOutput << startstr << "<library_visual_scenes>" << endstr;
  1078. PushTag();
  1079. mOutput << startstr << "<visual_scene id=\"" + sceneId + "\" name=\"" + sceneName + "\">" << endstr;
  1080. PushTag();
  1081. // start recursive write at the root node
  1082. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  1083. WriteNode( mScene, mScene->mRootNode->mChildren[a]);
  1084. PopTag();
  1085. mOutput << startstr << "</visual_scene>" << endstr;
  1086. PopTag();
  1087. mOutput << startstr << "</library_visual_scenes>" << endstr;
  1088. }
  1089. // ------------------------------------------------------------------------------------------------
  1090. void ColladaExporter::WriteAnimationLibrary(size_t pIndex)
  1091. {
  1092. static const float kSecondsFromMilliseconds = .001f;
  1093. const aiAnimation * anim = mScene->mAnimations[pIndex];
  1094. if ( anim->mNumChannels == 0 && anim->mNumMeshChannels == 0 && anim->mNumMorphMeshChannels ==0 ) {
  1095. return;
  1096. }
  1097. const std::string animation_name_escaped = XMLEscape( anim->mName.C_Str() );
  1098. std::string idstr = anim->mName.C_Str();
  1099. std::string ending = std::string( "AnimId" ) + to_string(pIndex);
  1100. if (idstr.length() >= ending.length()) {
  1101. if (0 != idstr.compare (idstr.length() - ending.length(), ending.length(), ending)) {
  1102. idstr = idstr + ending;
  1103. }
  1104. } else {
  1105. idstr = idstr + ending;
  1106. }
  1107. const std::string idstrEscaped = XMLIDEncode(idstr);
  1108. mOutput << startstr << "<animation id=\"" + idstrEscaped + "\" name=\"" + animation_name_escaped + "\">" << endstr;
  1109. PushTag();
  1110. std::string cur_node_idstr;
  1111. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1112. const aiNodeAnim * nodeAnim = anim->mChannels[a];
  1113. // sanity check
  1114. if (nodeAnim->mNumPositionKeys != nodeAnim->mNumScalingKeys || nodeAnim->mNumPositionKeys != nodeAnim->mNumRotationKeys) {
  1115. continue;
  1116. }
  1117. {
  1118. cur_node_idstr.clear();
  1119. cur_node_idstr += nodeAnim->mNodeName.data;
  1120. cur_node_idstr += std::string("_matrix-input");
  1121. std::vector<ai_real> frames;
  1122. for( size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1123. frames.push_back(static_cast<ai_real>(nodeAnim->mPositionKeys[i].mTime) * kSecondsFromMilliseconds);
  1124. }
  1125. WriteFloatArray(cur_node_idstr, FloatType_Time, (const ai_real *)frames.data(), frames.size());
  1126. frames.clear();
  1127. }
  1128. {
  1129. cur_node_idstr.clear();
  1130. cur_node_idstr += nodeAnim->mNodeName.data;
  1131. cur_node_idstr += std::string("_matrix-output");
  1132. std::vector<ai_real> keyframes;
  1133. keyframes.reserve(nodeAnim->mNumPositionKeys * 16);
  1134. for( size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1135. aiVector3D Scaling = nodeAnim->mScalingKeys[i].mValue;
  1136. aiMatrix4x4 ScalingM; // identity
  1137. ScalingM[0][0] = Scaling.x; ScalingM[1][1] = Scaling.y; ScalingM[2][2] = Scaling.z;
  1138. aiQuaternion RotationQ = nodeAnim->mRotationKeys[i].mValue;
  1139. aiMatrix4x4 s = aiMatrix4x4( RotationQ.GetMatrix() );
  1140. aiMatrix4x4 RotationM(s.a1, s.a2, s.a3, 0, s.b1, s.b2, s.b3, 0, s.c1, s.c2, s.c3, 0, 0, 0, 0, 1);
  1141. aiVector3D Translation = nodeAnim->mPositionKeys[i].mValue;
  1142. aiMatrix4x4 TranslationM; // identity
  1143. TranslationM[0][3] = Translation.x; TranslationM[1][3] = Translation.y; TranslationM[2][3] = Translation.z;
  1144. // Combine the above transformations
  1145. aiMatrix4x4 mat = TranslationM * RotationM * ScalingM;
  1146. for( unsigned int j = 0; j < 4; ++j) {
  1147. keyframes.insert(keyframes.end(), mat[j], mat[j] + 4);
  1148. }
  1149. }
  1150. WriteFloatArray(cur_node_idstr, FloatType_Mat4x4, (const ai_real *)keyframes.data(), keyframes.size() / 16);
  1151. }
  1152. {
  1153. std::vector<std::string> names;
  1154. for ( size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1155. if ( nodeAnim->mPreState == aiAnimBehaviour_DEFAULT
  1156. || nodeAnim->mPreState == aiAnimBehaviour_LINEAR
  1157. || nodeAnim->mPreState == aiAnimBehaviour_REPEAT
  1158. ) {
  1159. names.push_back( "LINEAR" );
  1160. } else if (nodeAnim->mPostState == aiAnimBehaviour_CONSTANT) {
  1161. names.push_back( "STEP" );
  1162. }
  1163. }
  1164. const std::string cur_node_idstr2 = nodeAnim->mNodeName.data + std::string("_matrix-interpolation");
  1165. std::string arrayId = XMLIDEncode(cur_node_idstr2) + "-array";
  1166. mOutput << startstr << "<source id=\"" << XMLIDEncode(cur_node_idstr2) << "\">" << endstr;
  1167. PushTag();
  1168. // source array
  1169. mOutput << startstr << "<Name_array id=\"" << arrayId << "\" count=\"" << names.size() << "\"> ";
  1170. for( size_t aa = 0; aa < names.size(); ++aa ) {
  1171. mOutput << names[aa] << " ";
  1172. }
  1173. mOutput << "</Name_array>" << endstr;
  1174. mOutput << startstr << "<technique_common>" << endstr;
  1175. PushTag();
  1176. mOutput << startstr << "<accessor source=\"#" << arrayId << "\" count=\"" << names.size() << "\" stride=\"" << 1 << "\">" << endstr;
  1177. PushTag();
  1178. mOutput << startstr << "<param name=\"INTERPOLATION\" type=\"name\"></param>" << endstr;
  1179. PopTag();
  1180. mOutput << startstr << "</accessor>" << endstr;
  1181. PopTag();
  1182. mOutput << startstr << "</technique_common>" << endstr;
  1183. PopTag();
  1184. mOutput << startstr << "</source>" << endstr;
  1185. }
  1186. }
  1187. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1188. const aiNodeAnim * nodeAnim = anim->mChannels[a];
  1189. {
  1190. // samplers
  1191. const std::string node_idstr = nodeAnim->mNodeName.data + std::string("_matrix-sampler");
  1192. mOutput << startstr << "<sampler id=\"" << XMLIDEncode(node_idstr) << "\">" << endstr;
  1193. PushTag();
  1194. mOutput << startstr << "<input semantic=\"INPUT\" source=\"#" << XMLIDEncode( nodeAnim->mNodeName.data + std::string("_matrix-input") ) << "\"/>" << endstr;
  1195. mOutput << startstr << "<input semantic=\"OUTPUT\" source=\"#" << XMLIDEncode( nodeAnim->mNodeName.data + std::string("_matrix-output") ) << "\"/>" << endstr;
  1196. mOutput << startstr << "<input semantic=\"INTERPOLATION\" source=\"#" << XMLIDEncode( nodeAnim->mNodeName.data + std::string("_matrix-interpolation") ) << "\"/>" << endstr;
  1197. PopTag();
  1198. mOutput << startstr << "</sampler>" << endstr;
  1199. }
  1200. }
  1201. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1202. const aiNodeAnim * nodeAnim = anim->mChannels[a];
  1203. {
  1204. // channels
  1205. mOutput << startstr << "<channel source=\"#" << XMLIDEncode( nodeAnim->mNodeName.data + std::string("_matrix-sampler") ) << "\" target=\"" << XMLIDEncode(nodeAnim->mNodeName.data) << "/matrix\"/>" << endstr;
  1206. }
  1207. }
  1208. PopTag();
  1209. mOutput << startstr << "</animation>" << endstr;
  1210. }
  1211. // ------------------------------------------------------------------------------------------------
  1212. void ColladaExporter::WriteAnimationsLibrary()
  1213. {
  1214. if ( mScene->mNumAnimations > 0 ) {
  1215. mOutput << startstr << "<library_animations>" << endstr;
  1216. PushTag();
  1217. // start recursive write at the root node
  1218. for( size_t a = 0; a < mScene->mNumAnimations; ++a)
  1219. WriteAnimationLibrary( a );
  1220. PopTag();
  1221. mOutput << startstr << "</library_animations>" << endstr;
  1222. }
  1223. }
  1224. // ------------------------------------------------------------------------------------------------
  1225. // Helper to find a bone by name in the scene
  1226. aiBone* findBone( const aiScene* scene, const char * name) {
  1227. for (size_t m=0; m<scene->mNumMeshes; m++) {
  1228. aiMesh * mesh = scene->mMeshes[m];
  1229. for (size_t b=0; b<mesh->mNumBones; b++) {
  1230. aiBone * bone = mesh->mBones[b];
  1231. if (0 == strcmp(name, bone->mName.C_Str())) {
  1232. return bone;
  1233. }
  1234. }
  1235. }
  1236. return NULL;
  1237. }
  1238. // ------------------------------------------------------------------------------------------------
  1239. const aiNode * findBoneNode( const aiNode* aNode, const aiBone* bone)
  1240. {
  1241. if ( aNode && bone && aNode->mName == bone->mName ) {
  1242. return aNode;
  1243. }
  1244. if ( aNode && bone ) {
  1245. for (unsigned int i=0; i < aNode->mNumChildren; ++i) {
  1246. aiNode * aChild = aNode->mChildren[i];
  1247. const aiNode * foundFromChild = 0;
  1248. if ( aChild ) {
  1249. foundFromChild = findBoneNode( aChild, bone );
  1250. if ( foundFromChild ) return foundFromChild;
  1251. }
  1252. }
  1253. }
  1254. return NULL;
  1255. }
  1256. const aiNode * findSkeletonRootNode( const aiScene* scene, const aiMesh * mesh)
  1257. {
  1258. std::set<const aiNode*> topParentBoneNodes;
  1259. if ( mesh && mesh->mNumBones > 0 ) {
  1260. for (unsigned int i=0; i < mesh->mNumBones; ++i) {
  1261. aiBone * bone = mesh->mBones[i];
  1262. const aiNode * node = findBoneNode( scene->mRootNode, bone);
  1263. if ( node ) {
  1264. while ( node->mParent && findBone(scene, node->mParent->mName.C_Str() ) != 0 ) {
  1265. node = node->mParent;
  1266. }
  1267. topParentBoneNodes.insert( node );
  1268. }
  1269. }
  1270. }
  1271. if ( !topParentBoneNodes.empty() ) {
  1272. const aiNode * parentBoneNode = *topParentBoneNodes.begin();
  1273. if ( topParentBoneNodes.size() == 1 ) {
  1274. return parentBoneNode;
  1275. } else {
  1276. for (auto it : topParentBoneNodes) {
  1277. if ( it->mParent ) return it->mParent;
  1278. }
  1279. return parentBoneNode;
  1280. }
  1281. }
  1282. return NULL;
  1283. }
  1284. // ------------------------------------------------------------------------------------------------
  1285. // Recursively writes the given node
  1286. void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
  1287. {
  1288. // the node must have a name
  1289. if (pNode->mName.length == 0)
  1290. {
  1291. std::stringstream ss;
  1292. ss << "Node_" << pNode;
  1293. pNode->mName.Set(ss.str());
  1294. }
  1295. // If the node is associated with a bone, it is a joint node (JOINT)
  1296. // otherwise it is a normal node (NODE)
  1297. const char * node_type;
  1298. bool is_joint, is_skeleton_root = false;
  1299. if (nullptr == findBone(pScene, pNode->mName.C_Str())) {
  1300. node_type = "NODE";
  1301. is_joint = false;
  1302. } else {
  1303. node_type = "JOINT";
  1304. is_joint = true;
  1305. if (!pNode->mParent || nullptr == findBone(pScene, pNode->mParent->mName.C_Str())) {
  1306. is_skeleton_root = true;
  1307. }
  1308. }
  1309. const std::string node_id = XMLIDEncode(pNode->mName.data);
  1310. const std::string node_name = XMLEscape(pNode->mName.data);
  1311. mOutput << startstr << "<node ";
  1312. if(is_skeleton_root) {
  1313. mOutput << "id=\"" << node_id << "\" " << (is_joint ? "sid=\"" + node_id +"\"" : "") ; // For now, only support one skeleton in a scene.
  1314. mFoundSkeletonRootNodeID = node_id;
  1315. } else {
  1316. mOutput << "id=\"" << node_id << "\" " << (is_joint ? "sid=\"" + node_id +"\"": "") ;
  1317. }
  1318. mOutput << " name=\"" << node_name
  1319. << "\" type=\"" << node_type
  1320. << "\">" << endstr;
  1321. PushTag();
  1322. // write transformation - we can directly put the matrix there
  1323. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  1324. aiMatrix4x4 mat = pNode->mTransformation;
  1325. // If this node is a Camera node, the camera coordinate system needs to be multiplied in.
  1326. // When importing from Collada, the mLookAt is set to 0, 0, -1, and the node transform is unchanged.
  1327. // When importing from a different format, mLookAt is set to 0, 0, 1. Therefore, the local camera
  1328. // coordinate system must be changed to matche the Collada specification.
  1329. for (size_t i = 0; i<mScene->mNumCameras; i++){
  1330. if (mScene->mCameras[i]->mName == pNode->mName){
  1331. aiMatrix4x4 sourceView;
  1332. mScene->mCameras[i]->GetCameraMatrix(sourceView);
  1333. aiMatrix4x4 colladaView;
  1334. colladaView.a1 = colladaView.c3 = -1; // move into -z space.
  1335. mat *= (sourceView * colladaView);
  1336. break;
  1337. }
  1338. }
  1339. // customized, sid should be 'matrix' to match with loader code.
  1340. //mOutput << startstr << "<matrix sid=\"transform\">";
  1341. mOutput << startstr << "<matrix sid=\"matrix\">";
  1342. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  1343. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  1344. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  1345. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  1346. mOutput << "</matrix>" << endstr;
  1347. if(pNode->mNumMeshes==0){
  1348. //check if it is a camera node
  1349. for(size_t i=0; i<mScene->mNumCameras; i++){
  1350. if(mScene->mCameras[i]->mName == pNode->mName){
  1351. mOutput << startstr <<"<instance_camera url=\"#" << node_id << "-camera\"/>" << endstr;
  1352. break;
  1353. }
  1354. }
  1355. //check if it is a light node
  1356. for(size_t i=0; i<mScene->mNumLights; i++){
  1357. if(mScene->mLights[i]->mName == pNode->mName){
  1358. mOutput << startstr <<"<instance_light url=\"#" << node_id << "-light\"/>" << endstr;
  1359. break;
  1360. }
  1361. }
  1362. }else
  1363. // instance every geometry
  1364. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  1365. {
  1366. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  1367. // do not instantiate mesh if empty. I wonder how this could happen
  1368. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  1369. continue;
  1370. const std::string meshName = mesh->mName.length == 0 ? GetMeshId(pNode->mMeshes[a]) : mesh->mName.C_Str();
  1371. if( mesh->mNumBones == 0 )
  1372. {
  1373. mOutput << startstr << "<instance_geometry url=\"#" << XMLIDEncode(meshName) << "\">" << endstr;
  1374. PushTag();
  1375. }
  1376. else
  1377. {
  1378. mOutput << startstr
  1379. << "<instance_controller url=\"#" << XMLIDEncode(meshName) << "-skin\">"
  1380. << endstr;
  1381. PushTag();
  1382. // note! this mFoundSkeletonRootNodeID some how affects animation, it makes the mesh attaches to armature skeleton root node.
  1383. // use the first bone to find skeleton root
  1384. const aiNode * skeletonRootBoneNode = findSkeletonRootNode( pScene, mesh );
  1385. if ( skeletonRootBoneNode ) {
  1386. mFoundSkeletonRootNodeID = XMLIDEncode( skeletonRootBoneNode->mName.C_Str() );
  1387. }
  1388. mOutput << startstr << "<skeleton>#" << mFoundSkeletonRootNodeID << "</skeleton>" << endstr;
  1389. }
  1390. mOutput << startstr << "<bind_material>" << endstr;
  1391. PushTag();
  1392. mOutput << startstr << "<technique_common>" << endstr;
  1393. PushTag();
  1394. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLIDEncode(materials[mesh->mMaterialIndex].name) << "\">" << endstr;
  1395. PushTag();
  1396. for( size_t aa = 0; aa < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++aa )
  1397. {
  1398. if( mesh->HasTextureCoords( static_cast<unsigned int>(aa) ) )
  1399. // semantic as in <texture texcoord=...>
  1400. // input_semantic as in <input semantic=...>
  1401. // input_set as in <input set=...>
  1402. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << aa << "\" input_semantic=\"TEXCOORD\" input_set=\"" << aa << "\"/>" << endstr;
  1403. }
  1404. PopTag();
  1405. mOutput << startstr << "</instance_material>" << endstr;
  1406. PopTag();
  1407. mOutput << startstr << "</technique_common>" << endstr;
  1408. PopTag();
  1409. mOutput << startstr << "</bind_material>" << endstr;
  1410. PopTag();
  1411. if( mesh->mNumBones == 0)
  1412. mOutput << startstr << "</instance_geometry>" << endstr;
  1413. else
  1414. mOutput << startstr << "</instance_controller>" << endstr;
  1415. }
  1416. // recurse into subnodes
  1417. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  1418. WriteNode( pScene, pNode->mChildren[a]);
  1419. PopTag();
  1420. mOutput << startstr << "</node>" << endstr;
  1421. }
  1422. #endif
  1423. #endif