ColladaExporter.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, 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 "Bitmap.h"
  37. #include "fast_atof.h"
  38. #include "SceneCombiner.h"
  39. #include "DefaultIOSystem.h"
  40. #include "StringUtils.h"
  41. #include "XMLTools.h"
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/Exporter.hpp>
  44. #include <assimp/scene.h>
  45. #include "Exceptional.h"
  46. #include <memory>
  47. #include <ctime>
  48. #include <set>
  49. using namespace Assimp;
  50. namespace Assimp
  51. {
  52. // ------------------------------------------------------------------------------------------------
  53. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  54. void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  55. {
  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. // we're still here - export successfully completed. Write result to the given IOSYstem
  61. std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  62. if(outfile == NULL) {
  63. throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
  64. }
  65. // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
  66. outfile->Write( iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()),1);
  67. }
  68. } // end of namespace Assimp
  69. // ------------------------------------------------------------------------------------------------
  70. // Constructor for a specific scene to export
  71. ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file) : mIOSystem(pIOSystem), mPath(path), mFile(file)
  72. {
  73. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  74. mOutput.imbue( std::locale("C") );
  75. mOutput.precision(16);
  76. mScene = pScene;
  77. mSceneOwned = false;
  78. // set up strings
  79. endstr = "\n";
  80. // start writing
  81. WriteFile();
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Destructor
  85. ColladaExporter::~ColladaExporter()
  86. {
  87. if(mSceneOwned) {
  88. delete mScene;
  89. }
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Starts writing the contents
  93. void ColladaExporter::WriteFile()
  94. {
  95. // write the DTD
  96. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  97. // COLLADA element start
  98. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  99. PushTag();
  100. WriteTextures();
  101. WriteHeader();
  102. WriteCamerasLibrary();
  103. WriteLightsLibrary();
  104. WriteMaterials();
  105. WriteGeometryLibrary();
  106. WriteSceneLibrary();
  107. // useless Collada fu at the end, just in case we haven't had enough indirections, yet.
  108. mOutput << startstr << "<scene>" << endstr;
  109. PushTag();
  110. mOutput << startstr << "<instance_visual_scene url=\"#" + XMLEscape(mScene->mRootNode->mName.C_Str()) + "\" />" << endstr;
  111. PopTag();
  112. mOutput << startstr << "</scene>" << endstr;
  113. PopTag();
  114. mOutput << "</COLLADA>" << endstr;
  115. }
  116. // ------------------------------------------------------------------------------------------------
  117. // Writes the asset header
  118. void ColladaExporter::WriteHeader()
  119. {
  120. static const ai_real epsilon = ai_real( 0.00001 );
  121. static const aiQuaternion x_rot(aiMatrix3x3(
  122. 0, -1, 0,
  123. 1, 0, 0,
  124. 0, 0, 1));
  125. static const aiQuaternion y_rot(aiMatrix3x3(
  126. 1, 0, 0,
  127. 0, 1, 0,
  128. 0, 0, 1));
  129. static const aiQuaternion z_rot(aiMatrix3x3(
  130. 1, 0, 0,
  131. 0, 0, 1,
  132. 0, -1, 0));
  133. static const unsigned int date_nb_chars = 20;
  134. char date_str[date_nb_chars];
  135. std::time_t date = std::time(NULL);
  136. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  137. aiVector3D scaling;
  138. aiQuaternion rotation;
  139. aiVector3D position;
  140. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  141. rotation.Normalize();
  142. bool add_root_node = false;
  143. ai_real scale = 1.0;
  144. if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  145. scale = (ai_real) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
  146. } else {
  147. add_root_node = true;
  148. }
  149. std::string up_axis = "Y_UP";
  150. if(rotation.Equal(x_rot, epsilon)) {
  151. up_axis = "X_UP";
  152. } else if(rotation.Equal(y_rot, epsilon)) {
  153. up_axis = "Y_UP";
  154. } else if(rotation.Equal(z_rot, epsilon)) {
  155. up_axis = "Z_UP";
  156. } else {
  157. add_root_node = true;
  158. }
  159. if(! position.Equal(aiVector3D(0, 0, 0))) {
  160. add_root_node = true;
  161. }
  162. if(mScene->mRootNode->mNumChildren == 0) {
  163. add_root_node = true;
  164. }
  165. if(add_root_node) {
  166. aiScene* scene;
  167. SceneCombiner::CopyScene(&scene, mScene);
  168. aiNode* root = new aiNode("Scene");
  169. root->mNumChildren = 1;
  170. root->mChildren = new aiNode*[root->mNumChildren];
  171. root->mChildren[0] = scene->mRootNode;
  172. scene->mRootNode->mParent = root;
  173. scene->mRootNode = root;
  174. mScene = scene;
  175. mSceneOwned = true;
  176. up_axis = "Y_UP";
  177. scale = 1.0;
  178. }
  179. mOutput << startstr << "<asset>" << endstr;
  180. PushTag();
  181. mOutput << startstr << "<contributor>" << endstr;
  182. PushTag();
  183. aiMetadata* meta = mScene->mRootNode->mMetaData;
  184. aiString value;
  185. if (!meta || !meta->Get("Author", value))
  186. mOutput << startstr << "<author>" << "Assimp" << "</author>" << endstr;
  187. else
  188. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  189. if (!meta || !meta->Get("AuthoringTool", value))
  190. mOutput << startstr << "<authoring_tool>" << "Assimp Exporter" << "</authoring_tool>" << endstr;
  191. else
  192. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  193. //mOutput << startstr << "<author>" << mScene->author.C_Str() << "</author>" << endstr;
  194. //mOutput << startstr << "<authoring_tool>" << mScene->authoringTool.C_Str() << "</authoring_tool>" << endstr;
  195. PopTag();
  196. mOutput << startstr << "</contributor>" << endstr;
  197. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  198. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  199. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  200. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  201. PopTag();
  202. mOutput << startstr << "</asset>" << endstr;
  203. }
  204. // ------------------------------------------------------------------------------------------------
  205. // Write the embedded textures
  206. void ColladaExporter::WriteTextures() {
  207. static const unsigned int buffer_size = 1024;
  208. char str[buffer_size];
  209. if(mScene->HasTextures()) {
  210. for(unsigned int i = 0; i < mScene->mNumTextures; i++) {
  211. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  212. // so we just write the textures in the current directory.
  213. aiTexture* texture = mScene->mTextures[i];
  214. ASSIMP_itoa10(str, buffer_size, i + 1);
  215. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
  216. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb"));
  217. if(outfile == NULL) {
  218. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  219. }
  220. if(texture->mHeight == 0) {
  221. outfile->Write((void*) texture->pcData, texture->mWidth, 1);
  222. } else {
  223. Bitmap::Save(texture, outfile.get());
  224. }
  225. outfile->Flush();
  226. textures.insert(std::make_pair(i, name));
  227. }
  228. }
  229. }
  230. // ------------------------------------------------------------------------------------------------
  231. // Write the embedded textures
  232. void ColladaExporter::WriteCamerasLibrary() {
  233. if(mScene->HasCameras()) {
  234. mOutput << startstr << "<library_cameras>" << endstr;
  235. PushTag();
  236. for( size_t a = 0; a < mScene->mNumCameras; ++a)
  237. WriteCamera( a);
  238. PopTag();
  239. mOutput << startstr << "</library_cameras>" << endstr;
  240. }
  241. }
  242. void ColladaExporter::WriteCamera(size_t pIndex){
  243. const aiCamera *cam = mScene->mCameras[pIndex];
  244. const std::string idstrEscaped = XMLEscape(cam->mName.C_Str());
  245. mOutput << startstr << "<camera id=\"" << idstrEscaped << "-camera\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  246. PushTag();
  247. mOutput << startstr << "<optics>" << endstr;
  248. PushTag();
  249. mOutput << startstr << "<technique_common>" << endstr;
  250. PushTag();
  251. //assimp doesn't support the import of orthographic cameras! se we write
  252. //always perspective
  253. mOutput << startstr << "<perspective>" << endstr;
  254. PushTag();
  255. mOutput << startstr << "<xfov sid=\"xfov\">"<<
  256. AI_RAD_TO_DEG(cam->mHorizontalFOV)
  257. <<"</xfov>" << endstr;
  258. mOutput << startstr << "<aspect_ratio>"
  259. << cam->mAspect
  260. << "</aspect_ratio>" << endstr;
  261. mOutput << startstr << "<znear sid=\"znear\">"
  262. << cam->mClipPlaneNear
  263. << "</znear>" << endstr;
  264. mOutput << startstr << "<zfar sid=\"zfar\">"
  265. << cam->mClipPlaneFar
  266. << "</zfar>" << endstr;
  267. PopTag();
  268. mOutput << startstr << "</perspective>" << endstr;
  269. PopTag();
  270. mOutput << startstr << "</technique_common>" << endstr;
  271. PopTag();
  272. mOutput << startstr << "</optics>" << endstr;
  273. PopTag();
  274. mOutput << startstr << "</camera>" << endstr;
  275. }
  276. // ------------------------------------------------------------------------------------------------
  277. // Write the embedded textures
  278. void ColladaExporter::WriteLightsLibrary() {
  279. if(mScene->HasLights()) {
  280. mOutput << startstr << "<library_lights>" << endstr;
  281. PushTag();
  282. for( size_t a = 0; a < mScene->mNumLights; ++a)
  283. WriteLight( a);
  284. PopTag();
  285. mOutput << startstr << "</library_lights>" << endstr;
  286. }
  287. }
  288. void ColladaExporter::WriteLight(size_t pIndex){
  289. const aiLight *light = mScene->mLights[pIndex];
  290. const std::string idstrEscaped = XMLEscape(light->mName.C_Str());
  291. mOutput << startstr << "<light id=\"" << idstrEscaped << "-light\" name=\""
  292. << idstrEscaped << "_name\" >" << endstr;
  293. PushTag();
  294. mOutput << startstr << "<technique_common>" << endstr;
  295. PushTag();
  296. switch(light->mType){
  297. case aiLightSource_AMBIENT:
  298. WriteAmbienttLight(light);
  299. break;
  300. case aiLightSource_DIRECTIONAL:
  301. WriteDirectionalLight(light);
  302. break;
  303. case aiLightSource_POINT:
  304. WritePointLight(light);
  305. break;
  306. case aiLightSource_SPOT:
  307. WriteSpotLight(light);
  308. break;
  309. case aiLightSource_AREA:
  310. case aiLightSource_UNDEFINED:
  311. case _aiLightSource_Force32Bit:
  312. break;
  313. }
  314. PopTag();
  315. mOutput << startstr << "</technique_common>" << endstr;
  316. PopTag();
  317. mOutput << startstr << "</light>" << endstr;
  318. }
  319. void ColladaExporter::WritePointLight(const aiLight *const light){
  320. const aiColor3D &color= light->mColorDiffuse;
  321. mOutput << startstr << "<point>" << endstr;
  322. PushTag();
  323. mOutput << startstr << "<color sid=\"color\">"
  324. << color.r<<" "<<color.g<<" "<<color.b
  325. <<"</color>" << endstr;
  326. mOutput << startstr << "<constant_attenuation>"
  327. << light->mAttenuationConstant
  328. <<"</constant_attenuation>" << endstr;
  329. mOutput << startstr << "<linear_attenuation>"
  330. << light->mAttenuationLinear
  331. <<"</linear_attenuation>" << endstr;
  332. mOutput << startstr << "<quadratic_attenuation>"
  333. << light->mAttenuationQuadratic
  334. <<"</quadratic_attenuation>" << endstr;
  335. PopTag();
  336. mOutput << startstr << "</point>" << endstr;
  337. }
  338. void ColladaExporter::WriteDirectionalLight(const aiLight *const light){
  339. const aiColor3D &color= light->mColorDiffuse;
  340. mOutput << startstr << "<directional>" << endstr;
  341. PushTag();
  342. mOutput << startstr << "<color sid=\"color\">"
  343. << color.r<<" "<<color.g<<" "<<color.b
  344. <<"</color>" << endstr;
  345. PopTag();
  346. mOutput << startstr << "</directional>" << endstr;
  347. }
  348. void ColladaExporter::WriteSpotLight(const aiLight *const light){
  349. const aiColor3D &color= light->mColorDiffuse;
  350. mOutput << startstr << "<spot>" << endstr;
  351. PushTag();
  352. mOutput << startstr << "<color sid=\"color\">"
  353. << color.r<<" "<<color.g<<" "<<color.b
  354. <<"</color>" << endstr;
  355. mOutput << startstr << "<constant_attenuation>"
  356. << light->mAttenuationConstant
  357. <<"</constant_attenuation>" << endstr;
  358. mOutput << startstr << "<linear_attenuation>"
  359. << light->mAttenuationLinear
  360. <<"</linear_attenuation>" << endstr;
  361. mOutput << startstr << "<quadratic_attenuation>"
  362. << light->mAttenuationQuadratic
  363. <<"</quadratic_attenuation>" << endstr;
  364. /*
  365. out->mAngleOuterCone = AI_DEG_TO_RAD (std::acos(std::pow(0.1f,1.f/srcLight->mFalloffExponent))+
  366. srcLight->mFalloffAngle);
  367. */
  368. const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
  369. mOutput << startstr <<"<falloff_angle sid=\"fall_off_angle\">"
  370. << fallOffAngle
  371. <<"</falloff_angle>" << endstr;
  372. double temp = light->mAngleOuterCone-light->mAngleInnerCone;
  373. temp = std::cos(temp);
  374. temp = std::log(temp)/std::log(0.1);
  375. temp = 1/temp;
  376. mOutput << startstr << "<falloff_exponent sid=\"fall_off_exponent\">"
  377. << temp
  378. <<"</falloff_exponent>" << endstr;
  379. PopTag();
  380. mOutput << startstr << "</spot>" << endstr;
  381. }
  382. void ColladaExporter::WriteAmbienttLight(const aiLight *const light){
  383. const aiColor3D &color= light->mColorAmbient;
  384. mOutput << startstr << "<ambient>" << endstr;
  385. PushTag();
  386. mOutput << startstr << "<color sid=\"color\">"
  387. << color.r<<" "<<color.g<<" "<<color.b
  388. <<"</color>" << endstr;
  389. PopTag();
  390. mOutput << startstr << "</ambient>" << endstr;
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. // Reads a single surface entry from the given material keys
  394. void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex)
  395. {
  396. if( pSrcMat->GetTextureCount( pTexture) > 0 )
  397. {
  398. aiString texfile;
  399. unsigned int uvChannel = 0;
  400. pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel);
  401. std::string index_str(texfile.C_Str());
  402. if(index_str.size() != 0 && index_str[0] == '*')
  403. {
  404. unsigned int index;
  405. index_str = index_str.substr(1, std::string::npos);
  406. try {
  407. index = (unsigned int) strtoul10_64(index_str.c_str());
  408. } catch(std::exception& error) {
  409. throw DeadlyExportError(error.what());
  410. }
  411. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  412. if(name != textures.end()) {
  413. poSurface.texture = name->second;
  414. } else {
  415. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  416. }
  417. } else
  418. {
  419. poSurface.texture = texfile.C_Str();
  420. }
  421. poSurface.channel = uvChannel;
  422. poSurface.exist = true;
  423. } else
  424. {
  425. if( pKey )
  426. poSurface.exist = pSrcMat->Get( pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
  427. }
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version.
  431. static bool isalnum_C(char c)
  432. {
  433. return ( nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c) );
  434. }
  435. // ------------------------------------------------------------------------------------------------
  436. // Writes an image entry for the given surface
  437. void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd)
  438. {
  439. if( !pSurface.texture.empty() )
  440. {
  441. mOutput << startstr << "<image id=\"" << XMLEscape(pNameAdd) << "\">" << endstr;
  442. PushTag();
  443. mOutput << startstr << "<init_from>";
  444. // URL encode image file name first, then XML encode on top
  445. std::stringstream imageUrlEncoded;
  446. for( std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it )
  447. {
  448. if( isalnum_C( (unsigned char) *it) || *it == ':' || *it == '_' || *it == '.' || *it == '/' || *it == '\\' )
  449. imageUrlEncoded << *it;
  450. else
  451. imageUrlEncoded << '%' << std::hex << size_t( (unsigned char) *it) << std::dec;
  452. }
  453. mOutput << XMLEscape(imageUrlEncoded.str());
  454. mOutput << "</init_from>" << endstr;
  455. PopTag();
  456. mOutput << startstr << "</image>" << endstr;
  457. }
  458. }
  459. // ------------------------------------------------------------------------------------------------
  460. // Writes a color-or-texture entry into an effect definition
  461. void ColladaExporter::WriteTextureColorEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pImageName)
  462. {
  463. if(pSurface.exist) {
  464. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  465. PushTag();
  466. if( pSurface.texture.empty() )
  467. {
  468. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  469. }
  470. else
  471. {
  472. mOutput << startstr << "<texture texture=\"" << XMLEscape(pImageName) << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  473. }
  474. PopTag();
  475. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  476. }
  477. }
  478. // ------------------------------------------------------------------------------------------------
  479. // Writes the two parameters necessary for referencing a texture in an effect entry
  480. void ColladaExporter::WriteTextureParamEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pMatName)
  481. {
  482. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  483. if( !pSurface.texture.empty() )
  484. {
  485. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-surface\">" << endstr;
  486. PushTag();
  487. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  488. PushTag();
  489. mOutput << startstr << "<init_from>" << XMLEscape(pMatName) << "-" << pTypeName << "-image</init_from>" << endstr;
  490. PopTag();
  491. mOutput << startstr << "</surface>" << endstr;
  492. PopTag();
  493. mOutput << startstr << "</newparam>" << endstr;
  494. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-sampler\">" << endstr;
  495. PushTag();
  496. mOutput << startstr << "<sampler2D>" << endstr;
  497. PushTag();
  498. mOutput << startstr << "<source>" << XMLEscape(pMatName) << "-" << pTypeName << "-surface</source>" << endstr;
  499. PopTag();
  500. mOutput << startstr << "</sampler2D>" << endstr;
  501. PopTag();
  502. mOutput << startstr << "</newparam>" << endstr;
  503. }
  504. }
  505. // ------------------------------------------------------------------------------------------------
  506. // Writes a scalar property
  507. void ColladaExporter::WriteFloatEntry( const Property& pProperty, const std::string& pTypeName)
  508. {
  509. if(pProperty.exist) {
  510. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  511. PushTag();
  512. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  513. PopTag();
  514. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  515. }
  516. }
  517. // ------------------------------------------------------------------------------------------------
  518. // Writes the material setup
  519. void ColladaExporter::WriteMaterials()
  520. {
  521. materials.resize( mScene->mNumMaterials);
  522. /// collect all materials from the scene
  523. size_t numTextures = 0;
  524. for( size_t a = 0; a < mScene->mNumMaterials; ++a )
  525. {
  526. const aiMaterial* mat = mScene->mMaterials[a];
  527. aiString name;
  528. if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) {
  529. name = "mat";
  530. materials[a].name = std::string( "m") + to_string(a) + name.C_Str();
  531. } else {
  532. // try to use the material's name if no other material has already taken it, else append #
  533. std::string testName = name.C_Str();
  534. size_t materialCountWithThisName = 0;
  535. for( size_t i = 0; i < a; i ++ ) {
  536. if( materials[i].name == testName ) {
  537. materialCountWithThisName ++;
  538. }
  539. }
  540. if( materialCountWithThisName == 0 ) {
  541. materials[a].name = name.C_Str();
  542. } else {
  543. materials[a].name = std::string(name.C_Str()) + to_string(materialCountWithThisName);
  544. }
  545. }
  546. for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
  547. if( !isalnum_C( *it ) ) {
  548. *it = '_';
  549. }
  550. }
  551. aiShadingMode shading = aiShadingMode_Flat;
  552. materials[a].shading_model = "phong";
  553. if(mat->Get( AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  554. if(shading == aiShadingMode_Phong) {
  555. materials[a].shading_model = "phong";
  556. } else if(shading == aiShadingMode_Blinn) {
  557. materials[a].shading_model = "blinn";
  558. } else if(shading == aiShadingMode_NoShading) {
  559. materials[a].shading_model = "constant";
  560. } else if(shading == aiShadingMode_Gouraud) {
  561. materials[a].shading_model = "lambert";
  562. }
  563. }
  564. ReadMaterialSurface( materials[a].ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  565. if( !materials[a].ambient.texture.empty() ) numTextures++;
  566. ReadMaterialSurface( materials[a].diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  567. if( !materials[a].diffuse.texture.empty() ) numTextures++;
  568. ReadMaterialSurface( materials[a].specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  569. if( !materials[a].specular.texture.empty() ) numTextures++;
  570. ReadMaterialSurface( materials[a].emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  571. if( !materials[a].emissive.texture.empty() ) numTextures++;
  572. ReadMaterialSurface( materials[a].reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE);
  573. if( !materials[a].reflective.texture.empty() ) numTextures++;
  574. ReadMaterialSurface( materials[a].transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT);
  575. if( !materials[a].transparent.texture.empty() ) numTextures++;
  576. ReadMaterialSurface( materials[a].normal, mat, aiTextureType_NORMALS, NULL, 0, 0);
  577. if( !materials[a].normal.texture.empty() ) numTextures++;
  578. materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
  579. materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
  580. materials[a].transparency.value = materials[a].transparency.value;
  581. materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  582. }
  583. // output textures if present
  584. if( numTextures > 0 )
  585. {
  586. mOutput << startstr << "<library_images>" << endstr;
  587. PushTag();
  588. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  589. {
  590. const Material& mat = *it;
  591. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  592. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  593. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  594. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  595. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  596. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  597. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  598. }
  599. PopTag();
  600. mOutput << startstr << "</library_images>" << endstr;
  601. }
  602. // output effects - those are the actual carriers of information
  603. if( !materials.empty() )
  604. {
  605. mOutput << startstr << "<library_effects>" << endstr;
  606. PushTag();
  607. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  608. {
  609. const Material& mat = *it;
  610. // this is so ridiculous it must be right
  611. mOutput << startstr << "<effect id=\"" << XMLEscape(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  612. PushTag();
  613. mOutput << startstr << "<profile_COMMON>" << endstr;
  614. PushTag();
  615. // write sampler- and surface params for the texture entries
  616. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  617. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  618. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  619. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  620. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  621. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  622. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  623. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  624. PushTag();
  625. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  626. PushTag();
  627. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  628. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  629. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  630. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  631. WriteFloatEntry(mat.shininess, "shininess");
  632. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  633. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  634. WriteFloatEntry(mat.transparency, "transparency");
  635. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  636. if(! mat.normal.texture.empty()) {
  637. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  638. }
  639. PopTag();
  640. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  641. PopTag();
  642. mOutput << startstr << "</technique>" << endstr;
  643. PopTag();
  644. mOutput << startstr << "</profile_COMMON>" << endstr;
  645. PopTag();
  646. mOutput << startstr << "</effect>" << endstr;
  647. }
  648. PopTag();
  649. mOutput << startstr << "</library_effects>" << endstr;
  650. // write materials - they're just effect references
  651. mOutput << startstr << "<library_materials>" << endstr;
  652. PushTag();
  653. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  654. {
  655. const Material& mat = *it;
  656. mOutput << startstr << "<material id=\"" << XMLEscape(mat.name) << "\" name=\"" << mat.name << "\">" << endstr;
  657. PushTag();
  658. mOutput << startstr << "<instance_effect url=\"#" << XMLEscape(mat.name) << "-fx\"/>" << endstr;
  659. PopTag();
  660. mOutput << startstr << "</material>" << endstr;
  661. }
  662. PopTag();
  663. mOutput << startstr << "</library_materials>" << endstr;
  664. }
  665. }
  666. // ------------------------------------------------------------------------------------------------
  667. // Writes the geometry library
  668. void ColladaExporter::WriteGeometryLibrary()
  669. {
  670. mOutput << startstr << "<library_geometries>" << endstr;
  671. PushTag();
  672. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  673. WriteGeometry( a);
  674. PopTag();
  675. mOutput << startstr << "</library_geometries>" << endstr;
  676. }
  677. // ------------------------------------------------------------------------------------------------
  678. // Writes the given mesh
  679. void ColladaExporter::WriteGeometry( size_t pIndex)
  680. {
  681. const aiMesh* mesh = mScene->mMeshes[pIndex];
  682. const std::string idstr = GetMeshId( pIndex);
  683. const std::string idstrEscaped = XMLEscape(idstr);
  684. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  685. return;
  686. // opening tag
  687. mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  688. PushTag();
  689. mOutput << startstr << "<mesh>" << endstr;
  690. PushTag();
  691. // Positions
  692. WriteFloatArray( idstr + "-positions", FloatType_Vector, (ai_real*) mesh->mVertices, mesh->mNumVertices);
  693. // Normals, if any
  694. if( mesh->HasNormals() )
  695. WriteFloatArray( idstr + "-normals", FloatType_Vector, (ai_real*) mesh->mNormals, mesh->mNumVertices);
  696. // texture coords
  697. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  698. {
  699. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  700. {
  701. WriteFloatArray( idstr + "-tex" + to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  702. (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
  703. }
  704. }
  705. // vertex colors
  706. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  707. {
  708. if( mesh->HasVertexColors(static_cast<unsigned int>(a)) )
  709. WriteFloatArray( idstr + "-color" + to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
  710. }
  711. // assemble vertex structure
  712. mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
  713. PushTag();
  714. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
  715. if( mesh->HasNormals() )
  716. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  717. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  718. {
  719. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  720. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " /*<< "set=\"" << a << "\"" */ << " />" << endstr;
  721. }
  722. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  723. {
  724. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  725. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " /*<< set=\"" << a << "\"" */ << " />" << endstr;
  726. }
  727. PopTag();
  728. mOutput << startstr << "</vertices>" << endstr;
  729. // count the number of lines, triangles and polygon meshes
  730. int countLines = 0;
  731. int countPoly = 0;
  732. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  733. {
  734. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  735. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  736. }
  737. // lines
  738. if (countLines)
  739. {
  740. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  741. PushTag();
  742. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  743. mOutput << startstr << "<p>";
  744. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  745. {
  746. const aiFace& face = mesh->mFaces[a];
  747. if (face.mNumIndices != 2) continue;
  748. for( size_t b = 0; b < face.mNumIndices; ++b )
  749. mOutput << face.mIndices[b] << " ";
  750. }
  751. mOutput << "</p>" << endstr;
  752. PopTag();
  753. mOutput << startstr << "</lines>" << endstr;
  754. }
  755. // triangle - don't use it, because compatibility problems
  756. // polygons
  757. if (countPoly)
  758. {
  759. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  760. PushTag();
  761. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  762. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  763. {
  764. if( mesh->HasTextureCoords(static_cast<unsigned int>(a) ) )
  765. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" set=\"" << a << "\" />" << endstr;
  766. }
  767. mOutput << startstr << "<vcount>";
  768. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  769. {
  770. if (mesh->mFaces[a].mNumIndices < 3) continue;
  771. mOutput << mesh->mFaces[a].mNumIndices << " ";
  772. }
  773. mOutput << "</vcount>" << endstr;
  774. mOutput << startstr << "<p>";
  775. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  776. {
  777. const aiFace& face = mesh->mFaces[a];
  778. if (face.mNumIndices < 3) continue;
  779. for( size_t b = 0; b < face.mNumIndices; ++b )
  780. mOutput << face.mIndices[b] << " ";
  781. }
  782. mOutput << "</p>" << endstr;
  783. PopTag();
  784. mOutput << startstr << "</polylist>" << endstr;
  785. }
  786. // closing tags
  787. PopTag();
  788. mOutput << startstr << "</mesh>" << endstr;
  789. PopTag();
  790. mOutput << startstr << "</geometry>" << endstr;
  791. }
  792. // ------------------------------------------------------------------------------------------------
  793. // Writes a float array of the given type
  794. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount)
  795. {
  796. size_t floatsPerElement = 0;
  797. switch( pType )
  798. {
  799. case FloatType_Vector: floatsPerElement = 3; break;
  800. case FloatType_TexCoord2: floatsPerElement = 2; break;
  801. case FloatType_TexCoord3: floatsPerElement = 3; break;
  802. case FloatType_Color: floatsPerElement = 3; break;
  803. default:
  804. return;
  805. }
  806. std::string arrayId = pIdString + "-array";
  807. mOutput << startstr << "<source id=\"" << XMLEscape(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  808. PushTag();
  809. // source array
  810. mOutput << startstr << "<float_array id=\"" << XMLEscape(arrayId) << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  811. PushTag();
  812. if( pType == FloatType_TexCoord2 )
  813. {
  814. for( size_t a = 0; a < pElementCount; ++a )
  815. {
  816. mOutput << pData[a*3+0] << " ";
  817. mOutput << pData[a*3+1] << " ";
  818. }
  819. }
  820. else if( pType == FloatType_Color )
  821. {
  822. for( size_t a = 0; a < pElementCount; ++a )
  823. {
  824. mOutput << pData[a*4+0] << " ";
  825. mOutput << pData[a*4+1] << " ";
  826. mOutput << pData[a*4+2] << " ";
  827. }
  828. }
  829. else
  830. {
  831. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  832. mOutput << pData[a] << " ";
  833. }
  834. mOutput << "</float_array>" << endstr;
  835. PopTag();
  836. // the usual Collada fun. Let's bloat it even more!
  837. mOutput << startstr << "<technique_common>" << endstr;
  838. PushTag();
  839. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  840. PushTag();
  841. switch( pType )
  842. {
  843. case FloatType_Vector:
  844. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  845. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  846. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  847. break;
  848. case FloatType_TexCoord2:
  849. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  850. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  851. break;
  852. case FloatType_TexCoord3:
  853. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  854. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  855. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  856. break;
  857. case FloatType_Color:
  858. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  859. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  860. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  861. break;
  862. }
  863. PopTag();
  864. mOutput << startstr << "</accessor>" << endstr;
  865. PopTag();
  866. mOutput << startstr << "</technique_common>" << endstr;
  867. PopTag();
  868. mOutput << startstr << "</source>" << endstr;
  869. }
  870. // ------------------------------------------------------------------------------------------------
  871. // Writes the scene library
  872. void ColladaExporter::WriteSceneLibrary()
  873. {
  874. const std::string scene_name_escaped = XMLEscape(mScene->mRootNode->mName.C_Str());
  875. mOutput << startstr << "<library_visual_scenes>" << endstr;
  876. PushTag();
  877. mOutput << startstr << "<visual_scene id=\"" + scene_name_escaped + "\" name=\"" + scene_name_escaped + "\">" << endstr;
  878. PushTag();
  879. // start recursive write at the root node
  880. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  881. WriteNode( mScene, mScene->mRootNode->mChildren[a]);
  882. PopTag();
  883. mOutput << startstr << "</visual_scene>" << endstr;
  884. PopTag();
  885. mOutput << startstr << "</library_visual_scenes>" << endstr;
  886. }
  887. // ------------------------------------------------------------------------------------------------
  888. // Helper to find a bone by name in the scene
  889. aiBone* findBone( const aiScene* scene, const char * name) {
  890. for (size_t m=0; m<scene->mNumMeshes; m++) {
  891. aiMesh * mesh = scene->mMeshes[m];
  892. for (size_t b=0; b<mesh->mNumBones; b++) {
  893. aiBone * bone = mesh->mBones[b];
  894. if (0 == strcmp(name, bone->mName.C_Str())) {
  895. return bone;
  896. }
  897. }
  898. }
  899. return NULL;
  900. }
  901. // ------------------------------------------------------------------------------------------------
  902. // Recursively writes the given node
  903. void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
  904. {
  905. // the node must have a name
  906. if (pNode->mName.length == 0)
  907. {
  908. std::stringstream ss;
  909. ss << "Node_" << pNode;
  910. pNode->mName.Set(ss.str());
  911. }
  912. // If the node is associated with a bone, it is a joint node (JOINT)
  913. // otherwise it is a normal node (NODE)
  914. const char * node_type;
  915. if (NULL == findBone(pScene, pNode->mName.C_Str())) {
  916. node_type = "NODE";
  917. } else {
  918. node_type = "JOINT";
  919. }
  920. const std::string node_name_escaped = XMLEscape(pNode->mName.data);
  921. mOutput << startstr
  922. << "<node id=\"" << node_name_escaped
  923. << "\" name=\"" << node_name_escaped
  924. << "\" type=\"" << node_type
  925. << "\">" << endstr;
  926. PushTag();
  927. // write transformation - we can directly put the matrix there
  928. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  929. const aiMatrix4x4& mat = pNode->mTransformation;
  930. mOutput << startstr << "<matrix>";
  931. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  932. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  933. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  934. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  935. mOutput << "</matrix>" << endstr;
  936. if(pNode->mNumMeshes==0){
  937. //check if it is a camera node
  938. for(size_t i=0; i<mScene->mNumCameras; i++){
  939. if(mScene->mCameras[i]->mName == pNode->mName){
  940. mOutput << startstr <<"<instance_camera url=\"#" << node_name_escaped << "-camera\"/>" << endstr;
  941. break;
  942. }
  943. }
  944. //check if it is a light node
  945. for(size_t i=0; i<mScene->mNumLights; i++){
  946. if(mScene->mLights[i]->mName == pNode->mName){
  947. mOutput << startstr <<"<instance_light url=\"#" << node_name_escaped << "-light\"/>" << endstr;
  948. break;
  949. }
  950. }
  951. }else
  952. // instance every geometry
  953. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  954. {
  955. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  956. // do not instanciate mesh if empty. I wonder how this could happen
  957. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  958. continue;
  959. mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
  960. PushTag();
  961. mOutput << startstr << "<bind_material>" << endstr;
  962. PushTag();
  963. mOutput << startstr << "<technique_common>" << endstr;
  964. PushTag();
  965. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\">" << endstr;
  966. PushTag();
  967. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  968. {
  969. if( mesh->HasTextureCoords( static_cast<unsigned int>(a) ) )
  970. // semantic as in <texture texcoord=...>
  971. // input_semantic as in <input semantic=...>
  972. // input_set as in <input set=...>
  973. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << a << "\" input_semantic=\"TEXCOORD\" input_set=\"" << a << "\"/>" << endstr;
  974. }
  975. PopTag();
  976. mOutput << startstr << "</instance_material>" << endstr;
  977. PopTag();
  978. mOutput << startstr << "</technique_common>" << endstr;
  979. PopTag();
  980. mOutput << startstr << "</bind_material>" << endstr;
  981. PopTag();
  982. mOutput << startstr << "</instance_geometry>" << endstr;
  983. }
  984. // recurse into subnodes
  985. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  986. WriteNode( pScene, pNode->mChildren[a]);
  987. PopTag();
  988. mOutput << startstr << "</node>" << endstr;
  989. }
  990. #endif
  991. #endif