Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

822 строки
30 KiB

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