DAESceneEncoder.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. /*
  2. * DAESceneEncoder.h
  3. */
  4. #include <algorithm>
  5. #include "DAESceneEncoder.h"
  6. #include "DAEOptimizer.h"
  7. //#define ENCODER_PRINT_TIME 1
  8. using namespace gameplay;
  9. DAESceneEncoder::DAESceneEncoder()
  10. : _collada(NULL), _dom(NULL), file(NULL), _vertexBlendWeights(NULL), _vertexBlendIndices(NULL)
  11. {
  12. }
  13. DAESceneEncoder::~DAESceneEncoder()
  14. {
  15. }
  16. std::string getFilenameFromFilePath(const std::string& filepath)
  17. {
  18. if (filepath.find_last_of("/") != std::string::npos)
  19. {
  20. return filepath.substr(filepath.find_last_of("/")+1);
  21. }
  22. return "";
  23. }
  24. std::string getFilenameNoExt(const std::string& filename)
  25. {
  26. if (filename.find_last_of(".") != std::string::npos)
  27. {
  28. return filename.substr(0, filename.find_last_of("."));
  29. }
  30. return filename;
  31. }
  32. unsigned int getMaxOffset(domInputLocalOffset_Array& inputArray)
  33. {
  34. unsigned int maxOffset = 0;
  35. for (unsigned int i = 0; i < (int)inputArray.getCount(); i++ )
  36. {
  37. if ( inputArray[i]->getOffset() > maxOffset )
  38. {
  39. maxOffset = (unsigned int)inputArray[i]->getOffset();
  40. }
  41. }
  42. return maxOffset;
  43. }
  44. void DAESceneEncoder::optimizeCOLLADA(const EncoderArguments& arguments, domCOLLADA* dom)
  45. {
  46. DAEOptimizer optimizer(dom);
  47. const std::vector<std::string>& groupAnimatioNodeIds = arguments.getGroupAnimationNodeId();
  48. const std::vector<std::string>& groupAnimatioIds = arguments.getGroupAnimationAnimationId();
  49. assert(groupAnimatioNodeIds.size() == groupAnimatioIds.size());
  50. size_t size = groupAnimatioNodeIds.size();
  51. if (size > 0)
  52. {
  53. begin();
  54. for (size_t i = 0; i < size; i++)
  55. {
  56. optimizer.combineAnimations(groupAnimatioNodeIds[i], groupAnimatioIds[i]);
  57. }
  58. end("groupAnimation");
  59. }
  60. if (arguments.DAEOutputEnabled())
  61. {
  62. if (!_collada->writeTo(arguments.getFilePath(), arguments.getDAEOutputPath()))
  63. {
  64. fprintf(stderr,"Error: COLLADA failed to write the dom for file:%s\n", arguments.getDAEOutputPath().c_str());
  65. }
  66. }
  67. }
  68. void DAESceneEncoder::triangulate(DAE* dae)
  69. {
  70. daeDatabase* dataBase = dae->getDatabase();
  71. int geometryCount = (int)(dataBase->getElementCount(0, "geometry"));
  72. for (int i = 0; i < geometryCount; i++)
  73. {
  74. // Find the next geometry element.
  75. domGeometry* domGeometry;
  76. dataBase->getElement((daeElement**)&domGeometry, i, 0, "geometry");
  77. // Get the mesh out of the geometry.
  78. const domMeshRef domMesh = domGeometry->getMesh();
  79. if (!domMesh)
  80. {
  81. continue;
  82. }
  83. // Loop over all the polygons elements.
  84. int polygonsCount = (int)(domMesh->getPolygons_array().getCount());
  85. for (int j = 0; j < polygonsCount; j++)
  86. {
  87. // Get the polygons out of the mesh.
  88. domPolygons* domPolygons = domMesh->getPolygons_array()[j];
  89. // Create the triangles from the polygons
  90. createTrianglesFromPolygons(domMesh, domPolygons);
  91. }
  92. while(domMesh->getPolygons_array().getCount() > 0)
  93. {
  94. domPolygons* domPolygons = domMesh->getPolygons_array().get(0);
  95. // Remove the polygons from the mesh.
  96. domMesh->removeChildElement(domPolygons);
  97. }
  98. // Loop over all the polylist elements.
  99. int polylistCount = (int)(domMesh->getPolylist_array().getCount());
  100. for (int j = 0; j < polylistCount; j++)
  101. {
  102. // Get the polylist out of the mesh.
  103. domPolylist* domPolylist = domMesh->getPolylist_array()[j];
  104. // Create the triangles from the polygon list
  105. createTrianglesFromPolylist(domMesh, domPolylist);
  106. }
  107. while(domMesh->getPolylist_array().getCount() > 0)
  108. {
  109. domPolylist* domPolylist = domMesh->getPolylist_array().get(0);
  110. // Remove the polylist from the mesh.
  111. domMesh->removeChildElement(domPolylist);
  112. }
  113. }
  114. }
  115. void DAESceneEncoder::createTrianglesFromPolygons(domMesh* domMesh, domPolygons* domPolygons)
  116. {
  117. // Create a new <triangles> inside the mesh that has the same material as the <polygons>.
  118. domTriangles* triangles = (domTriangles*)domMesh->createAndPlace("triangles");
  119. triangles->setCount(0);
  120. triangles->setMaterial(domPolygons->getMaterial());
  121. domP* domTrianglesP = (domP*)triangles->createAndPlace("p");
  122. // Give the new <triangles> the same <_dae> and <parameters> as the old <polygons>.
  123. for (unsigned int i = 0; i < domPolygons->getInput_array().getCount(); i++)
  124. {
  125. triangles->placeElement(domPolygons->getInput_array()[i]->clone());
  126. }
  127. // Get the number of inputs and primitives for the polygons array.
  128. unsigned int inputCount = getMaxOffset(domPolygons->getInput_array()) + 1;
  129. unsigned int primitiveCount = domPolygons->getP_array().getCount();
  130. // Triangulate all the primitives, this generates all the triangles in a single <p> element.
  131. for (unsigned int j = 0; j < primitiveCount; j++)
  132. {
  133. // Check the polygons for consistancy (some exported files have had the wrong number of indices).
  134. domP* domCurrentP = domPolygons->getP_array()[j];
  135. int elementCount = (int)(domCurrentP->getValue().getCount());
  136. if ( (elementCount % inputCount) != 0 )
  137. {
  138. // Skip this case.
  139. }
  140. else
  141. {
  142. unsigned int triangleCount = (elementCount / inputCount) - 2;
  143. // Write out the primitives as triangles, just fan using the first element as the base.
  144. unsigned int index = inputCount;
  145. for (unsigned int k = 0; k < triangleCount; k++)
  146. {
  147. // First vertex.
  148. for (unsigned int l = 0; l < inputCount; l++)
  149. {
  150. domTrianglesP->getValue().append(domCurrentP->getValue()[l]);
  151. }
  152. // Second vertex.
  153. for (unsigned int l = 0; l < inputCount; l++)
  154. {
  155. domTrianglesP->getValue().append(domCurrentP->getValue()[index + l]);
  156. }
  157. // Third vertex.
  158. index += inputCount;
  159. for (unsigned int l = 0; l < inputCount; l++)
  160. {
  161. domTrianglesP->getValue().append(domCurrentP->getValue()[index + l]);
  162. }
  163. triangles->setCount(triangles->getCount() + 1);
  164. }
  165. }
  166. }
  167. }
  168. void DAESceneEncoder::createTrianglesFromPolylist(domMesh* domMesh, domPolylist* domPolylist)
  169. {
  170. // Create a new <triangles> inside the mesh that has the same material as the <polylist>.
  171. domTriangles* triangles = (domTriangles*)domMesh->createAndPlace("triangles");
  172. triangles->setMaterial(domPolylist->getMaterial());
  173. domP* domTrianglesP = (domP*)triangles->createAndPlace("p");
  174. // Give the new <triangles> the same <_dae> and <parameters> as the old <polylist>.
  175. for (int i = 0; i < (int)(domPolylist->getInput_array().getCount()); i++)
  176. {
  177. triangles->placeElement(domPolylist->getInput_array()[i]->clone());
  178. }
  179. // Get the number of inputs and primitives for the polygons array.
  180. unsigned int inputCount = getMaxOffset(domPolylist->getInput_array()) + 1;
  181. unsigned int primitiveCount = domPolylist->getVcount()->getValue().getCount();
  182. unsigned int offset = 0;
  183. unsigned int trianglesProcessed = 0;
  184. // Triangulate all the primitives, this generates all the triangles in a single <p> element.
  185. for (unsigned int j = 0; j < primitiveCount; j++)
  186. {
  187. unsigned int triangleCount = (unsigned int)domPolylist->getVcount()->getValue()[j] - 2;
  188. // Write out the primitives as triangles, just fan using the first element as the base.
  189. int index = inputCount;
  190. for (unsigned int k = 0; k < triangleCount; k++)
  191. {
  192. // First vertex.
  193. for (unsigned int l = 0; l < inputCount; l++)
  194. {
  195. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + l]);
  196. }
  197. // Second vertex.
  198. for (unsigned int l = 0; l < inputCount; l++)
  199. {
  200. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + index + l]);
  201. }
  202. // Third vertex.
  203. index += inputCount;
  204. for (unsigned int l = 0; l < inputCount; l++)
  205. {
  206. domTrianglesP->getValue().append(domPolylist->getP()->getValue()[offset + index + l]);
  207. }
  208. trianglesProcessed++;
  209. }
  210. offset += (unsigned int)domPolylist->getVcount()->getValue()[j] * inputCount;
  211. }
  212. triangles->setCount(trianglesProcessed);
  213. }
  214. void DAESceneEncoder::write(const std::string& filepath, const EncoderArguments& arguments)
  215. {
  216. _begin = std::clock();
  217. const char* nodeId = arguments.getNodeId();
  218. bool text = arguments.textOutputEnabled();
  219. std::string filenameOnly = getFilenameFromFilePath(filepath);
  220. std::string dstPath = filepath.substr(0, filepath.find_last_of('/'));
  221. // Load the collada document
  222. _collada = new DAE();
  223. begin();
  224. _dom = _collada->open(filepath);
  225. end("Open file");
  226. if (!_dom)
  227. {
  228. fprintf(stderr,"Error: COLLADA failed to open file:%s\n", filepath.c_str());
  229. if (_collada)
  230. {
  231. delete _collada;
  232. _collada = NULL;
  233. }
  234. return;
  235. }
  236. // Run collada conditioners
  237. begin();
  238. triangulate(_collada);
  239. end("triangulate");
  240. // Optimize the dom before encoding
  241. optimizeCOLLADA(arguments, _dom);
  242. // Find the <visual_scene> element within the <scene>
  243. const domCOLLADA::domSceneRef& domScene = _dom->getScene();
  244. daeElement* scene = NULL;
  245. if (domScene && domScene->getInstance_visual_scene())
  246. {
  247. scene = domScene->getInstance_visual_scene()->getUrl().getElement();
  248. if (scene->getElementType() != COLLADA_TYPE::VISUAL_SCENE)
  249. {
  250. // This occured once where Maya exported a Node and Scene element with the same ID.
  251. fprintf(stderr,"Error: instance_visual_scene does not reference visual_scene for file:%s\n", filepath.c_str());
  252. return;
  253. }
  254. if (scene)
  255. {
  256. if (nodeId == NULL)
  257. {
  258. // If the -n <node_id> parameter was not passed then write out the entire scene.
  259. begin();
  260. loadScene((domVisual_scene*)scene);
  261. end("load scene");
  262. }
  263. else
  264. {
  265. // Resolve/Search for the node the user specified with the -n <node_id> parameter.
  266. daeSIDResolver resolver(scene, nodeId);
  267. const domNode* node = daeSafeCast<domNode>(resolver.getElement());
  268. if (node)
  269. {
  270. //createNode(node, NULL);
  271. }
  272. else
  273. {
  274. fprintf(stderr,"COLLADA File loaded to the dom, but node was not found with -n%s.\n", nodeId);
  275. }
  276. }
  277. }
  278. else
  279. {
  280. fprintf(stderr,"COLLADA File loaded to the dom, but query for the dom assets failed.\n");
  281. }
  282. }
  283. else
  284. {
  285. fprintf(stderr, "COLLADA File loaded to the dom, but missing <visual_scene>.\n");
  286. }
  287. // The animations should be loaded last
  288. begin();
  289. loadAnimations(_dom);
  290. end("loadAnimations");
  291. std::string dstFilename = dstPath;
  292. dstFilename.append(1, '/');
  293. dstFilename.append(getFilenameNoExt(filenameOnly));
  294. _gamePlayFile.adjust();
  295. if (text)
  296. {
  297. std::string outFile = dstFilename + ".xml";
  298. fprintf(stderr, "Saving debug file: %s\n", outFile.c_str());
  299. _gamePlayFile.saveText(outFile);
  300. }
  301. else
  302. {
  303. std::string outFile = dstFilename + ".gpb";
  304. fprintf(stderr, "Saving binary file: %s\n", outFile.c_str());
  305. begin();
  306. _gamePlayFile.saveBinary(outFile);
  307. end("save binary");
  308. }
  309. // Cleanup
  310. if (file)
  311. {
  312. fclose(file);
  313. }
  314. if (_collada)
  315. {
  316. delete _collada;
  317. _collada = NULL;
  318. }
  319. }
  320. void DAESceneEncoder::loadAnimations(const domCOLLADA* dom)
  321. {
  322. // Call loadAnimation on all <animation> elements in all <library_animations>
  323. const domLibrary_animations_Array& animationLibrarys = dom->getLibrary_animations_array();
  324. size_t animationLibrarysCount = animationLibrarys.getCount();
  325. for (size_t i = 0; i < animationLibrarysCount; i++)
  326. {
  327. const domLibrary_animationsRef& libraryAnimation = animationLibrarys.get(i);
  328. const domAnimation_Array& animationArray = libraryAnimation->getAnimation_array();
  329. size_t animationCount = animationArray.getCount();
  330. for (size_t j = 0; j < animationCount; j++)
  331. {
  332. const domAnimationRef& animationRef = animationArray.get(j);
  333. loadAnimation(animationRef);
  334. }
  335. }
  336. }
  337. void DAESceneEncoder::loadAnimation(const domAnimationRef animationRef)
  338. {
  339. // <channel> points to one <sampler>
  340. // <sampler> points to multiple <input> elements
  341. Animation* animation = new Animation();
  342. const char* str = animationRef->getId();
  343. if (str)
  344. {
  345. animation->setId(str);
  346. }
  347. // <channel>
  348. const domChannel_Array& channelArray = animationRef->getChannel_array();
  349. size_t channelArrayCount = channelArray.getCount();
  350. for (size_t i = 0; i < channelArrayCount; i++)
  351. {
  352. AnimationChannel* animationChannel = new AnimationChannel();
  353. const domChannelRef& channelRef = channelArray.get(i);
  354. // <sampler>
  355. const domSamplerRef sampler = getSampler(channelRef);
  356. assert(sampler);
  357. // <input>
  358. const domInputLocal_Array& inputArray = sampler->getInput_array();
  359. size_t inputArrayCount = inputArray.getCount();
  360. for (size_t j = 0; j < inputArrayCount; j++)
  361. {
  362. const domInputLocalRef& inputLocal = inputArray.get(j);
  363. // <source>
  364. const domSourceRef source = getSource(inputLocal, animationRef);
  365. std::string semantic = inputLocal->getSemantic();
  366. if (equals(semantic, "INTERPOLATION"))
  367. {
  368. // Interpolation source is a list of strings
  369. loadInterpolation(source, animationChannel);
  370. }
  371. else
  372. {
  373. // The other sources are lists of floats.
  374. std::vector<float> floats;
  375. copyFloats(source->getFloat_array(), &floats);
  376. if (equals(semantic, "INPUT"))
  377. {
  378. // TODO: Ensure param name is TIME?
  379. for (std::vector<float>::iterator k = floats.begin(); k != floats.end(); k++)
  380. {
  381. // Convert seconds to milliseconds
  382. *k = *k * 1000.0f;
  383. }
  384. animationChannel->setKeyTimes(floats);
  385. }
  386. else if (equals(semantic, "OUTPUT"))
  387. {
  388. animationChannel->setKeyValues(floats);
  389. }
  390. else if (equals(semantic, "IN_TANGENT"))
  391. {
  392. animationChannel->setTangentsIn(floats);
  393. }
  394. else if (equals(semantic, "OUT_TANGENT"))
  395. {
  396. animationChannel->setTangentsOut(floats);
  397. }
  398. }
  399. }
  400. // get target attribute enum value
  401. if (loadTarget(channelRef, animationChannel))
  402. {
  403. animation->add(animationChannel);
  404. }
  405. }
  406. if (animation->getAnimationChannelCount() > 0)
  407. {
  408. _gamePlayFile.addAnimation(animation);
  409. }
  410. else
  411. {
  412. delete animation;
  413. }
  414. }
  415. void DAESceneEncoder::loadInterpolation(const domSourceRef source, AnimationChannel* animationChannel)
  416. {
  417. // COLLADA stores the interpolations as a list of strings while GBP uses unsigned int
  418. std::vector<unsigned int> values;
  419. const domName_arrayRef nameArray = getSourceNameArray(source);
  420. assert(nameArray);
  421. const domListOfNames& names = nameArray->getValue();
  422. size_t count = (size_t)names.getCount();
  423. values.resize(count);
  424. if (count > 0)
  425. {
  426. for (size_t i = 0; i < count; i++)
  427. {
  428. values[i] = AnimationChannel::getInterpolationType(names.get(i));
  429. }
  430. // If all of the interpolation types are the same then only store the interpolation once
  431. // instead of storing the same type for each key frame.
  432. unsigned int firstType = values[0];
  433. bool allEqual = true;
  434. for (size_t i = 1; i < count; i++)
  435. {
  436. if (firstType != values[i])
  437. {
  438. allEqual = false;
  439. break;
  440. }
  441. }
  442. if (allEqual)
  443. {
  444. values.resize(1);
  445. }
  446. }
  447. animationChannel->setInterpolations(values);
  448. }
  449. bool DAESceneEncoder::loadTarget(const domChannelRef& channelRef, AnimationChannel* animationChannel)
  450. {
  451. // GamePlay requires that animations are baked. Use "Bake Transforms" in your 3D modeling tool.
  452. // If the target of an animation is not a matrix then an error will be printed.
  453. const static char* TRANSFORM_WARNING_FORMAT = "Warning: Node \"%s\":\n %s %s\n";
  454. const static char* TRANSFORM_MESSAGE = "transform found but not supported.\n Use \"Bake Transforms\" option when exporting.";
  455. unsigned int targetProperty = 0;
  456. DAEChannelTarget channelTarget(channelRef);
  457. const char* targetId = channelTarget.getTargetId().c_str();
  458. // TODO: Do we want to support more than one? If yes then this needs to be fixed.
  459. for (size_t i = 0; i < channelTarget.getTargetAttributeCount(); i++)
  460. {
  461. std::string prop;
  462. channelTarget.getPropertyName(i, &prop);
  463. daeElement* attributeElement = channelTarget.getTargetAttribute(i);
  464. if (attributeElement)
  465. {
  466. daeInt type = attributeElement->typeID();
  467. if (type == domRotate::ID())
  468. {
  469. printf(TRANSFORM_WARNING_FORMAT, targetId, "Rotate", TRANSFORM_MESSAGE);
  470. return false;
  471. /*
  472. // <rotate>
  473. const domRotate* rotate = daeSafeCast<domRotate>(attributeElement);
  474. if (prop.size() > 0)
  475. {
  476. if (equalsIgnoreCase(prop, "ANGLE"))
  477. {
  478. targetProperty = Transform::ANIMATE_ROTATE;
  479. // get the rotation axis
  480. const domFloat4& f = rotate->getValue();
  481. float x = (float)f.get(0);
  482. float y = (float)f.get(1);
  483. float z = (float)f.get(2);
  484. // Get the angle values that were already read
  485. const std::vector<float>& keyValues = animationChannel->getKeyValues();
  486. size_t size = keyValues.size();
  487. assert(size > 0);
  488. // COLLADA only targeted a single prop but GBP requires all 4 rotate values.
  489. // Convert (ANGLE ANGLE ANGLE) to (X Y Z ANGLE X Y Z ANGLE X Y Z ANGLE)
  490. std::vector<float> floats(size * 4);
  491. // Duplicate rotation axis. We will replace only the angle that COLLADA is targeting.
  492. for (size_t j = 0; j < size; j++)
  493. {
  494. size_t k = j * 4;
  495. floats[k+0] = x;
  496. floats[k+1] = y;
  497. floats[k+2] = z;
  498. floats[k+3] = keyValues[j]; // angle
  499. }
  500. animationChannel->setKeyValues(floats);
  501. }
  502. }
  503. */
  504. }
  505. else if (type == domScale::ID())
  506. {
  507. printf(TRANSFORM_WARNING_FORMAT, targetId, "Scale", TRANSFORM_MESSAGE);
  508. return false;
  509. /*
  510. // <scale>
  511. //const domScale* scale = daeSafeCast<domScale>(attributeElement);
  512. if (equalsIgnoreCase(prop, "X"))
  513. {
  514. targetProperty = Transform::ANIMATE_SCALE_X;
  515. }
  516. else if (equalsIgnoreCase(prop, "Y"))
  517. {
  518. targetProperty = Transform::ANIMATE_SCALE_Y;
  519. }
  520. else if (equalsIgnoreCase(prop, "Z"))
  521. {
  522. targetProperty = Transform::ANIMATE_SCALE_Z;
  523. }
  524. else
  525. {
  526. targetProperty = Transform::ANIMATE_SCALE;
  527. }
  528. */
  529. }
  530. else if (type == domTranslate::ID())
  531. {
  532. printf(TRANSFORM_WARNING_FORMAT, targetId, "Translate", TRANSFORM_MESSAGE);
  533. return false;
  534. /*
  535. // <translate>
  536. //const domTranslate* translate = daeSafeCast<domTranslate>(attributeElement);
  537. if (equalsIgnoreCase(prop, "X"))
  538. {
  539. targetProperty = Transform::ANIMATE_TRANSLATE_X;
  540. }
  541. else if (equalsIgnoreCase(prop, "Y"))
  542. {
  543. targetProperty = Transform::ANIMATE_TRANSLATE_Y;
  544. }
  545. else if (equalsIgnoreCase(prop, "Z"))
  546. {
  547. targetProperty = Transform::ANIMATE_TRANSLATE_Z;
  548. }
  549. else
  550. {
  551. targetProperty = Transform::ANIMATE_TRANSLATE;
  552. }
  553. */
  554. }
  555. else if (type == domMatrix::ID())
  556. {
  557. // If the animation is targetting a matrix then convert it into
  558. // a scale, rotate, translate animation by decomposing the matrix.
  559. targetProperty = Transform::ANIMATE_SCALE_ROTATE_TRANSLATE;
  560. const std::vector<float>& keyValues = animationChannel->getKeyValues();
  561. assert(keyValues.size() % 16 == 0);
  562. // The matrix was 16 floats and the new values will be 10 floats
  563. size_t newSize = keyValues.size() / 16 * 10;
  564. std::vector<float> floats(newSize);
  565. size_t matrixCount = keyValues.size() / 16;
  566. for (size_t i = 0; i < matrixCount; i++)
  567. {
  568. size_t j = i * 16;
  569. // COLLADA used row-major but the Matrix class uses column-major
  570. Matrix matrix(
  571. keyValues[j+0], keyValues[j+4], keyValues[j+8], keyValues[j+12],
  572. keyValues[j+1], keyValues[j+5], keyValues[j+9], keyValues[j+13],
  573. keyValues[j+2], keyValues[j+6], keyValues[j+10], keyValues[j+14],
  574. keyValues[j+3], keyValues[j+7], keyValues[j+11], keyValues[j+15]);
  575. Vector3 scale;
  576. Quaternion rotation;
  577. Vector3 translation;
  578. matrix.decompose(&scale, &rotation, &translation);
  579. size_t k = i * 10;
  580. floats[k+0] = scale.x;
  581. floats[k+1] = scale.y;
  582. floats[k+2] = scale.z;
  583. floats[k+3] = rotation.x;
  584. floats[k+4] = rotation.y;
  585. floats[k+5] = rotation.z;
  586. floats[k+6] = rotation.w;
  587. floats[k+7] = translation.x;
  588. floats[k+8] = translation.y;
  589. floats[k+9] = translation.z;
  590. }
  591. animationChannel->setKeyValues(floats);
  592. }
  593. }
  594. }
  595. animationChannel->setTargetAttribute(targetProperty);
  596. animationChannel->setTargetId(channelTarget.getTargetId());
  597. return true;
  598. }
  599. void DAESceneEncoder::begin()
  600. {
  601. #ifdef ENCODER_PRINT_TIME
  602. _begin = std::clock();
  603. #endif
  604. }
  605. void DAESceneEncoder::end(const char* str)
  606. {
  607. #ifdef ENCODER_PRINT_TIME
  608. clock_t time = std::clock() - _begin;
  609. fprintf(stderr,"%5d %s\n", time, str);
  610. #endif
  611. }
  612. void DAESceneEncoder::copyFloats(const domFloat_array* source, std::vector<float>* target)
  613. {
  614. std::vector<float>& t = *target;
  615. size_t count = (size_t)source->getCount();
  616. t.resize(count);
  617. const domListOfFloats& listOfFloats = source->getValue();
  618. for (size_t i = 0; i < count; i++)
  619. {
  620. t[i] = (float)listOfFloats.get(i);
  621. }
  622. }
  623. void DAESceneEncoder::loadScene(const domVisual_scene* visualScene)
  624. {
  625. Scene* scene = new Scene();
  626. const domNode_Array& nodes = visualScene->getNode_array();
  627. scene->setId(visualScene->getId());
  628. size_t childCount = nodes.getCount();
  629. for (size_t i = 0; i < childCount; i++)
  630. {
  631. scene->add(loadNode(nodes[i], NULL));
  632. }
  633. Node* activeCameraNode = findSceneActiveCameraNode(visualScene, scene);
  634. if (activeCameraNode)
  635. {
  636. scene->setActiveCameraNode(activeCameraNode);
  637. }
  638. _gamePlayFile.addScene(scene);
  639. }
  640. Node* DAESceneEncoder::findSceneActiveCameraNode(const domVisual_scene* visualScene, Scene* scene)
  641. {
  642. // Loops through each evaluate_scene's render until an active camera node is found.
  643. // Returns the first one found.
  644. // Find the active camera
  645. const domVisual_scene::domEvaluate_scene_Array& evaluateScenes = visualScene->getEvaluate_scene_array();
  646. size_t evaluateSceneCount = evaluateScenes.getCount();
  647. for (size_t i = 0; i < evaluateSceneCount; i++)
  648. {
  649. const domVisual_scene::domEvaluate_scene::domRender_Array& renders = evaluateScenes[i]->getRender_array();
  650. size_t renderCount = renders.getCount();
  651. for (size_t j = 0; j < renderCount; j++)
  652. {
  653. xsAnyURI cameraNodeURI = renders[i]->getCamera_node();
  654. domNode* nodeRef = daeSafeCast<domNode>(cameraNodeURI.getElement());
  655. if (nodeRef)
  656. {
  657. std::string id = nodeRef->getId();
  658. Node* node = _gamePlayFile.getNode(id.c_str());
  659. if (node)
  660. {
  661. return node;
  662. }
  663. }
  664. }
  665. }
  666. // Find the first node in the scene that contains a camera.
  667. return scene->getFirstCameraNode();
  668. }
  669. Node* DAESceneEncoder::loadNode(domNode* n, Node* parent)
  670. {
  671. Node* node = NULL;
  672. // Check if this node has already been loaded
  673. const char* id = n->getID();
  674. if (id && strlen(id) > 0)
  675. {
  676. node = _gamePlayFile.getNode(n->getID());
  677. if (node)
  678. {
  679. return node;
  680. }
  681. }
  682. // Load the node
  683. node = new Node();
  684. if (parent)
  685. {
  686. parent->addChild(node);
  687. }
  688. if (n->getType() == NODETYPE_JOINT)
  689. {
  690. node->setIsJoint(true);
  691. }
  692. // Set node id
  693. node->setId(n->getId());
  694. // If this node has an id then add it to the ref table
  695. _gamePlayFile.addNode(node);
  696. transformNode(n, node);
  697. loadControllerInstance(n, node);
  698. loadCameraInstance(n, node);
  699. loadLightInstance(n, node);
  700. loadGeometryInstance(n, node);
  701. // Load child nodes
  702. const domNode_Array& childNodes = n->getNode_array();
  703. size_t childCount = childNodes.getCount();
  704. for (size_t i = 0; i < childCount; i++)
  705. {
  706. loadNode(childNodes.get(i), node);
  707. }
  708. return node;
  709. }
  710. void DAESceneEncoder::transformNode(domNode* domNode, Node* node)
  711. {
  712. // Apply the transform.
  713. // Note that we only honor the first matrix transform specified for the DOM node.
  714. const domMatrix_Array& matrixArray = domNode->getMatrix_array();
  715. if (matrixArray.getCount() > 0)
  716. {
  717. const domMatrixRef& matrix = matrixArray.get(0);
  718. if (!matrix)
  719. {
  720. return;
  721. }
  722. const domFloat4x4& tx = matrix->getValue();
  723. float transform[] = {(float)tx.get(0), (float)tx.get(4), (float)tx.get(8), (float)tx.get(12),
  724. (float)tx.get(1), (float)tx.get(5), (float)tx.get(9), (float)tx.get(13),
  725. (float)tx.get(2), (float)tx.get(6), (float)tx.get(10), (float)tx.get(14),
  726. (float)tx.get(3), (float)tx.get(7), (float)tx.get(11), (float)tx.get(15)};
  727. node->setTransformMatrix(transform);
  728. }
  729. else
  730. {
  731. Matrix transform;
  732. calcTransform(domNode, transform);
  733. node->setTransformMatrix(transform.m);
  734. }
  735. // TODO: Handle transforming by other types (SRT, etc) (see "Node" child elements spec)
  736. /*Vector3 scale;
  737. Quaternion rotation;
  738. Vector3 translation;
  739. localTransform.Decompose(&scale, &rotation, &translation);
  740. node->SetScale(scale);
  741. node->SetRotation(rotation);
  742. node->SetTranslation(translation);*/
  743. }
  744. void DAESceneEncoder::calcTransform(domNode* domNode, Matrix& dstTransform)
  745. {
  746. daeTArray<daeSmartRef<daeElement>> children;
  747. domNode->getChildren(children);
  748. size_t childCount = children.getCount();
  749. for (size_t i = 0; i < childCount; i++)
  750. {
  751. daeElementRef childElement = children[i];
  752. switch (childElement->getElementType())
  753. {
  754. case COLLADA_TYPE::TRANSLATE:
  755. {
  756. domTranslateRef translateNode = daeSafeCast<domTranslate>(childElement);
  757. float x = (float)translateNode->getValue().get(0);
  758. float y = (float)translateNode->getValue().get(1);
  759. float z = (float)translateNode->getValue().get(2);
  760. dstTransform.translate(x, y, z);
  761. break;
  762. }
  763. case COLLADA_TYPE::ROTATE:
  764. {
  765. domRotateRef rotateNode = daeSafeCast<domRotate>(childElement);
  766. float x = (float)rotateNode->getValue().get(0);
  767. float y = (float)rotateNode->getValue().get(1);
  768. float z = (float)rotateNode->getValue().get(2);
  769. float angle = MATH_DEG_TO_RAD((float)rotateNode->getValue().get(3)); // COLLADA uses degrees, gameplay uses radians
  770. if (x == 1.0f && y == 0.0f && z == 0.0f)
  771. {
  772. dstTransform.rotateX(angle);
  773. }
  774. else if (x == 0.0f && y == 1.0f && z == 0.0f)
  775. {
  776. dstTransform.rotateY(angle);
  777. }
  778. else if (x == 0.0f && y == 0.0f && z == 1.0f)
  779. {
  780. dstTransform.rotateZ(angle);
  781. }
  782. else
  783. {
  784. dstTransform.rotate(x, y, z, angle);
  785. }
  786. break;
  787. }
  788. case COLLADA_TYPE::SCALE:
  789. {
  790. domScaleRef scaleNode = daeSafeCast<domScale>(childElement);
  791. float x = (float)scaleNode->getValue().get(0);
  792. float y = (float)scaleNode->getValue().get(1);
  793. float z = (float)scaleNode->getValue().get(2);
  794. dstTransform.scale(x, y, z);
  795. break;
  796. }
  797. case COLLADA_TYPE::SKEW:
  798. warning("Skew transform found but not supported.");
  799. break;
  800. case COLLADA_TYPE::LOOKAT:
  801. warning("Lookat transform found but not supported.");
  802. break;
  803. default:
  804. break;
  805. }
  806. }
  807. }
  808. void DAESceneEncoder::loadCameraInstance(const domNode* n, Node* node)
  809. {
  810. // Does this node have any camera instances?
  811. const domInstance_camera_Array& instanceCameras = n->getInstance_camera_array();
  812. size_t instanceCameraCount = instanceCameras.getCount();
  813. for (size_t i = 0; i < instanceCameraCount; i++)
  814. {
  815. // Get the camrea object
  816. const domInstance_camera* cameraInstanceRef = instanceCameras.get(i);
  817. xsAnyURI cameraURI = cameraInstanceRef->getUrl();
  818. domCamera* cameraRef = daeSafeCast<domCamera>(cameraURI.getElement());
  819. if (cameraRef)
  820. {
  821. CameraInstance* cameraInstance = loadCamera(cameraRef);
  822. if (cameraInstance)
  823. {
  824. node->setCameraInstance(cameraInstance);
  825. }
  826. }
  827. else
  828. {
  829. // warning
  830. }
  831. }
  832. }
  833. void DAESceneEncoder::loadLightInstance(const domNode* n, Node* node)
  834. {
  835. // Does this node have any light instances?
  836. const domInstance_light_Array& instanceLights = n->getInstance_light_array();
  837. size_t instanceLightCount = instanceLights.getCount();
  838. for (size_t i = 0; i < instanceLightCount; i++)
  839. {
  840. // Get the camrea object
  841. const domInstance_light* lightInstanceRef = instanceLights.get(i);
  842. xsAnyURI lightURI = lightInstanceRef->getUrl();
  843. domLight* lightRef = daeSafeCast<domLight>(lightURI.getElement());
  844. if (lightRef)
  845. {
  846. LightInstance* lightInstance = loadLight(lightRef);
  847. if (lightInstance)
  848. {
  849. node->setLightInstance(lightInstance);
  850. }
  851. }
  852. else
  853. {
  854. // warning
  855. }
  856. }
  857. }
  858. void DAESceneEncoder::loadGeometryInstance(const domNode* n, Node* node)
  859. {
  860. // Does this node have any geometry instances?
  861. const domInstance_geometry_Array& instanceGeometries = n->getInstance_geometry_array();
  862. size_t instanceGeometryCount = instanceGeometries.getCount();
  863. for (size_t i = 0; i < instanceGeometryCount; i++)
  864. {
  865. // Get the geometry object
  866. const domInstance_geometryRef geometryInstanceRef = instanceGeometries.get(i);
  867. xsAnyURI geometryURI = geometryInstanceRef->getUrl();
  868. domGeometry* geometry = daeSafeCast<domGeometry>(geometryURI.getElement());
  869. // Load the model from this geometry
  870. if (geometry)
  871. {
  872. Model* model = loadGeometry(geometry, geometryInstanceRef->getBind_material());
  873. if (model)
  874. {
  875. node->setModel(model);
  876. }
  877. }
  878. else
  879. {
  880. warning(std::string("Failed to resolve geometry url: ") + geometryURI.getURI());
  881. }
  882. }
  883. }
  884. void DAESceneEncoder::loadControllerInstance(const domNode* n, Node* node)
  885. {
  886. // Does this node have any controller instances?
  887. const domInstance_controller_Array& instanceControllers = n->getInstance_controller_array();
  888. size_t instanceControllerCount = instanceControllers.getCount();
  889. for (size_t i = 0; i < instanceControllerCount; i++)
  890. {
  891. const domInstance_controllerRef instanceControllerRef = instanceControllers.get(i);
  892. xsAnyURI controllerURI = instanceControllerRef->getUrl();
  893. domController* controllerRef = daeSafeCast<domController>(controllerURI.getElement());
  894. if (controllerRef)
  895. {
  896. const domSkin* skinElement = controllerRef->getSkin();
  897. if (skinElement)
  898. {
  899. Model* model = loadSkin(skinElement);
  900. if (model)
  901. {
  902. domInstance_controller::domSkeleton_Array& skeletons = instanceControllerRef->getSkeleton_array();
  903. if (skeletons.getCount() == 0)
  904. {
  905. warning("No skeletons found for instance controller: ");
  906. delete model;
  907. continue;
  908. }
  909. // Load the skeleton for this skin
  910. domInstance_controller::domSkeletonRef skeleton = getSkeleton(instanceControllerRef);
  911. assert(skeleton);
  912. loadSkeleton(skeleton, model->getSkin());
  913. node->setModel(model);
  914. }
  915. }
  916. }
  917. else
  918. {
  919. // warning
  920. }
  921. _jointLookupTable.clear();
  922. _jointInverseBindPoseMatrices.clear();
  923. }
  924. }
  925. CameraInstance* DAESceneEncoder::loadCamera(const domCamera* cameraRef)
  926. {
  927. ///////////////////////////// CAMERA
  928. // check if camera is already added to gamePlayFile
  929. const char* id = cameraRef->getId();
  930. Camera* camera = _gamePlayFile.getCamera(id);
  931. if (camera == NULL)
  932. {
  933. camera = new Camera();
  934. camera->setId(id);
  935. // Optics
  936. const domCamera::domOpticsRef opticsRef = cameraRef->getOptics();
  937. if (opticsRef.cast())
  938. {
  939. const domCamera::domOptics::domTechnique_commonRef techRef = opticsRef->getTechnique_common();
  940. // Orthographics
  941. const domCamera::domOptics::domTechnique_common::domOrthographicRef orthographicRef = techRef->getOrthographic();
  942. if (orthographicRef.cast())
  943. {
  944. camera->setOrthographic();
  945. camera->setNearPlane((float)orthographicRef->getZnear()->getValue());
  946. camera->setFarPlane((float)orthographicRef->getZfar()->getValue());
  947. const domTargetableFloatRef xmag = orthographicRef->getXmag();
  948. const domTargetableFloatRef ymag = orthographicRef->getYmag();
  949. // Viewport width
  950. if (xmag.cast())
  951. {
  952. camera->setViewportWidth((float)xmag->getValue());
  953. }
  954. // Viewport height
  955. if (ymag.cast())
  956. {
  957. camera->setViewportHeight((float)ymag->getValue());
  958. }
  959. // TODO: Viewport x and y?
  960. }
  961. // Perspective
  962. const domCamera::domOptics::domTechnique_common::domPerspectiveRef perspectiveRef = techRef->getPerspective();
  963. if (perspectiveRef.cast())
  964. {
  965. camera->setPerspective();
  966. camera->setNearPlane((float)perspectiveRef->getZnear()->getValue());
  967. camera->setFarPlane((float)perspectiveRef->getZfar()->getValue());
  968. float aspectRatio = -1.0f;
  969. if (perspectiveRef->getAspect_ratio().cast())
  970. {
  971. aspectRatio = (float)perspectiveRef->getAspect_ratio()->getValue();
  972. camera->setAspectRatio(aspectRatio);
  973. }
  974. if (perspectiveRef->getYfov().cast())
  975. {
  976. camera->setFieldOfView((float)perspectiveRef->getYfov()->getValue());
  977. }
  978. else if (perspectiveRef->getXfov().cast() && aspectRatio > 0.0f)
  979. {
  980. // The gameplaybinary stores the yfov but collada might have specified
  981. // an xfov and an aspect ratio. So use those to calculate the yfov.
  982. float xfov = (float)perspectiveRef->getXfov()->getValue();
  983. float yfov = xfov / aspectRatio;
  984. camera->setFieldOfView(yfov);
  985. }
  986. }
  987. }
  988. _gamePlayFile.addCamera(camera);
  989. }
  990. CameraInstance* cameraInstance = new CameraInstance();
  991. cameraInstance->setCamera(camera);
  992. return cameraInstance;
  993. }
  994. LightInstance* DAESceneEncoder::loadLight(const domLight* lightRef)
  995. {
  996. ///////////////////////////// LIGHT
  997. // check if light is already added to gamePlayFile
  998. const char* id = lightRef->getId();
  999. Light* light = _gamePlayFile.getLight(id);
  1000. if (light == NULL)
  1001. {
  1002. light = new Light();
  1003. light->setId(lightRef->getId());
  1004. const domLight::domTechnique_commonRef techRef = lightRef->getTechnique_common();
  1005. // Ambient light
  1006. {
  1007. const domLight::domTechnique_common::domAmbientRef ambientRef = techRef->getAmbient();
  1008. if (ambientRef.cast())
  1009. {
  1010. light->setAmbientLight();
  1011. // color
  1012. const domTargetableFloat3Ref float3Ref = ambientRef->getColor();
  1013. const domFloat3& color3 = float3Ref->getValue();
  1014. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1015. }
  1016. }
  1017. // Directional light
  1018. {
  1019. const domLight::domTechnique_common::domDirectionalRef direcitonalRef = techRef->getDirectional();
  1020. if (direcitonalRef.cast())
  1021. {
  1022. light->setDirectionalLight();
  1023. // color
  1024. const domTargetableFloat3Ref float3Ref = direcitonalRef->getColor();
  1025. const domFloat3& color3 = float3Ref->getValue();
  1026. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1027. }
  1028. }
  1029. // Spot light
  1030. {
  1031. const domLight::domTechnique_common::domSpotRef spotRef = techRef->getSpot();
  1032. if (spotRef.cast())
  1033. {
  1034. light->setSpotLight();
  1035. // color
  1036. const domTargetableFloat3Ref float3Ref = spotRef->getColor();
  1037. const domFloat3& color3 = float3Ref->getValue();
  1038. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1039. const domTargetableFloatRef& constAtt = spotRef->getConstant_attenuation();
  1040. if (constAtt.cast())
  1041. {
  1042. light->setConstantAttenuation((float)constAtt->getValue());
  1043. }
  1044. const domTargetableFloatRef& linearAtt = spotRef->getLinear_attenuation();
  1045. if (linearAtt.cast())
  1046. {
  1047. light->setLinearAttenuation((float)linearAtt->getValue());
  1048. }
  1049. const domTargetableFloatRef& quadAtt = spotRef->getQuadratic_attenuation();
  1050. if (quadAtt.cast())
  1051. {
  1052. light->setQuadraticAttenuation((float)quadAtt->getValue());
  1053. }
  1054. const domTargetableFloatRef& falloffAngle = spotRef->getFalloff_angle();
  1055. if (falloffAngle.cast())
  1056. {
  1057. light->setFalloffAngle((float)falloffAngle->getValue());
  1058. }
  1059. const domTargetableFloatRef& falloffExp = spotRef->getFalloff_exponent();
  1060. if (falloffExp.cast())
  1061. {
  1062. light->setFalloffExponent((float)falloffExp->getValue());
  1063. }
  1064. }
  1065. }
  1066. // Point light
  1067. {
  1068. const domLight::domTechnique_common::domPointRef pointRef = techRef->getPoint();
  1069. if (pointRef.cast())
  1070. {
  1071. light->setPointLight();
  1072. // color
  1073. const domTargetableFloat3Ref float3Ref = pointRef->getColor();
  1074. const domFloat3& color3 = float3Ref->getValue();
  1075. light->setColor((float)color3.get(0), (float)color3.get(1), (float)color3.get(2));
  1076. const domTargetableFloatRef& constAtt = pointRef->getConstant_attenuation();
  1077. if (constAtt.cast())
  1078. {
  1079. light->setConstantAttenuation((float)constAtt->getValue());
  1080. }
  1081. const domTargetableFloatRef& linearAtt = pointRef->getLinear_attenuation();
  1082. if (linearAtt.cast())
  1083. {
  1084. light->setLinearAttenuation((float)linearAtt->getValue());
  1085. }
  1086. const domTargetableFloatRef& quadAtt = pointRef->getQuadratic_attenuation();
  1087. if (quadAtt.cast())
  1088. {
  1089. light->setQuadraticAttenuation((float)quadAtt->getValue());
  1090. }
  1091. }
  1092. }
  1093. _gamePlayFile.addLight(light);
  1094. }
  1095. LightInstance* lightInstance = new LightInstance();
  1096. lightInstance->setLight(light);
  1097. return lightInstance;
  1098. }
  1099. void DAESceneEncoder::loadSkeleton(domInstance_controller::domSkeleton* skeletonElement, MeshSkin* skin)
  1100. {
  1101. xsAnyURI skeletonUri = skeletonElement->getValue();
  1102. daeString skeletonId = skeletonUri.getID();
  1103. daeSIDResolver resolver(skeletonUri.getElement(), skeletonId);
  1104. domNode* rootNode = daeSafeCast<domNode>(resolver.getElement());
  1105. // Get the lookup scene id (sid) and joint index.
  1106. std::string id = std::string(skeletonId);
  1107. // Has the skeleton (root joint) been loaded yet?
  1108. Node* skeleton = (Node*)_gamePlayFile.getFromRefTable(id);
  1109. // The skeleton node is not loaded yet, so let's load it now
  1110. if (skeleton == NULL)
  1111. {
  1112. // Find the top most parent of rootNode that has not yet been loaded
  1113. domNode* topLevelParent = rootNode;
  1114. while (
  1115. topLevelParent->getParent() &&
  1116. topLevelParent->getParent()->getElementType() == COLLADA_TYPE::NODE &&
  1117. _gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID()) == NULL)
  1118. {
  1119. topLevelParent = (domNode*)topLevelParent->getParent();
  1120. }
  1121. // Is the parent of this node loaded yet?
  1122. Node* parentNode = NULL;
  1123. if (topLevelParent->getParent() &&
  1124. topLevelParent->getParent()->getElementType() == COLLADA_TYPE::NODE &&
  1125. _gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID()) != NULL)
  1126. {
  1127. parentNode = (Node*)_gamePlayFile.getFromRefTable(topLevelParent->getParent()->getID());
  1128. }
  1129. // Finally, load the node hierarchy that includes the skeleton
  1130. skeleton = loadNode(topLevelParent, parentNode);
  1131. }
  1132. if (skeleton == NULL)
  1133. {
  1134. // This shouldn't really happen..
  1135. skeleton = new Node();
  1136. skeleton->setId(id);
  1137. _gamePlayFile.addNode(skeleton);
  1138. }
  1139. // Resolve and set joints array for skin
  1140. std::list<Node*> _joints;
  1141. const std::list<std::string>& jointNames = skin->getJointNames();
  1142. for (std::list<std::string>::const_iterator i = jointNames.begin(); i != jointNames.end(); i++)
  1143. {
  1144. Object* obj = _gamePlayFile.getFromRefTable(*i);
  1145. if (obj)
  1146. {
  1147. Node* node = (Node*)obj;
  1148. _joints.push_back(node);
  1149. }
  1150. }
  1151. skin->setJoints(_joints);
  1152. }
  1153. Model* DAESceneEncoder::loadSkin(const domSkin* skinElement)
  1154. {
  1155. ///////////////////////////// SKIN
  1156. Model* model = new Model();
  1157. MeshSkin* skin = new MeshSkin();
  1158. // Bind Shape Matrix
  1159. const domSkin::domBind_shape_matrix* bindShapeMatrix = skinElement->getBind_shape_matrix();
  1160. if (bindShapeMatrix)
  1161. {
  1162. const domFloat4x4& m = bindShapeMatrix->getValue();
  1163. float transform[] = {(float)m.get(0), (float)m.get(4), (float)m.get(8), (float)m.get(12),
  1164. (float)m.get(1), (float)m.get(5), (float)m.get(9), (float)m.get(13),
  1165. (float)m.get(2), (float)m.get(6), (float)m.get(10), (float)m.get(14),
  1166. (float)m.get(3), (float)m.get(7), (float)m.get(11), (float)m.get(15)};
  1167. skin->setBindShape(transform);
  1168. }
  1169. // Read and set our joints
  1170. domSkin::domJointsRef _joints = skinElement->getJoints();
  1171. domInputLocal_Array& jointInputs = _joints->getInput_array();
  1172. // Process "JOINT" input semantic first (we need to do this to set the joint count)
  1173. unsigned int jointCount = 0;
  1174. for (unsigned int i = 0; i < jointInputs.getCount(); i++)
  1175. {
  1176. domInputLocalRef input = jointInputs.get(i);
  1177. std::string inputSemantic = std::string(input->getSemantic());
  1178. domURIFragmentType* sourceURI = &input->getSource();
  1179. sourceURI->resolveElement();
  1180. const domSourceRef source = (domSource*)(daeElement*)sourceURI->getElement();
  1181. if (equals(inputSemantic, "JOINT"))
  1182. {
  1183. // Get the joint Ids's
  1184. std::list<std::string> list;
  1185. getJointNames(source, list);
  1186. // Go through the joint list and conver them from sid to id because the sid information is
  1187. // lost when converting to the gameplay binary format.
  1188. for (std::list<std::string>::iterator i = list.begin(); i != list.end(); i++)
  1189. {
  1190. daeSIDResolver resolver(source->getDocument()->getDomRoot(), i->c_str());
  1191. daeElement* element = resolver.getElement();
  1192. if (element && element->getElementType() == COLLADA_TYPE::NODE)
  1193. {
  1194. domNodeRef node = daeSafeCast<domNode>(element);
  1195. const char* nodeId = node->getId();
  1196. if (nodeId && !equals(*i, nodeId))
  1197. {
  1198. *i = nodeId;
  1199. }
  1200. }
  1201. }
  1202. // Get the joint count and set the capacities for both the
  1203. jointCount = list.size();
  1204. _jointInverseBindPoseMatrices.reserve(jointCount);
  1205. unsigned int j = 0;
  1206. for (std::list<std::string>::const_iterator i = list.begin(); i != list.end(); i++)
  1207. {
  1208. _jointLookupTable[*i] = j++;
  1209. }
  1210. skin->setJointNames(list);
  1211. }
  1212. }
  1213. // Make sure we have some joints
  1214. if (jointCount == 0)
  1215. {
  1216. warning("No joints found for skin: ");
  1217. return NULL;
  1218. }
  1219. // Process "INV_BIND_MATRIX" next
  1220. for (unsigned int i = 0; i < jointInputs.getCount(); i++)
  1221. {
  1222. domInputLocalRef input = jointInputs.get(i);
  1223. std::string inputSemantic = std::string(input->getSemantic());
  1224. domURIFragmentType* sourceURI = &input->getSource();
  1225. sourceURI->resolveElement();
  1226. domSource* source = (domSource*)(daeElement*)sourceURI->getElement();
  1227. if (equals(inputSemantic, "INV_BIND_MATRIX"))
  1228. {
  1229. domListOfFloats& matrixFloats = source->getFloat_array()->getValue();
  1230. //unsigned int matrixFloatsCount = (unsigned int)source->getFloat_array()->getCount();
  1231. unsigned int jointIndex = 0;
  1232. for (unsigned int j = 0; j < jointCount; j++)
  1233. {
  1234. Matrix matrix((float)matrixFloats.get(jointIndex + 0), (float)matrixFloats.get(jointIndex + 4), (float)matrixFloats.get(jointIndex + 8), (float)matrixFloats.get(jointIndex + 12),
  1235. (float)matrixFloats.get(jointIndex + 1), (float)matrixFloats.get(jointIndex + 5), (float)matrixFloats.get(jointIndex + 9), (float)matrixFloats.get(jointIndex + 13),
  1236. (float)matrixFloats.get(jointIndex + 2), (float)matrixFloats.get(jointIndex + 6), (float)matrixFloats.get(jointIndex + 10), (float)matrixFloats.get(jointIndex + 14),
  1237. (float)matrixFloats.get(jointIndex + 3), (float)matrixFloats.get(jointIndex + 7), (float)matrixFloats.get(jointIndex + 11), (float)matrixFloats.get(jointIndex + 15));
  1238. _jointInverseBindPoseMatrices.push_back(matrix);
  1239. jointIndex += 16;
  1240. }
  1241. }
  1242. }
  1243. skin->setBindPoses(_jointInverseBindPoseMatrices);
  1244. // Get the vertex weights inputs
  1245. domSkin::domVertex_weights* vertexWeights = skinElement->getVertex_weights();
  1246. domInputLocalOffset_Array& vertexWeightsInputs = vertexWeights->getInput_array();
  1247. unsigned int vertexWeightsCount = (unsigned int)vertexWeights->getCount();
  1248. domListOfFloats jointWeights;
  1249. for (unsigned int i = 0; i < jointInputs.getCount(); i++)
  1250. {
  1251. domInputLocalOffsetRef input = vertexWeightsInputs.get(i);
  1252. std::string inputSemantic = std::string(input->getSemantic());
  1253. domURIFragmentType* sourceURI = &input->getSource();
  1254. sourceURI->resolveElement();
  1255. domSource* source = (domSource*)(daeElement*)sourceURI->getElement();
  1256. if (equals(inputSemantic, "WEIGHT"))
  1257. {
  1258. domFloat_array* weights = source->getFloat_array();
  1259. if (weights)
  1260. {
  1261. jointWeights = weights->getValue();
  1262. }
  1263. }
  1264. }
  1265. // Get the number of joint influences per vertex
  1266. domSkin::domVertex_weights::domVcount* vCountElement = vertexWeights->getVcount();
  1267. domListOfUInts skinVertexInfluenceCounts = vCountElement->getValue();
  1268. // Get the joint/weight pair data.
  1269. domSkin::domVertex_weights::domV* vElement = vertexWeights->getV();
  1270. domListOfInts skinVertexJointWeightPairIndices = vElement->getValue();
  1271. // Get the vertex influence count for any given vertex (up to max of 4)
  1272. unsigned int maxVertexInfluencesCount = SCENE_SKIN_VERTEXINFLUENCES_MAX;
  1273. skin->setVertexInfluenceCount(maxVertexInfluencesCount);
  1274. // Get the vertex blend weights and joint indices and
  1275. // allocate our vertex blend weights and blend indices arrays.
  1276. // These will be used and cleaned up later in LoadMesh
  1277. int skinVertexInfluenceCountTotal = skinVertexInfluenceCounts.getCount();
  1278. int totalVertexInfluencesCount = vertexWeightsCount * maxVertexInfluencesCount;
  1279. _vertexBlendWeights = new float[totalVertexInfluencesCount];
  1280. _vertexBlendIndices = new unsigned int[totalVertexInfluencesCount];
  1281. // Preset the default blend weights to 0.0f (no effect) and blend indices to 0 (uses the first which when multiplied
  1282. // will have no effect anyhow.
  1283. memset(_vertexBlendWeights, 0, totalVertexInfluencesCount * sizeof(float));
  1284. memset(_vertexBlendIndices , 0, totalVertexInfluencesCount * sizeof(unsigned int));
  1285. int vOffset = 0;
  1286. int weightOffset = 0;
  1287. // Go through all the skin vertex influence weights from the indexed data.
  1288. for (int i = 0; i < skinVertexInfluenceCountTotal; i++)
  1289. {
  1290. // Get the influence count and directly get the vertext blend weights and indices.
  1291. unsigned int vertexInfluenceCount = (unsigned int)skinVertexInfluenceCounts.get(i);
  1292. float vertexInfluencesTotalWeights = 0.0f;
  1293. std::vector<SkinnedVertexWeightPair> vertexInfluences;
  1294. //vertexInfluences.SetCapacity(vertexInfluenceCount);
  1295. // Get the index/weight pairs and some the weight totals while at it.
  1296. for (unsigned int j = 0; j < vertexInfluenceCount; j++)
  1297. {
  1298. float weight = (float)jointWeights.get((unsigned int)skinVertexJointWeightPairIndices[vOffset + 1]);
  1299. int index = (int)skinVertexJointWeightPairIndices[vOffset];
  1300. // Set invalid index corresponding weights to zero
  1301. if (index < 0 || index > (int)vertexWeightsCount)
  1302. {
  1303. weight = 0.0f;
  1304. index = 0;
  1305. }
  1306. SkinnedVertexWeightPair pair(weight, index);
  1307. vertexInfluences.push_back(pair);
  1308. vertexInfluencesTotalWeights += weight;
  1309. vOffset+=2;
  1310. }
  1311. // Get up the the maximum vertex weight influence count.
  1312. for (unsigned int j = 0; j < maxVertexInfluencesCount; j++)
  1313. {
  1314. if (j < vertexInfluenceCount)
  1315. {
  1316. SkinnedVertexWeightPair pair = vertexInfluences[j];
  1317. _vertexBlendIndices[weightOffset] = pair.BlendIndex;
  1318. if (vertexInfluencesTotalWeights > 0.0f)
  1319. {
  1320. _vertexBlendWeights[weightOffset] = pair.BlendWeight;
  1321. }
  1322. else
  1323. {
  1324. if (j == 0)
  1325. {
  1326. _vertexBlendWeights[weightOffset] = 1.0f;
  1327. }
  1328. else
  1329. {
  1330. _vertexBlendWeights[weightOffset] = 0.0f;
  1331. }
  1332. }
  1333. }
  1334. weightOffset++;
  1335. }
  1336. }
  1337. model->setSkin(skin);
  1338. ///////////////////////////////////////////////////////////
  1339. // get geometry
  1340. xsAnyURI geometryURI = skinElement->getSource();
  1341. domGeometry* geometry = daeSafeCast<domGeometry>(geometryURI.getElement());
  1342. if (geometry)
  1343. {
  1344. const domMesh* meshElement = geometry->getMesh();
  1345. if (meshElement)
  1346. {
  1347. Mesh* mesh = loadMesh(meshElement, geometry->getId());
  1348. if (mesh)
  1349. {
  1350. model->setMesh(mesh);
  1351. }
  1352. }
  1353. }
  1354. ///////////////////////////////////////////////////////////
  1355. return model;
  1356. }
  1357. Model* DAESceneEncoder::loadGeometry(const domGeometry* geometry, const domBind_materialRef bindMaterial)
  1358. {
  1359. // Does this geometry have a valid mesh?
  1360. // Get the mesh for the geometry (if it has one)
  1361. const domMesh* meshElement = geometry->getMesh();
  1362. if (meshElement == NULL)
  1363. {
  1364. warning(std::string("No mesh found for geometry: ") + geometry->getId());
  1365. return NULL;
  1366. }
  1367. ///////////////////////////// GEOMETRY
  1368. // Load the mesh for this model
  1369. Mesh* mesh = loadMesh(meshElement, geometry->getId());
  1370. if (mesh == NULL)
  1371. {
  1372. return NULL;
  1373. }
  1374. // Mesh instance
  1375. Model* model = new Model();
  1376. model->setMesh(mesh);
  1377. return model;
  1378. }
  1379. Mesh* DAESceneEncoder::loadMesh(const domMesh* meshElement, const std::string& geometryId)
  1380. {
  1381. const domTriangles_Array& trianglesArray = meshElement->getTriangles_array();
  1382. unsigned int trianglesArrayCount = (unsigned int)trianglesArray.getCount();
  1383. // Ensure the data is exported as triangles.
  1384. if (trianglesArrayCount == 0)
  1385. {
  1386. warning(std::string("Geometry mesh has no triangles: ") + geometryId);
  1387. return NULL;
  1388. }
  1389. // Check if this mesh already exists
  1390. Mesh* mesh = _gamePlayFile.getMesh(geometryId.c_str());
  1391. if (mesh)
  1392. {
  1393. return mesh;
  1394. }
  1395. mesh = new Mesh();
  1396. mesh->setId(geometryId.c_str());
  1397. std::vector<DAEPolygonInput*> polygonInputs;
  1398. // Quickly just go through each triangles array and make sure they have the same number of inputs
  1399. // with the same layout.
  1400. // const domSource_Array& sourceArray = meshElement->getSource_array();
  1401. const domInputLocal_Array& vertexArray = meshElement->getVertices()->getInput_array();
  1402. unsigned int inputCount = (unsigned int)-1;
  1403. // Loop through our set of triangle lists (each list of triangles corresponds to a single MeshPart)
  1404. for (unsigned int i = 0; i < trianglesArrayCount; i++)
  1405. {
  1406. const domTrianglesRef& triangles = trianglesArray.get(i);
  1407. const domInputLocalOffset_Array& inputArray = triangles->getInput_array();
  1408. // If not set then determine the number of input for all the triangles.
  1409. if (inputCount == -1)
  1410. {
  1411. inputCount = (unsigned int)inputArray.getCount();
  1412. for (unsigned int j = 0; j < inputCount; j++)
  1413. {
  1414. const domInputLocalOffsetRef& input = inputArray.get(j);
  1415. std::string inputSemantic = input->getSemantic();
  1416. // If its a vertex first do an extra lookup for the inclusive inputs
  1417. if (equals(inputSemantic, "VERTEX"))
  1418. {
  1419. unsigned int vertexArrayCount = (unsigned int)vertexArray.getCount();
  1420. for (unsigned int k = 0; k < vertexArrayCount; k++)
  1421. {
  1422. const domInputLocalRef& vertexInput = vertexArray.get(k);
  1423. std::string semantic = std::string(vertexInput->getSemantic());
  1424. int type = getVertexUsageType(semantic);
  1425. if (type == -1)
  1426. {
  1427. warning(std::string("Vertex semantic (") + semantic + ") is invalid/unsupported for geometry mesh: " + geometryId);
  1428. }
  1429. DAEPolygonInput* polygonInput = new DAEPolygonInput();
  1430. domURIFragmentType& sourceURI = vertexInput->getSource();
  1431. sourceURI.resolveElement();
  1432. domSource* source = (domSource*)(daeElement*)sourceURI.getElement();
  1433. polygonInput->offset = 0;
  1434. polygonInput->sourceValues = source->getFloat_array()->getValue();
  1435. polygonInput->type = type;
  1436. polygonInputs.push_back(polygonInput);
  1437. }
  1438. }
  1439. else
  1440. {
  1441. std::string semantic = input->getSemantic();
  1442. int type = getVertexUsageType(semantic);
  1443. if (type == -1)
  1444. {
  1445. warning(std::string("Semantic (") + semantic + ") is invalid/unsupported for geometry mesh: " + geometryId);
  1446. }
  1447. DAEPolygonInput* polygonInput = new DAEPolygonInput();
  1448. domURIFragmentType& sourceURI = input->getSource();
  1449. sourceURI.resolveElement();
  1450. domSource* source = (domSource*)(daeElement*)sourceURI.getElement();
  1451. polygonInput->offset = (unsigned int)input->getOffset();
  1452. polygonInput->sourceValues = source->getFloat_array()->getValue();
  1453. polygonInput->type = type;
  1454. // Get the accessor info
  1455. const domSource::domTechnique_commonRef& technique = source->getTechnique_common();
  1456. if (technique.cast())
  1457. {
  1458. const domAccessorRef& accessor = technique->getAccessor();
  1459. polygonInput->accessor = accessor;
  1460. }
  1461. polygonInputs.push_back(polygonInput);
  1462. }
  1463. }
  1464. }
  1465. else
  1466. {
  1467. // If there is a triangle array with a different number of inputs, this is not supported.
  1468. if (inputCount != (unsigned int)inputArray.getCount())
  1469. {
  1470. for (size_t j = 0; j < polygonInputs.size(); j++)
  1471. {
  1472. delete polygonInputs[j];
  1473. }
  1474. warning(std::string("Triangles do not all have the same number of input sources for geometry mesh: ") + geometryId);
  1475. return false;
  1476. }
  1477. else
  1478. {
  1479. // TODO: Check if they are in the same order...
  1480. }
  1481. }
  1482. }
  1483. // Now we have validated that all input in all triangles are the same and in the same input layout.
  1484. // Lets start to read them and build our subsets.
  1485. for (unsigned int i = 0; i < trianglesArrayCount; i++)
  1486. {
  1487. // Subset to be built.
  1488. MeshPart* subset = new MeshPart();
  1489. // All of the information about the triangles and the sources to access the data from.
  1490. domTriangles* triangles = daeSafeCast<domTriangles>(trianglesArray.get(i));
  1491. // Parse the material for this subset
  1492. //std::string materialName = triangles->getMaterial() == NULL ? _T("") : triangles->getMaterial();
  1493. //if (materialName.size() > 0)
  1494. /// subset->material = ParseMaterial(bindMaterial, materialName);
  1495. //const domInputLocalOffset_Array& inputArray = triangles->getInput_array();
  1496. const domListOfUInts& polyInts = triangles->getP()->getValue();
  1497. unsigned int polyIntsCount = (unsigned int)polyInts.getCount();
  1498. unsigned int poly = 0;
  1499. unsigned int inputSourceCount = (unsigned int)polygonInputs.size();
  1500. unsigned int maxOffset = 0;
  1501. // Go through the polygon indices for each input source retrieve the values
  1502. // and iterate by its offset.
  1503. Vertex vertex;
  1504. for (unsigned int k = 0; k < inputSourceCount && poly < polyIntsCount;)
  1505. {
  1506. const domListOfFloats& source = polygonInputs[k]->sourceValues;
  1507. unsigned int offset = polygonInputs[k]->offset;
  1508. if (offset > maxOffset)
  1509. {
  1510. maxOffset = offset;
  1511. }
  1512. int type = polygonInputs[k]->type;
  1513. unsigned int polyIndex = (unsigned int) polyInts.get(poly + offset);
  1514. switch (type)
  1515. {
  1516. case POSITION:
  1517. vertex.reset();
  1518. if (_vertexBlendWeights && _vertexBlendIndices)
  1519. {
  1520. vertex.hasWeights = true;
  1521. vertex.blendWeights.x = _vertexBlendWeights[polyIndex * 4];
  1522. vertex.blendWeights.y = _vertexBlendWeights[polyIndex * 4 + 1];
  1523. vertex.blendWeights.z = _vertexBlendWeights[polyIndex * 4 + 2];
  1524. vertex.blendWeights.w = _vertexBlendWeights[polyIndex * 4 + 3];
  1525. vertex.blendIndices.x = (float)_vertexBlendIndices[polyIndex * 4];
  1526. vertex.blendIndices.y = (float)_vertexBlendIndices[polyIndex * 4 + 1];
  1527. vertex.blendIndices.z = (float)_vertexBlendIndices[polyIndex * 4 + 2];
  1528. vertex.blendIndices.w = (float)_vertexBlendIndices[polyIndex * 4 + 3];
  1529. }
  1530. vertex.position.x = (float)source.get(polyIndex * 3);
  1531. vertex.position.y = (float)source.get(polyIndex * 3 + 1);
  1532. vertex.position.z = (float)source.get(polyIndex * 3 + 2);
  1533. break;
  1534. case NORMAL:
  1535. vertex.hasNormal = true;
  1536. vertex.normal.x = (float)source.get(polyIndex * 3);
  1537. vertex.normal.y = (float)source.get(polyIndex * 3 + 1);
  1538. vertex.normal.z = (float)source.get(polyIndex * 3 + 2);
  1539. break;
  1540. // TODO: Handle reading of per-vertex colors.
  1541. // HOW do we know how many color components to read?
  1542. // We must examine the Collada input accessor and read the stride/count to verify this - not ONLY for Color, but we should be doing this for ALL components (i.e. Position, Normal, etc).
  1543. // case Color:
  1544. // vertex.hasColor = true;
  1545. // vertex.Diffuse.R = (float)source.get(polyIndex * 3);
  1546. // vertex.Diffuse.G = (float)source.get(polyIndex * 3 + 1);
  1547. // vertex.Diffuse.B = (float)source.get(polyIndex * 3 + 2);
  1548. // vertex.Diffuse.A = (float)source.get(polyIndex * 3 + 3);
  1549. // break;
  1550. case TANGENT:
  1551. vertex.hasTangent = true;
  1552. vertex.tangent.x = (float)source.get(polyIndex * 3);
  1553. vertex.tangent.y = (float)source.get(polyIndex * 3 + 1);
  1554. vertex.tangent.z = (float)source.get(polyIndex * 3 + 2);
  1555. break;
  1556. case BINORMAL:
  1557. vertex.hasBinormal = true;
  1558. vertex.binormal.x = (float)source.get(polyIndex * 3);
  1559. vertex.binormal.y = (float)source.get(polyIndex * 3 + 1);
  1560. vertex.binormal.z = (float)source.get(polyIndex * 3 + 2);
  1561. break;
  1562. case TEXCOORD0:
  1563. vertex.hasTexCoord = true;
  1564. if (polygonInputs[k]->accessor)
  1565. {
  1566. // TODO: This assumes (s, t) are first
  1567. unsigned int stride = (unsigned int)polygonInputs[k]->accessor->getStride();
  1568. vertex.texCoord.x = (float)source.get(polyIndex * stride);
  1569. vertex.texCoord.y = (float)source.get(polyIndex * stride + 1);
  1570. }
  1571. else
  1572. {
  1573. vertex.texCoord.x = (float)source.get(polyIndex * 2);
  1574. vertex.texCoord.y = (float)source.get(polyIndex * 2 + 1);
  1575. }
  1576. break;
  1577. }
  1578. // On the last input source attempt to add the vertex or index an existing one.
  1579. if (k == (inputSourceCount - 1))
  1580. {
  1581. // Only add unique vertices, use a hashtable and compare the hash functions of the
  1582. // vertices. If they exist simply lookup the index of the existing ones.
  1583. // otherwise add and new one and index it.
  1584. unsigned int index;
  1585. if (mesh->contains(vertex))
  1586. {
  1587. index = mesh->getVertexIndex(vertex);
  1588. }
  1589. else
  1590. {
  1591. index = mesh->addVertex(vertex);
  1592. }
  1593. subset->addIndex(index);
  1594. poly += (maxOffset+1);
  1595. k = 0;
  1596. }
  1597. else
  1598. {
  1599. k++;
  1600. }
  1601. }
  1602. // Add our new subset for the mesh.
  1603. mesh->addMeshPart(subset);
  1604. }
  1605. bool hasNormals = mesh->vertices[0].hasNormal;
  1606. bool hasColors = mesh->vertices[0].hasColor;
  1607. bool hasTangents = mesh->vertices[0].hasTangent;
  1608. bool hasBinormals = mesh->vertices[0].hasBinormal;
  1609. bool hasTexCoords = mesh->vertices[0].hasTexCoord;
  1610. bool hasWeights = mesh->vertices[0].hasWeights;
  1611. // The order that the vertex elements are add to the list matters.
  1612. // It should be the same order as how the Vertex data is written.
  1613. // Position
  1614. mesh->addVetexAttribute(POSITION, 3);
  1615. // Normals
  1616. if (hasNormals)
  1617. {
  1618. mesh->addVetexAttribute(NORMAL, 3);
  1619. }
  1620. // Tangents
  1621. if (hasTangents)
  1622. {
  1623. mesh->addVetexAttribute(TANGENT, 3);
  1624. }
  1625. // Binormals
  1626. if (hasBinormals)
  1627. {
  1628. mesh->addVetexAttribute(BINORMAL, 3);
  1629. }
  1630. // Texture Coordinates
  1631. if (hasTexCoords)
  1632. {
  1633. mesh->addVetexAttribute(TEXCOORD0, 2);
  1634. }
  1635. // Diffuse Color
  1636. if (hasColors)
  1637. {
  1638. mesh->addVetexAttribute(COLOR, 3);
  1639. }
  1640. // Skinning BlendWeights BlendIndices
  1641. if (hasWeights /*_vertexBlendWeights && _vertexBlendIndices*/)
  1642. {
  1643. mesh->addVetexAttribute(BLENDWEIGHTS, 4);
  1644. mesh->addVetexAttribute(BLENDINDICES, 4);
  1645. }
  1646. _gamePlayFile.addMesh(mesh);
  1647. return mesh;
  1648. }
  1649. void DAESceneEncoder::warning(const std::string& message)
  1650. {
  1651. printf("Warning: %s\n", message.c_str());
  1652. }
  1653. void DAESceneEncoder::warning(const char* message)
  1654. {
  1655. printf("Warning: %s\n", message);
  1656. }
  1657. int DAESceneEncoder::getVertexUsageType(const std::string& semantic)
  1658. {
  1659. int type = -1;
  1660. if (semantic.length() > 0)
  1661. {
  1662. switch (semantic[0])
  1663. {
  1664. case 'P':
  1665. if (equals(semantic, "POSITION"))
  1666. {
  1667. type = POSITION;
  1668. }
  1669. break;
  1670. case 'N':
  1671. if (equals(semantic, "NORMAL"))
  1672. {
  1673. type = NORMAL;
  1674. }
  1675. case 'C':
  1676. if (equals(semantic, "COLOR"))
  1677. {
  1678. type = COLOR;
  1679. }
  1680. case 'T':
  1681. if (equals(semantic, "TANGENT"))
  1682. {
  1683. type = TANGENT;
  1684. }
  1685. else if (equals(semantic, "TEXCOORD"))
  1686. {
  1687. type = TEXCOORD0;
  1688. }
  1689. case 'B':
  1690. if (equals(semantic, "BINORMAL"))
  1691. {
  1692. type = BINORMAL;
  1693. }
  1694. default:
  1695. break;
  1696. }
  1697. }
  1698. return type;
  1699. }
  1700. DAESceneEncoder::DAEPolygonInput::DAEPolygonInput(void) :
  1701. offset(0),
  1702. type(0),
  1703. accessor(NULL)
  1704. {
  1705. }
  1706. DAESceneEncoder::DAEPolygonInput::~DAEPolygonInput(void)
  1707. {
  1708. }