ColladaExporter.cpp 63 KB

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