ColladaExporter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, 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. #include "AssimpPCH.h"
  34. #ifndef ASSIMP_BUILD_NO_EXPORT
  35. #ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER
  36. #include "ColladaExporter.h"
  37. #include "Bitmap.h"
  38. #include "fast_atof.h"
  39. #include "SceneCombiner.h"
  40. #include "XMLTools.h"
  41. #include <ctime>
  42. #include <set>
  43. using namespace Assimp;
  44. namespace Assimp
  45. {
  46. // ------------------------------------------------------------------------------------------------
  47. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  48. void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  49. {
  50. std::string path = "";
  51. std::string file = pFile;
  52. // We need to test both types of folder separators because pIOSystem->getOsSeparator() is not reliable.
  53. // Moreover, the path given by some applications is not even consistent with the OS specific type of separator.
  54. const char* end_path = std::max(strrchr(pFile, '\\'), strrchr(pFile, '/'));
  55. if(end_path != NULL) {
  56. path = std::string(pFile, end_path + 1 - pFile);
  57. file = file.substr(end_path + 1 - pFile, file.npos);
  58. std::size_t pos = file.find_last_of('.');
  59. if(pos != file.npos) {
  60. file = file.substr(0, pos);
  61. }
  62. }
  63. // invoke the exporter
  64. ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file);
  65. // we're still here - export successfully completed. Write result to the given IOSYstem
  66. boost::scoped_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. mScene = pScene;
  81. mSceneOwned = false;
  82. // set up strings
  83. endstr = "\n";
  84. // start writing
  85. WriteFile();
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Destructor
  89. ColladaExporter::~ColladaExporter()
  90. {
  91. if(mSceneOwned) {
  92. delete mScene;
  93. }
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Starts writing the contents
  97. void ColladaExporter::WriteFile()
  98. {
  99. // write the DTD
  100. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  101. // COLLADA element start
  102. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  103. PushTag();
  104. WriteTextures();
  105. WriteHeader();
  106. WriteMaterials();
  107. WriteGeometryLibrary();
  108. WriteSceneLibrary();
  109. // useless Collada fu at the end, just in case we haven't had enough indirections, yet.
  110. mOutput << startstr << "<scene>" << endstr;
  111. PushTag();
  112. mOutput << startstr << "<instance_visual_scene url=\"#" + XMLEscape(mScene->mRootNode->mName.C_Str()) + "\" />" << endstr;
  113. PopTag();
  114. mOutput << startstr << "</scene>" << endstr;
  115. PopTag();
  116. mOutput << "</COLLADA>" << endstr;
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. // Writes the asset header
  120. void ColladaExporter::WriteHeader()
  121. {
  122. static const float epsilon = 0.00001f;
  123. static const aiQuaternion x_rot(aiMatrix3x3(
  124. 0, -1, 0,
  125. 1, 0, 0,
  126. 0, 0, 1));
  127. static const aiQuaternion y_rot(aiMatrix3x3(
  128. 1, 0, 0,
  129. 0, 1, 0,
  130. 0, 0, 1));
  131. static const aiQuaternion z_rot(aiMatrix3x3(
  132. 1, 0, 0,
  133. 0, 0, 1,
  134. 0, -1, 0));
  135. static const unsigned int date_nb_chars = 20;
  136. char date_str[date_nb_chars];
  137. std::time_t date = std::time(NULL);
  138. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  139. std::string scene_name = mScene->mRootNode->mName.C_Str();
  140. aiVector3D scaling;
  141. aiQuaternion rotation;
  142. aiVector3D position;
  143. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  144. rotation.Normalize();
  145. bool add_root_node = false;
  146. float scale = 1.0;
  147. if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  148. scale = (float) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
  149. } else {
  150. add_root_node = true;
  151. }
  152. std::string up_axis = "Y_UP";
  153. if(rotation.Equal(x_rot, epsilon)) {
  154. up_axis = "X_UP";
  155. } else if(rotation.Equal(y_rot, epsilon)) {
  156. up_axis = "Y_UP";
  157. } else if(rotation.Equal(z_rot, epsilon)) {
  158. up_axis = "Z_UP";
  159. } else {
  160. add_root_node = true;
  161. }
  162. if(! position.Equal(aiVector3D(0, 0, 0))) {
  163. add_root_node = true;
  164. }
  165. if(mScene->mRootNode->mNumChildren == 0) {
  166. add_root_node = true;
  167. }
  168. if(add_root_node) {
  169. aiScene* scene;
  170. SceneCombiner::CopyScene(&scene, mScene);
  171. aiNode* root = new aiNode("Scene");
  172. root->mNumChildren = 1;
  173. root->mChildren = new aiNode*[root->mNumChildren];
  174. root->mChildren[0] = scene->mRootNode;
  175. scene->mRootNode->mParent = root;
  176. scene->mRootNode = root;
  177. mScene = scene;
  178. mSceneOwned = true;
  179. up_axis = "Y_UP";
  180. scale = 1.0;
  181. }
  182. mOutput << startstr << "<asset>" << endstr;
  183. PushTag();
  184. mOutput << startstr << "<contributor>" << endstr;
  185. PushTag();
  186. aiMetadata* meta = mScene->mRootNode->mMetaData;
  187. aiString value;
  188. if (!meta || !meta->Get("Author", value))
  189. mOutput << startstr << "<author>" << "Assimp" << "</author>" << endstr;
  190. else
  191. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  192. if (!meta || !meta->Get("AuthoringTool", value))
  193. mOutput << startstr << "<authoring_tool>" << "Assimp Exporter" << "</authoring_tool>" << endstr;
  194. else
  195. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  196. //mOutput << startstr << "<author>" << mScene->author.C_Str() << "</author>" << endstr;
  197. //mOutput << startstr << "<authoring_tool>" << mScene->authoringTool.C_Str() << "</authoring_tool>" << endstr;
  198. PopTag();
  199. mOutput << startstr << "</contributor>" << endstr;
  200. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  201. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  202. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  203. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  204. PopTag();
  205. mOutput << startstr << "</asset>" << endstr;
  206. }
  207. // ------------------------------------------------------------------------------------------------
  208. // Write the embedded textures
  209. void ColladaExporter::WriteTextures() {
  210. static const unsigned int buffer_size = 1024;
  211. char str[buffer_size];
  212. if(mScene->HasTextures()) {
  213. for(unsigned int i = 0; i < mScene->mNumTextures; i++) {
  214. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  215. // so we just write the textures in the current directory.
  216. aiTexture* texture = mScene->mTextures[i];
  217. ASSIMP_itoa10(str, buffer_size, i + 1);
  218. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
  219. boost::scoped_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb"));
  220. if(outfile == NULL) {
  221. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  222. }
  223. if(texture->mHeight == 0) {
  224. outfile->Write((void*) texture->pcData, texture->mWidth, 1);
  225. } else {
  226. Bitmap::Save(texture, outfile.get());
  227. }
  228. outfile->Flush();
  229. textures.insert(std::make_pair(i, name));
  230. }
  231. }
  232. }
  233. // ------------------------------------------------------------------------------------------------
  234. // Reads a single surface entry from the given material keys
  235. void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex)
  236. {
  237. if( pSrcMat->GetTextureCount( pTexture) > 0 )
  238. {
  239. aiString texfile;
  240. unsigned int uvChannel = 0;
  241. pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel);
  242. std::string index_str(texfile.C_Str());
  243. if(index_str.size() != 0 && index_str[0] == '*')
  244. {
  245. unsigned int index;
  246. index_str = index_str.substr(1, std::string::npos);
  247. try {
  248. index = (unsigned int) strtoul10_64(index_str.c_str());
  249. } catch(std::exception& error) {
  250. throw DeadlyExportError(error.what());
  251. }
  252. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  253. if(name != textures.end()) {
  254. poSurface.texture = name->second;
  255. } else {
  256. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  257. }
  258. } else
  259. {
  260. poSurface.texture = texfile.C_Str();
  261. }
  262. poSurface.channel = uvChannel;
  263. poSurface.exist = true;
  264. } else
  265. {
  266. if( pKey )
  267. poSurface.exist = pSrcMat->Get( pKey, pType, pIndex, poSurface.color) == aiReturn_SUCCESS;
  268. }
  269. }
  270. // ------------------------------------------------------------------------------------------------
  271. // Writes an image entry for the given surface
  272. void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd)
  273. {
  274. if( !pSurface.texture.empty() )
  275. {
  276. mOutput << startstr << "<image id=\"" << XMLEscape(pNameAdd) << "\">" << endstr;
  277. PushTag();
  278. mOutput << startstr << "<init_from>";
  279. // URL encode image file name first, then XML encode on top
  280. std::stringstream imageUrlEncoded;
  281. for( std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it )
  282. {
  283. if( isalnum( *it) || *it == '_' || *it == '.' || *it == '/' || *it == '\\' )
  284. imageUrlEncoded << *it;
  285. else
  286. imageUrlEncoded << '%' << std::hex << size_t( (unsigned char) *it) << std::dec;
  287. }
  288. mOutput << XMLEscape(imageUrlEncoded.str());
  289. mOutput << "</init_from>" << endstr;
  290. PopTag();
  291. mOutput << startstr << "</image>" << endstr;
  292. }
  293. }
  294. // ------------------------------------------------------------------------------------------------
  295. // Writes a color-or-texture entry into an effect definition
  296. void ColladaExporter::WriteTextureColorEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pImageName)
  297. {
  298. if(pSurface.exist) {
  299. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  300. PushTag();
  301. if( pSurface.texture.empty() )
  302. {
  303. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  304. }
  305. else
  306. {
  307. mOutput << startstr << "<texture texture=\"" << XMLEscape(pImageName) << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  308. }
  309. PopTag();
  310. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  311. }
  312. }
  313. // ------------------------------------------------------------------------------------------------
  314. // Writes the two parameters necessary for referencing a texture in an effect entry
  315. void ColladaExporter::WriteTextureParamEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pMatName)
  316. {
  317. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  318. if( !pSurface.texture.empty() )
  319. {
  320. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-surface\">" << endstr;
  321. PushTag();
  322. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  323. PushTag();
  324. mOutput << startstr << "<init_from>" << XMLEscape(pMatName) << "-" << pTypeName << "-image</init_from>" << endstr;
  325. PopTag();
  326. mOutput << startstr << "</surface>" << endstr;
  327. PopTag();
  328. mOutput << startstr << "</newparam>" << endstr;
  329. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-sampler\">" << endstr;
  330. PushTag();
  331. mOutput << startstr << "<sampler2D>" << endstr;
  332. PushTag();
  333. mOutput << startstr << "<source>" << XMLEscape(pMatName) << "-" << pTypeName << "-surface</source>" << endstr;
  334. PopTag();
  335. mOutput << startstr << "</sampler2D>" << endstr;
  336. PopTag();
  337. mOutput << startstr << "</newparam>" << endstr;
  338. }
  339. }
  340. // ------------------------------------------------------------------------------------------------
  341. // Writes a scalar property
  342. void ColladaExporter::WriteFloatEntry( const Property& pProperty, const std::string& pTypeName)
  343. {
  344. if(pProperty.exist) {
  345. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  346. PushTag();
  347. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  348. PopTag();
  349. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  350. }
  351. }
  352. // ------------------------------------------------------------------------------------------------
  353. // Writes the material setup
  354. void ColladaExporter::WriteMaterials()
  355. {
  356. materials.resize( mScene->mNumMaterials);
  357. std::set<std::string> material_names;
  358. /// collect all materials from the scene
  359. size_t numTextures = 0;
  360. for( size_t a = 0; a < mScene->mNumMaterials; ++a )
  361. {
  362. const aiMaterial* mat = mScene->mMaterials[a];
  363. aiString name;
  364. if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS )
  365. name = "mat";
  366. materials[a].name = std::string( "m") + boost::lexical_cast<std::string> (a) + name.C_Str();
  367. for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
  368. // isalnum on MSVC asserts for code points outside [0,255]. Thus prevent unwanted promotion
  369. // of char to signed int and take the unsigned char value.
  370. if( !isalnum( static_cast<uint8_t>(*it) ) ) {
  371. *it = '_';
  372. }
  373. }
  374. aiShadingMode shading = aiShadingMode_Flat;
  375. materials[a].shading_model = "phong";
  376. if(mat->Get( AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  377. if(shading == aiShadingMode_Phong) {
  378. materials[a].shading_model = "phong";
  379. } else if(shading == aiShadingMode_Blinn) {
  380. materials[a].shading_model = "blinn";
  381. } else if(shading == aiShadingMode_NoShading) {
  382. materials[a].shading_model = "constant";
  383. } else if(shading == aiShadingMode_Gouraud) {
  384. materials[a].shading_model = "lambert";
  385. }
  386. }
  387. ReadMaterialSurface( materials[a].ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  388. if( !materials[a].ambient.texture.empty() ) numTextures++;
  389. ReadMaterialSurface( materials[a].diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  390. if( !materials[a].diffuse.texture.empty() ) numTextures++;
  391. ReadMaterialSurface( materials[a].specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  392. if( !materials[a].specular.texture.empty() ) numTextures++;
  393. ReadMaterialSurface( materials[a].emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  394. if( !materials[a].emissive.texture.empty() ) numTextures++;
  395. ReadMaterialSurface( materials[a].reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE);
  396. if( !materials[a].reflective.texture.empty() ) numTextures++;
  397. ReadMaterialSurface( materials[a].transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT);
  398. if( !materials[a].transparent.texture.empty() ) numTextures++;
  399. ReadMaterialSurface( materials[a].normal, mat, aiTextureType_NORMALS, NULL, 0, 0);
  400. if( !materials[a].normal.texture.empty() ) numTextures++;
  401. materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
  402. materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
  403. materials[a].transparency.value = 1 - materials[a].transparency.value;
  404. materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  405. }
  406. // output textures if present
  407. if( numTextures > 0 )
  408. {
  409. mOutput << startstr << "<library_images>" << endstr;
  410. PushTag();
  411. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  412. {
  413. const Material& mat = *it;
  414. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  415. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  416. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  417. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  418. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  419. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  420. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  421. }
  422. PopTag();
  423. mOutput << startstr << "</library_images>" << endstr;
  424. }
  425. // output effects - those are the actual carriers of information
  426. if( !materials.empty() )
  427. {
  428. mOutput << startstr << "<library_effects>" << endstr;
  429. PushTag();
  430. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  431. {
  432. const Material& mat = *it;
  433. // this is so ridiculous it must be right
  434. mOutput << startstr << "<effect id=\"" << XMLEscape(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  435. PushTag();
  436. mOutput << startstr << "<profile_COMMON>" << endstr;
  437. PushTag();
  438. // write sampler- and surface params for the texture entries
  439. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  440. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  441. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  442. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  443. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  444. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  445. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  446. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  447. PushTag();
  448. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  449. PushTag();
  450. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  451. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  452. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  453. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  454. WriteFloatEntry(mat.shininess, "shininess");
  455. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  456. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  457. WriteFloatEntry(mat.transparency, "transparency");
  458. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  459. if(! mat.normal.texture.empty()) {
  460. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  461. }
  462. PopTag();
  463. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  464. PopTag();
  465. mOutput << startstr << "</technique>" << endstr;
  466. PopTag();
  467. mOutput << startstr << "</profile_COMMON>" << endstr;
  468. PopTag();
  469. mOutput << startstr << "</effect>" << endstr;
  470. }
  471. PopTag();
  472. mOutput << startstr << "</library_effects>" << endstr;
  473. // write materials - they're just effect references
  474. mOutput << startstr << "<library_materials>" << endstr;
  475. PushTag();
  476. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  477. {
  478. const Material& mat = *it;
  479. mOutput << startstr << "<material id=\"" << XMLEscape(mat.name) << "\" name=\"" << mat.name << "\">" << endstr;
  480. PushTag();
  481. mOutput << startstr << "<instance_effect url=\"#" << XMLEscape(mat.name) << "-fx\"/>" << endstr;
  482. PopTag();
  483. mOutput << startstr << "</material>" << endstr;
  484. }
  485. PopTag();
  486. mOutput << startstr << "</library_materials>" << endstr;
  487. }
  488. }
  489. // ------------------------------------------------------------------------------------------------
  490. // Writes the geometry library
  491. void ColladaExporter::WriteGeometryLibrary()
  492. {
  493. mOutput << startstr << "<library_geometries>" << endstr;
  494. PushTag();
  495. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  496. WriteGeometry( a);
  497. PopTag();
  498. mOutput << startstr << "</library_geometries>" << endstr;
  499. }
  500. // ------------------------------------------------------------------------------------------------
  501. // Writes the given mesh
  502. void ColladaExporter::WriteGeometry( size_t pIndex)
  503. {
  504. const aiMesh* mesh = mScene->mMeshes[pIndex];
  505. const std::string idstr = GetMeshId( pIndex);
  506. const std::string idstrEscaped = XMLEscape(idstr);
  507. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  508. return;
  509. // opening tag
  510. mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  511. PushTag();
  512. mOutput << startstr << "<mesh>" << endstr;
  513. PushTag();
  514. // Positions
  515. WriteFloatArray( idstr + "-positions", FloatType_Vector, (float*) mesh->mVertices, mesh->mNumVertices);
  516. // Normals, if any
  517. if( mesh->HasNormals() )
  518. WriteFloatArray( idstr + "-normals", FloatType_Vector, (float*) mesh->mNormals, mesh->mNumVertices);
  519. // texture coords
  520. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  521. {
  522. if( mesh->HasTextureCoords( a) )
  523. {
  524. WriteFloatArray( idstr + "-tex" + boost::lexical_cast<std::string> (a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  525. (float*) mesh->mTextureCoords[a], mesh->mNumVertices);
  526. }
  527. }
  528. // vertex colors
  529. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  530. {
  531. if( mesh->HasVertexColors( a) )
  532. WriteFloatArray( idstr + "-color" + boost::lexical_cast<std::string> (a), FloatType_Color, (float*) mesh->mColors[a], mesh->mNumVertices);
  533. }
  534. // assemble vertex structure
  535. mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
  536. PushTag();
  537. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
  538. if( mesh->HasNormals() )
  539. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  540. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  541. {
  542. if( mesh->HasTextureCoords( a) )
  543. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " /*<< "set=\"" << a << "\"" */ << " />" << endstr;
  544. }
  545. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  546. {
  547. if( mesh->HasVertexColors( a) )
  548. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " /*<< set=\"" << a << "\"" */ << " />" << endstr;
  549. }
  550. PopTag();
  551. mOutput << startstr << "</vertices>" << endstr;
  552. // count the number of lines, triangles and polygon meshes
  553. int countLines = 0;
  554. int countPoly = 0;
  555. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  556. {
  557. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  558. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  559. }
  560. // lines
  561. if (countLines)
  562. {
  563. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  564. PushTag();
  565. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  566. mOutput << startstr << "<p>";
  567. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  568. {
  569. const aiFace& face = mesh->mFaces[a];
  570. if (face.mNumIndices != 2) continue;
  571. for( size_t b = 0; b < face.mNumIndices; ++b )
  572. mOutput << face.mIndices[b] << " ";
  573. }
  574. mOutput << "</p>" << endstr;
  575. PopTag();
  576. mOutput << startstr << "</lines>" << endstr;
  577. }
  578. // triangle - dont use it, because compatibility problems
  579. // polygons
  580. if (countPoly)
  581. {
  582. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  583. PushTag();
  584. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  585. mOutput << startstr << "<vcount>";
  586. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  587. {
  588. if (mesh->mFaces[a].mNumIndices < 3) continue;
  589. mOutput << mesh->mFaces[a].mNumIndices << " ";
  590. }
  591. mOutput << "</vcount>" << endstr;
  592. mOutput << startstr << "<p>";
  593. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  594. {
  595. const aiFace& face = mesh->mFaces[a];
  596. if (face.mNumIndices < 3) continue;
  597. for( size_t b = 0; b < face.mNumIndices; ++b )
  598. mOutput << face.mIndices[b] << " ";
  599. }
  600. mOutput << "</p>" << endstr;
  601. PopTag();
  602. mOutput << startstr << "</polylist>" << endstr;
  603. }
  604. // closing tags
  605. PopTag();
  606. mOutput << startstr << "</mesh>" << endstr;
  607. PopTag();
  608. mOutput << startstr << "</geometry>" << endstr;
  609. }
  610. // ------------------------------------------------------------------------------------------------
  611. // Writes a float array of the given type
  612. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const float* pData, size_t pElementCount)
  613. {
  614. size_t floatsPerElement = 0;
  615. switch( pType )
  616. {
  617. case FloatType_Vector: floatsPerElement = 3; break;
  618. case FloatType_TexCoord2: floatsPerElement = 2; break;
  619. case FloatType_TexCoord3: floatsPerElement = 3; break;
  620. case FloatType_Color: floatsPerElement = 3; break;
  621. default:
  622. return;
  623. }
  624. std::string arrayId = pIdString + "-array";
  625. mOutput << startstr << "<source id=\"" << XMLEscape(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  626. PushTag();
  627. // source array
  628. mOutput << startstr << "<float_array id=\"" << XMLEscape(arrayId) << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  629. PushTag();
  630. if( pType == FloatType_TexCoord2 )
  631. {
  632. for( size_t a = 0; a < pElementCount; ++a )
  633. {
  634. mOutput << pData[a*3+0] << " ";
  635. mOutput << pData[a*3+1] << " ";
  636. }
  637. }
  638. else if( pType == FloatType_Color )
  639. {
  640. for( size_t a = 0; a < pElementCount; ++a )
  641. {
  642. mOutput << pData[a*4+0] << " ";
  643. mOutput << pData[a*4+1] << " ";
  644. mOutput << pData[a*4+2] << " ";
  645. }
  646. }
  647. else
  648. {
  649. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  650. mOutput << pData[a] << " ";
  651. }
  652. mOutput << "</float_array>" << endstr;
  653. PopTag();
  654. // the usual Collada fun. Let's bloat it even more!
  655. mOutput << startstr << "<technique_common>" << endstr;
  656. PushTag();
  657. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  658. PushTag();
  659. switch( pType )
  660. {
  661. case FloatType_Vector:
  662. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  663. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  664. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  665. break;
  666. case FloatType_TexCoord2:
  667. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  668. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  669. break;
  670. case FloatType_TexCoord3:
  671. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  672. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  673. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  674. break;
  675. case FloatType_Color:
  676. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  677. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  678. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  679. break;
  680. }
  681. PopTag();
  682. mOutput << startstr << "</accessor>" << endstr;
  683. PopTag();
  684. mOutput << startstr << "</technique_common>" << endstr;
  685. PopTag();
  686. mOutput << startstr << "</source>" << endstr;
  687. }
  688. // ------------------------------------------------------------------------------------------------
  689. // Writes the scene library
  690. void ColladaExporter::WriteSceneLibrary()
  691. {
  692. const std::string scene_name_escaped = XMLEscape(mScene->mRootNode->mName.C_Str());
  693. mOutput << startstr << "<library_visual_scenes>" << endstr;
  694. PushTag();
  695. mOutput << startstr << "<visual_scene id=\"" + scene_name_escaped + "\" name=\"" + scene_name_escaped + "\">" << endstr;
  696. PushTag();
  697. // start recursive write at the root node
  698. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  699. WriteNode( mScene->mRootNode->mChildren[a]);
  700. PopTag();
  701. mOutput << startstr << "</visual_scene>" << endstr;
  702. PopTag();
  703. mOutput << startstr << "</library_visual_scenes>" << endstr;
  704. }
  705. // ------------------------------------------------------------------------------------------------
  706. // Recursively writes the given node
  707. void ColladaExporter::WriteNode(aiNode* pNode)
  708. {
  709. // the must have a name
  710. if (pNode->mName.length == 0)
  711. {
  712. std::stringstream ss;
  713. ss << "Node_" << pNode;
  714. pNode->mName.Set(ss.str());
  715. }
  716. const std::string node_name_escaped = XMLEscape(pNode->mName.data);
  717. mOutput << startstr << "<node id=\"" << node_name_escaped << "\" name=\"" << node_name_escaped << "\">" << endstr;
  718. PushTag();
  719. // write transformation - we can directly put the matrix there
  720. // TODO: (thom) decompose into scale - rot - quad to allow adressing it by animations afterwards
  721. const aiMatrix4x4& mat = pNode->mTransformation;
  722. mOutput << startstr << "<matrix>";
  723. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  724. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  725. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  726. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  727. mOutput << "</matrix>" << endstr;
  728. // instance every geometry
  729. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  730. {
  731. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  732. // do not instanciate mesh if empty. I wonder how this could happen
  733. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  734. continue;
  735. mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
  736. PushTag();
  737. mOutput << startstr << "<bind_material>" << endstr;
  738. PushTag();
  739. mOutput << startstr << "<technique_common>" << endstr;
  740. PushTag();
  741. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\" />" << endstr;
  742. PopTag();
  743. mOutput << startstr << "</technique_common>" << endstr;
  744. PopTag();
  745. mOutput << startstr << "</bind_material>" << endstr;
  746. PopTag();
  747. mOutput << startstr << "</instance_geometry>" << endstr;
  748. }
  749. // recurse into subnodes
  750. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  751. WriteNode( pNode->mChildren[a]);
  752. PopTag();
  753. mOutput << startstr << "</node>" << endstr;
  754. }
  755. #endif
  756. #endif