colladaUtils.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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. #include <algorithm>
  23. #include "console/console.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "ts/collada/colladaUtils.h"
  26. #include "materials/matInstance.h"
  27. using namespace ColladaUtils;
  28. #define MAX_PATH_LENGTH 256
  29. // Helper macro to create Collada elements
  30. #define CREATE_ELEMENT(container, name, type) \
  31. type* name = daeSafeCast<type>(container->createAndPlace(#name));
  32. ColladaUtils::ImportOptions& ColladaUtils::getOptions()
  33. {
  34. static ImportOptions options;
  35. return options;
  36. }
  37. //------------------------------------------------------------------------------
  38. // Utility functions
  39. // Convert a transform from the Collada model coordinate system to the DTS coordinate
  40. // system
  41. void ColladaUtils::convertTransform(MatrixF& mat)
  42. {
  43. MatrixF rot(true);
  44. switch (ColladaUtils::getOptions().upAxis)
  45. {
  46. case UPAXISTYPE_X_UP:
  47. // rotate 90 around Y-axis, then 90 around Z-axis
  48. rot(0,0) = 0.0f; rot(1,0) = 1.0f;
  49. rot(1,1) = 0.0f; rot(2,1) = 1.0f;
  50. rot(0,2) = 1.0f; rot(2,2) = 0.0f;
  51. // pre-multiply the transform by the rotation matrix
  52. mat.mulL(rot);
  53. break;
  54. case UPAXISTYPE_Y_UP:
  55. // rotate 180 around Y-axis, then 90 around X-axis
  56. rot(0,0) = -1.0f;
  57. rot(1,1) = 0.0f; rot(2,1) = 1.0f;
  58. rot(1,2) = 1.0f; rot(2,2) = 0.0f;
  59. // pre-multiply the transform by the rotation matrix
  60. mat.mulL(rot);
  61. break;
  62. case UPAXISTYPE_Z_UP:
  63. default:
  64. // nothing to do
  65. break;
  66. }
  67. }
  68. /// Find the COMMON profile element in an effect
  69. const domProfile_COMMON* ColladaUtils::findEffectCommonProfile(const domEffect* effect)
  70. {
  71. if (effect) {
  72. // Find the COMMON profile
  73. const domFx_profile_abstract_Array& profiles = effect->getFx_profile_abstract_array();
  74. for (S32 iProfile = 0; iProfile < profiles.getCount(); iProfile++) {
  75. if (profiles[iProfile]->getElementType() == COLLADA_TYPE::PROFILE_COMMON)
  76. return daeSafeCast<domProfile_COMMON>(profiles[iProfile]);
  77. }
  78. }
  79. return NULL;
  80. }
  81. /// Find the <diffuse> element in the COMMON profile of an effect
  82. const domCommon_color_or_texture_type_complexType* ColladaUtils::findEffectDiffuse(const domEffect* effect)
  83. {
  84. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  85. if (profile) {
  86. if (profile->getTechnique()->getLambert())
  87. return profile->getTechnique()->getLambert()->getDiffuse();
  88. else if (profile->getTechnique()->getPhong())
  89. return profile->getTechnique()->getPhong()->getDiffuse();
  90. else if (profile->getTechnique()->getBlinn())
  91. return profile->getTechnique()->getBlinn()->getDiffuse();
  92. }
  93. return NULL;
  94. }
  95. /// Find the <specular> element in the COMMON profile of an effect
  96. const domCommon_color_or_texture_type_complexType* ColladaUtils::findEffectSpecular(const domEffect* effect)
  97. {
  98. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  99. if (profile) {
  100. if (profile->getTechnique()->getLambert())
  101. return NULL; // no <specular> element for Lambert shader
  102. else if (profile->getTechnique()->getPhong())
  103. return profile->getTechnique()->getPhong()->getSpecular();
  104. else if (profile->getTechnique()->getBlinn())
  105. return profile->getTechnique()->getBlinn()->getSpecular();
  106. }
  107. return NULL;
  108. }
  109. const domFx_sampler2D_common_complexType* ColladaUtils::getTextureSampler(const domEffect* effect,
  110. const domCommon_color_or_texture_type_complexType* texture)
  111. {
  112. // <texture texture="new_param_SID">.<newparam>.<sampler2D>
  113. if (texture) {
  114. const domCommon_color_or_texture_type_complexType::domTexture* domTex = texture->getTexture();
  115. if (domTex && domTex->getTexture()) {
  116. daeSIDResolver resolver(const_cast<domEffect*>(effect), domTex->getTexture());
  117. const domCommon_newparam_type* param = daeSafeCast<domCommon_newparam_type>(resolver.getElement());
  118. if (param)
  119. return param->getSampler2D();
  120. }
  121. }
  122. return NULL;
  123. }
  124. String ColladaUtils::getSamplerImagePath(const domEffect* effect,
  125. const domFx_sampler2D_common_complexType* sampler2D)
  126. {
  127. // <sampler2D>.<source>.<newparam>.<surface>.<init_from>.<image>.<init_from>
  128. const domProfile_COMMON* profile = findEffectCommonProfile(effect);
  129. if (profile && sampler2D && sampler2D->getSource()) {
  130. // Resolve the SID to get the <surface> param
  131. daeSIDResolver resolver(const_cast<domProfile_COMMON*>(profile), sampler2D->getSource()->getValue());
  132. domCommon_newparam_type* surfaceParam = daeSafeCast<domCommon_newparam_type>(resolver.getElement());
  133. // Get the surface <init_from> element
  134. if (surfaceParam && surfaceParam->getSurface()) {
  135. const domFx_surface_init_common* surfaceInit = surfaceParam->getSurface()->getFx_surface_init_common();
  136. if (surfaceInit && surfaceInit->getInit_from_array().getCount()) {
  137. // Resolve the ID to get the <image>, then read the texture path
  138. xsIDREF& idRef = surfaceInit->getInit_from_array()[0]->getValue();
  139. const domImage* image = daeSafeCast<domImage>(idRef.getElement());
  140. if (image && image->getInit_from())
  141. return resolveImagePath(image);
  142. }
  143. }
  144. }
  145. return "";
  146. }
  147. // Resolve image path into something we can use.
  148. String ColladaUtils::resolveImagePath(const domImage* image)
  149. {
  150. // 1. If the URI string contains an absolute path, use it if
  151. // it is inside the Torque folder, otherwise force textures
  152. // to be in the same folder as the shape.
  153. // 2. If the URI string contains a relative path, append it
  154. // to the shape path (since materials.cs cannot handle
  155. // relative paths).
  156. Torque::Path imagePath;
  157. String imageStr(image->getInit_from()->getValue().originalStr().c_str());
  158. // Trim leading "file://"
  159. if (imageStr.compare("file://", 7) == 0)
  160. imageStr.erase(0, 7);
  161. // Trim leading slash from absolute windows paths. eg. /D:/
  162. if ((imageStr.compare("/", 1) == 0) && (imageStr.find(':') == 2))
  163. imageStr.erase(0, 1);
  164. // Replace %20 with space
  165. imageStr.replace("%20", " ");
  166. if (Platform::isFullPath(imageStr))
  167. {
  168. // Absolute path => check for outside the Torque game folder
  169. imagePath = String( Platform::makeRelativePathName(imageStr, Platform::getMainDotCsDir()) );
  170. if ( !imagePath.getRoot().isEmpty() || // different drive (eg. C:/ vs D:/)
  171. (imagePath.getPath().find("/") == 0) || // different OS (eg. /home vs C:/home)
  172. (imagePath.getPath().find("../") == 0) ) // same drive, outside Torque game folder
  173. {
  174. // Force these to the shape folder
  175. imagePath.setRoot("");
  176. imagePath.setPath("");
  177. }
  178. }
  179. else
  180. {
  181. // Relative path => prepend with shape path
  182. Torque::Path tempPath(imageStr);
  183. imagePath = TSShapeLoader::getShapePath();
  184. imagePath.appendPath(tempPath);
  185. imagePath.setFileName(tempPath.getFileName());
  186. }
  187. // No need to specify the path if it is in the same folder as the model
  188. if (imagePath.getPath() == TSShapeLoader::getShapePath().getPath())
  189. imagePath.setPath("");
  190. // Don't care about the extension
  191. imagePath.setExtension("");
  192. return imagePath.getFullPath();
  193. }
  194. //-----------------------------------------------------------------------------
  195. // Construct the appropriate child class
  196. BasePrimitive* BasePrimitive::get(const daeElement* element)
  197. {
  198. switch (element->getElementType()) {
  199. case COLLADA_TYPE::TRIANGLES: return new ColladaPrimitive<domTriangles>(element);
  200. case COLLADA_TYPE::TRISTRIPS: return new ColladaPrimitive<domTristrips>(element);
  201. case COLLADA_TYPE::TRIFANS: return new ColladaPrimitive<domTrifans>(element);
  202. case COLLADA_TYPE::POLYGONS: return new ColladaPrimitive<domPolygons>(element);
  203. case COLLADA_TYPE::POLYLIST: return new ColladaPrimitive<domPolylist>(element);
  204. default: return 0;
  205. }
  206. }
  207. //------------------------------------------------------------------------------
  208. // Collada animation curves
  209. /// Determine which elements are being targeted
  210. void AnimData::parseTargetString(const char* target, S32 fullCount, const char* elements[])
  211. {
  212. // Assume targeting all elements at offset 0
  213. targetValueCount = fullCount;
  214. targetValueOffset = 0;
  215. // Check for array syntax: (n) or (n)(m)
  216. if (const char* p = dStrchr(target, '(')) {
  217. S32 indN, indM;
  218. if (dSscanf(p, "(%d)(%d)", &indN, &indM) == 2) {
  219. targetValueOffset = (indN * 4) + indM; // @todo: 4x4 matrix only
  220. targetValueCount = 1;
  221. }
  222. else if (dSscanf(p, "(%d)", &indN) == 1) {
  223. targetValueOffset = indN;
  224. targetValueCount = 1;
  225. }
  226. }
  227. else if (const char* p = dStrrchr(target, '.')) {
  228. // Check for named elements
  229. for (S32 iElem = 0; elements[iElem][0] != 0; iElem++) {
  230. if (!dStrcmp(p, elements[iElem])) {
  231. targetValueOffset = iElem;
  232. targetValueCount = 1;
  233. break;
  234. }
  235. }
  236. }
  237. }
  238. /// Solve the cubic spline B(s) = param for s
  239. F32 AnimData::invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const
  240. {
  241. const F64 INVERTPARAMCUBIC_TOL = 1.0e-09;
  242. const F64 INVERTPARAMCUBIC_SMALLERTOL = 1.0e-20;
  243. const F64 INVERTPARAMCUBIC_MAXIT = 100;
  244. // check input value for outside range
  245. if ((param - x0) < INVERTPARAMCUBIC_SMALLERTOL)
  246. return 0.0f;
  247. else if ((x3 - param) < INVERTPARAMCUBIC_SMALLERTOL)
  248. return 1.0f;
  249. U32 iterations = 0;
  250. // de Casteljau Subdivision.
  251. F32 u = 0.0f;
  252. F32 v = 1.0f;
  253. while (iterations < INVERTPARAMCUBIC_MAXIT) {
  254. F64 a = (x0 + x1)*0.5f;
  255. F64 b = (x1 + x2)*0.5f;
  256. F64 c = (x2 + x3)*0.5f;
  257. F64 d = (a + b)*0.5f;
  258. F64 e = (b + c)*0.5f;
  259. F64 f = (d + e)*0.5f;
  260. if (mFabs(f - param) < INVERTPARAMCUBIC_TOL)
  261. break;
  262. if (f < param) {
  263. x0 = f;
  264. x1 = e;
  265. x2 = c;
  266. u = (u + v)*0.5f;
  267. }
  268. else {
  269. x1 = a;
  270. x2 = d;
  271. x3 = f;
  272. v = (u + v)*0.5f;
  273. }
  274. iterations++;
  275. }
  276. return mClampF((u+v)*0.5f, 0.0f, 1.0f);
  277. }
  278. /// Get the interpolated value at time 't'
  279. void AnimData::interpValue(F32 t, U32 offset, double* value) const
  280. {
  281. // handle degenerate animation data
  282. if (input.size() == 0)
  283. {
  284. *value = 0.0f;
  285. return;
  286. }
  287. else if (input.size() == 1)
  288. {
  289. *value = output.getStringArrayData(0)[offset];
  290. return;
  291. }
  292. // clamp time to valid range
  293. F32 curveStart = input.getFloatValue(0);
  294. F32 curveEnd = input.getFloatValue(input.size()-1);
  295. t = mClampF(t, curveStart, curveEnd);
  296. // find the index of the input keyframe BEFORE 't'
  297. S32 index;
  298. for (index = 0; index < input.size()-2; index++) {
  299. if (input.getFloatValue(index + 1) > t)
  300. break;
  301. }
  302. // get the data for the two control points either side of 't'
  303. Point2F v0;
  304. v0.x = input.getFloatValue(index);
  305. v0.y = output.getStringArrayData(index)[offset];
  306. Point2F v3;
  307. v3.x = input.getFloatValue(index + 1);
  308. v3.y = output.getStringArrayData(index + 1)[offset];
  309. // If spline interpolation is specified but the tangents are not available,
  310. // default to LINEAR.
  311. const char* interp_method = interpolation.getStringValue(index);
  312. if (dStrEqual(interp_method, "BEZIER") ||
  313. dStrEqual(interp_method, "HERMITE") ||
  314. dStrEqual(interp_method, "CARDINAL")) {
  315. const double* inArray = inTangent.getStringArrayData(index + 1);
  316. const double* outArray = outTangent.getStringArrayData(index);
  317. if (!inArray || !outArray)
  318. interp_method = "LINEAR";
  319. }
  320. if (dStrEqual(interp_method, "STEP")) {
  321. // STEP interpolation
  322. *value = v0.y;
  323. }
  324. else if (dStrEqual(interp_method, "BEZIER") ||
  325. dStrEqual(interp_method, "HERMITE") ||
  326. dStrEqual(interp_method, "CARDINAL") ||
  327. dStrEqual(interp_method, "BSPLINE"))
  328. {
  329. // Cubic spline interpolation. The only difference between the 4 supported
  330. // forms is in the calculation of the other 2 control points:
  331. // BEZIER: control points are specified explicitly
  332. // HERMITE: tangents are specified, need to offset to get the control points
  333. // CARDINAL: (baked) tangents are specified, need to offset to get the control points
  334. // BSPLINE: control points are based on previous and next points
  335. // Get the 2 extra control points
  336. Point2F v1, v2;
  337. if (dStrEqual(interp_method, "BSPLINE")) {
  338. // v0 and v3 are the center points => need to
  339. // get the control points before and after them
  340. v1 = v0;
  341. v2 = v3;
  342. if (index > 0) {
  343. v0.x = input.getFloatValue(index-1);
  344. v0.y = output.getStringArrayData(index-1)[offset];
  345. }
  346. else {
  347. // mirror P1 through P0
  348. v0 = v1 + (v1 - v2);
  349. }
  350. if (index < (input.size()-2)) {
  351. v3.x = input.getFloatValue(index+2);
  352. v3.y = output.getStringArrayData(index+2)[offset];
  353. }
  354. else {
  355. // mirror P0 through P1
  356. v3 = v2 + (v2 - v1);
  357. }
  358. }
  359. else {
  360. const double* inArray = inTangent.getStringArrayData(index + 1);
  361. const double* outArray = outTangent.getStringArrayData(index);
  362. if (output.stride() == inTangent.stride()) {
  363. // This degenerate form (1D control points) does 2 things wrong:
  364. // 1) it does not specify the key (time) value
  365. // 2) the control point is specified as a tangent for both bezier and hermite
  366. // => interpolate to get the key values, and offset the tangent values
  367. v1.set((v0.x*2 + v3.x)/3, v0.y + outArray[offset]);
  368. v2.set((v0.x + v3.x*2)/3, v3.y - inArray[offset]);
  369. }
  370. else {
  371. // the expected form (2D control points)
  372. v1.set(outArray[offset*2], outArray[offset*2+1]);
  373. v2.set(inArray[offset*2], inArray[offset*2+1]);
  374. // if this is a hermite or cardinal spline, treat the values as tangents
  375. if (dStrEqual(interp_method, "HERMITE") || dStrEqual(interp_method, "CARDINAL")) {
  376. v1.set(v0.x + v1.x, v3.y - v1.y);
  377. v2.set(v0.x + v2.x, v3.x - v2.y);
  378. }
  379. }
  380. }
  381. // find 's' that gives the desired 't' value
  382. F32 s = invertParamCubic(t, v0.x, v1.x, v2.x, v3.x);
  383. // Calculate the output value using Bernstein evaluation and the
  384. // computed 's' value
  385. F32 c = 3.0f*(v1.y - v0.y);
  386. F32 e = 3.0f*(v2.y - v1.y);
  387. *value = (((v3.y - v0.y - e)*s + e - c)*s + c)*s + v0.y;
  388. }
  389. else {
  390. // default to LINEAR interpolation
  391. F32 s = mClampF((t - v0.x) / (v3.x - v0.x), 0.0f, 1.0f);
  392. *value = v0.y + (v3.y - v0.y) * s;
  393. }
  394. }
  395. void AnimData::interpValue(F32 t, U32 offset, const char** value) const
  396. {
  397. if (input.size() == 0)
  398. *value = "";
  399. else if (input.size() == 1)
  400. *value = output.getStringValue(0);
  401. else
  402. {
  403. // clamp time to valid range
  404. F32 curveStart = input.getFloatValue(0);
  405. F32 curveEnd = input.getFloatValue(input.size()-1);
  406. t = mClampF(t, curveStart, curveEnd);
  407. // find the index of the input keyframe BEFORE 't'
  408. S32 index;
  409. for (index = 0; index < input.size()-2; index++) {
  410. if (input.getFloatValue(index + 1) > t)
  411. break;
  412. }
  413. // String values only support STEP interpolation, so just get the
  414. // value at the input keyframe
  415. *value = output.getStringValue(index);
  416. }
  417. }
  418. //------------------------------------------------------------------------------
  419. // Collada document conditioners
  420. static void conditioner_fixupTextureSIDs(domCOLLADA* root)
  421. {
  422. for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) {
  423. domLibrary_effects* lib = root->getLibrary_effects_array()[iLib];
  424. for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) {
  425. domEffect* effect = lib->getEffect_array()[iEffect];
  426. const domCommon_color_or_texture_type_complexType* diffuse = findEffectDiffuse(effect);
  427. if (!diffuse || !diffuse->getTexture())
  428. continue;
  429. // Resolve the SID => if it is an <image>, add <sampler2D> and
  430. // <surface> elements to conform to the Collada spec.
  431. const char *image_sid = diffuse->getTexture()->getTexture();
  432. daeSIDResolver resolver(effect, image_sid);
  433. if (!daeSafeCast<domImage>(resolver.getElement()))
  434. continue;
  435. daeErrorHandler::get()->handleWarning(avar("Fixup %s <diffuse>.<texture> "
  436. "pointing at <image> instead of <sampler2D>", effect->getID()));
  437. // Generate SIDs for the new sampler2D and surface elements
  438. std::string sampler_sid(std::string(image_sid) + "-sampler");
  439. std::string surface_sid(std::string(image_sid) + "-surface");
  440. domProfile_COMMON* profile = const_cast<domProfile_COMMON*>(findEffectCommonProfile(effect));
  441. // Create <newparam>.<sampler2D>.<source>
  442. {
  443. CREATE_ELEMENT(profile, newparam, domCommon_newparam_type)
  444. CREATE_ELEMENT(newparam, sampler2D, domFx_sampler2D_common)
  445. CREATE_ELEMENT(sampler2D, source, domFx_sampler2D_common_complexType::domSource)
  446. newparam->setSid(sampler_sid.c_str());
  447. source->setValue(surface_sid.c_str());
  448. }
  449. // Create <newparam>.<surface>.<init_from>
  450. {
  451. CREATE_ELEMENT(profile, newparam, domCommon_newparam_type)
  452. CREATE_ELEMENT(newparam, surface, domFx_surface_common)
  453. CREATE_ELEMENT(surface, init_from, domFx_surface_init_from_common)
  454. CREATE_ELEMENT(surface, format, domFx_surface_common_complexType::domFormat)
  455. newparam->setSid(surface_sid.c_str());
  456. surface->setType(FX_SURFACE_TYPE_ENUM_2D);
  457. format->setValue("A8R8G8B8");
  458. init_from->setValue(image_sid);
  459. }
  460. // Store sampler2D sid in the <diffuse>.<texture> "texture" attribute
  461. diffuse->getTexture()->setTexture(sampler_sid.c_str());
  462. }
  463. }
  464. }
  465. static void conditioner_fixupImageURIs(domCOLLADA* root)
  466. {
  467. for (S32 iLib = 0; iLib < root->getLibrary_images_array().getCount(); iLib++) {
  468. domLibrary_images* lib = root->getLibrary_images_array()[iLib];
  469. for (S32 iImage = 0; iImage < lib->getImage_array().getCount(); iImage++) {
  470. domImage* image = lib->getImage_array()[iImage];
  471. if (image->getInit_from()) {
  472. xsAnyURI& uri = image->getInit_from()->getValue();
  473. // Replace '\' with '/'
  474. if (uri.originalStr().find("\\") != std::string::npos) {
  475. daeErrorHandler::get()->handleWarning(avar("Fixup invalid URI "
  476. "in %s: \"%s\"", image->getID(), uri.originalStr().c_str()));
  477. std::string str(uri.originalStr());
  478. std::replace(str.begin(), str.end(), '\\', '/');
  479. uri.set(str);
  480. }
  481. // Detect file://texture.jpg => this is an invalid URI and will
  482. // not be parsed correctly
  483. if (uri.scheme() == "file" &&
  484. uri.pathFile().empty() &&
  485. !uri.authority().empty()) {
  486. daeErrorHandler::get()->handleWarning(avar("Fixup invalid URI "
  487. "in %s: \"%s\"", image->getID(), uri.originalStr().c_str()));
  488. uri.set(uri.authority());
  489. }
  490. }
  491. }
  492. }
  493. }
  494. static void conditioner_fixupTransparency(domCOLLADA* root)
  495. {
  496. // Transparency is another example of something simple made complicated by
  497. // Collada. There are two (optional) elements that determine transparency:
  498. //
  499. // <transparent>: a color
  500. // <transparency>: a percentage applied to the color values
  501. //
  502. // Additionally, <transparent> has an optional "opaque" attribute that changes
  503. // the way transparency is determined. If set to A_ONE (the default), only the
  504. // alpha value of the transparent color is used, and a value of "1" means fully
  505. // opaque. If set to RGB_ZERO, only the RGB values of transparent are used, and
  506. // a value of "0" means fully opaque.
  507. //
  508. // To further complicate matters, Google Sketchup (all versions) and FeelingSoftware
  509. // ColladaMax (pre 3.03) export materials with the transparency element inverted
  510. // (1-transparency)
  511. // Get the <authoring_tool> string
  512. const char *authoringTool = "";
  513. if (const domAsset* asset = root->getAsset()) {
  514. for (S32 iContrib = 0; iContrib < asset->getContributor_array().getCount(); iContrib++) {
  515. const domAsset::domContributor* contrib = asset->getContributor_array()[iContrib];
  516. if (contrib->getAuthoring_tool()) {
  517. authoringTool = contrib->getAuthoring_tool()->getValue();
  518. break;
  519. }
  520. }
  521. }
  522. // Check for a match with the known problem-tools
  523. bool invertTransparency = false;
  524. const char *toolNames[] = { "FBX COLLADA exporter", "Google SketchUp",
  525. "Illusoft Collada Exporter", "FCollada" };
  526. for (S32 iName = 0; iName < (sizeof(toolNames)/sizeof(toolNames[0])); iName++) {
  527. if (dStrstr(authoringTool, toolNames[iName])) {
  528. invertTransparency = true;
  529. break;
  530. }
  531. }
  532. if (!invertTransparency)
  533. return;
  534. // Invert transparency as required for each effect
  535. for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) {
  536. domLibrary_effects* lib = root->getLibrary_effects_array()[iLib];
  537. for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) {
  538. domEffect* effect = lib->getEffect_array()[iEffect];
  539. // Find the common profile
  540. const domProfile_COMMON* commonProfile = findEffectCommonProfile(effect);
  541. if (!commonProfile)
  542. continue;
  543. domCommon_transparent_type* transparent = 0;
  544. if (commonProfile->getTechnique()->getConstant())
  545. transparent = commonProfile->getTechnique()->getConstant()->getTransparent();
  546. else if (commonProfile->getTechnique()->getLambert())
  547. transparent = commonProfile->getTechnique()->getLambert()->getTransparent();
  548. else if (commonProfile->getTechnique()->getPhong())
  549. transparent = commonProfile->getTechnique()->getPhong()->getTransparent();
  550. else if (commonProfile->getTechnique()->getBlinn())
  551. transparent = commonProfile->getTechnique()->getBlinn()->getTransparent();
  552. if (!transparent)
  553. continue;
  554. // If the shader "opaque" attribute is not specified, set it to
  555. // RGB_ZERO (the opposite of the Collada default), as this is what
  556. // the bad exporter tools seem to assume.
  557. if (!transparent->isAttributeSet("opaque")) {
  558. daeErrorHandler::get()->handleWarning(avar("Setting <transparent> "
  559. "\"opaque\" attribute to RGB_ZERO for %s <effect>", effect->getID()));
  560. transparent->setOpaque(FX_OPAQUE_ENUM_RGB_ZERO);
  561. }
  562. }
  563. }
  564. }
  565. static void conditioner_checkBindShapeMatrix(domCOLLADA* root)
  566. {
  567. for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) {
  568. domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib);
  569. for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) {
  570. domController* con = lib->getController_array().get(iCon);
  571. if (con->getSkin() && con->getSkin()->getBind_shape_matrix()) {
  572. MatrixF mat = vecToMatrixF<domMatrix>(con->getSkin()->getBind_shape_matrix()->getValue());
  573. if (!mat.fullInverse()) {
  574. daeErrorHandler::get()->handleWarning(avar("<bind_shape_matrix> "
  575. "in %s <controller> is not invertible (may cause problems with "
  576. "skinning)", con->getID()));
  577. }
  578. }
  579. }
  580. }
  581. }
  582. static void conditioner_fixupVertexWeightJoints(domCOLLADA* root)
  583. {
  584. for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) {
  585. domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib);
  586. for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) {
  587. domController* con = lib->getController_array().get(iCon);
  588. if (con->getSkin() && con->getSkin()->getVertex_weights())
  589. {
  590. domInputLocalOffset_Array& vw_inputs = con->getSkin()->getVertex_weights()->getInput_array();
  591. for (S32 vInput = 0; vInput < vw_inputs.getCount(); vInput++) {
  592. domInputLocalOffset *vw_input = vw_inputs.get(vInput);
  593. if (dStrEqual(vw_input->getSemantic(), "JOINT")) {
  594. // Check if this input points at a float array (bad)
  595. domSource* vw_source = daeSafeCast<domSource>(vw_input->getSource().getElement());
  596. if (vw_source->getFloat_array()) {
  597. // Copy the value from the <joints> JOINTS input instead
  598. domInputLocal_Array& joint_inputs = con->getSkin()->getJoints()->getInput_array();
  599. for (S32 jInput = 0; jInput < joint_inputs.getCount(); jInput++) {
  600. domInputLocal *joint_input = joint_inputs.get(jInput);
  601. if (dStrEqual(joint_input->getSemantic(), "JOINT")) {
  602. vw_input->setSource(joint_input->getSource());
  603. break;
  604. }
  605. }
  606. }
  607. }
  608. }
  609. }
  610. }
  611. }
  612. }
  613. static void conditioner_createDefaultClip(domCOLLADA* root)
  614. {
  615. // Check if the document has any <animation_clip>s
  616. for (S32 iLib = 0; iLib < root->getLibrary_animation_clips_array().getCount(); iLib++) {
  617. if (root->getLibrary_animation_clips_array()[iLib]->getAnimation_clip_array().getCount())
  618. return;
  619. }
  620. // Get all top-level <animation>s into an array
  621. domAnimation_Array animations;
  622. for (S32 iAnimLib = 0; iAnimLib < root->getLibrary_animations_array().getCount(); iAnimLib++) {
  623. const domLibrary_animations* libraryAnims = root->getLibrary_animations_array()[iAnimLib];
  624. for (S32 iAnim = 0; iAnim < libraryAnims->getAnimation_array().getCount(); iAnim++)
  625. animations.append(libraryAnims->getAnimation_array()[iAnim]);
  626. }
  627. if (!animations.getCount())
  628. return;
  629. daeErrorHandler::get()->handleWarning("Creating cyclic animation clip to "
  630. "hold all animations");
  631. // Get animation_clip library (create one if necessary)
  632. if (!root->getLibrary_animation_clips_array().getCount()) {
  633. root->createAndPlace("library_animation_clips");
  634. }
  635. domLibrary_animation_clips* libraryClips = root->getLibrary_animation_clips_array()[0];
  636. // Create new animation_clip for the default sequence
  637. CREATE_ELEMENT(libraryClips, animation_clip, domAnimation_clip)
  638. animation_clip->setName("ambient");
  639. animation_clip->setId("dummy_ambient_clip");
  640. animation_clip->setStart(0);
  641. animation_clip->setEnd(0);
  642. // Add all top_level animations to the clip (sub-animations will be included
  643. // when the clip is procesed)
  644. for (S32 iAnim = 0; iAnim < animations.getCount(); iAnim++) {
  645. if (!animations[iAnim]->getId())
  646. animations[iAnim]->setId(avar("dummy-animation-id%d", iAnim));
  647. CREATE_ELEMENT(animation_clip, instance_animation, domInstanceWithExtra)
  648. std::string url(std::string("#") + animations[iAnim]->getId());
  649. instance_animation->setUrl(url.c_str());
  650. }
  651. // Add the 'Torque' profile to specify the 'Cyclic' flag
  652. CREATE_ELEMENT(animation_clip, extra, domExtra)
  653. CREATE_ELEMENT(extra, technique, domTechnique)
  654. CREATE_ELEMENT(technique, any, domAny)
  655. technique->setProfile("Torque");
  656. any->setElementName("cyclic");
  657. any->setValue("1");
  658. }
  659. static void conditioner_fixupAnimation(domAnimation* anim)
  660. {
  661. for (S32 iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) {
  662. // Get the animation elements: <channel>, <sampler>
  663. domChannel* channel = anim->getChannel_array()[iChannel];
  664. domSampler* sampler = daeSafeCast<domSampler>(channel->getSource().getElement());
  665. if (!sampler)
  666. continue;
  667. /*
  668. // If using a spline interpolation type but no tangents are specified,
  669. // fall back to LINEAR interpolation.
  670. bool isSpline = false;
  671. bool foundInTangent = false;
  672. bool foundOutTangent = false;
  673. for (int iInput = 0; iInput < sampler->getInput_array().getCount(); iInput++) {
  674. const char *semantic = sampler->getInput_array()[iInput]->getSemantic();
  675. if (dStrEqual(semantic, "INTERPOLATION")) {
  676. if (
  677. }
  678. if (dStrEqual(semantic, "IN_TANGENT"))
  679. foundInTangent = true;
  680. if (dStrEqual(semantic, "OUT_TANGENT"))
  681. foundOutTangent = true;
  682. }
  683. if (isSpline && (!foundInTangent || !foundOutTangent)) {
  684. daeErrorHandler::get()->handleWarning(avar("%s type interpolation "
  685. "specified for %s, but IN/OUT TANGENTS are not provided. Using "
  686. "LINEAR interpolation instead.");
  687. }
  688. */
  689. // Find the animation channel target
  690. daeSIDResolver resolver(channel, channel->getTarget());
  691. daeElement* target = resolver.getElement();
  692. if (!target) {
  693. // Some exporters generate visibility animations but don't add the
  694. // FCOLLADA extension, so the target doesn't actually exist! Detect
  695. // this situation and add the extension manually so the animation
  696. // still works.
  697. if (dStrEndsWith(channel->getTarget(), "/visibility")) {
  698. // Get parent SID string
  699. char *parentSID = dStrdup(channel->getTarget());
  700. parentSID[dStrlen(parentSID) - dStrlen("/visibility")] = '\0';
  701. // Find the parent element (should be a <node>)
  702. daeSIDResolver parentResolver(channel, parentSID);
  703. daeElement* parent = parentResolver.getElement();
  704. delete [] parentSID;
  705. if (parent && (parent->getElementType() == COLLADA_TYPE::NODE)) {
  706. // Create the FCOLLADA extension
  707. daeErrorHandler::get()->handleWarning(avar("Creating missing "
  708. "visibility animation target: %s", channel->getTarget()));
  709. // Check if the <visibility> element exists but is missing the SID
  710. daeElement* vis = parent->getDescendant("visibility");
  711. if (vis)
  712. {
  713. vis->setAttribute("sid", "visibility");
  714. }
  715. else
  716. {
  717. CREATE_ELEMENT(parent, extra, domExtra)
  718. CREATE_ELEMENT(extra, technique, domTechnique)
  719. CREATE_ELEMENT(technique, any, domAny)
  720. technique->setProfile("FCOLLADA");
  721. any->setElementName("visibility");
  722. any->setAttribute("sid", "visibility");
  723. any->setValue(""); // real initial value will be set when animation is processed in ColladaShapeLoader::processAnimation
  724. }
  725. }
  726. }
  727. }
  728. }
  729. // Process child animations
  730. for (S32 iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++)
  731. conditioner_fixupAnimation(anim->getAnimation_array()[iAnim]);
  732. }
  733. /// Apply the set of model conditioners
  734. void ColladaUtils::applyConditioners(domCOLLADA* root)
  735. {
  736. //--------------------------------------------------------------------------
  737. // The built-in MAX FBX exporter specifies an <image> SID in the <texture>
  738. // "texture" attribute instead of a <newparam> SID. Detect and fix this.
  739. conditioner_fixupTextureSIDs(root);
  740. //--------------------------------------------------------------------------
  741. // The built-in MAX FBX exporter also generates invalid URI paths in the
  742. // <image>.<init_from> tag, so fix that up too.
  743. conditioner_fixupImageURIs(root);
  744. //--------------------------------------------------------------------------
  745. // Many exporters get transparency backwards. Check if the model was exported
  746. // by one with a known issue and correct it.
  747. conditioner_fixupTransparency(root);
  748. //--------------------------------------------------------------------------
  749. // Some exporters (AutoDesk) generate invalid bind_shape matrices. Warn if
  750. // the bind_shape_matrix is not invertible.
  751. conditioner_checkBindShapeMatrix(root);
  752. //--------------------------------------------------------------------------
  753. // The PoserPro exporter points the <vertex_weights> JOINT input to the
  754. // inverse bind matrices instead of the joint names array. Detect and fix it.
  755. conditioner_fixupVertexWeightJoints(root);
  756. //--------------------------------------------------------------------------
  757. // If the model contains <animation>s but no <animation_clip>s, just put all
  758. // top level animations into a single clip.
  759. conditioner_createDefaultClip(root);
  760. //--------------------------------------------------------------------------
  761. // Apply some animation fixups:
  762. // 1) Some exporters (eg. Blender) generate "BEZIER" type animation curves,
  763. // but do not specify the IN and OUT tangent data arrays. Detect this and
  764. // fall back to LINEAR interpolation.
  765. // 2) Some exporters generate visibility animations but don't add the FCOLLADA
  766. // extension, so the target doesn't actually exist! Detect this situation
  767. // and add the extension manually so the animation still works.
  768. for (S32 iLib = 0; iLib < root->getLibrary_animations_array().getCount(); iLib++) {
  769. const domLibrary_animations* lib = root->getLibrary_animations_array()[iLib];
  770. for (S32 iAnim = 0; iAnim < lib->getAnimation_array().getCount(); iAnim++)
  771. conditioner_fixupAnimation(lib->getAnimation_array()[iAnim]);
  772. }
  773. }
  774. Torque::Path ColladaUtils::findTexture(const Torque::Path& diffuseMap)
  775. {
  776. Vector<Torque::Path> foundPaths;
  777. GBitmap::sFindFiles(diffuseMap, &foundPaths);
  778. if (foundPaths.size() > 0)
  779. return Torque::Path(foundPaths[0]);
  780. // If unable to load texture in current directory
  781. // look in the parent directory. But never look in the root.
  782. Torque::Path newPath(diffuseMap);
  783. String filePath = newPath.getPath();
  784. String::SizeType slash = filePath.find('/', filePath.length(), String::Right);
  785. if (slash != String::NPos)
  786. {
  787. slash = filePath.find('/', filePath.length(), String::Right);
  788. if (slash != String::NPos)
  789. {
  790. String truncPath = filePath.substr(0, slash);
  791. newPath.setPath(truncPath);
  792. return findTexture(newPath);
  793. }
  794. }
  795. return String::EmptyString;
  796. }
  797. void ColladaUtils::exportColladaHeader(TiXmlElement* rootNode)
  798. {
  799. TiXmlElement* assetNode = new TiXmlElement("asset");
  800. rootNode->LinkEndChild(assetNode);
  801. TiXmlElement* contributorNode = new TiXmlElement("contributor");
  802. assetNode->LinkEndChild(contributorNode);
  803. TiXmlElement* authorNode = new TiXmlElement("author");
  804. contributorNode->LinkEndChild(authorNode);
  805. TiXmlElement* authoringToolNode = new TiXmlElement("authoring_tool");
  806. contributorNode->LinkEndChild(authoringToolNode);
  807. TiXmlText* authorText = new TiXmlText(avar("%s %s Object Exporter", getEngineProductString(), getVersionString()));
  808. authoringToolNode->LinkEndChild(authorText);
  809. TiXmlElement* commentsNode = new TiXmlElement("comments");
  810. contributorNode->LinkEndChild(commentsNode);
  811. // Get the current time
  812. Platform::LocalTime lt;
  813. Platform::getLocalTime(lt);
  814. String localTime = Platform::localTimeToString(lt);
  815. localTime.replace('\t', ' ');
  816. TiXmlElement* createdNode = new TiXmlElement("created");
  817. assetNode->LinkEndChild(createdNode);
  818. TiXmlText* createdText = new TiXmlText(avar("%s", localTime.c_str()));
  819. createdNode->LinkEndChild(createdText);
  820. TiXmlElement* modifiedNode = new TiXmlElement("modified");
  821. assetNode->LinkEndChild(modifiedNode);
  822. TiXmlText* modifiedText = new TiXmlText(avar("%s", localTime.c_str()));
  823. modifiedNode->LinkEndChild(modifiedText);
  824. TiXmlElement* revisionNode = new TiXmlElement("revision");
  825. assetNode->LinkEndChild(revisionNode);
  826. TiXmlElement* titleNode = new TiXmlElement("title");
  827. assetNode->LinkEndChild(titleNode);
  828. TiXmlElement* subjectNode = new TiXmlElement("subject");
  829. assetNode->LinkEndChild(subjectNode);
  830. TiXmlElement* keywordsNode = new TiXmlElement("keywords");
  831. assetNode->LinkEndChild(keywordsNode);
  832. // Torque uses Z_UP with 1 unit equal to 1 meter by default
  833. TiXmlElement* unitNode = new TiXmlElement("unit");
  834. assetNode->LinkEndChild(unitNode);
  835. unitNode->SetAttribute("meter", "1.000000");
  836. TiXmlElement* axisNode = new TiXmlElement("up_axis");
  837. assetNode->LinkEndChild(axisNode);
  838. TiXmlText* axisText = new TiXmlText("Z_UP");
  839. axisNode->LinkEndChild(axisText);
  840. }
  841. void ColladaUtils::exportColladaMaterials(TiXmlElement* rootNode, const OptimizedPolyList& mesh, Vector<String>& matNames, const Torque::Path& colladaFile)
  842. {
  843. // First the image library
  844. TiXmlElement* imgLibNode = new TiXmlElement("library_images");
  845. rootNode->LinkEndChild(imgLibNode);
  846. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  847. {
  848. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  849. matNames.push_back(String::ToString("Material%d", i));
  850. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  851. if (!mat)
  852. continue;
  853. String diffuseMap;
  854. if (mat->getName() && mat->getName()[0])
  855. matNames.last() = String(mat->getName());
  856. // Handle an auto-generated "Default Material" specially
  857. if (mat->isAutoGenerated())
  858. {
  859. Torque::Path diffusePath;
  860. if (mat->mDiffuseMapFilename[0].isNotEmpty())
  861. diffusePath = mat->mDiffuseMapFilename[0];
  862. else
  863. diffusePath = String("warningMat");
  864. matNames.last() = diffusePath.getFileName();
  865. diffuseMap += diffusePath.getFullFileName();
  866. }
  867. else
  868. {
  869. if (mat->mDiffuseMapFilename[0].isNotEmpty())
  870. diffuseMap += mat->mDiffuseMapFilename[0];
  871. else
  872. diffuseMap += "warningMat";
  873. }
  874. Torque::Path diffusePath = findTexture(colladaFile.getPath() + "/" + diffuseMap);
  875. // If we didn't get a path
  876. if (diffusePath.getFullPath().isNotEmpty())
  877. diffuseMap = Torque::Path::MakeRelativePath(diffusePath, colladaFile);
  878. TiXmlElement* imageNode = new TiXmlElement("image");
  879. imgLibNode->LinkEndChild(imageNode);
  880. imageNode->SetAttribute("id", avar("%s-Diffuse", matNames.last().c_str()));
  881. imageNode->SetAttribute("name", avar("%s-Diffuse", matNames.last().c_str()));
  882. TiXmlElement* initNode = new TiXmlElement("init_from");
  883. imageNode->LinkEndChild(initNode);
  884. TiXmlText* initText = new TiXmlText(avar("file://%s", diffuseMap.c_str()));
  885. initNode->LinkEndChild(initText);
  886. }
  887. // Next the material library
  888. TiXmlElement* matLibNode = new TiXmlElement("library_materials");
  889. rootNode->LinkEndChild(matLibNode);
  890. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  891. {
  892. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  893. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  894. if (!mat)
  895. continue;
  896. TiXmlElement* materialNode = new TiXmlElement("material");
  897. matLibNode->LinkEndChild(materialNode);
  898. materialNode->SetAttribute("id", matNames[i].c_str());
  899. materialNode->SetAttribute("name", matNames[i].c_str());
  900. TiXmlElement* instEffectNode = new TiXmlElement("instance_effect");
  901. materialNode->LinkEndChild(instEffectNode);
  902. instEffectNode->SetAttribute("url", avar("#%s-fx", matNames[i].c_str()));
  903. }
  904. // Finally the effects library
  905. TiXmlElement* effectLibNode = new TiXmlElement("library_effects");
  906. rootNode->LinkEndChild(effectLibNode);
  907. for (U32 i = 0; i < mesh.mMaterialList.size(); i++)
  908. {
  909. BaseMatInstance* baseInst = mesh.mMaterialList[i];
  910. Material* mat = dynamic_cast<Material*>(baseInst->getMaterial());
  911. if (!mat)
  912. continue;
  913. TiXmlElement* effectNode = new TiXmlElement("effect");
  914. effectLibNode->LinkEndChild(effectNode);
  915. effectNode->SetAttribute("id", avar("%s-fx", matNames[i].c_str()));
  916. effectNode->SetAttribute("name", avar("%s-fx", matNames[i].c_str()));
  917. TiXmlElement* profileNode = new TiXmlElement("profile_COMMON");
  918. effectNode->LinkEndChild(profileNode);
  919. TiXmlElement* techniqueNode = new TiXmlElement("technique");
  920. profileNode->LinkEndChild(techniqueNode);
  921. techniqueNode->SetAttribute("sid", "standard");
  922. TiXmlElement* phongNode = new TiXmlElement("phong");
  923. techniqueNode->LinkEndChild(phongNode);
  924. TiXmlElement* diffuseNode = new TiXmlElement("diffuse");
  925. phongNode->LinkEndChild(diffuseNode);
  926. TiXmlElement* textureNode = new TiXmlElement("texture");
  927. diffuseNode->LinkEndChild(textureNode);
  928. textureNode->SetAttribute("texture", avar("%s-Diffuse", matNames[i].c_str()));
  929. textureNode->SetAttribute("texcoord", "CHANNEL0");
  930. // Extra info useful for getting the texture to show up correctly in some apps
  931. TiXmlElement* extraNode = new TiXmlElement("extra");
  932. textureNode->LinkEndChild(extraNode);
  933. TiXmlElement* extraTechNode = new TiXmlElement("technique");
  934. extraNode->LinkEndChild(extraTechNode);
  935. extraTechNode->SetAttribute("profile", "MAYA");
  936. TiXmlElement* extraWrapUNode = new TiXmlElement("wrapU");
  937. extraTechNode->LinkEndChild(extraWrapUNode);
  938. extraWrapUNode->SetAttribute("sid", "wrapU0");
  939. TiXmlText* extraWrapUText = new TiXmlText("TRUE");
  940. extraWrapUNode->LinkEndChild(extraWrapUText);
  941. TiXmlElement* extraWrapVNode = new TiXmlElement("wrapV");
  942. extraTechNode->LinkEndChild(extraWrapVNode);
  943. extraWrapVNode->SetAttribute("sid", "wrapV0");
  944. TiXmlText* extraWrapVText = new TiXmlText("TRUE");
  945. extraWrapVNode->LinkEndChild(extraWrapVText);
  946. TiXmlElement* extraBlendNode = new TiXmlElement("blend_mode");
  947. extraTechNode->LinkEndChild(extraBlendNode);
  948. TiXmlText* extraBlendText = new TiXmlText("ADD");
  949. extraBlendNode->LinkEndChild(extraBlendText);
  950. }
  951. }
  952. void ColladaUtils::exportColladaTriangles(TiXmlElement* meshNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames)
  953. {
  954. // Start at -1 so we will export polygons that do not have a material.
  955. for (S32 i = -1; i < matNames.size(); i++)
  956. {
  957. // Calculate the number of triangles that uses this Material
  958. U32 triangleCount = 0;
  959. for (U32 j = 0; j < mesh.mPolyList.size(); j++)
  960. {
  961. const OptimizedPolyList::Poly& poly = mesh.mPolyList[j];
  962. if (poly.material != i)
  963. continue;
  964. if (poly.vertexCount < 3)
  965. continue;
  966. if (poly.type == OptimizedPolyList::TriangleList ||
  967. poly.type == OptimizedPolyList::TriangleFan ||
  968. poly.type == OptimizedPolyList::TriangleStrip)
  969. {
  970. triangleCount += poly.vertexCount - 2;
  971. }
  972. else
  973. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  974. }
  975. // Make sure that we are actually using this Material
  976. if (triangleCount == 0)
  977. continue;
  978. TiXmlElement* trianglesNode = new TiXmlElement("triangles");
  979. meshNode->LinkEndChild(trianglesNode);
  980. trianglesNode->SetAttribute("material", ( i > -1 ) ? matNames[i].c_str() : "" );
  981. trianglesNode->SetAttribute("count", avar("%d", triangleCount));
  982. TiXmlElement* trianglesVertInputNode = new TiXmlElement("input");
  983. trianglesNode->LinkEndChild(trianglesVertInputNode);
  984. trianglesVertInputNode->SetAttribute("semantic", "VERTEX");
  985. trianglesVertInputNode->SetAttribute("offset", "0");
  986. trianglesVertInputNode->SetAttribute("source", avar("#%s-Vertex", meshName.c_str()));
  987. TiXmlElement* trianglesNormalInputNode = new TiXmlElement("input");
  988. trianglesNode->LinkEndChild(trianglesNormalInputNode);
  989. trianglesNormalInputNode->SetAttribute("semantic", "NORMAL");
  990. trianglesNormalInputNode->SetAttribute("offset", "1");
  991. trianglesNormalInputNode->SetAttribute("source", avar("#%s-Normal", meshName.c_str()));
  992. TiXmlElement* trianglesUV0InputNode = new TiXmlElement("input");
  993. trianglesNode->LinkEndChild(trianglesUV0InputNode);
  994. trianglesUV0InputNode->SetAttribute("semantic", "TEXCOORD");
  995. trianglesUV0InputNode->SetAttribute("offset", "2");
  996. trianglesUV0InputNode->SetAttribute("set", "0");
  997. trianglesUV0InputNode->SetAttribute("source", avar("#%s-UV0", meshName.c_str()));
  998. TiXmlElement* polyNode = new TiXmlElement("p");
  999. trianglesNode->LinkEndChild(polyNode);
  1000. Vector<U32> tempIndices;
  1001. tempIndices.reserve(4);
  1002. for (U32 j = 0; j < mesh.mPolyList.size(); j++)
  1003. {
  1004. const OptimizedPolyList::Poly& poly = mesh.mPolyList[j];
  1005. if (poly.vertexCount < 3)
  1006. continue;
  1007. if (poly.material != i)
  1008. continue;
  1009. tempIndices.setSize(poly.vertexCount);
  1010. dMemset(tempIndices.address(), 0, poly.vertexCount);
  1011. if (poly.type == OptimizedPolyList::TriangleStrip)
  1012. {
  1013. tempIndices[0] = 0;
  1014. U32 idx = 1;
  1015. for (U32 k = 1; k < poly.vertexCount; k += 2)
  1016. tempIndices[idx++] = k;
  1017. for (U32 k = ((poly.vertexCount - 1) & (~0x1)); k > 0; k -= 2)
  1018. tempIndices[idx++] = k;
  1019. }
  1020. else if (poly.type == OptimizedPolyList::TriangleList ||
  1021. poly.type == OptimizedPolyList::TriangleFan)
  1022. {
  1023. for (U32 k = 0; k < poly.vertexCount; k++)
  1024. tempIndices[k] = k;
  1025. }
  1026. else
  1027. AssertISV(false, "ColladaUtils::exportColladaTriangles(): Unknown Poly type!");
  1028. const U32& firstIdx = mesh.mIndexList[poly.vertexStart];
  1029. const OptimizedPolyList::VertIndex& firstVertIdx = mesh.mVertexList[firstIdx];
  1030. for (U32 k = 1; k < poly.vertexCount - 1; k++)
  1031. {
  1032. const U32& secondIdx = mesh.mIndexList[poly.vertexStart + tempIndices[k]];
  1033. const U32& thirdIdx = mesh.mIndexList[poly.vertexStart + tempIndices[k + 1]];
  1034. const OptimizedPolyList::VertIndex& secondVertIdx = mesh.mVertexList[secondIdx];
  1035. const OptimizedPolyList::VertIndex& thirdVertIdx = mesh.mVertexList[thirdIdx];
  1036. // Note the reversed winding on the triangles
  1037. const char* tri = avar("%d %d %d %d %d %d %d %d %d",
  1038. thirdVertIdx.vertIdx, thirdVertIdx.normalIdx, thirdVertIdx.uv0Idx,
  1039. secondVertIdx.vertIdx, secondVertIdx.normalIdx, secondVertIdx.uv0Idx,
  1040. firstVertIdx.vertIdx, firstVertIdx.normalIdx, firstVertIdx.uv0Idx);
  1041. TiXmlText* triangleText = new TiXmlText(tri);
  1042. polyNode->LinkEndChild(triangleText);
  1043. }
  1044. }
  1045. }
  1046. }
  1047. void ColladaUtils::exportColladaMesh(TiXmlElement* rootNode, const OptimizedPolyList& mesh, const String& meshName, const Vector<String>& matNames)
  1048. {
  1049. TiXmlElement* libGeomsNode = new TiXmlElement("library_geometries");
  1050. rootNode->LinkEndChild(libGeomsNode);
  1051. TiXmlElement* geometryNode = new TiXmlElement("geometry");
  1052. libGeomsNode->LinkEndChild(geometryNode);
  1053. geometryNode->SetAttribute("id", avar("%s-lib", meshName.c_str()));
  1054. geometryNode->SetAttribute("name", avar("%sMesh", meshName.c_str()));
  1055. TiXmlElement* meshNode = new TiXmlElement("mesh");
  1056. geometryNode->LinkEndChild(meshNode);
  1057. // Save out the vertices
  1058. TiXmlElement* vertsSourceNode = new TiXmlElement("source");
  1059. meshNode->LinkEndChild(vertsSourceNode);
  1060. vertsSourceNode->SetAttribute("id", avar("%s-Position", meshName.c_str()));
  1061. TiXmlElement* vertsNode = new TiXmlElement("float_array");
  1062. vertsSourceNode->LinkEndChild(vertsNode);
  1063. vertsNode->SetAttribute("id", avar("%s-Position-array", meshName.c_str()));
  1064. vertsNode->SetAttribute("count", avar("%d", mesh.mPoints.size() * 3));
  1065. for (U32 i = 0; i < mesh.mPoints.size(); i++)
  1066. {
  1067. const Point3F& vert = mesh.mPoints[i];
  1068. TiXmlText* vertText = new TiXmlText(avar("%.4f %.4f %.4f", vert.x, vert.y, vert.z));
  1069. vertsNode->LinkEndChild(vertText);
  1070. }
  1071. // Save the vertex accessor
  1072. TiXmlElement* vertsTechNode = new TiXmlElement("technique_common");
  1073. vertsSourceNode->LinkEndChild(vertsTechNode);
  1074. TiXmlElement* vertsAccNode = new TiXmlElement("accessor");
  1075. vertsTechNode->LinkEndChild(vertsAccNode);
  1076. vertsAccNode->SetAttribute("source", avar("#%s-Position-array", meshName.c_str()));
  1077. vertsAccNode->SetAttribute("count", avar("%d", mesh.mPoints.size()));
  1078. vertsAccNode->SetAttribute("stride", "3");
  1079. TiXmlElement* vertsAccXNode = new TiXmlElement("param");
  1080. vertsAccNode->LinkEndChild(vertsAccXNode);
  1081. vertsAccXNode->SetAttribute("name", "X");
  1082. vertsAccXNode->SetAttribute("type", "float");
  1083. TiXmlElement* vertsAccYNode = new TiXmlElement("param");
  1084. vertsAccNode->LinkEndChild(vertsAccYNode);
  1085. vertsAccYNode->SetAttribute("name", "Y");
  1086. vertsAccYNode->SetAttribute("type", "float");
  1087. TiXmlElement* vertsAccZNode = new TiXmlElement("param");
  1088. vertsAccNode->LinkEndChild(vertsAccZNode);
  1089. vertsAccZNode->SetAttribute("name", "Z");
  1090. vertsAccZNode->SetAttribute("type", "float");
  1091. // Save out the normals
  1092. TiXmlElement* normalsSourceNode = new TiXmlElement("source");
  1093. meshNode->LinkEndChild(normalsSourceNode);
  1094. normalsSourceNode->SetAttribute("id", avar("%s-Normal", meshName.c_str()));
  1095. TiXmlElement* normalsNode = new TiXmlElement("float_array");
  1096. normalsSourceNode->LinkEndChild(normalsNode);
  1097. normalsNode->SetAttribute("id", avar("%s-Normal-array", meshName.c_str()));
  1098. normalsNode->SetAttribute("count", avar("%d", mesh.mNormals.size() * 3));
  1099. for (U32 i = 0; i < mesh.mNormals.size(); i++)
  1100. {
  1101. const Point3F& normal = mesh.mNormals[i];
  1102. TiXmlText* normalText = new TiXmlText(avar("%.4f %.4f %.4f", normal.x, normal.y, normal.z));
  1103. normalsNode->LinkEndChild(normalText);
  1104. }
  1105. // Save the normals accessor
  1106. TiXmlElement* normalsTechNode = new TiXmlElement("technique_common");
  1107. normalsSourceNode->LinkEndChild(normalsTechNode);
  1108. TiXmlElement* normalsAccNode = new TiXmlElement("accessor");
  1109. normalsTechNode->LinkEndChild(normalsAccNode);
  1110. normalsAccNode->SetAttribute("source", avar("#%s-Normal-array", meshName.c_str()));
  1111. normalsAccNode->SetAttribute("count", avar("%d", mesh.mNormals.size()));
  1112. normalsAccNode->SetAttribute("stride", "3");
  1113. TiXmlElement* normalsAccXNode = new TiXmlElement("param");
  1114. normalsAccNode->LinkEndChild(normalsAccXNode);
  1115. normalsAccXNode->SetAttribute("name", "X");
  1116. normalsAccXNode->SetAttribute("type", "float");
  1117. TiXmlElement* normalsAccYNode = new TiXmlElement("param");
  1118. normalsAccNode->LinkEndChild(normalsAccYNode);
  1119. normalsAccYNode->SetAttribute("name", "Y");
  1120. normalsAccYNode->SetAttribute("type", "float");
  1121. TiXmlElement* normalsAccZNode = new TiXmlElement("param");
  1122. normalsAccNode->LinkEndChild(normalsAccZNode);
  1123. normalsAccZNode->SetAttribute("name", "Z");
  1124. normalsAccZNode->SetAttribute("type", "float");
  1125. // Save out the uvs
  1126. TiXmlElement* uv0SourceNode = new TiXmlElement("source");
  1127. meshNode->LinkEndChild(uv0SourceNode);
  1128. uv0SourceNode->SetAttribute("id", avar("%s-UV0", meshName.c_str()));
  1129. TiXmlElement* uv0Node = new TiXmlElement("float_array");
  1130. uv0SourceNode->LinkEndChild(uv0Node);
  1131. uv0Node->SetAttribute("id", avar("%s-UV0-array", meshName.c_str()));
  1132. uv0Node->SetAttribute("count", avar("%d", mesh.mUV0s.size() * 2));
  1133. for (U32 i = 0; i < mesh.mUV0s.size(); i++)
  1134. {
  1135. const Point2F& uv0 = mesh.mUV0s[i];
  1136. TiXmlText* uv0Text = new TiXmlText(avar("%.4f %.4f", uv0.x, 1.0f - uv0.y)); // COLLADA uvs are upside down compared to Torque
  1137. uv0Node->LinkEndChild(uv0Text);
  1138. }
  1139. // Save the uv0 accessor
  1140. TiXmlElement* uv0TechNode = new TiXmlElement("technique_common");
  1141. uv0SourceNode->LinkEndChild(uv0TechNode);
  1142. TiXmlElement* uv0AccNode = new TiXmlElement("accessor");
  1143. uv0TechNode->LinkEndChild(uv0AccNode);
  1144. uv0AccNode->SetAttribute("source", avar("#%s-UV0-array", meshName.c_str()));
  1145. uv0AccNode->SetAttribute("count", avar("%d", mesh.mUV0s.size()));
  1146. uv0AccNode->SetAttribute("stride", "2");
  1147. TiXmlElement* uv0AccSNode = new TiXmlElement("param");
  1148. uv0AccNode->LinkEndChild(uv0AccSNode);
  1149. uv0AccSNode->SetAttribute("name", "S");
  1150. uv0AccSNode->SetAttribute("type", "float");
  1151. TiXmlElement* uv0AccTNode = new TiXmlElement("param");
  1152. uv0AccNode->LinkEndChild(uv0AccTNode);
  1153. uv0AccTNode->SetAttribute("name", "T");
  1154. uv0AccTNode->SetAttribute("type", "float");
  1155. // Define the vertices position array
  1156. TiXmlElement* verticesNode = new TiXmlElement("vertices");
  1157. meshNode->LinkEndChild(verticesNode);
  1158. verticesNode->SetAttribute("id", avar("%s-Vertex", meshName.c_str()));
  1159. TiXmlElement* verticesInputNode = new TiXmlElement("input");
  1160. verticesNode->LinkEndChild(verticesInputNode);
  1161. verticesInputNode->SetAttribute("semantic", "POSITION");
  1162. verticesInputNode->SetAttribute("source", avar("#%s-Position", meshName.c_str()));
  1163. exportColladaTriangles(meshNode, mesh, meshName, matNames);
  1164. }
  1165. void ColladaUtils::exportColladaScene(TiXmlElement* rootNode, const String& meshName, const Vector<String>& matNames)
  1166. {
  1167. TiXmlElement* libSceneNode = new TiXmlElement("library_visual_scenes");
  1168. rootNode->LinkEndChild(libSceneNode);
  1169. TiXmlElement* visSceneNode = new TiXmlElement("visual_scene");
  1170. libSceneNode->LinkEndChild(visSceneNode);
  1171. visSceneNode->SetAttribute("id", "RootNode");
  1172. visSceneNode->SetAttribute("name", "RootNode");
  1173. TiXmlElement* nodeNode = new TiXmlElement("node");
  1174. visSceneNode->LinkEndChild(nodeNode);
  1175. nodeNode->SetAttribute("id", avar("%s", meshName.c_str()));
  1176. nodeNode->SetAttribute("name", avar("%s", meshName.c_str()));
  1177. TiXmlElement* instanceGeomNode = new TiXmlElement("instance_geometry");
  1178. nodeNode->LinkEndChild(instanceGeomNode);
  1179. instanceGeomNode->SetAttribute("url", avar("#%s-lib", meshName.c_str()));
  1180. TiXmlElement* bindMatNode = new TiXmlElement("bind_material");
  1181. instanceGeomNode->LinkEndChild(bindMatNode);
  1182. TiXmlElement* techniqueNode = new TiXmlElement("technique_common");
  1183. bindMatNode->LinkEndChild(techniqueNode);
  1184. // Bind the materials
  1185. for (U32 i = 0; i < matNames.size(); i++)
  1186. {
  1187. TiXmlElement* instMatNode = new TiXmlElement("instance_material");
  1188. techniqueNode->LinkEndChild(instMatNode);
  1189. instMatNode->SetAttribute("symbol", avar("%s", matNames[i].c_str()));
  1190. instMatNode->SetAttribute("target", avar("#%s", matNames[i].c_str()));
  1191. }
  1192. TiXmlElement* sceneNode = new TiXmlElement("scene");
  1193. rootNode->LinkEndChild(sceneNode);
  1194. TiXmlElement* instVisSceneNode = new TiXmlElement("instance_visual_scene");
  1195. sceneNode->LinkEndChild(instVisSceneNode);
  1196. instVisSceneNode->SetAttribute("url", "#RootNode");
  1197. }
  1198. void ColladaUtils::exportToCollada(const Torque::Path& colladaFile, const OptimizedPolyList& mesh, const String& meshName)
  1199. {
  1200. // Get the mesh name
  1201. String outMeshName = meshName;
  1202. if (outMeshName.isEmpty())
  1203. outMeshName = colladaFile.getFileName();
  1204. // The XML document that will hold all of our data
  1205. TiXmlDocument doc;
  1206. // Add a standard XML declaration to the top
  1207. TiXmlDeclaration* xmlDecl = new TiXmlDeclaration("1.0", "utf-8", "");
  1208. doc.LinkEndChild(xmlDecl);
  1209. // Create our Collada root node and populate a couple standard attributes
  1210. TiXmlElement* rootNode = new TiXmlElement("COLLADA");
  1211. rootNode->SetAttribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema");
  1212. rootNode->SetAttribute("version", "1.4.0");
  1213. // Add the root node to the document
  1214. doc.LinkEndChild(rootNode);
  1215. // Save out our header info
  1216. exportColladaHeader(rootNode);
  1217. // Save out the materials
  1218. Vector<String> mapNames;
  1219. exportColladaMaterials(rootNode, mesh, mapNames, colladaFile);
  1220. // Save out our geometry
  1221. exportColladaMesh(rootNode, mesh, outMeshName, mapNames);
  1222. // Save out our scene nodes
  1223. exportColladaScene(rootNode, outMeshName, mapNames);
  1224. // Write out the actual Collada file
  1225. char fullPath[MAX_PATH_LENGTH];
  1226. Platform::makeFullPathName(colladaFile.getFullPath(), fullPath, MAX_PATH_LENGTH);
  1227. if (!doc.SaveFile(fullPath))
  1228. Con::errorf("ColladaUtils::exportToCollada(): Unable to export to %s", fullPath);
  1229. }