colladaUtils.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _COLLADA_UTILS_H_
  23. #define _COLLADA_UTILS_H_
  24. #ifdef _MSC_VER
  25. #pragma warning(disable : 4786) // disable warning about long debug symbol names
  26. #pragma warning(disable : 4355) // disable "'this' : used in base member initializer list" warnings
  27. #endif
  28. #ifndef _MMATRIX_H_
  29. #include "math/mMatrix.h"
  30. #endif
  31. #ifndef _MQUAT_H_
  32. #include "math/mQuat.h"
  33. #endif
  34. #ifndef _TVECTOR_H_
  35. #include "core/util/tVector.h"
  36. #endif
  37. #ifndef _TSSHAPE_LOADER_H_
  38. #include "ts/loader/tsShapeLoader.h"
  39. #endif
  40. #ifndef _OPTIMIZEDPOLYLIST_H_
  41. #include "collision/optimizedPolyList.h"
  42. #endif
  43. #ifndef TINYXML_INCLUDED
  44. #include "tinyxml.h"
  45. #endif
  46. #ifndef _CONSOLE_H_
  47. #include "console/console.h"
  48. #endif
  49. #ifndef _TSSHAPEINSTANCE_H_
  50. #include "ts/tsShapeInstance.h"
  51. #endif
  52. #include "platform/tmm_off.h"
  53. #include "dae.h"
  54. #include "dae/daeErrorHandler.h"
  55. #include "dae/domAny.h"
  56. #include "dom/domProfile_COMMON.h"
  57. #include "dom/domMaterial.h"
  58. #include "dom/domGeometry.h"
  59. #include "dom/domMorph.h"
  60. #include "dom/domNode.h"
  61. #include "dom/domCOLLADA.h"
  62. #include "platform/tmm_on.h"
  63. #include "core/strings/findMatch.h"
  64. namespace ColladaUtils
  65. {
  66. struct ImportOptions
  67. {
  68. enum eLodType
  69. {
  70. DetectDTS = 0,
  71. SingleSize,
  72. TrailingNumber,
  73. NumLodTypes
  74. };
  75. domUpAxisType upAxis; // Override for the collada <up_axis> element
  76. F32 unit; // Override for the collada <unit> element
  77. eLodType lodType; // LOD type option
  78. S32 singleDetailSize; // Detail size for all meshes in the model
  79. String matNamePrefix; // Prefix to apply to collada material names
  80. String alwaysImport; // List of node names (with wildcards) to import, even if in the neverImport list
  81. String neverImport; // List of node names (with wildcards) to ignore on loading
  82. String alwaysImportMesh; // List of mesh names (with wildcards) to import, even if in the neverImportMesh list
  83. String neverImportMesh; // List of mesh names (with wildcards) to ignore on loading
  84. bool ignoreNodeScale; // Ignore <scale> elements in <node>s
  85. bool adjustCenter; // Translate model so origin is at the center
  86. bool adjustFloor; // Translate model so origin is at the bottom
  87. bool forceUpdateMaterials; // Force update of materials.cs
  88. bool useDiffuseNames; // Use diffuse texture as the material name
  89. ImportOptions()
  90. {
  91. reset();
  92. }
  93. void reset()
  94. {
  95. upAxis = UPAXISTYPE_COUNT;
  96. unit = -1.0f;
  97. lodType = TrailingNumber;
  98. singleDetailSize = 2;
  99. matNamePrefix = "";
  100. alwaysImport = "";
  101. neverImport = "";
  102. alwaysImportMesh = "";
  103. neverImportMesh = "";
  104. ignoreNodeScale = false;
  105. adjustCenter = false;
  106. adjustFloor = false;
  107. forceUpdateMaterials = false;
  108. useDiffuseNames = false;
  109. }
  110. };
  111. ImportOptions& getOptions();
  112. struct ExportData
  113. {
  114. struct detailLevel
  115. {
  116. OptimizedPolyList mesh;
  117. S32 size;
  118. Map<int, int> materialRefList;
  119. };
  120. struct meshLODData
  121. {
  122. Vector<detailLevel> meshDetailLevels;
  123. TSShapeInstance* shapeInst;
  124. MatrixF meshTransform;
  125. SceneObject* originatingObject;
  126. Point3F scale;
  127. S32 hasDetailLevel(S32 size)
  128. {
  129. for (U32 i = 0; i < meshDetailLevels.size(); ++i)
  130. {
  131. U32 mdlSize = meshDetailLevels[i].size;
  132. if (mdlSize == size)
  133. return i;
  134. }
  135. return -1;
  136. }
  137. meshLODData() : shapeInst(nullptr), meshTransform(true), originatingObject(nullptr), scale(0)
  138. {}
  139. };
  140. struct colMesh
  141. {
  142. OptimizedPolyList mesh;
  143. String colMeshName;
  144. };
  145. Vector<detailLevel> detailLevels;
  146. Vector<meshLODData> meshData;
  147. Vector<colMesh> colMeshes;
  148. Vector<BaseMatInstance*> materials;
  149. void processData();
  150. S32 hasDetailLevel(U32 dl)
  151. {
  152. for (U32 i = 0; i < detailLevels.size(); i++)
  153. {
  154. if (detailLevels[i].size == dl)
  155. return i;
  156. }
  157. return -1;
  158. }
  159. S32 hasMaterialInstance(BaseMatInstance* matInst)
  160. {
  161. for (U32 i = 0; i < materials.size(); i++)
  162. {
  163. if (materials[i] == matInst)
  164. return i;
  165. }
  166. return -1;
  167. }
  168. S32 numberOfDetailLevels()
  169. {
  170. Vector<S32> detailLevelIdxs;
  171. for (U32 i = 0; i < meshData.size(); ++i)
  172. {
  173. for (U32 d = 0; d < meshData[i].meshDetailLevels.size(); ++d)
  174. {
  175. detailLevelIdxs.push_back_unique(meshData[i].meshDetailLevels[d].size);
  176. }
  177. }
  178. return detailLevelIdxs.size();
  179. }
  180. static S32 _Sort(const S32 *p1, const S32 *p2)
  181. {
  182. S32 e1 = (*p1);
  183. S32 e2 = (*p2);
  184. if (e1 > e2)
  185. return 1;
  186. else if (e1 < e2)
  187. return -1;
  188. return 0;
  189. }
  190. S32 getDetailLevelSize(U32 detailIdx)
  191. {
  192. Vector<S32> detailLevelIdxs;
  193. for (U32 i = 0; i < meshData.size(); ++i)
  194. {
  195. for (U32 d = 0; d < meshData[i].meshDetailLevels.size(); ++d)
  196. {
  197. S32 mdlSize = meshData[i].meshDetailLevels[d].size;
  198. detailLevelIdxs.push_back_unique(mdlSize);
  199. }
  200. }
  201. if (detailIdx >= detailLevelIdxs.size())
  202. return -1;
  203. detailLevelIdxs.sort(&_Sort);
  204. return detailLevelIdxs[detailIdx];
  205. }
  206. };
  207. void convertTransform(MatrixF& m);
  208. void collapsePath(std::string& path);
  209. // Apply the set of Collada conditioners (suited for loading Collada models into Torque)
  210. void applyConditioners(domCOLLADA* root);
  211. const domProfile_COMMON* findEffectCommonProfile(const domEffect* effect);
  212. const domCommon_color_or_texture_type_complexType* findEffectDiffuse(const domEffect* effect);
  213. const domCommon_color_or_texture_type_complexType* findEffectSpecular(const domEffect* effect);
  214. const domFx_sampler2D_common_complexType* getTextureSampler(const domEffect* effect, const domCommon_color_or_texture_type_complexType* texture);
  215. String getSamplerImagePath(const domEffect* effect, const domFx_sampler2D_common_complexType* sampler2D);
  216. String resolveImagePath(const domImage* image);
  217. // Collada export helper functions
  218. Torque::Path findTexture(const Torque::Path& diffuseMap);
  219. void exportColladaHeader(TiXmlElement* rootNode);
  220. void exportColladaMaterials(TiXmlElement* rootNode, const OptimizedPolyList& mesh, Vector<String>& matNames, const Torque::Path& colladaFile);
  221. void exportColladaTriangles(TiXmlElement* meshNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames);
  222. void exportColladaMesh(TiXmlElement* rootNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames);
  223. void exportColladaScene(TiXmlElement* rootNode, const String& meshName, const Vector<String>& matNames);
  224. void exportColladaMaterials(TiXmlElement* rootNode, const ExportData& exportData, const Torque::Path& colladaFile);
  225. void exportColladaMesh(TiXmlElement* rootNode, const ExportData& exportData, const String& meshName);
  226. void exportColladaCollisionTriangles(TiXmlElement* meshNode, const ExportData& exportData, const U32 collisionIdx);
  227. void exportColladaTriangles(TiXmlElement* meshNode, const ExportData& exportData, const U32 detailLevel, const String& meshName);
  228. void exportColladaScene(TiXmlElement* rootNode, const ExportData& exportData, const String& meshName);
  229. // Export an OptimizedPolyList to a simple Collada file
  230. void exportToCollada(const Torque::Path& colladaFile, const OptimizedPolyList& mesh, const String& meshName = String::EmptyString);
  231. void exportToCollada(const Torque::Path& colladaFile, const ExportData& exportData);
  232. };
  233. //-----------------------------------------------------------------------------
  234. // Helper Classes
  235. //
  236. // The Collada DOM uses a different class for each XML element, and there is very
  237. // little class inheritance, even though many elements have the same attributes
  238. // and children. This makes the DOM a bit ugly to work with, and the following
  239. // templates attempt to make this situation a bit nicer by providing a common way
  240. // to access common elements, while retaining the strong typing of the DOM classes.
  241. //-----------------------------------------------------------------------------
  242. /// Convert from the Collada transform types to a Torque MatrixF
  243. template<class T> inline MatrixF vecToMatrixF(const domListOfFloats& vec) { return MatrixF(true); }
  244. /// Collada <translate>: [x_translate, y_translate, z_translate]
  245. template<> inline MatrixF vecToMatrixF<domTranslate>(const domListOfFloats& vec)
  246. {
  247. MatrixF mat(true);
  248. mat.setPosition(Point3F(vec[0], vec[1], vec[2]));
  249. return mat;
  250. }
  251. /// Collada <scale>: [x_scale, y_scale, z_scale]
  252. template<> inline MatrixF vecToMatrixF<domScale>(const domListOfFloats& vec)
  253. {
  254. MatrixF mat(true);
  255. mat.scale(Point3F(vec[0], vec[1], vec[2]));
  256. return mat;
  257. }
  258. /// Collada <rotate>: [rotation_axis, angle_in_degrees]
  259. template<> inline MatrixF vecToMatrixF<domRotate>(const domListOfFloats& vec)
  260. {
  261. AngAxisF aaxis(Point3F(vec[0], vec[1], vec[2]), -(vec[3] * M_PI) / 180.0f);
  262. MatrixF mat(true);
  263. aaxis.setMatrix(&mat);
  264. return mat;
  265. }
  266. /// Collada <matrix>: same form as TGE (woohoo!)
  267. template<> inline MatrixF vecToMatrixF<domMatrix>(const domListOfFloats& vec)
  268. {
  269. MatrixF mat;
  270. for (S32 i = 0; i < 16; i++)
  271. mat[i] = vec[i];
  272. return mat;
  273. }
  274. /// Collada <skew>: [angle_in_degrees, rotation_axis, translation_axis]
  275. /// skew transform code adapted from GMANMatrix4 implementation
  276. template<> inline MatrixF vecToMatrixF<domSkew>(const domListOfFloats& vec)
  277. {
  278. F32 angle = -(vec[0] * M_PI) / 180.0f;
  279. Point3F rotAxis(vec[1], vec[2], vec[3]);
  280. Point3F transAxis(vec[4], vec[5], vec[6]);
  281. transAxis.normalize();
  282. Point3F a1 = transAxis * mDot(rotAxis, transAxis);
  283. Point3F a2 = rotAxis - a1;
  284. a2.normalize();
  285. F32 an1 = mDot(rotAxis, a2);
  286. F32 an2 = mDot(rotAxis, transAxis);
  287. F32 rx = an1 * mCos(angle) - an2 * mSin(angle);
  288. F32 ry = an1 * mSin(angle) + an2 * mCos(angle);
  289. // Check for rotation parallel to translation
  290. F32 alpha = (an1 == 0) ? 0 : (ry/rx - an2/an1);
  291. MatrixF mat(true);
  292. mat(0,0) = a2.x * transAxis.x * alpha + 1.0;
  293. mat(1,0) = a2.y * transAxis.x * alpha;
  294. mat(2,0) = a2.z * transAxis.x * alpha;
  295. mat(0,1) = a2.x * transAxis.y * alpha;
  296. mat(1,1) = a2.y * transAxis.y * alpha + 1.0;
  297. mat(2,1) = a2.z * transAxis.y * alpha;
  298. mat(0,2) = a2.x * transAxis.z * alpha;
  299. mat(1,2) = a2.y * transAxis.z * alpha;
  300. mat(2,2) = a2.z * transAxis.z * alpha + 1.0;
  301. return mat;
  302. }
  303. /// Collada <lookat>: [eye, target, up]
  304. template<> inline MatrixF vecToMatrixF<domLookat>(const domListOfFloats& vec)
  305. {
  306. Point3F eye(vec[0], vec[1], vec[2]);
  307. Point3F target(vec[3], vec[4], vec[5]);
  308. Point3F up(vec[6], vec[7], vec[8]);
  309. Point3F fwd = target - eye;
  310. fwd.normalizeSafe();
  311. Point3F right = mCross(fwd, up);
  312. right.normalizeSafe();
  313. up = mCross(right, fwd);
  314. up.normalizeSafe();
  315. MatrixF mat(true);
  316. mat.setColumn(0, right);
  317. mat.setColumn(1, fwd);
  318. mat.setColumn(2, up);
  319. mat.setColumn(3, eye);
  320. return mat;
  321. }
  322. //-----------------------------------------------------------------------------
  323. /// Try to get a name for the element using the following attributes (in order):
  324. /// name, sid, id, "null"
  325. template<class T> inline const char* _GetNameOrId(const T* element)
  326. {
  327. return element ? (element->getName() ? element->getName() : (element->getId() ? element->getId() : "null")) : "null";
  328. }
  329. template<> inline const char* _GetNameOrId(const domInstance_geometry* element)
  330. {
  331. return element ? (element->getName() ? element->getName() : (element->getSid() ? element->getSid() : "null")) : "null";
  332. }
  333. template<> inline const char* _GetNameOrId(const domInstance_controller* element)
  334. {
  335. return element ? (element->getName() ? element->getName() : (element->getSid() ? element->getSid() : "null")) : "null";
  336. }
  337. //-----------------------------------------------------------------------------
  338. // Collada <source>s are extremely flexible, and thus difficult to access in a nice
  339. // way. This class attempts to provide a clean interface to convert Collada source
  340. // data to the appropriate Torque data structure without losing any of the flexibility
  341. // of the underlying Collada DOM.
  342. //
  343. // Some of the conversions we need to handle are:
  344. // - daeString to const char*
  345. // - daeIDRef to const char*
  346. // - double to F32
  347. // - double to Point2F
  348. // - double to Point3F
  349. // - double to MatrixF
  350. //
  351. // The _SourceReader object is initialized with a list of parameter names that it
  352. // tries to match to <param> elements in the source accessor to figure out how to
  353. // pull values out of the 1D source array. Note that no type checking of any kind
  354. // is done until we actually try to extract values from the source.
  355. class _SourceReader
  356. {
  357. const domSource* source; // the wrapped Collada source
  358. const domAccessor* accessor; // shortcut to the source accessor
  359. Vector<U32> offsets; // offset of each of the desired values to pull from the source array
  360. public:
  361. _SourceReader() : source(0), accessor(0) {}
  362. void reset()
  363. {
  364. source = 0;
  365. accessor = 0;
  366. offsets.clear();
  367. }
  368. //------------------------------------------------------
  369. // Initialize the _SourceReader object
  370. bool initFromSource(const domSource* src, const char* paramNames[] = 0)
  371. {
  372. source = src;
  373. accessor = source->getTechnique_common()->getAccessor();
  374. offsets.clear();
  375. // The source array has groups of values in a 1D stream => need to map the
  376. // input param names to source params to determine the offset within the
  377. // group for each desired value
  378. U32 paramCount = 0;
  379. while (paramNames && paramNames[paramCount][0]) {
  380. // lookup the index of the source param that matches the input param
  381. offsets.push_back(paramCount);
  382. for (U32 iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++) {
  383. if (accessor->getParam_array()[iParam]->getName() &&
  384. dStrEqual(accessor->getParam_array()[iParam]->getName(), paramNames[paramCount])) {
  385. offsets.last() = iParam;
  386. break;
  387. }
  388. }
  389. paramCount++;
  390. }
  391. // If no input params were specified, just map the source params directly
  392. if (!offsets.size()) {
  393. for (S32 iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++)
  394. offsets.push_back(iParam);
  395. }
  396. return true;
  397. }
  398. //------------------------------------------------------
  399. // Shortcut to the size of the array (should be the number of destination objects)
  400. S32 size() const { return accessor ? accessor->getCount() : 0; }
  401. // Get the number of elements per group in the source
  402. S32 stride() const { return accessor ? accessor->getStride() : 0; }
  403. //------------------------------------------------------
  404. // Get a pointer to the start of a group of values (index advances by stride)
  405. //template<class T> T getArrayData(S32 index) const { return 0; }
  406. const double* getStringArrayData(S32 index) const
  407. {
  408. if ((index >= 0) && (index < size())) {
  409. if (source->getFloat_array())
  410. return &source->getFloat_array()->getValue()[index*stride()];
  411. }
  412. return 0;
  413. }
  414. //------------------------------------------------------
  415. // Read a single value from the source array
  416. //template<class T> T getValue(S32 index) const { return T; }
  417. const char* getStringValue(S32 index) const
  418. {
  419. if ((index >= 0) && (index < size())) {
  420. // could be plain strings or IDREFs
  421. if (source->getName_array())
  422. return source->getName_array()->getValue()[index*stride()];
  423. else if (source->getIDREF_array())
  424. return source->getIDREF_array()->getValue()[index*stride()].getID();
  425. }
  426. return "";
  427. }
  428. F32 getFloatValue(S32 index) const
  429. {
  430. F32 value(0);
  431. if (const double* data = getStringArrayData(index))
  432. return data[offsets[0]];
  433. return value;
  434. }
  435. Point2F getPoint2FValue(S32 index) const
  436. {
  437. Point2F value(0, 0);
  438. if (const double* data = getStringArrayData(index))
  439. value.set(data[offsets[0]], data[offsets[1]]);
  440. return value;
  441. }
  442. Point3F getPoint3FValue(S32 index) const
  443. {
  444. Point3F value(1, 0, 0);
  445. if (const double* data = getStringArrayData(index))
  446. value.set(data[offsets[0]], data[offsets[1]], data[offsets[2]]);
  447. return value;
  448. }
  449. ColorI getColorIValue(S32 index) const
  450. {
  451. ColorI value(255, 255, 255, 255);
  452. if (const double* data = getStringArrayData(index))
  453. {
  454. value.red = data[offsets[0]] * 255.0;
  455. value.green = data[offsets[1]] * 255.0;
  456. value.blue = data[offsets[2]] * 255.0;
  457. if ( stride() == 4 )
  458. value.alpha = data[offsets[3]] * 255.0;
  459. }
  460. return value;
  461. }
  462. MatrixF getMatrixFValue(S32 index) const
  463. {
  464. MatrixF value(true);
  465. if (const double* data = getStringArrayData(index)) {
  466. for (S32 i = 0; i < 16; i++)
  467. value[i] = data[i];
  468. }
  469. return value;
  470. }
  471. };
  472. //-----------------------------------------------------------------------------
  473. // Collada geometric primitives: Use the BasePrimitive class to access the
  474. // different primitive types in a nice way.
  475. class BasePrimitive
  476. {
  477. public:
  478. virtual ~BasePrimitive() { }
  479. /// Return true if the element is a geometric primitive type
  480. static bool isPrimitive(const daeElement* element)
  481. {
  482. switch (element->getElementType()) {
  483. case COLLADA_TYPE::TRIANGLES: case COLLADA_TYPE::POLYLIST:
  484. case COLLADA_TYPE::POLYGONS: case COLLADA_TYPE::TRIFANS:
  485. case COLLADA_TYPE::TRISTRIPS: case COLLADA_TYPE::CAPSULE:
  486. case COLLADA_TYPE::CYLINDER: case COLLADA_TYPE::LINES:
  487. case COLLADA_TYPE::LINESTRIPS: case COLLADA_TYPE::PLANE:
  488. case COLLADA_TYPE::SPLINE: case COLLADA_TYPE::SPHERE:
  489. case COLLADA_TYPE::TAPERED_CAPSULE: case COLLADA_TYPE::TAPERED_CYLINDER:
  490. return true;
  491. }
  492. return false;
  493. }
  494. /// Return true if the element is a supported primitive type
  495. static bool isSupportedPrimitive(const daeElement* element)
  496. {
  497. switch (element->getElementType()) {
  498. case COLLADA_TYPE::TRIANGLES:
  499. case COLLADA_TYPE::TRISTRIPS:
  500. case COLLADA_TYPE::TRIFANS:
  501. case COLLADA_TYPE::POLYLIST:
  502. case COLLADA_TYPE::POLYGONS:
  503. return true;
  504. }
  505. return false;
  506. }
  507. /// Construct a child class based on the type of Collada element
  508. static BasePrimitive* get(const daeElement* element);
  509. /// Methods to be implemented for each supported Collada geometric element
  510. virtual const char* getElementName() = 0;
  511. virtual const char* getMaterial() = 0;
  512. virtual const domInputLocalOffset_Array& getInputs() = 0;
  513. virtual S32 getStride() const = 0;
  514. virtual const domListOfUInts *getTriangleData() = 0;
  515. };
  516. /// Template child class for supported Collada primitive elements
  517. template<class T> class ColladaPrimitive : public BasePrimitive
  518. {
  519. T* primitive;
  520. domListOfUInts *pTriangleData;
  521. S32 stride;
  522. public:
  523. ColladaPrimitive(const daeElement* e) : pTriangleData(0)
  524. {
  525. // Cast to geometric primitive element
  526. primitive = daeSafeCast<T>(const_cast<daeElement*>(e));
  527. // Determine stride
  528. stride = 0;
  529. for (S32 iInput = 0; iInput < getInputs().getCount(); iInput++) {
  530. if (getInputs()[iInput]->getOffset() >= stride)
  531. stride = getInputs()[iInput]->getOffset() + 1;
  532. }
  533. }
  534. ~ColladaPrimitive()
  535. {
  536. delete pTriangleData;
  537. }
  538. /// Most primitives can use these common implementations
  539. const char* getElementName() { return primitive->getElementName(); }
  540. const char* getMaterial() { return primitive->getMaterial(); }
  541. const domInputLocalOffset_Array& getInputs() { return primitive->getInput_array(); }
  542. S32 getStride() const { return stride; }
  543. /// Each supported primitive needs to implement this method (and convert
  544. /// to triangles if required)
  545. const domListOfUInts *getTriangleData() { return NULL; }
  546. };
  547. //-----------------------------------------------------------------------------
  548. // <triangles>
  549. template<> inline const domListOfUInts *ColladaPrimitive<domTriangles>::getTriangleData()
  550. {
  551. // Return the <p> integer list directly
  552. return (primitive->getP() ? &(primitive->getP()->getValue()) : NULL);
  553. }
  554. //-----------------------------------------------------------------------------
  555. // <tristrips>
  556. template<> inline const domListOfUInts *ColladaPrimitive<domTristrips>::getTriangleData()
  557. {
  558. if (!pTriangleData)
  559. {
  560. // Convert strips to triangles
  561. pTriangleData = new domListOfUInts();
  562. for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) {
  563. domP* P = primitive->getP_array()[iStrip];
  564. // Ignore invalid P arrays
  565. if (!P || !P->getValue().getCount())
  566. continue;
  567. domUint* pSrcData = &(P->getValue()[0]);
  568. size_t numTriangles = (P->getValue().getCount() / stride) - 2;
  569. // Convert the strip back to a triangle list
  570. domUint* v0 = pSrcData;
  571. for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) {
  572. if (iTri & 0x1)
  573. {
  574. // CW triangle
  575. pTriangleData->appendArray(stride, v0);
  576. pTriangleData->appendArray(stride, v0 + 2*stride);
  577. pTriangleData->appendArray(stride, v0 + stride);
  578. }
  579. else
  580. {
  581. // CCW triangle
  582. pTriangleData->appendArray(stride*3, v0);
  583. }
  584. }
  585. }
  586. }
  587. return pTriangleData;
  588. }
  589. //-----------------------------------------------------------------------------
  590. // <trifans>
  591. template<> inline const domListOfUInts *ColladaPrimitive<domTrifans>::getTriangleData()
  592. {
  593. if (!pTriangleData)
  594. {
  595. // Convert strips to triangles
  596. pTriangleData = new domListOfUInts();
  597. for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) {
  598. domP* P = primitive->getP_array()[iStrip];
  599. // Ignore invalid P arrays
  600. if (!P || !P->getValue().getCount())
  601. continue;
  602. domUint* pSrcData = &(P->getValue()[0]);
  603. size_t numTriangles = (P->getValue().getCount() / stride) - 2;
  604. // Convert the fan back to a triangle list
  605. domUint* v0 = pSrcData + stride;
  606. for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) {
  607. pTriangleData->appendArray(stride, pSrcData); // shared vertex
  608. pTriangleData->appendArray(stride, v0); // previous vertex
  609. pTriangleData->appendArray(stride, v0+stride); // current vertex
  610. }
  611. }
  612. }
  613. return pTriangleData;
  614. }
  615. //-----------------------------------------------------------------------------
  616. // <polygons>
  617. template<> inline const domListOfUInts *ColladaPrimitive<domPolygons>::getTriangleData()
  618. {
  619. if (!pTriangleData)
  620. {
  621. // Convert polygons to triangles
  622. pTriangleData = new domListOfUInts();
  623. for (S32 iPoly = 0; iPoly < primitive->getCount(); iPoly++) {
  624. domP* P = primitive->getP_array()[iPoly];
  625. // Ignore invalid P arrays
  626. if (!P || !P->getValue().getCount())
  627. continue;
  628. domUint* pSrcData = &(P->getValue()[0]);
  629. size_t numPoints = P->getValue().getCount() / stride;
  630. // Use a simple tri-fan (centered at the first point) method of
  631. // converting the polygon to triangles.
  632. domUint* v0 = pSrcData;
  633. pSrcData += stride;
  634. for (S32 iTri = 0; iTri < numPoints-2; iTri++) {
  635. pTriangleData->appendArray(stride, v0);
  636. pTriangleData->appendArray(stride*2, pSrcData);
  637. pSrcData += stride;
  638. }
  639. }
  640. }
  641. return pTriangleData;
  642. }
  643. //-----------------------------------------------------------------------------
  644. // <polylist>
  645. template<> inline const domListOfUInts *ColladaPrimitive<domPolylist>::getTriangleData()
  646. {
  647. if (!pTriangleData)
  648. {
  649. // Convert polygons to triangles
  650. pTriangleData = new domListOfUInts();
  651. // Check that the P element has the right number of values (this
  652. // has been seen with certain models exported using COLLADAMax)
  653. const domListOfUInts& vcount = primitive->getVcount()->getValue();
  654. U32 expectedCount = 0;
  655. for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++)
  656. expectedCount += vcount[iPoly];
  657. expectedCount *= stride;
  658. if (!primitive->getP() || !primitive->getP()->getValue().getCount() ||
  659. (primitive->getP()->getValue().getCount() != expectedCount) )
  660. {
  661. Con::warnf("<polylist> element found with invalid <p> array. This primitive will be ignored.");
  662. return pTriangleData;
  663. }
  664. domUint* pSrcData = &(primitive->getP()->getValue()[0]);
  665. for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++) {
  666. // Use a simple tri-fan (centered at the first point) method of
  667. // converting the polygon to triangles.
  668. domUint* v0 = pSrcData;
  669. pSrcData += stride;
  670. for (S32 iTri = 0; iTri < vcount[iPoly]-2; iTri++) {
  671. pTriangleData->appendArray(stride, v0);
  672. pTriangleData->appendArray(stride*2, pSrcData);
  673. pSrcData += stride;
  674. }
  675. pSrcData += stride;
  676. }
  677. }
  678. return pTriangleData;
  679. }
  680. //-----------------------------------------------------------------------------
  681. /// Convert a custom parameter string to a particular type
  682. template<typename T> inline T convert(const char* value) { return value; }
  683. template<> inline bool convert(const char* value) { return dAtob(value); }
  684. template<> inline S32 convert(const char* value) { return dAtoi(value); }
  685. template<> inline F64 convert(const char* value) { return dAtof(value); }
  686. template<> inline F32 convert(const char* value) { return convert<double>(value); }
  687. //-----------------------------------------------------------------------------
  688. /// Collada animation data
  689. struct AnimChannels : public Vector<struct AnimData*>
  690. {
  691. daeElement *element;
  692. AnimChannels(daeElement* el) : element(el)
  693. {
  694. element->setUserData(this);
  695. }
  696. ~AnimChannels()
  697. {
  698. if (element)
  699. element->setUserData(0);
  700. }
  701. };
  702. struct AnimData
  703. {
  704. bool enabled; ///!< Used to select animation channels for the current clip
  705. _SourceReader input;
  706. _SourceReader output;
  707. _SourceReader inTangent;
  708. _SourceReader outTangent;
  709. _SourceReader interpolation;
  710. U32 targetValueOffset; ///< Offset into the target element (for arrays of values)
  711. U32 targetValueCount; ///< Number of values animated (from OUTPUT source array)
  712. /// Get the animation channels for the Collada element (if any)
  713. static AnimChannels* getAnimChannels(const daeElement* element)
  714. {
  715. return element ? (AnimChannels*)const_cast<daeElement*>(element)->getUserData() : 0;
  716. }
  717. AnimData() : enabled(false) { }
  718. void parseTargetString(const char* target, S32 fullCount, const char* elements[]);
  719. F32 invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const;
  720. void interpValue(F32 t, U32 offset, double* value) const;
  721. void interpValue(F32 t, U32 offset, const char** value) const;
  722. };
  723. //-----------------------------------------------------------------------------
  724. // Collada allows any element with an SID or ID attribute to be the target of
  725. // an animation channel, which is very flexible, but awkward to work with. Some
  726. // examples of animated values are:
  727. // - single float
  728. // - single int
  729. // - single bool
  730. // - single string
  731. // - list of floats (transform elements or morph weights)
  732. //
  733. // This class provides a generic way to check if an element is animated, and
  734. // to get the value of the element at a given time.
  735. template<class T>
  736. struct AnimatedElement
  737. {
  738. const daeElement* element; ///< The Collada element (can be NULL)
  739. T defaultVal; ///< Default value (used when element is NULL)
  740. AnimatedElement(const daeElement* e=0) : element(e) { }
  741. /// Check if the element has any animations channels
  742. bool isAnimated() { return (AnimData::getAnimChannels(element) != 0); }
  743. bool isAnimated(F32 start, F32 end) { return isAnimated(); }
  744. /// Get the value of the element at the specified time
  745. T getValue(F32 time)
  746. {
  747. // If the element is NULL, just use the default (handy for <extra> profiles which
  748. // may or may not be present in the document)
  749. T value(defaultVal);
  750. if (const domAny* param = daeSafeCast<domAny>(const_cast<daeElement*>(element))) {
  751. // If the element is not animated, just use its current value
  752. value = convert<T>(param->getValue());
  753. // Animate the value
  754. const AnimChannels* channels = AnimData::getAnimChannels(element);
  755. if (channels && (time >= 0)) {
  756. for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) {
  757. const AnimData* animData = (*channels)[iChannel];
  758. if (animData->enabled)
  759. animData->interpValue(time, 0, &value);
  760. }
  761. }
  762. }
  763. return value;
  764. }
  765. };
  766. template<class T> struct AnimatedElementList : public AnimatedElement<T>
  767. {
  768. AnimatedElementList(const daeElement* e=0) : AnimatedElement<T>(e) { }
  769. // @todo: Disable morph animations for now since they are not supported by T3D
  770. bool isAnimated() { return false; }
  771. bool isAnimated(F32 start, F32 end) { return false; }
  772. // Get the value of the element list at the specified time
  773. T getValue(F32 time)
  774. {
  775. T vec(this->defaultVal);
  776. if (this->element) {
  777. // Get a copy of the vector
  778. vec = *(T*)const_cast<daeElement*>(this->element)->getValuePointer();
  779. // Animate the vector
  780. const AnimChannels* channels = AnimData::getAnimChannels(this->element);
  781. if (channels && (time >= 0)) {
  782. for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) {
  783. const AnimData* animData = (*channels)[iChannel];
  784. if (animData->enabled) {
  785. for (S32 iValue = 0; iValue < animData->targetValueCount; iValue++)
  786. animData->interpValue(time, iValue, &vec[animData->targetValueOffset + iValue]);
  787. }
  788. }
  789. }
  790. }
  791. return vec;
  792. }
  793. };
  794. // Strongly typed animated values
  795. typedef AnimatedElement<double> AnimatedFloat;
  796. typedef AnimatedElement<bool> AnimatedBool;
  797. typedef AnimatedElement<S32> AnimatedInt;
  798. typedef AnimatedElement<const char*> AnimatedString;
  799. typedef AnimatedElementList<domListOfFloats> AnimatedFloatList;
  800. #endif // _COLLADA_UTILS_H_