ColladaExporter.cpp 52 KB

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