DAESceneEncoder.cpp 72 KB

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