Bundle.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. #include "Base.h"
  2. #include "Bundle.h"
  3. #include "FileSystem.h"
  4. #include "MeshPart.h"
  5. #include "Scene.h"
  6. #include "Joint.h"
  7. // Minimum version numbers supported
  8. #define BUNDLE_VERSION_MAJOR_REQUIRED 1
  9. #define BUNDLE_VERSION_MINOR_REQUIRED 2
  10. #define BUNDLE_TYPE_SCENE 1
  11. #define BUNDLE_TYPE_NODE 2
  12. #define BUNDLE_TYPE_ANIMATIONS 3
  13. #define BUNDLE_TYPE_ANIMATION 4
  14. #define BUNDLE_TYPE_ANIMATION_CHANNEL 5
  15. #define BUNDLE_TYPE_MODEL 10
  16. #define BUNDLE_TYPE_MATERIAL 16
  17. #define BUNDLE_TYPE_EFFECT 18
  18. #define BUNDLE_TYPE_CAMERA 32
  19. #define BUNDLE_TYPE_LIGHT 33
  20. #define BUNDLE_TYPE_MESH 34
  21. #define BUNDLE_TYPE_MESHPART 35
  22. #define BUNDLE_TYPE_MESHSKIN 36
  23. #define BUNDLE_TYPE_FONT 128
  24. // For sanity checking string reads
  25. #define BUNDLE_MAX_STRING_LENGTH 5000
  26. #define BUNDLE_VERSION_MAJOR_FONT_FORMAT 1
  27. #define BUNDLE_VERSION_MINOR_FONT_FORMAT 3
  28. namespace gameplay
  29. {
  30. static std::vector<Bundle*> __bundleCache;
  31. Bundle::Bundle(const char* path) :
  32. _path(path), _referenceCount(0), _references(NULL), _stream(NULL), _trackedNodes(NULL)
  33. {
  34. }
  35. Bundle::~Bundle()
  36. {
  37. clearLoadSession();
  38. // Remove this Bundle from the cache.
  39. std::vector<Bundle*>::iterator itr = std::find(__bundleCache.begin(), __bundleCache.end(), this);
  40. if (itr != __bundleCache.end())
  41. {
  42. __bundleCache.erase(itr);
  43. }
  44. SAFE_DELETE_ARRAY(_references);
  45. if (_stream)
  46. {
  47. SAFE_DELETE(_stream);
  48. }
  49. }
  50. unsigned int Bundle::getVersionMajor() const
  51. {
  52. return (unsigned int)_version[0];
  53. }
  54. unsigned int Bundle::getVersionMinor() const
  55. {
  56. return (unsigned int)_version[1];
  57. }
  58. template <class T>
  59. bool Bundle::readArray(unsigned int* length, T** ptr)
  60. {
  61. GP_ASSERT(length);
  62. GP_ASSERT(ptr);
  63. GP_ASSERT(_stream);
  64. if (!read(length))
  65. {
  66. GP_ERROR("Failed to read the length of an array of data (to be read into an array).");
  67. return false;
  68. }
  69. if (*length > 0)
  70. {
  71. *ptr = new T[*length];
  72. if (_stream->read(*ptr, sizeof(T), *length) != *length)
  73. {
  74. GP_ERROR("Failed to read an array of data from bundle (into an array).");
  75. SAFE_DELETE_ARRAY(*ptr);
  76. return false;
  77. }
  78. }
  79. return true;
  80. }
  81. template <class T>
  82. bool Bundle::readArray(unsigned int* length, std::vector<T>* values)
  83. {
  84. GP_ASSERT(length);
  85. GP_ASSERT(_stream);
  86. if (!read(length))
  87. {
  88. GP_ERROR("Failed to read the length of an array of data (to be read into a std::vector).");
  89. return false;
  90. }
  91. if (*length > 0 && values)
  92. {
  93. values->resize(*length);
  94. if (_stream->read(&(*values)[0], sizeof(T), *length) != *length)
  95. {
  96. GP_ERROR("Failed to read an array of data from bundle (into a std::vector).");
  97. return false;
  98. }
  99. }
  100. return true;
  101. }
  102. template <class T>
  103. bool Bundle::readArray(unsigned int* length, std::vector<T>* values, unsigned int readSize)
  104. {
  105. GP_ASSERT(length);
  106. GP_ASSERT(_stream);
  107. GP_ASSERT(sizeof(T) >= readSize);
  108. if (!read(length))
  109. {
  110. GP_ERROR("Failed to read the length of an array of data (to be read into a std::vector with a specified single element read size).");
  111. return false;
  112. }
  113. if (*length > 0 && values)
  114. {
  115. values->resize(*length);
  116. if (_stream->read(&(*values)[0], readSize, *length) != *length)
  117. {
  118. GP_ERROR("Failed to read an array of data from bundle (into a std::vector with a specified single element read size).");
  119. return false;
  120. }
  121. }
  122. return true;
  123. }
  124. static std::string readString(Stream* stream)
  125. {
  126. GP_ASSERT(stream);
  127. unsigned int length;
  128. if (stream->read(&length, 4, 1) != 1)
  129. {
  130. GP_ERROR("Failed to read the length of a string from a bundle.");
  131. return std::string();
  132. }
  133. // Sanity check to detect if string length is far too big.
  134. GP_ASSERT(length < BUNDLE_MAX_STRING_LENGTH);
  135. std::string str;
  136. if (length > 0)
  137. {
  138. str.resize(length);
  139. if (stream->read(&str[0], 1, length) != length)
  140. {
  141. GP_ERROR("Failed to read string from bundle.");
  142. return std::string();
  143. }
  144. }
  145. return str;
  146. }
  147. Bundle* Bundle::create(const char* path)
  148. {
  149. GP_ASSERT(path);
  150. // Search the cache for this bundle.
  151. for (size_t i = 0, count = __bundleCache.size(); i < count; ++i)
  152. {
  153. Bundle* p = __bundleCache[i];
  154. GP_ASSERT(p);
  155. if (p->_path == path)
  156. {
  157. // Found a match
  158. p->addRef();
  159. return p;
  160. }
  161. }
  162. // Open the bundle.
  163. Stream* stream = FileSystem::open(path);
  164. if (!stream)
  165. {
  166. GP_ERROR("Failed to open file '%s'.", path);
  167. return NULL;
  168. }
  169. // Read the GPB header info.
  170. char sig[9];
  171. if (stream->read(sig, 1, 9) != 9 || memcmp(sig, "\xABGPB\xBB\r\n\x1A\n", 9) != 0)
  172. {
  173. SAFE_DELETE(stream);
  174. GP_ERROR("Invalid GPB header for bundle '%s'.", path);
  175. return NULL;
  176. }
  177. // Read version.
  178. unsigned char version[2];
  179. if (stream->read(version, 1, 2) != 2)
  180. {
  181. SAFE_DELETE(stream);
  182. GP_ERROR("Failed to read GPB version for bundle '%s'.", path);
  183. return NULL;
  184. }
  185. // Check for the minimal
  186. if (version[0] != BUNDLE_VERSION_MAJOR_REQUIRED || version[1] < BUNDLE_VERSION_MINOR_REQUIRED)
  187. {
  188. SAFE_DELETE(stream);
  189. GP_ERROR("Unsupported version (%d.%d) for bundle '%s' (expected %d.%d).", (int)version[0], (int)version[1], path, BUNDLE_VERSION_MAJOR_REQUIRED, BUNDLE_VERSION_MINOR_REQUIRED);
  190. return NULL;
  191. }
  192. // Read ref table.
  193. unsigned int refCount;
  194. if (stream->read(&refCount, 4, 1) != 1)
  195. {
  196. SAFE_DELETE(stream);
  197. GP_ERROR("Failed to read ref table for bundle '%s'.", path);
  198. return NULL;
  199. }
  200. // Read all refs.
  201. Reference* refs = new Reference[refCount];
  202. for (unsigned int i = 0; i < refCount; ++i)
  203. {
  204. if ((refs[i].id = readString(stream)).empty() ||
  205. stream->read(&refs[i].type, 4, 1) != 1 ||
  206. stream->read(&refs[i].offset, 4, 1) != 1)
  207. {
  208. SAFE_DELETE(stream);
  209. GP_ERROR("Failed to read ref number %d for bundle '%s'.", i, path);
  210. SAFE_DELETE_ARRAY(refs);
  211. return NULL;
  212. }
  213. }
  214. // Keep file open for faster reading later.
  215. Bundle* bundle = new Bundle(path);
  216. bundle->_version[0] = version[0];
  217. bundle->_version[1] = version[1];
  218. bundle->_referenceCount = refCount;
  219. bundle->_references = refs;
  220. bundle->_stream = stream;
  221. return bundle;
  222. }
  223. Bundle::Reference* Bundle::find(const char* id) const
  224. {
  225. GP_ASSERT(id);
  226. GP_ASSERT(_references);
  227. // Search the ref table for the given id (case-sensitive).
  228. for (unsigned int i = 0; i < _referenceCount; ++i)
  229. {
  230. if (_references[i].id == id)
  231. {
  232. // Found a match
  233. return &_references[i];
  234. }
  235. }
  236. return NULL;
  237. }
  238. void Bundle::clearLoadSession()
  239. {
  240. for (size_t i = 0, count = _meshSkins.size(); i < count; ++i)
  241. {
  242. SAFE_DELETE(_meshSkins[i]);
  243. }
  244. _meshSkins.clear();
  245. }
  246. const char* Bundle::getIdFromOffset() const
  247. {
  248. GP_ASSERT(_stream);
  249. return getIdFromOffset((unsigned int) _stream->position());
  250. }
  251. const char* Bundle::getIdFromOffset(unsigned int offset) const
  252. {
  253. // Search the ref table for the given offset.
  254. if (offset > 0)
  255. {
  256. GP_ASSERT(_references);
  257. for (unsigned int i = 0; i < _referenceCount; ++i)
  258. {
  259. if (_references[i].offset == offset && _references[i].id.length() > 0)
  260. {
  261. return _references[i].id.c_str();
  262. }
  263. }
  264. }
  265. return NULL;
  266. }
  267. const std::string& Bundle::getMaterialPath()
  268. {
  269. if (_materialPath.empty())
  270. {
  271. int pos = _path.find_last_of('.');
  272. if (pos > 2)
  273. {
  274. _materialPath = _path.substr(0, pos);
  275. _materialPath.append(".material");
  276. if (!FileSystem::fileExists(_materialPath.c_str()))
  277. {
  278. _materialPath.clear();
  279. }
  280. }
  281. }
  282. return _materialPath;
  283. }
  284. Bundle::Reference* Bundle::seekTo(const char* id, unsigned int type)
  285. {
  286. Reference* ref = find(id);
  287. if (ref == NULL)
  288. {
  289. GP_ERROR("No object with name '%s' in bundle '%s'.", id, _path.c_str());
  290. return NULL;
  291. }
  292. if (ref->type != type)
  293. {
  294. GP_ERROR("Object '%s' in bundle '%s' has type %d (expected type %d).", id, _path.c_str(), (int)ref->type, (int)type);
  295. return NULL;
  296. }
  297. // Seek to the offset of this object.
  298. GP_ASSERT(_stream);
  299. if (_stream->seek(ref->offset, SEEK_SET) == false)
  300. {
  301. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", id, _path.c_str());
  302. return NULL;
  303. }
  304. return ref;
  305. }
  306. Bundle::Reference* Bundle::seekToFirstType(unsigned int type)
  307. {
  308. GP_ASSERT(_references);
  309. GP_ASSERT(_stream);
  310. for (unsigned int i = 0; i < _referenceCount; ++i)
  311. {
  312. Reference* ref = &_references[i];
  313. if (ref->type == type)
  314. {
  315. // Found a match.
  316. if (_stream->seek(ref->offset, SEEK_SET) == false)
  317. {
  318. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  319. return NULL;
  320. }
  321. return ref;
  322. }
  323. }
  324. return NULL;
  325. }
  326. bool Bundle::read(unsigned int* ptr)
  327. {
  328. return _stream->read(ptr, sizeof(unsigned int), 1) == 1;
  329. }
  330. bool Bundle::read(unsigned char* ptr)
  331. {
  332. return _stream->read(ptr, sizeof(unsigned char), 1) == 1;
  333. }
  334. bool Bundle::read(float* ptr)
  335. {
  336. return _stream->read(ptr, sizeof(float), 1) == 1;
  337. }
  338. bool Bundle::readMatrix(float* m)
  339. {
  340. return _stream->read(m, sizeof(float), 16) == 16;
  341. }
  342. Scene* Bundle::loadScene(const char* id)
  343. {
  344. clearLoadSession();
  345. Reference* ref = NULL;
  346. if (id)
  347. {
  348. ref = seekTo(id, BUNDLE_TYPE_SCENE);
  349. if (!ref)
  350. {
  351. GP_ERROR("Failed to load scene with id '%s' from bundle.", id);
  352. return NULL;
  353. }
  354. }
  355. else
  356. {
  357. ref = seekToFirstType(BUNDLE_TYPE_SCENE);
  358. if (!ref)
  359. {
  360. GP_ERROR("Failed to load scene from bundle; bundle contains no scene objects.");
  361. return NULL;
  362. }
  363. }
  364. Scene* scene = Scene::create(getIdFromOffset());
  365. // Read the number of children.
  366. unsigned int childrenCount;
  367. if (!read(&childrenCount))
  368. {
  369. GP_ERROR("Failed to read the scene's number of children.");
  370. SAFE_RELEASE(scene);
  371. return NULL;
  372. }
  373. if (childrenCount > 0)
  374. {
  375. // Read each child directly into the scene.
  376. for (unsigned int i = 0; i < childrenCount; i++)
  377. {
  378. Node* node = readNode(scene, NULL);
  379. if (node)
  380. {
  381. scene->addNode(node);
  382. node->release(); // scene now owns node
  383. }
  384. }
  385. }
  386. // Read active camera.
  387. std::string xref = readString(_stream);
  388. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  389. {
  390. Node* node = scene->findNode(xref.c_str() + 1, true);
  391. GP_ASSERT(node);
  392. Camera* camera = node->getCamera();
  393. GP_ASSERT(camera);
  394. scene->setActiveCamera(camera);
  395. }
  396. // Read ambient color.
  397. float red, blue, green;
  398. if (!read(&red))
  399. {
  400. GP_ERROR("Failed to read red component of the scene's ambient color in bundle '%s'.", _path.c_str());
  401. SAFE_RELEASE(scene);
  402. return NULL;
  403. }
  404. if (!read(&green))
  405. {
  406. GP_ERROR("Failed to read green component of the scene's ambient color in bundle '%s'.", _path.c_str());
  407. SAFE_RELEASE(scene);
  408. return NULL;
  409. }
  410. if (!read(&blue))
  411. {
  412. GP_ERROR("Failed to read blue component of the scene's ambient color in bundle '%s'.", _path.c_str());
  413. SAFE_RELEASE(scene);
  414. return NULL;
  415. }
  416. scene->setAmbientColor(red, green, blue);
  417. // Parse animations.
  418. GP_ASSERT(_references);
  419. GP_ASSERT(_stream);
  420. for (unsigned int i = 0; i < _referenceCount; ++i)
  421. {
  422. Reference* ref = &_references[i];
  423. if (ref->type == BUNDLE_TYPE_ANIMATIONS)
  424. {
  425. // Found a match.
  426. if (_stream->seek(ref->offset, SEEK_SET) == false)
  427. {
  428. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  429. return NULL;
  430. }
  431. readAnimations(scene);
  432. }
  433. }
  434. resolveJointReferences(scene, NULL);
  435. return scene;
  436. }
  437. Node* Bundle::loadNode(const char* id)
  438. {
  439. return loadNode(id, NULL);
  440. }
  441. Node* Bundle::loadNode(const char* id, Scene* sceneContext)
  442. {
  443. GP_ASSERT(id);
  444. GP_ASSERT(_references);
  445. GP_ASSERT(_stream);
  446. clearLoadSession();
  447. // Load the node and any referenced joints with node tracking enabled.
  448. _trackedNodes = new std::map<std::string, Node*>();
  449. Node* node = loadNode(id, sceneContext, NULL);
  450. if (node)
  451. resolveJointReferences(sceneContext, node);
  452. // Load all animations targeting any nodes or mesh skins under this node's hierarchy.
  453. for (unsigned int i = 0; i < _referenceCount; i++)
  454. {
  455. Reference* ref = &_references[i];
  456. if (ref->type == BUNDLE_TYPE_ANIMATIONS)
  457. {
  458. if (_stream->seek(ref->offset, SEEK_SET) == false)
  459. {
  460. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  461. SAFE_DELETE(_trackedNodes);
  462. return NULL;
  463. }
  464. // Read the number of animations in this object.
  465. unsigned int animationCount;
  466. if (!read(&animationCount))
  467. {
  468. GP_ERROR("Failed to read the number of animations for object '%s'.", ref->id.c_str());
  469. SAFE_DELETE(_trackedNodes);
  470. return NULL;
  471. }
  472. for (unsigned int j = 0; j < animationCount; j++)
  473. {
  474. const std::string id = readString(_stream);
  475. // Read the number of animation channels in this animation.
  476. unsigned int animationChannelCount;
  477. if (!read(&animationChannelCount))
  478. {
  479. GP_ERROR("Failed to read the number of animation channels for animation '%s'.", "animationChannelCount", id.c_str());
  480. SAFE_DELETE(_trackedNodes);
  481. return NULL;
  482. }
  483. Animation* animation = NULL;
  484. for (unsigned int k = 0; k < animationChannelCount; k++)
  485. {
  486. // Read target id.
  487. std::string targetId = readString(_stream);
  488. if (targetId.empty())
  489. {
  490. GP_ERROR("Failed to read target id for animation '%s'.", id.c_str());
  491. SAFE_DELETE(_trackedNodes);
  492. return NULL;
  493. }
  494. // If the target is one of the loaded nodes/joints, then load the animation.
  495. std::map<std::string, Node*>::iterator iter = _trackedNodes->find(targetId);
  496. if (iter != _trackedNodes->end())
  497. {
  498. // Read target attribute.
  499. unsigned int targetAttribute;
  500. if (!read(&targetAttribute))
  501. {
  502. GP_ERROR("Failed to read target attribute for animation '%s'.", id.c_str());
  503. SAFE_DELETE(_trackedNodes);
  504. return NULL;
  505. }
  506. AnimationTarget* target = iter->second;
  507. if (!target)
  508. {
  509. GP_ERROR("Failed to read %s for %s: %s", "animation target", targetId.c_str(), id.c_str());
  510. SAFE_DELETE(_trackedNodes);
  511. return NULL;
  512. }
  513. animation = readAnimationChannelData(animation, id.c_str(), target, targetAttribute);
  514. }
  515. else
  516. {
  517. // Skip over the target attribute.
  518. unsigned int data;
  519. if (!read(&data))
  520. {
  521. GP_ERROR("Failed to skip over target attribute for animation '%s'.", id.c_str());
  522. SAFE_DELETE(_trackedNodes);
  523. return NULL;
  524. }
  525. // Skip the animation channel (passing a target attribute of
  526. // 0 causes the animation to not be created).
  527. readAnimationChannelData(NULL, id.c_str(), NULL, 0);
  528. }
  529. }
  530. }
  531. }
  532. }
  533. SAFE_DELETE(_trackedNodes);
  534. return node;
  535. }
  536. Node* Bundle::loadNode(const char* id, Scene* sceneContext, Node* nodeContext)
  537. {
  538. GP_ASSERT(id);
  539. Node* node = NULL;
  540. // Search the passed in loading contexts (scene/node) first to see
  541. // if we've already loaded this node during this load session.
  542. if (sceneContext)
  543. {
  544. node = sceneContext->findNode(id, true);
  545. if (node)
  546. node->addRef();
  547. }
  548. if (node == NULL && nodeContext)
  549. {
  550. node = nodeContext->findNode(id, true);
  551. if (node)
  552. node->addRef();
  553. }
  554. if (node == NULL)
  555. {
  556. // If not yet found, search the ref table and read.
  557. Reference* ref = seekTo(id, BUNDLE_TYPE_NODE);
  558. if (ref == NULL)
  559. {
  560. return NULL;
  561. }
  562. node = readNode(sceneContext, nodeContext);
  563. }
  564. return node;
  565. }
  566. bool Bundle::skipNode()
  567. {
  568. const char* id = getIdFromOffset();
  569. GP_ASSERT(id);
  570. GP_ASSERT(_stream);
  571. // Skip the node's type.
  572. unsigned int nodeType;
  573. if (!read(&nodeType))
  574. {
  575. GP_ERROR("Failed to skip node type for node '%s'.", id);
  576. return false;
  577. }
  578. // Skip over the node's transform and parent ID.
  579. if (_stream->seek(sizeof(float) * 16, SEEK_CUR) == false)
  580. {
  581. GP_ERROR("Failed to skip over node transform for node '%s'.", id);
  582. return false;
  583. }
  584. readString(_stream);
  585. // Skip over the node's children.
  586. unsigned int childrenCount;
  587. if (!read(&childrenCount))
  588. {
  589. GP_ERROR("Failed to skip over node's children count for node '%s'.", id);
  590. return false;
  591. }
  592. else if (childrenCount > 0)
  593. {
  594. for (unsigned int i = 0; i < childrenCount; i++)
  595. {
  596. if (!skipNode())
  597. return false;
  598. }
  599. }
  600. // Skip over the node's camera, light, and model attachments.
  601. Camera* camera = readCamera(); SAFE_RELEASE(camera);
  602. Light* light = readLight(); SAFE_RELEASE(light);
  603. Model* model = readModel(id); SAFE_RELEASE(model);
  604. return true;
  605. }
  606. Node* Bundle::readNode(Scene* sceneContext, Node* nodeContext)
  607. {
  608. const char* id = getIdFromOffset();
  609. GP_ASSERT(id);
  610. GP_ASSERT(_stream);
  611. // If we are tracking nodes and it's not in the set yet, add it.
  612. if (_trackedNodes)
  613. {
  614. std::map<std::string, Node*>::iterator iter = _trackedNodes->find(id);
  615. if (iter != _trackedNodes->end())
  616. {
  617. // Skip over this node since we previously read it
  618. if (!skipNode())
  619. return NULL;
  620. iter->second->addRef();
  621. return iter->second;
  622. }
  623. }
  624. // Read node type.
  625. unsigned int nodeType;
  626. if (!read(&nodeType))
  627. {
  628. GP_ERROR("Failed to read node type for node '%s'.", id);
  629. return NULL;
  630. }
  631. Node* node = NULL;
  632. switch (nodeType)
  633. {
  634. case Node::NODE:
  635. node = Node::create(id);
  636. break;
  637. case Node::JOINT:
  638. node = Joint::create(id);
  639. break;
  640. default:
  641. return NULL;
  642. }
  643. if (_trackedNodes)
  644. {
  645. // Add the new node to the list of tracked nodes
  646. _trackedNodes->insert(std::make_pair(id, node));
  647. }
  648. // If no loading context is set, set this node as the loading context.
  649. if (sceneContext == NULL && nodeContext == NULL)
  650. {
  651. nodeContext = node;
  652. }
  653. // Read transform.
  654. float transform[16];
  655. if (_stream->read(transform, sizeof(float), 16) != 16)
  656. {
  657. GP_ERROR("Failed to read transform for node '%s'.", id);
  658. SAFE_RELEASE(node);
  659. return NULL;
  660. }
  661. setTransform(transform, node);
  662. // Skip the parent ID.
  663. readString(_stream);
  664. // Read children.
  665. unsigned int childrenCount;
  666. if (!read(&childrenCount))
  667. {
  668. GP_ERROR("Failed to read children count for node '%s'.", id);
  669. SAFE_RELEASE(node);
  670. return NULL;
  671. }
  672. if (childrenCount > 0)
  673. {
  674. // Read each child.
  675. for (unsigned int i = 0; i < childrenCount; i++)
  676. {
  677. // Search the passed in loading contexts (scene/node) first to see
  678. // if we've already loaded this child node during this load session.
  679. Node* child = NULL;
  680. id = getIdFromOffset();
  681. GP_ASSERT(id);
  682. if (sceneContext)
  683. {
  684. child = sceneContext->findNode(id, true);
  685. }
  686. if (child == NULL && nodeContext)
  687. {
  688. child = nodeContext->findNode(id, true);
  689. }
  690. // If the child was already loaded, skip it, otherwise read it
  691. if (child)
  692. {
  693. skipNode();
  694. }
  695. else
  696. {
  697. child = readNode(sceneContext, nodeContext);
  698. }
  699. if (child)
  700. {
  701. node->addChild(child);
  702. child->release(); // 'node' now owns this child
  703. }
  704. }
  705. }
  706. // Read camera.
  707. Camera* camera = readCamera();
  708. if (camera)
  709. {
  710. node->setCamera(camera);
  711. SAFE_RELEASE(camera);
  712. }
  713. // Read light.
  714. Light* light = readLight();
  715. if (light)
  716. {
  717. node->setLight(light);
  718. SAFE_RELEASE(light);
  719. }
  720. // Read model.
  721. Model* model = readModel(node->getId());
  722. if (model)
  723. {
  724. node->setModel(model);
  725. SAFE_RELEASE(model);
  726. }
  727. return node;
  728. }
  729. Camera* Bundle::readCamera()
  730. {
  731. unsigned char cameraType;
  732. if (!read(&cameraType))
  733. {
  734. GP_ERROR("Failed to load camera type in bundle '%s'.", _path.c_str());
  735. return NULL;
  736. }
  737. // Check if there isn't a camera to load.
  738. if (cameraType == 0)
  739. {
  740. return NULL;
  741. }
  742. float aspectRatio;
  743. if (!read(&aspectRatio))
  744. {
  745. GP_ERROR("Failed to load camera aspect ratio in bundle '%s'.", _path.c_str());
  746. return NULL;
  747. }
  748. float nearPlane;
  749. if (!read(&nearPlane))
  750. {
  751. GP_ERROR("Failed to load camera near plane in bundle '%s'.", _path.c_str());
  752. return NULL;
  753. }
  754. float farPlane;
  755. if (!read(&farPlane))
  756. {
  757. GP_ERROR("Failed to load camera far plane in bundle '%s'.", _path.c_str());
  758. return NULL;
  759. }
  760. Camera* camera = NULL;
  761. if (cameraType == Camera::PERSPECTIVE)
  762. {
  763. float fieldOfView;
  764. if (!read(&fieldOfView))
  765. {
  766. GP_ERROR("Failed to load camera field of view in bundle '%s'.", _path.c_str());
  767. return NULL;
  768. }
  769. camera = Camera::createPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  770. }
  771. else if (cameraType == Camera::ORTHOGRAPHIC)
  772. {
  773. float zoomX;
  774. if (!read(&zoomX))
  775. {
  776. GP_ERROR("Failed to load camera zoomX in bundle '%s'.", _path.c_str());
  777. return NULL;
  778. }
  779. float zoomY;
  780. if (!read(&zoomY))
  781. {
  782. GP_ERROR("Failed to load camera zoomY in bundle '%s'.", _path.c_str());
  783. return NULL;
  784. }
  785. camera = Camera::createOrthographic(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
  786. }
  787. else
  788. {
  789. GP_ERROR("Unsupported camera type (%d) in bundle '%s'.", cameraType, _path.c_str());
  790. return NULL;
  791. }
  792. return camera;
  793. }
  794. Light* Bundle::readLight()
  795. {
  796. unsigned char type;
  797. if (!read(&type))
  798. {
  799. GP_ERROR("Failed to load light type in bundle '%s'.", _path.c_str());
  800. return NULL;
  801. }
  802. // Check if there isn't a light to load.
  803. if (type == 0)
  804. {
  805. return NULL;
  806. }
  807. // Read color.
  808. float red, blue, green;
  809. if (!read(&red) || !read(&blue) || !read(&green))
  810. {
  811. GP_ERROR("Failed to load light color in bundle '%s'.", _path.c_str());
  812. return NULL;
  813. }
  814. Vector3 color(red, blue, green);
  815. Light* light = NULL;
  816. if (type == Light::DIRECTIONAL)
  817. {
  818. light = Light::createDirectional(color);
  819. }
  820. else if (type == Light::POINT)
  821. {
  822. float range;
  823. if (!read(&range))
  824. {
  825. GP_ERROR("Failed to load point light range in bundle '%s'.", _path.c_str());
  826. return NULL;
  827. }
  828. light = Light::createPoint(color, range);
  829. }
  830. else if (type == Light::SPOT)
  831. {
  832. float range, innerAngle, outerAngle;
  833. if (!read(&range))
  834. {
  835. GP_ERROR("Failed to load spot light range in bundle '%s'.", _path.c_str());
  836. return NULL;
  837. }
  838. if (!read(&innerAngle))
  839. {
  840. GP_ERROR("Failed to load spot light inner angle in bundle '%s'.", _path.c_str());
  841. return NULL;
  842. }
  843. if (!read(&outerAngle))
  844. {
  845. GP_ERROR("Failed to load spot light outer angle in bundle '%s'.", _path.c_str());
  846. return NULL;
  847. }
  848. light = Light::createSpot(color, range, innerAngle, outerAngle);
  849. }
  850. else
  851. {
  852. GP_ERROR("Unsupported light type (%d) in bundle '%s'.", type, _path.c_str());
  853. return NULL;
  854. }
  855. return light;
  856. }
  857. Model* Bundle::readModel(const char* nodeId)
  858. {
  859. std::string xref = readString(_stream);
  860. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  861. {
  862. Mesh* mesh = loadMesh(xref.c_str() + 1, nodeId);
  863. if (mesh)
  864. {
  865. Model* model = Model::create(mesh);
  866. SAFE_RELEASE(mesh);
  867. // Read skin.
  868. unsigned char hasSkin;
  869. if (!read(&hasSkin))
  870. {
  871. GP_ERROR("Failed to load whether model with mesh '%s' has a mesh skin in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  872. return NULL;
  873. }
  874. if (hasSkin)
  875. {
  876. MeshSkin* skin = readMeshSkin();
  877. if (skin)
  878. {
  879. model->setSkin(skin);
  880. }
  881. }
  882. // Read material.
  883. unsigned int materialCount;
  884. if (!read(&materialCount))
  885. {
  886. GP_ERROR("Failed to load material count for model with mesh '%s' in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  887. return NULL;
  888. }
  889. if (materialCount > 0)
  890. {
  891. for (unsigned int i = 0; i < materialCount; ++i)
  892. {
  893. std::string materialName = readString(_stream);
  894. std::string materialPath = getMaterialPath();
  895. materialPath.append("#");
  896. materialPath.append(materialName);
  897. Material* material = Material::create(materialPath.c_str());
  898. if (material)
  899. {
  900. int partIndex = model->getMesh()->getPartCount() > 0 ? i : -1;
  901. model->setMaterial(material, partIndex);
  902. SAFE_RELEASE(material);
  903. }
  904. }
  905. }
  906. return model;
  907. }
  908. }
  909. return NULL;
  910. }
  911. MeshSkin* Bundle::readMeshSkin()
  912. {
  913. MeshSkin* meshSkin = new MeshSkin();
  914. // Read bindShape.
  915. float bindShape[16];
  916. if (!readMatrix(bindShape))
  917. {
  918. GP_ERROR("Failed to load bind shape for mesh skin in bundle '%s'.", _path.c_str());
  919. SAFE_DELETE(meshSkin);
  920. return NULL;
  921. }
  922. meshSkin->setBindShape(bindShape);
  923. MeshSkinData* skinData = new MeshSkinData();
  924. skinData->skin = meshSkin;
  925. // Read joint count.
  926. unsigned int jointCount;
  927. if (!read(&jointCount))
  928. {
  929. GP_ERROR("Failed to load joint count for mesh skin in bundle '%s'.", _path.c_str());
  930. SAFE_DELETE(meshSkin);
  931. SAFE_DELETE(skinData);
  932. return NULL;
  933. }
  934. if (jointCount == 0)
  935. {
  936. GP_ERROR("Invalid joint count (must be greater than 0) for mesh skin in bundle '%s'.", _path.c_str());
  937. SAFE_DELETE(meshSkin);
  938. SAFE_DELETE(skinData);
  939. return NULL;
  940. }
  941. meshSkin->setJointCount(jointCount);
  942. // Read joint xref strings for all joints in the list.
  943. for (unsigned int i = 0; i < jointCount; i++)
  944. {
  945. skinData->joints.push_back(readString(_stream));
  946. }
  947. // Read bind poses.
  948. unsigned int jointsBindPosesCount;
  949. if (!read(&jointsBindPosesCount))
  950. {
  951. GP_ERROR("Failed to load number of joint bind poses in bundle '%s'.", _path.c_str());
  952. SAFE_DELETE(meshSkin);
  953. SAFE_DELETE(skinData);
  954. return NULL;
  955. }
  956. if (jointsBindPosesCount > 0)
  957. {
  958. GP_ASSERT(jointCount * 16 == jointsBindPosesCount);
  959. float m[16];
  960. for (unsigned int i = 0; i < jointCount; i++)
  961. {
  962. if (!readMatrix(m))
  963. {
  964. GP_ERROR("Failed to load joint bind pose matrix (for joint with index %d) in bundle '%s'.", i, _path.c_str());
  965. SAFE_DELETE(meshSkin);
  966. SAFE_DELETE(skinData);
  967. return NULL;
  968. }
  969. skinData->inverseBindPoseMatrices.push_back(m);
  970. }
  971. }
  972. // Store the MeshSkinData so we can go back and resolve all joint references later.
  973. _meshSkins.push_back(skinData);
  974. return meshSkin;
  975. }
  976. void Bundle::resolveJointReferences(Scene* sceneContext, Node* nodeContext)
  977. {
  978. GP_ASSERT(_stream);
  979. for (size_t i = 0, skinCount = _meshSkins.size(); i < skinCount; ++i)
  980. {
  981. MeshSkinData* skinData = _meshSkins[i];
  982. GP_ASSERT(skinData);
  983. GP_ASSERT(skinData->skin);
  984. // Resolve all joints in skin joint list.
  985. size_t jointCount = skinData->joints.size();
  986. for (size_t j = 0; j < jointCount; ++j)
  987. {
  988. // TODO: Handle full xrefs (not just local # xrefs).
  989. std::string jointId = skinData->joints[j];
  990. if (jointId.length() > 1 && jointId[0] == '#')
  991. {
  992. jointId = jointId.substr(1, jointId.length() - 1);
  993. Node* n = loadNode(jointId.c_str(), sceneContext, nodeContext);
  994. if (n && n->getType() == Node::JOINT)
  995. {
  996. Joint* joint = static_cast<Joint*>(n);
  997. joint->setInverseBindPose(skinData->inverseBindPoseMatrices[j]);
  998. skinData->skin->setJoint(joint, (unsigned int)j);
  999. SAFE_RELEASE(joint);
  1000. }
  1001. }
  1002. }
  1003. // Set the root joint.
  1004. if (jointCount > 0)
  1005. {
  1006. Joint* rootJoint = skinData->skin->getJoint((unsigned int)0);
  1007. Node* node = rootJoint;
  1008. GP_ASSERT(node);
  1009. Node* parent = node->getParent();
  1010. std::vector<Node*> loadedNodes;
  1011. while (true)
  1012. {
  1013. if (parent)
  1014. {
  1015. if (skinData->skin->getJointIndex(static_cast<Joint*>(parent)) != -1)
  1016. {
  1017. // Parent is a joint in the MeshSkin, so treat it as the new root.
  1018. rootJoint = static_cast<Joint*>(parent);
  1019. }
  1020. node = parent;
  1021. parent = node->getParent();
  1022. }
  1023. else
  1024. {
  1025. // No parent currently set for this joint.
  1026. // Lookup its parentID in case it references a node that was not yet loaded as part
  1027. // of the mesh skin's joint list.
  1028. std::string nodeId = node->getId();
  1029. while (true)
  1030. {
  1031. // Get the node's type.
  1032. Reference* ref = find(nodeId.c_str());
  1033. if (ref == NULL)
  1034. {
  1035. GP_ERROR("No object with name '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1036. return;
  1037. }
  1038. // Seek to the current node in the file so we can get it's parent ID.
  1039. seekTo(nodeId.c_str(), ref->type);
  1040. // Skip over the node type (1 unsigned int) and transform (16 floats) and read the parent id.
  1041. if (_stream->seek(sizeof(unsigned int) + sizeof(float)*16, SEEK_CUR) == false)
  1042. {
  1043. GP_ERROR("Failed to skip over node type and transform for node '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1044. return;
  1045. }
  1046. std::string parentID = readString(_stream);
  1047. if (!parentID.empty())
  1048. nodeId = parentID;
  1049. else
  1050. break;
  1051. }
  1052. if (nodeId != rootJoint->getId())
  1053. loadedNodes.push_back(loadNode(nodeId.c_str(), sceneContext, nodeContext));
  1054. break;
  1055. }
  1056. }
  1057. skinData->skin->setRootJoint(rootJoint);
  1058. // Release all the nodes that we loaded since the nodes are now owned by the mesh skin/joints.
  1059. for (unsigned int i = 0; i < loadedNodes.size(); i++)
  1060. {
  1061. SAFE_RELEASE(loadedNodes[i]);
  1062. }
  1063. }
  1064. // Remove the joint hierarchy from the scene since it is owned by the mesh skin.
  1065. if (sceneContext)
  1066. sceneContext->removeNode(skinData->skin->_rootNode);
  1067. // Done with this MeshSkinData entry.
  1068. SAFE_DELETE(_meshSkins[i]);
  1069. }
  1070. _meshSkins.clear();
  1071. }
  1072. void Bundle::readAnimation(Scene* scene)
  1073. {
  1074. const std::string animationId = readString(_stream);
  1075. // Read the number of animation channels in this animation.
  1076. unsigned int animationChannelCount;
  1077. if (!read(&animationChannelCount))
  1078. {
  1079. GP_ERROR("Failed to read animation channel count for animation '%s'.", animationId.c_str());
  1080. return;
  1081. }
  1082. Animation* animation = NULL;
  1083. for (unsigned int i = 0; i < animationChannelCount; i++)
  1084. {
  1085. animation = readAnimationChannel(scene, animation, animationId.c_str());
  1086. }
  1087. }
  1088. void Bundle::readAnimations(Scene* scene)
  1089. {
  1090. // Read the number of animations in this object.
  1091. unsigned int animationCount;
  1092. if (!read(&animationCount))
  1093. {
  1094. GP_ERROR("Failed to read the number of animations in the scene.");
  1095. return;
  1096. }
  1097. for (unsigned int i = 0; i < animationCount; i++)
  1098. {
  1099. readAnimation(scene);
  1100. }
  1101. }
  1102. Animation* Bundle::readAnimationChannel(Scene* scene, Animation* animation, const char* animationId)
  1103. {
  1104. GP_ASSERT(animationId);
  1105. // Read target id.
  1106. std::string targetId = readString(_stream);
  1107. if (targetId.empty())
  1108. {
  1109. GP_ERROR("Failed to read target id for animation '%s'.", animationId);
  1110. return NULL;
  1111. }
  1112. // Read target attribute.
  1113. unsigned int targetAttribute;
  1114. if (!read(&targetAttribute))
  1115. {
  1116. GP_ERROR("Failed to read target attribute for animation '%s'.", animationId);
  1117. return NULL;
  1118. }
  1119. AnimationTarget* target = NULL;
  1120. // Search for a node that matches the target.
  1121. if (!target)
  1122. {
  1123. target = scene->findNode(targetId.c_str());
  1124. if (!target)
  1125. {
  1126. GP_ERROR("Failed to find the animation target (with id '%s') for animation '%s'.", targetId.c_str(), animationId);
  1127. return NULL;
  1128. }
  1129. }
  1130. return readAnimationChannelData(animation, animationId, target, targetAttribute);
  1131. }
  1132. Animation* Bundle::readAnimationChannelData(Animation* animation, const char* id, AnimationTarget* target, unsigned int targetAttribute)
  1133. {
  1134. GP_ASSERT(id);
  1135. std::vector<unsigned int> keyTimes;
  1136. std::vector<float> values;
  1137. std::vector<float> tangentsIn;
  1138. std::vector<float> tangentsOut;
  1139. std::vector<unsigned int> interpolation;
  1140. // Length of the arrays.
  1141. unsigned int keyTimesCount;
  1142. unsigned int valuesCount;
  1143. unsigned int tangentsInCount;
  1144. unsigned int tangentsOutCount;
  1145. unsigned int interpolationCount;
  1146. // Read key times.
  1147. if (!readArray(&keyTimesCount, &keyTimes, sizeof(unsigned int)))
  1148. {
  1149. GP_ERROR("Failed to read key times for animation '%s'.", id);
  1150. return NULL;
  1151. }
  1152. // Read key values.
  1153. if (!readArray(&valuesCount, &values))
  1154. {
  1155. GP_ERROR("Failed to read key values for animation '%s'.", id);
  1156. return NULL;
  1157. }
  1158. // Read in-tangents.
  1159. if (!readArray(&tangentsInCount, &tangentsIn))
  1160. {
  1161. GP_ERROR("Failed to read in tangents for animation '%s'.", id);
  1162. return NULL;
  1163. }
  1164. // Read out-tangents.
  1165. if (!readArray(&tangentsOutCount, &tangentsOut))
  1166. {
  1167. GP_ERROR("Failed to read out tangents for animation '%s'.", id);
  1168. return NULL;
  1169. }
  1170. // Read interpolations.
  1171. if (!readArray(&interpolationCount, &interpolation, sizeof(unsigned int)))
  1172. {
  1173. GP_ERROR("Failed to read the interpolation values for animation '%s'.", id);
  1174. return NULL;
  1175. }
  1176. if (targetAttribute > 0)
  1177. {
  1178. GP_ASSERT(target);
  1179. GP_ASSERT(keyTimes.size() > 0 && values.size() > 0);
  1180. if (animation == NULL)
  1181. {
  1182. // TODO: This code currently assumes LINEAR only.
  1183. animation = target->createAnimation(id, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1184. }
  1185. else
  1186. {
  1187. animation->createChannel(target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1188. }
  1189. }
  1190. return animation;
  1191. }
  1192. Mesh* Bundle::loadMesh(const char* id)
  1193. {
  1194. return loadMesh(id, NULL);
  1195. }
  1196. Mesh* Bundle::loadMesh(const char* id, const char* nodeId)
  1197. {
  1198. GP_ASSERT(_stream);
  1199. GP_ASSERT(id);
  1200. // Save the file position.
  1201. long position = _stream->position();
  1202. if (position == -1L)
  1203. {
  1204. GP_ERROR("Failed to save the current file position before loading mesh '%s'.", id);
  1205. return NULL;
  1206. }
  1207. // Seek to the specified mesh.
  1208. Reference* ref = seekTo(id, BUNDLE_TYPE_MESH);
  1209. if (ref == NULL)
  1210. {
  1211. GP_ERROR("Failed to locate ref for mesh '%s'.", id);
  1212. return NULL;
  1213. }
  1214. // Read mesh data.
  1215. MeshData* meshData = readMeshData();
  1216. if (meshData == NULL)
  1217. {
  1218. GP_ERROR("Failed to load mesh data for mesh '%s'.", id);
  1219. return NULL;
  1220. }
  1221. // Create mesh.
  1222. Mesh* mesh = Mesh::createMesh(meshData->vertexFormat, meshData->vertexCount, false);
  1223. if (mesh == NULL)
  1224. {
  1225. GP_ERROR("Failed to create mesh '%s'.", id);
  1226. SAFE_DELETE_ARRAY(meshData);
  1227. return NULL;
  1228. }
  1229. mesh->_url = _path;
  1230. mesh->_url += "#";
  1231. mesh->_url += id;
  1232. mesh->setVertexData((float*)meshData->vertexData, 0, meshData->vertexCount);
  1233. mesh->_boundingBox.set(meshData->boundingBox);
  1234. mesh->_boundingSphere.set(meshData->boundingSphere);
  1235. // Create mesh parts.
  1236. for (unsigned int i = 0; i < meshData->parts.size(); ++i)
  1237. {
  1238. MeshPartData* partData = meshData->parts[i];
  1239. GP_ASSERT(partData);
  1240. MeshPart* part = mesh->addPart(partData->primitiveType, partData->indexFormat, partData->indexCount, false);
  1241. if (part == NULL)
  1242. {
  1243. GP_ERROR("Failed to create mesh part (with index %d) for mesh '%s'.", i, id);
  1244. SAFE_DELETE(meshData);
  1245. return NULL;
  1246. }
  1247. part->setIndexData(partData->indexData, 0, partData->indexCount);
  1248. }
  1249. SAFE_DELETE(meshData);
  1250. // Restore file pointer.
  1251. if (_stream->seek(position, SEEK_SET) == false)
  1252. {
  1253. GP_ERROR("Failed to restore file pointer after loading mesh '%s'.", id);
  1254. return NULL;
  1255. }
  1256. return mesh;
  1257. }
  1258. Bundle::MeshData* Bundle::readMeshData()
  1259. {
  1260. // Read vertex format/elements.
  1261. unsigned int vertexElementCount;
  1262. if (_stream->read(&vertexElementCount, 4, 1) != 1)
  1263. {
  1264. GP_ERROR("Failed to load vertex element count.");
  1265. return NULL;
  1266. }
  1267. if (vertexElementCount < 1)
  1268. {
  1269. GP_ERROR("Failed to load mesh data; invalid vertex element count (must be greater than 0).");
  1270. return NULL;
  1271. }
  1272. VertexFormat::Element* vertexElements = new VertexFormat::Element[vertexElementCount];
  1273. for (unsigned int i = 0; i < vertexElementCount; ++i)
  1274. {
  1275. unsigned int vUsage, vSize;
  1276. if (_stream->read(&vUsage, 4, 1) != 1)
  1277. {
  1278. GP_ERROR("Failed to load vertex usage.");
  1279. SAFE_DELETE_ARRAY(vertexElements);
  1280. return NULL;
  1281. }
  1282. if (_stream->read(&vSize, 4, 1) != 1)
  1283. {
  1284. GP_ERROR("Failed to load vertex size.");
  1285. SAFE_DELETE_ARRAY(vertexElements);
  1286. return NULL;
  1287. }
  1288. vertexElements[i].usage = (VertexFormat::Usage)vUsage;
  1289. vertexElements[i].size = vSize;
  1290. }
  1291. MeshData* meshData = new MeshData(VertexFormat(vertexElements, vertexElementCount));
  1292. SAFE_DELETE_ARRAY(vertexElements);
  1293. // Read vertex data.
  1294. unsigned int vertexByteCount;
  1295. if (_stream->read(&vertexByteCount, 4, 1) != 1)
  1296. {
  1297. GP_ERROR("Failed to load vertex byte count.");
  1298. SAFE_DELETE(meshData);
  1299. return NULL;
  1300. }
  1301. if (vertexByteCount == 0)
  1302. {
  1303. GP_ERROR("Failed to load mesh data; invalid vertex byte count of 0.");
  1304. SAFE_DELETE(meshData);
  1305. return NULL;
  1306. }
  1307. GP_ASSERT(meshData->vertexFormat.getVertexSize());
  1308. meshData->vertexCount = vertexByteCount / meshData->vertexFormat.getVertexSize();
  1309. meshData->vertexData = new unsigned char[vertexByteCount];
  1310. if (_stream->read(meshData->vertexData, 1, vertexByteCount) != vertexByteCount)
  1311. {
  1312. GP_ERROR("Failed to load vertex data.");
  1313. SAFE_DELETE(meshData);
  1314. return NULL;
  1315. }
  1316. // Read mesh bounds (bounding box and bounding sphere).
  1317. if (_stream->read(&meshData->boundingBox.min.x, 4, 3) != 3 || _stream->read(&meshData->boundingBox.max.x, 4, 3) != 3)
  1318. {
  1319. GP_ERROR("Failed to load mesh bounding box.");
  1320. SAFE_DELETE(meshData);
  1321. return NULL;
  1322. }
  1323. if (_stream->read(&meshData->boundingSphere.center.x, 4, 3) != 3 || _stream->read(&meshData->boundingSphere.radius, 4, 1) != 1)
  1324. {
  1325. GP_ERROR("Failed to load mesh bounding sphere.");
  1326. SAFE_DELETE(meshData);
  1327. return NULL;
  1328. }
  1329. // Read mesh parts.
  1330. unsigned int meshPartCount;
  1331. if (_stream->read(&meshPartCount, 4, 1) != 1)
  1332. {
  1333. GP_ERROR("Failed to load mesh part count.");
  1334. SAFE_DELETE(meshData);
  1335. return NULL;
  1336. }
  1337. for (unsigned int i = 0; i < meshPartCount; ++i)
  1338. {
  1339. // Read primitive type, index format and index count.
  1340. unsigned int pType, iFormat, iByteCount;
  1341. if (_stream->read(&pType, 4, 1) != 1)
  1342. {
  1343. GP_ERROR("Failed to load primitive type for mesh part with index %d.", i);
  1344. SAFE_DELETE(meshData);
  1345. return NULL;
  1346. }
  1347. if (_stream->read(&iFormat, 4, 1) != 1)
  1348. {
  1349. GP_ERROR("Failed to load index format for mesh part with index %d.", i);
  1350. SAFE_DELETE(meshData);
  1351. return NULL;
  1352. }
  1353. if (_stream->read(&iByteCount, 4, 1) != 1)
  1354. {
  1355. GP_ERROR("Failed to load index byte count for mesh part with index %d.", i);
  1356. SAFE_DELETE(meshData);
  1357. return NULL;
  1358. }
  1359. MeshPartData* partData = new MeshPartData();
  1360. meshData->parts.push_back(partData);
  1361. partData->primitiveType = (Mesh::PrimitiveType)pType;
  1362. partData->indexFormat = (Mesh::IndexFormat)iFormat;
  1363. unsigned int indexSize = 0;
  1364. switch (partData->indexFormat)
  1365. {
  1366. case Mesh::INDEX8:
  1367. indexSize = 1;
  1368. break;
  1369. case Mesh::INDEX16:
  1370. indexSize = 2;
  1371. break;
  1372. case Mesh::INDEX32:
  1373. indexSize = 4;
  1374. break;
  1375. default:
  1376. GP_ERROR("Unsupported index format for mesh part with index %d.", i);
  1377. return NULL;
  1378. }
  1379. GP_ASSERT(indexSize);
  1380. partData->indexCount = iByteCount / indexSize;
  1381. partData->indexData = new unsigned char[iByteCount];
  1382. if (_stream->read(partData->indexData, 1, iByteCount) != iByteCount)
  1383. {
  1384. GP_ERROR("Failed to read index data for mesh part with index %d.", i);
  1385. SAFE_DELETE(meshData);
  1386. return NULL;
  1387. }
  1388. }
  1389. return meshData;
  1390. }
  1391. Bundle::MeshData* Bundle::readMeshData(const char* url)
  1392. {
  1393. GP_ASSERT(url);
  1394. size_t len = strlen(url);
  1395. if (len == 0)
  1396. {
  1397. GP_ERROR("Mesh data URL must be non-empty.");
  1398. return NULL;
  1399. }
  1400. // Parse URL (formatted as 'bundle#id').
  1401. std::string urlstring(url);
  1402. size_t pos = urlstring.find('#');
  1403. if (pos == std::string::npos)
  1404. {
  1405. GP_ERROR("Invalid mesh data URL '%s' (must be of the form 'bundle#id').", url);
  1406. return NULL;
  1407. }
  1408. std::string file = urlstring.substr(0, pos);
  1409. std::string id = urlstring.substr(pos + 1);
  1410. // Load bundle.
  1411. Bundle* bundle = Bundle::create(file.c_str());
  1412. if (bundle == NULL)
  1413. {
  1414. GP_ERROR("Failed to load bundle '%s'.", file.c_str());
  1415. return NULL;
  1416. }
  1417. // Seek to mesh with specified ID in bundle.
  1418. Reference* ref = bundle->seekTo(id.c_str(), BUNDLE_TYPE_MESH);
  1419. if (ref == NULL)
  1420. {
  1421. GP_ERROR("Failed to load ref from bundle '%s' for mesh with id '%s'.", file.c_str(), id.c_str());
  1422. return NULL;
  1423. }
  1424. // Read mesh data from current file position.
  1425. MeshData* meshData = bundle->readMeshData();
  1426. SAFE_RELEASE(bundle);
  1427. return meshData;
  1428. }
  1429. Font* Bundle::loadFont(const char* id)
  1430. {
  1431. GP_ASSERT(id);
  1432. GP_ASSERT(_stream);
  1433. // Seek to the specified font.
  1434. Reference* ref = seekTo(id, BUNDLE_TYPE_FONT);
  1435. if (ref == NULL)
  1436. {
  1437. GP_ERROR("Failed to load ref for font '%s'.", id);
  1438. return NULL;
  1439. }
  1440. // Read font family.
  1441. std::string family = readString(_stream);
  1442. if (family.empty())
  1443. {
  1444. GP_ERROR("Failed to read font family for font '%s'.", id);
  1445. return NULL;
  1446. }
  1447. // Read font style and size.
  1448. unsigned int style, size;
  1449. if (_stream->read(&style, 4, 1) != 1)
  1450. {
  1451. GP_ERROR("Failed to read style for font '%s'.", id);
  1452. return NULL;
  1453. }
  1454. if (_stream->read(&size, 4, 1) != 1)
  1455. {
  1456. GP_ERROR("Failed to read size for font '%s'.", id);
  1457. return NULL;
  1458. }
  1459. // Read character set.
  1460. std::string charset = readString(_stream);
  1461. // Read font glyphs.
  1462. unsigned int glyphCount;
  1463. if (_stream->read(&glyphCount, 4, 1) != 1)
  1464. {
  1465. GP_ERROR("Failed to read glyph count for font '%s'.", id);
  1466. return NULL;
  1467. }
  1468. if (glyphCount == 0)
  1469. {
  1470. GP_ERROR("Invalid glyph count (must be greater than 0) for font '%s'.", id);
  1471. return NULL;
  1472. }
  1473. Font::Glyph* glyphs = new Font::Glyph[glyphCount];
  1474. if (_stream->read(glyphs, sizeof(Font::Glyph), glyphCount) != glyphCount)
  1475. {
  1476. GP_ERROR("Failed to read glyphs for font '%s'.", id);
  1477. SAFE_DELETE_ARRAY(glyphs);
  1478. return NULL;
  1479. }
  1480. // Read texture attributes.
  1481. unsigned int width, height, textureByteCount;
  1482. if (_stream->read(&width, 4, 1) != 1)
  1483. {
  1484. GP_ERROR("Failed to read texture width for font '%s'.", id);
  1485. SAFE_DELETE_ARRAY(glyphs);
  1486. return NULL;
  1487. }
  1488. if (_stream->read(&height, 4, 1) != 1)
  1489. {
  1490. GP_ERROR("Failed to read texture height for font '%s'.", id);
  1491. SAFE_DELETE_ARRAY(glyphs);
  1492. return NULL;
  1493. }
  1494. if (_stream->read(&textureByteCount, 4, 1) != 1)
  1495. {
  1496. GP_ERROR("Failed to read texture byte count for font '%s'.", id);
  1497. SAFE_DELETE_ARRAY(glyphs);
  1498. return NULL;
  1499. }
  1500. if (textureByteCount != (width * height))
  1501. {
  1502. GP_ERROR("Invalid texture byte count for font '%s'.", id);
  1503. SAFE_DELETE_ARRAY(glyphs);
  1504. return NULL;
  1505. }
  1506. // Read texture data.
  1507. unsigned char* textureData = new unsigned char[textureByteCount];
  1508. if (_stream->read(textureData, 1, textureByteCount) != textureByteCount)
  1509. {
  1510. GP_ERROR("Failed to read texture data for font '%s'.", id);
  1511. SAFE_DELETE_ARRAY(glyphs);
  1512. SAFE_DELETE_ARRAY(textureData);
  1513. return NULL;
  1514. }
  1515. unsigned int format = Font::BITMAP;
  1516. // After bundle version we add enum FontFormat to bundle format
  1517. if (getVersionMajor() >= BUNDLE_VERSION_MAJOR_FONT_FORMAT &&
  1518. getVersionMinor() >= BUNDLE_VERSION_MINOR_FONT_FORMAT)
  1519. {
  1520. if (_stream->read(&format, 4, 1) != 1)
  1521. {
  1522. GP_ERROR("Failed to font format'%u'.", format);
  1523. SAFE_DELETE_ARRAY(glyphs);
  1524. SAFE_DELETE_ARRAY(textureData);
  1525. return NULL;
  1526. }
  1527. }
  1528. // Create the texture for the font.
  1529. Texture* texture = Texture::create(Texture::ALPHA, width, height, textureData, true);
  1530. // Free the texture data (no longer needed).
  1531. SAFE_DELETE_ARRAY(textureData);
  1532. if (texture == NULL)
  1533. {
  1534. GP_ERROR("Failed to create texture for font '%s'.", id);
  1535. SAFE_DELETE_ARRAY(glyphs);
  1536. return NULL;
  1537. }
  1538. // Create the font.
  1539. Font* font = Font::create(family.c_str(), Font::PLAIN, size, glyphs, glyphCount, texture, (Font::Format)format);
  1540. // Free the glyph array.
  1541. SAFE_DELETE_ARRAY(glyphs);
  1542. // Release the texture since the Font now owns it.
  1543. SAFE_RELEASE(texture);
  1544. if (font)
  1545. {
  1546. font->_path = _path;
  1547. font->_id = id;
  1548. }
  1549. return font;
  1550. }
  1551. void Bundle::setTransform(const float* values, Transform* transform)
  1552. {
  1553. GP_ASSERT(transform);
  1554. // Load array into transform.
  1555. Matrix matrix(values);
  1556. Vector3 scale, translation;
  1557. Quaternion rotation;
  1558. matrix.decompose(&scale, &rotation, &translation);
  1559. transform->setScale(scale);
  1560. transform->setTranslation(translation);
  1561. transform->setRotation(rotation);
  1562. }
  1563. bool Bundle::contains(const char* id) const
  1564. {
  1565. return (find(id) != NULL);
  1566. }
  1567. unsigned int Bundle::getObjectCount() const
  1568. {
  1569. return _referenceCount;
  1570. }
  1571. const char* Bundle::getObjectId(unsigned int index) const
  1572. {
  1573. GP_ASSERT(_references);
  1574. return (index >= _referenceCount ? NULL : _references[index].id.c_str());
  1575. }
  1576. Bundle::Reference::Reference()
  1577. : type(0), offset(0)
  1578. {
  1579. }
  1580. Bundle::Reference::~Reference()
  1581. {
  1582. }
  1583. Bundle::MeshPartData::MeshPartData() :
  1584. indexCount(0), indexData(NULL)
  1585. {
  1586. }
  1587. Bundle::MeshPartData::~MeshPartData()
  1588. {
  1589. SAFE_DELETE_ARRAY(indexData);
  1590. }
  1591. Bundle::MeshData::MeshData(const VertexFormat& vertexFormat)
  1592. : vertexFormat(vertexFormat), vertexCount(0), vertexData(NULL)
  1593. {
  1594. }
  1595. Bundle::MeshData::~MeshData()
  1596. {
  1597. SAFE_DELETE_ARRAY(vertexData);
  1598. for (unsigned int i = 0; i < parts.size(); ++i)
  1599. {
  1600. SAFE_DELETE(parts[i]);
  1601. }
  1602. }
  1603. }