DAESceneEncoder.cpp 76 KB

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