Package.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. #include "Base.h"
  2. #include "Package.h"
  3. #include "FileSystem.h"
  4. #include "MeshPart.h"
  5. #include "Scene.h"
  6. #include "SceneLoader.h"
  7. #include "Joint.h"
  8. #define GPB_PACKAGE_VERSION_MAJOR 1
  9. #define GPB_PACKAGE_VERSION_MINOR 1
  10. #define PACKAGE_TYPE_SCENE 1
  11. #define PACKAGE_TYPE_NODE 2
  12. #define PACKAGE_TYPE_ANIMATIONS 3
  13. #define PACKAGE_TYPE_ANIMATION 4
  14. #define PACKAGE_TYPE_ANIMATION_CHANNEL 5
  15. #define PACKAGE_TYPE_MMODEL 10
  16. #define PACKAGE_TYPE_MATERIAL 16
  17. #define PACKAGE_TYPE_EFFECT 18
  18. #define PACKAGE_TYPE_CAMERA 32
  19. #define PACKAGE_TYPE_LIGHT 33
  20. #define PACKAGE_TYPE_MESH 34
  21. #define PACKAGE_TYPE_MESHPART 35
  22. #define PACKAGE_TYPE_MESHSKIN 36
  23. #define PACKAGE_TYPE_FONT 128
  24. // For sanity checking string reads
  25. #define PACKAGE_MAX_STRING_LENGTH 5000
  26. namespace gameplay
  27. {
  28. static std::vector<Package*> __packageCache;
  29. Package::Package(const char* path) :
  30. _path(path), _referenceCount(0), _references(NULL), _file(NULL)
  31. {
  32. }
  33. Package::~Package()
  34. {
  35. clearLoadSession();
  36. // Remove this Package from the cache
  37. std::vector<Package*>::iterator itr = std::find(__packageCache.begin(), __packageCache.end(), this);
  38. if (itr != __packageCache.end())
  39. {
  40. __packageCache.erase(itr);
  41. }
  42. SAFE_DELETE_ARRAY(_references);
  43. if (_file)
  44. {
  45. fclose(_file);
  46. _file = NULL;
  47. }
  48. }
  49. template <class T>
  50. bool Package::readArray(unsigned int* length, T** ptr)
  51. {
  52. if (!read(length))
  53. {
  54. return false;
  55. }
  56. if (*length > 0)
  57. {
  58. *ptr = new T[*length];
  59. if (fread(*ptr, sizeof(T), *length, _file) != *length)
  60. {
  61. SAFE_DELETE_ARRAY(*ptr);
  62. return false;
  63. }
  64. }
  65. return true;
  66. }
  67. template <class T>
  68. bool Package::readArray(unsigned int* length, std::vector<T>* values)
  69. {
  70. if (!read(length))
  71. {
  72. return false;
  73. }
  74. if (*length > 0 && values)
  75. {
  76. values->resize(*length);
  77. if (fread(&(*values)[0], sizeof(T), *length, _file) != *length)
  78. {
  79. return false;
  80. }
  81. }
  82. return true;
  83. }
  84. std::string readString(FILE* fp)
  85. {
  86. unsigned int length;
  87. if (fread(&length, 4, 1, fp) != 1)
  88. {
  89. return std::string();
  90. }
  91. // Sanity check to detect if string length is far too big
  92. assert(length < PACKAGE_MAX_STRING_LENGTH);
  93. std::string str;
  94. if (length > 0)
  95. {
  96. str.resize(length);
  97. if (fread(&str[0], 1, length, fp) != length)
  98. {
  99. return std::string();
  100. }
  101. }
  102. return str;
  103. }
  104. Package* Package::create(const char* path)
  105. {
  106. // Search the cache for this package
  107. for (unsigned int i = 0, count = __packageCache.size(); i < count; ++i)
  108. {
  109. Package* p = __packageCache[i];
  110. if (p->_path == path)
  111. {
  112. // Found a match
  113. p->addRef();
  114. return p;
  115. }
  116. }
  117. // Open the package
  118. FILE* fp = FileSystem::openFile(path, "rb");
  119. if (!fp)
  120. {
  121. WARN_VARG("Failed to open file: '%s'.", path);
  122. return NULL;
  123. }
  124. // Read the GPG header info
  125. char sig[9];
  126. if (fread(sig, 1, 9, fp) != 9 || memcmp(sig, "«GPB»\r\n\x1A\n", 9) != 0)
  127. {
  128. LOG_ERROR_VARG("Invalid package header: %s", path);
  129. fclose(fp);
  130. return NULL;
  131. }
  132. // Read version
  133. unsigned char ver[2];
  134. if (fread(ver, 1, 2, fp) != 2 || ver[0] != GPB_PACKAGE_VERSION_MAJOR || ver[1] != GPB_PACKAGE_VERSION_MINOR)
  135. {
  136. LOG_ERROR_VARG("Unsupported version (%d.%d) for package: %s (expected %d.%d)", (int)ver[0], (int)ver[1], path, GPB_PACKAGE_VERSION_MAJOR, GPB_PACKAGE_VERSION_MINOR);
  137. fclose(fp);
  138. return NULL;
  139. }
  140. // Read ref table
  141. unsigned int refCount;
  142. if (fread(&refCount, 4, 1, fp) != 1)
  143. {
  144. fclose(fp);
  145. return NULL;
  146. }
  147. // Read all refs
  148. Reference* refs = new Reference[refCount];
  149. for (unsigned int i = 0; i < refCount; ++i)
  150. {
  151. if ((refs[i].id = readString(fp)).empty() ||
  152. fread(&refs[i].type, 4, 1, fp) != 1 ||
  153. fread(&refs[i].offset, 4, 1, fp) != 1)
  154. {
  155. fclose(fp);
  156. SAFE_DELETE_ARRAY(refs);
  157. return NULL;
  158. }
  159. }
  160. // Keep file open for faster reading later
  161. Package* pkg = new Package(path);
  162. pkg->_referenceCount = refCount;
  163. pkg->_references = refs;
  164. pkg->_file = fp;
  165. return pkg;
  166. }
  167. Package::Reference* Package::find(const char* id) const
  168. {
  169. // Search the ref table for the given id (case-sensitive)
  170. for (unsigned int i = 0; i < _referenceCount; ++i)
  171. {
  172. if (_references[i].id == id)
  173. {
  174. // Found a match
  175. return &_references[i];
  176. }
  177. }
  178. return NULL;
  179. }
  180. void Package::clearLoadSession()
  181. {
  182. for (unsigned int i = 0, count = _meshSkins.size(); i < count; ++i)
  183. {
  184. SAFE_DELETE(_meshSkins[i]);
  185. }
  186. _meshSkins.clear();
  187. }
  188. const char* Package::getIdFromOffset() const
  189. {
  190. return getIdFromOffset((unsigned int) ftell(_file));
  191. }
  192. const char* Package::getIdFromOffset(unsigned int offset) const
  193. {
  194. // Search the ref table for the given offset
  195. if (offset > 0)
  196. {
  197. for (unsigned int i = 0; i < _referenceCount; ++i)
  198. {
  199. if (_references[i].offset == offset && _references[i].id.length() > 0)
  200. {
  201. return _references[i].id.c_str();
  202. }
  203. }
  204. }
  205. return NULL;
  206. }
  207. Package::Reference* Package::seekTo(const char* id, unsigned int type)
  208. {
  209. Reference* ref = find(id);
  210. if (ref == NULL)
  211. {
  212. LOG_ERROR_VARG("No object with name '%s' in package '%s'.", id, _path.c_str());
  213. return NULL;
  214. }
  215. if (ref->type != type)
  216. {
  217. LOG_ERROR_VARG("Object '%s' in package '%s' has type %d (expected type %d).", id, _path.c_str(), (int)ref->type, (int)type);
  218. return NULL;
  219. }
  220. // Seek to the offset of this object
  221. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  222. {
  223. LOG_ERROR_VARG("Failed to seek to object '%s' in package '%s'.", id, _path.c_str());
  224. return NULL;
  225. }
  226. return ref;
  227. }
  228. Package::Reference* Package::seekToFirstType(unsigned int type)
  229. {
  230. // for each Reference
  231. for (unsigned int i = 0; i < _referenceCount; ++i)
  232. {
  233. Reference* ref = &_references[i];
  234. if (ref->type == type)
  235. {
  236. // Found a match
  237. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  238. {
  239. LOG_ERROR_VARG("Failed to seek to object '%s' in package '%s'.", ref->id.c_str(), _path.c_str());
  240. return NULL;
  241. }
  242. return ref;
  243. }
  244. }
  245. return NULL;
  246. }
  247. bool Package::read(unsigned int* ptr)
  248. {
  249. return fread(ptr, sizeof(unsigned int), 1, _file) == 1;
  250. }
  251. bool Package::read(unsigned char* ptr)
  252. {
  253. return fread(ptr, sizeof(unsigned char), 1, _file) == 1;
  254. }
  255. bool Package::read(float* ptr)
  256. {
  257. return fread(ptr, sizeof(float), 1, _file) == 1;
  258. }
  259. bool Package::readMatrix(float* m)
  260. {
  261. return (fread(m, sizeof(float), 16, _file) == 16);
  262. }
  263. Scene* Package::loadScene(const char* id)
  264. {
  265. return loadScene(id, NULL);
  266. }
  267. Scene* Package::loadScene(const char* id, const std::vector<std::string>* nodesWithMeshRB)
  268. {
  269. clearLoadSession();
  270. Reference* ref = NULL;
  271. if (id)
  272. {
  273. ref = seekTo(id, PACKAGE_TYPE_SCENE);
  274. }
  275. else
  276. {
  277. ref = seekToFirstType(PACKAGE_TYPE_SCENE);
  278. }
  279. if (!ref)
  280. {
  281. return NULL;
  282. }
  283. Scene* scene = Scene::createScene();
  284. scene->setId(getIdFromOffset());
  285. // Read the number of children
  286. unsigned int childrenCount;
  287. if (!read(&childrenCount))
  288. {
  289. SAFE_RELEASE(scene);
  290. return NULL;
  291. }
  292. if (childrenCount > 0)
  293. {
  294. // Read each child directly into the scene
  295. for (unsigned int i = 0; i < childrenCount; i++)
  296. {
  297. Node* node = readNode(scene, NULL, nodesWithMeshRB);
  298. if (node)
  299. {
  300. scene->addNode(node);
  301. node->release(); // scene now owns node
  302. }
  303. }
  304. }
  305. // Read active camera
  306. std::string xref = readString(_file);
  307. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  308. {
  309. Node* node = scene->findNode(xref.c_str() + 1, true);
  310. Camera* camera = node->getCamera();
  311. assert(camera);
  312. scene->setActiveCamera(camera);
  313. }
  314. // Read ambient color
  315. float red, blue, green;
  316. if (!read(&red))
  317. {
  318. SAFE_RELEASE(scene);
  319. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "red", _path.c_str());
  320. return NULL;
  321. }
  322. if (!read(&green))
  323. {
  324. SAFE_RELEASE(scene);
  325. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "green", _path.c_str());
  326. return NULL;
  327. }
  328. if (!read(&blue))
  329. {
  330. SAFE_RELEASE(scene);
  331. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "blue", _path.c_str());
  332. return NULL;
  333. }
  334. scene->setAmbientColor(red, green, blue);
  335. // parse animations
  336. for (unsigned int i = 0; i < _referenceCount; ++i)
  337. {
  338. Reference* ref = &_references[i];
  339. if (ref->type == PACKAGE_TYPE_ANIMATIONS)
  340. {
  341. // Found a match
  342. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  343. {
  344. LOG_ERROR_VARG("Failed to seek to object '%s' in package '%s'.", ref->id.c_str(), _path.c_str());
  345. return NULL;
  346. }
  347. readAnimations(scene);
  348. }
  349. }
  350. resolveJointReferences(scene, NULL);
  351. return scene;
  352. }
  353. Node* Package::loadNode(const char* id)
  354. {
  355. return loadNode(id, false);
  356. }
  357. Node* Package::loadNode(const char* id, bool loadWithMeshRBSupport)
  358. {
  359. assert(id);
  360. clearLoadSession();
  361. Node* node = loadNode(id, NULL, NULL, loadWithMeshRBSupport);
  362. if (node)
  363. {
  364. resolveJointReferences(NULL, node);
  365. }
  366. return node;
  367. }
  368. Node* Package::loadNode(const char* id, Scene* sceneContext, Node* nodeContext, bool loadWithMeshRBSupport)
  369. {
  370. assert(id);
  371. Node* node = NULL;
  372. // Search the passed in loading contexts (scene/node) first to see
  373. // if we've already loaded this node during this load session
  374. if (sceneContext)
  375. {
  376. node = sceneContext->findNode(id, true);
  377. }
  378. else if (nodeContext)
  379. {
  380. node = nodeContext->findNode(id, true);
  381. }
  382. if (node == NULL)
  383. {
  384. // If not yet found, search the ref table and read
  385. Reference* ref = seekTo(id, PACKAGE_TYPE_NODE);
  386. if (ref == NULL)
  387. {
  388. return NULL;
  389. }
  390. if (loadWithMeshRBSupport)
  391. {
  392. std::vector<std::string> nodesWithMeshRBSupport;
  393. nodesWithMeshRBSupport.push_back(id);
  394. node = readNode(sceneContext, nodeContext, &nodesWithMeshRBSupport);
  395. }
  396. else
  397. {
  398. node = readNode(sceneContext, nodeContext, NULL);
  399. }
  400. }
  401. return node;
  402. }
  403. Node* Package::readNode(Scene* sceneContext, Node* nodeContext, const std::vector<std::string>* nodesWithMeshRB)
  404. {
  405. const char* id = getIdFromOffset();
  406. // Read node type
  407. unsigned int nodeType;
  408. if (!read(&nodeType))
  409. {
  410. return NULL;
  411. }
  412. Node* node = NULL;
  413. switch (nodeType)
  414. {
  415. case Node::NODE:
  416. node = Node::create(id);
  417. break;
  418. case Node::JOINT:
  419. node = Joint::create(id);
  420. break;
  421. default:
  422. return NULL;
  423. }
  424. // If no loading context is set, set this node to the loading context
  425. if (sceneContext == NULL && nodeContext == NULL)
  426. {
  427. nodeContext = node;
  428. }
  429. // Read transform
  430. float transform[16];
  431. if (fread(transform, sizeof(float), 16, _file) != 16)
  432. {
  433. SAFE_RELEASE(node);
  434. return NULL;
  435. }
  436. setTransform(transform, node);
  437. // Read children
  438. unsigned int childrenCount;
  439. if (!read(&childrenCount))
  440. {
  441. SAFE_RELEASE(node);
  442. return NULL;
  443. }
  444. if (childrenCount > 0)
  445. {
  446. // Read each child
  447. for (unsigned int i = 0; i < childrenCount; i++)
  448. {
  449. Node* child = readNode(sceneContext, nodeContext, nodesWithMeshRB);
  450. if (child)
  451. {
  452. node->addChild(child);
  453. child->release(); // 'node' now owns this child
  454. }
  455. }
  456. }
  457. // Read camera
  458. Camera* camera = readCamera();
  459. if (camera)
  460. {
  461. node->setCamera(camera);
  462. SAFE_RELEASE(camera);
  463. }
  464. // Read light
  465. Light* light = readLight();
  466. if (light)
  467. {
  468. node->setLight(light);
  469. SAFE_RELEASE(light);
  470. }
  471. // Check if this node's id is in the list of nodes to be loaded with
  472. // mesh rigid body support so that when we load the model we keep the proper data.
  473. bool loadWithMeshRBSupport = false;
  474. if (nodesWithMeshRB)
  475. {
  476. for (unsigned int i = 0; i < nodesWithMeshRB->size(); i++)
  477. {
  478. if (strcmp((*nodesWithMeshRB)[i].c_str(), id) == 0)
  479. {
  480. loadWithMeshRBSupport = true;
  481. break;
  482. }
  483. }
  484. }
  485. // Read model
  486. Model* model = readModel(sceneContext, nodeContext, loadWithMeshRBSupport, node->getId());
  487. if (model)
  488. {
  489. node->setModel(model);
  490. SAFE_RELEASE(model);
  491. }
  492. return node;
  493. }
  494. Camera* Package::readCamera()
  495. {
  496. unsigned char cameraType;
  497. if (!read(&cameraType))
  498. {
  499. LOG_ERROR_VARG("Failed to load camera type in package '%s'.", _path.c_str());
  500. }
  501. if (cameraType == 0)
  502. {
  503. return NULL;
  504. }
  505. // aspect ratio
  506. float aspectRatio;
  507. if (!read(&aspectRatio))
  508. {
  509. LOG_ERROR_VARG("Failed to load camera aspectRatio in package '%s'.", _path.c_str());
  510. }
  511. // near plane
  512. float nearPlane;
  513. if (!read(&nearPlane))
  514. {
  515. LOG_ERROR_VARG("Failed to load camera near plane in package '%s'.", _path.c_str());
  516. }
  517. // far plane
  518. float farPlane;
  519. if (!read(&farPlane))
  520. {
  521. LOG_ERROR_VARG("Failed to load camera far plane in package '%s'.", _path.c_str());
  522. }
  523. Camera* camera = NULL;
  524. if (cameraType == Camera::PERSPECTIVE)
  525. {
  526. // field of view
  527. float fieldOfView;
  528. if (!read(&fieldOfView))
  529. {
  530. LOG_ERROR_VARG("Failed to load camera field of view in package '%s'.", _path.c_str());
  531. }
  532. camera = Camera::createPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  533. }
  534. else if (cameraType == Camera::ORTHOGRAPHIC)
  535. {
  536. // magnification
  537. float zoomX;
  538. if (!read(&zoomX))
  539. {
  540. LOG_ERROR_VARG("Failed to load camera zoomX in package '%s'.", _path.c_str());
  541. }
  542. float zoomY;
  543. if (!read(&zoomY))
  544. {
  545. LOG_ERROR_VARG("Failed to load camera zoomY in package '%s'.", _path.c_str());
  546. }
  547. camera = Camera::createOrthographic(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
  548. }
  549. else
  550. {
  551. LOG_ERROR_VARG("Failed to load camera type in package '%s'. Invalid camera type.", _path.c_str());
  552. }
  553. return camera;
  554. }
  555. Light* Package::readLight()
  556. {
  557. unsigned char type;
  558. if (!read(&type))
  559. {
  560. LOG_ERROR_VARG("Failed to load light %s in package '%s'.", "type", _path.c_str());
  561. }
  562. if (type == 0)
  563. {
  564. return NULL;
  565. }
  566. // read color
  567. float red, blue, green;
  568. if (!read(&red) || !read(&blue) || !read(&green))
  569. {
  570. LOG_ERROR_VARG("Failed to load light %s in package '%s'.", "color", _path.c_str());
  571. }
  572. Vector3 color(red, blue, green);
  573. Light* light = NULL;
  574. if (type == Light::DIRECTIONAL)
  575. {
  576. light = Light::createDirectional(color);
  577. }
  578. else if (type == Light::POINT)
  579. {
  580. float range;
  581. if (!read(&range))
  582. {
  583. LOG_ERROR_VARG("Failed to load point light %s in package '%s'.", "point", _path.c_str());
  584. }
  585. light = Light::createPoint(color, range);
  586. }
  587. else if (type == Light::SPOT)
  588. {
  589. float range, innerAngle, outerAngle;
  590. if (!read(&range) || !read(&innerAngle) || !read(&outerAngle))
  591. {
  592. LOG_ERROR_VARG("Failed to load spot light %s in package '%s'.", "spot", _path.c_str());
  593. }
  594. light = Light::createSpot(color, range, innerAngle, outerAngle);
  595. }
  596. else
  597. {
  598. LOG_ERROR_VARG("Failed to load light %s in package '%s'.", "type", _path.c_str());
  599. }
  600. return light;
  601. }
  602. Model* Package::readModel(Scene* sceneContext, Node* nodeContext, bool loadWithMeshRBSupport, const char* nodeId)
  603. {
  604. // Read mesh
  605. Mesh* mesh = NULL;
  606. std::string xref = readString(_file);
  607. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  608. {
  609. mesh = loadMesh(xref.c_str() + 1, loadWithMeshRBSupport, nodeId);
  610. if (mesh)
  611. {
  612. Model* model = Model::create(mesh);
  613. SAFE_RELEASE(mesh);
  614. // Read skin
  615. unsigned char hasSkin;
  616. if (!read(&hasSkin))
  617. {
  618. LOG_ERROR_VARG("Failed to load hasSkin in package '%s'.", _path.c_str());
  619. return NULL;
  620. }
  621. if (hasSkin)
  622. {
  623. MeshSkin* skin = readMeshSkin(sceneContext, nodeContext);
  624. if (skin)
  625. {
  626. model->setSkin(skin);
  627. }
  628. }
  629. // Read material
  630. unsigned int materialCount;
  631. if (!read(&materialCount))
  632. {
  633. LOG_ERROR_VARG("Failed to load materialCount in package '%s'.", _path.c_str());
  634. return NULL;
  635. }
  636. if (materialCount > 0)
  637. {
  638. // TODO: Material loading not supported yet
  639. }
  640. return model;
  641. }
  642. }
  643. return NULL;
  644. }
  645. MeshSkin* Package::readMeshSkin(Scene* sceneContext, Node* nodeContext)
  646. {
  647. MeshSkin* meshSkin = new MeshSkin();
  648. // Read bindShape
  649. float bindShape[16];
  650. if (!readMatrix(bindShape))
  651. {
  652. LOG_ERROR_VARG("Failed to load MeshSkin in package '%s'.", _path.c_str());
  653. SAFE_DELETE(meshSkin);
  654. return NULL;
  655. }
  656. meshSkin->setBindShape(bindShape);
  657. MeshSkinData* skinData = new MeshSkinData();
  658. skinData->skin = meshSkin;
  659. // Read joint count
  660. unsigned int jointCount;
  661. if (!read(&jointCount))
  662. {
  663. LOG_ERROR_VARG("Failed to load MeshSkin in package '%s'.", _path.c_str());
  664. SAFE_DELETE(meshSkin);
  665. SAFE_DELETE(skinData);
  666. return NULL;
  667. }
  668. if (jointCount == 0)
  669. {
  670. SAFE_DELETE(meshSkin);
  671. SAFE_DELETE(skinData);
  672. return NULL;
  673. }
  674. meshSkin->setJointCount(jointCount);
  675. // Read joint xref strings for all joints in the list
  676. for (unsigned int i = 0; i < jointCount; i++)
  677. {
  678. skinData->joints.push_back(readString(_file));
  679. }
  680. // read bindposes
  681. unsigned int jointsBindPosesCount;
  682. if (!read(&jointsBindPosesCount))
  683. {
  684. LOG_ERROR_VARG("Failed to load MeshSkin in package '%s'.", _path.c_str());
  685. SAFE_DELETE(meshSkin);
  686. SAFE_DELETE(skinData);
  687. return NULL;
  688. }
  689. if (jointsBindPosesCount > 0)
  690. {
  691. assert(jointCount * 16 == jointsBindPosesCount);
  692. float m[16];
  693. for (unsigned int i = 0; i < jointCount; i++)
  694. {
  695. if (!readMatrix(m))
  696. {
  697. LOG_ERROR_VARG("Failed to load MeshSkin in package '%s'.", _path.c_str());
  698. SAFE_DELETE(meshSkin);
  699. SAFE_DELETE(skinData);
  700. return NULL;
  701. }
  702. skinData->inverseBindPoseMatrices.push_back(m);
  703. }
  704. }
  705. // Store the MeshSkinData so we can go back and resolve all joint references later
  706. _meshSkins.push_back(skinData);
  707. return meshSkin;
  708. }
  709. void Package::resolveJointReferences(Scene* sceneContext, Node* nodeContext)
  710. {
  711. const unsigned int skinCount = _meshSkins.size();
  712. for (unsigned int i = 0; i < skinCount; ++i)
  713. {
  714. MeshSkinData* skinData = _meshSkins[i];
  715. // Resolve all joints in skin joint list
  716. const unsigned int jointCount = skinData->joints.size();
  717. for (unsigned int j = 0; j < jointCount; ++j)
  718. {
  719. // TODO: Handle full xrefs (not just local # xrefs)
  720. std::string jointId = skinData->joints[j];
  721. if (jointId.length() > 1 && jointId[0] == '#')
  722. {
  723. jointId = jointId.substr(1, jointId.length() - 1);
  724. Node* n = loadNode(jointId.c_str(), sceneContext, nodeContext, false);
  725. if (n && n->getType() == Node::JOINT)
  726. {
  727. Joint* joint = static_cast<Joint*>(n);
  728. joint->setInverseBindPose(skinData->inverseBindPoseMatrices[j]);
  729. skinData->skin->setJoint(joint, j);
  730. }
  731. }
  732. }
  733. // Set the root joint
  734. if (jointCount > 0)
  735. {
  736. Joint* rootJoint = skinData->skin->getJoint((unsigned int)0);
  737. Node* parent = rootJoint->getParent();
  738. while (parent)
  739. {
  740. if (skinData->skin->getJointIndex(static_cast<Joint*>(parent)) != -1)
  741. {
  742. // Parent is a joint in the MeshSkin, so treat it as the new root
  743. rootJoint = static_cast<Joint*>(parent);
  744. }
  745. parent = parent->getParent();
  746. }
  747. skinData->skin->setRootJoint(rootJoint);
  748. }
  749. // Done with this MeshSkinData entry
  750. SAFE_DELETE(_meshSkins[i]);
  751. }
  752. _meshSkins.clear();
  753. }
  754. void Package::readAnimation(Scene* scene)
  755. {
  756. const std::string animationId = readString(_file);
  757. // read the number of animation channels in this animation
  758. unsigned int animationChannelCount;
  759. if (!read(&animationChannelCount))
  760. {
  761. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animationChannelCount", "animation", animationId.c_str());
  762. return;
  763. }
  764. Animation* animation = NULL;
  765. for (unsigned int i = 0; i < animationChannelCount; i++)
  766. {
  767. animation = readAnimationChannel(scene, animation, animationId.c_str());
  768. }
  769. }
  770. void Package::readAnimations(Scene* scene)
  771. {
  772. // read the number of animations in this object
  773. unsigned int animationCount;
  774. if (!read(&animationCount))
  775. {
  776. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animationCount", "Animations");
  777. return;
  778. }
  779. for (unsigned int i = 0; i < animationCount; i++)
  780. {
  781. readAnimation(scene);
  782. }
  783. }
  784. Animation* Package::readAnimationChannel(Scene* scene, Animation* animation, const char* animationId)
  785. {
  786. const char* id = animationId;
  787. // read targetId
  788. std::string targetId = readString(_file);
  789. if (targetId.empty())
  790. {
  791. LOG_ERROR_VARG("Failed to read %s for %s: %s", "targetId", "animation", id);
  792. return NULL;
  793. }
  794. // read target attribute
  795. unsigned int targetAttribute;
  796. if (!read(&targetAttribute))
  797. {
  798. LOG_ERROR_VARG("Failed to read %s for %s: %s", "targetAttribute", "animation", id);
  799. return NULL;
  800. }
  801. //long position = ftell(_file);
  802. //fseek(_file, position, SEEK_SET);
  803. AnimationTarget* target = NULL;
  804. // Search for a node that matches target
  805. if (!target)
  806. {
  807. target = scene->findNode(targetId.c_str());
  808. if (!target)
  809. {
  810. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animation target", targetId.c_str(), id);
  811. return NULL;
  812. }
  813. }
  814. std::vector<unsigned long> keyTimes;
  815. std::vector<float> values;
  816. std::vector<float> tangentsIn;
  817. std::vector<float> tangentsOut;
  818. std::vector<unsigned long> interpolation;
  819. // length of the arrays
  820. unsigned int keyTimesCount;
  821. unsigned int valuesCount;
  822. unsigned int tangentsInCount;
  823. unsigned int tangentsOutCount;
  824. unsigned int interpolationCount;
  825. // read key times
  826. if (!readArray(&keyTimesCount, &keyTimes))
  827. {
  828. LOG_ERROR_VARG("Failed to read %s for %s: %s", "keyTimes", "animation", id);
  829. return NULL;
  830. }
  831. // read key values
  832. if (!readArray(&valuesCount, &values))
  833. {
  834. LOG_ERROR_VARG("Failed to read %s for %s: %s", "values", "animation", id);
  835. return NULL;
  836. }
  837. // read tangentsIn
  838. if (!readArray(&tangentsInCount, &tangentsIn))
  839. {
  840. LOG_ERROR_VARG("Failed to read %s for %s: %s", "tangentsIn", "animation", id);
  841. return NULL;
  842. }
  843. // read tangent_out
  844. if (!readArray(&tangentsOutCount, &tangentsOut))
  845. {
  846. LOG_ERROR_VARG("Failed to read %s for %s: %s", "tangentsOut", "animation", id);
  847. return NULL;
  848. }
  849. // read interpolations
  850. if (!readArray(&interpolationCount, &interpolation))
  851. {
  852. LOG_ERROR_VARG("Failed to read %s for %s: %s", "interpolation", "animation", id);
  853. return NULL;
  854. }
  855. Game* game = Game::getInstance();
  856. AnimationController* controller = game->getAnimationController();
  857. // TODO: Handle other target attributes later.
  858. if (targetAttribute > 0)
  859. {
  860. assert(keyTimes.size() > 0 && values.size() > 0);
  861. if (animation == NULL)
  862. {
  863. // TODO: This code currently assumes LINEAR only
  864. animation = controller->createAnimation(animationId, target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  865. }
  866. else
  867. {
  868. animation->createChannel(target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  869. }
  870. }
  871. return animation;
  872. }
  873. Mesh* Package::loadMesh(const char* id)
  874. {
  875. return loadMesh(id, false, NULL);
  876. }
  877. Mesh* Package::loadMesh(const char* id, bool loadWithMeshRBSupport, const char* nodeId)
  878. {
  879. // save the file position
  880. long position = ftell(_file);
  881. // Seek to the specified Mesh
  882. Reference* ref = seekTo(id, PACKAGE_TYPE_MESH);
  883. if (ref == NULL)
  884. {
  885. return NULL;
  886. }
  887. // Read vertex format/elements
  888. unsigned int vertexElementCount;
  889. if (fread(&vertexElementCount, 4, 1, _file) != 1 || vertexElementCount < 1)
  890. {
  891. return NULL;
  892. }
  893. VertexFormat::Element* vertexElements = new VertexFormat::Element[vertexElementCount];
  894. for (unsigned int i = 0; i < vertexElementCount; ++i)
  895. {
  896. unsigned int vUsage, vSize;
  897. if (fread(&vUsage, 4, 1, _file) != 1 || fread(&vSize, 4, 1, _file) != 1)
  898. {
  899. SAFE_DELETE_ARRAY(vertexElements);
  900. return NULL;
  901. }
  902. vertexElements[i].usage = (VertexFormat::Usage)vUsage;
  903. vertexElements[i].size = vSize;
  904. }
  905. // Create VertexFormat
  906. VertexFormat vertexFormat(vertexElements, vertexElementCount);
  907. SAFE_DELETE_ARRAY(vertexElements);
  908. // Read vertex data
  909. unsigned int vertexByteCount;
  910. if (fread(&vertexByteCount, 4, 1, _file) != 1 || vertexByteCount == 0)
  911. {
  912. return NULL;
  913. }
  914. unsigned char* vertexData = new unsigned char[vertexByteCount];
  915. if (fread(vertexData, 1, vertexByteCount, _file) != vertexByteCount)
  916. {
  917. LOG_ERROR_VARG("Failed to read %d vertex data bytes for mesh: %s", vertexByteCount, id);
  918. return NULL;
  919. }
  920. // Read mesh bounds (bounding box and bounding sphere)
  921. Vector3 boundsMin, boundsMax, boundsCenter;
  922. float boundsRadius = 0.0f;
  923. if (fread(&boundsMin.x, 4, 3, _file) != 3 || fread(&boundsMax.x, 4, 3, _file) != 3)
  924. {
  925. LOG_ERROR_VARG("Failed to read bounding box for mesh: %s", id);
  926. return NULL;
  927. }
  928. if (fread(&boundsCenter.x, 4, 3, _file) != 3 || fread(&boundsRadius, 4, 1, _file) != 1)
  929. {
  930. LOG_ERROR_VARG("Failed to read bounding sphere for mesh: %s", id);
  931. return NULL;
  932. }
  933. // Create Mesh
  934. int vertexCount = vertexByteCount / vertexFormat.getVertexSize();
  935. Mesh* mesh = Mesh::createMesh(vertexFormat, vertexCount, false);
  936. if (mesh == NULL)
  937. {
  938. LOG_ERROR_VARG("Failed to create mesh: %s", id);
  939. SAFE_DELETE_ARRAY(vertexData);
  940. return NULL;
  941. }
  942. mesh->setVertexData(vertexData, 0, vertexCount);
  943. if (loadWithMeshRBSupport)
  944. SceneLoader::addMeshRigidBodyData(nodeId, mesh, vertexData, vertexByteCount);
  945. SAFE_DELETE_ARRAY(vertexData);
  946. // Set mesh bounding volumes
  947. mesh->_boundingBox.set(boundsMin, boundsMax);
  948. mesh->_boundingSphere.set(boundsCenter, boundsRadius);
  949. // Read mesh parts
  950. unsigned int meshPartCount;
  951. if (fread(&meshPartCount, 4, 1, _file) != 1)
  952. {
  953. SAFE_RELEASE(mesh);
  954. return NULL;
  955. }
  956. for (unsigned int i = 0; i < meshPartCount; ++i)
  957. {
  958. // Read primitive type, index format and index count
  959. unsigned int pType, iFormat, iByteCount;
  960. if (fread(&pType, 4, 1, _file) != 1 ||
  961. fread(&iFormat, 4, 1, _file) != 1 ||
  962. fread(&iByteCount, 4, 1, _file) != 1)
  963. {
  964. LOG_ERROR_VARG("Failed to read mesh part (i=%d): %s", i, id);
  965. SAFE_RELEASE(mesh);
  966. return NULL;
  967. }
  968. unsigned char* indexData = new unsigned char[iByteCount];
  969. if (fread(indexData, 1, iByteCount, _file) != iByteCount)
  970. {
  971. LOG_ERROR_VARG("Failed to read %d index data bytes for mesh part (i=%d): %s", iByteCount, i, id);
  972. SAFE_DELETE_ARRAY(indexData);
  973. SAFE_RELEASE(mesh);
  974. return NULL;
  975. }
  976. Mesh::IndexFormat indexFormat = (Mesh::IndexFormat)iFormat;
  977. unsigned int indexSize = 0;
  978. switch (indexFormat)
  979. {
  980. case Mesh::INDEX8:
  981. indexSize = 1;
  982. break;
  983. case Mesh::INDEX16:
  984. indexSize = 2;
  985. break;
  986. case Mesh::INDEX32:
  987. indexSize = 4;
  988. break;
  989. }
  990. unsigned int indexCount = iByteCount / indexSize;
  991. MeshPart* part = mesh->addPart((Mesh::PrimitiveType)pType, indexFormat, indexCount, false);
  992. if (part == NULL)
  993. {
  994. LOG_ERROR_VARG("Failed to create mesh part (i=%d): %s", i, id);
  995. SAFE_DELETE_ARRAY(indexData);
  996. SAFE_RELEASE(mesh);
  997. return NULL;
  998. }
  999. part->setIndexData(indexData, 0, indexCount);
  1000. if (loadWithMeshRBSupport)
  1001. SceneLoader::addMeshRigidBodyData(nodeId, indexData, iByteCount);
  1002. SAFE_DELETE_ARRAY(indexData);
  1003. }
  1004. fseek(_file, position, SEEK_SET);
  1005. return mesh;
  1006. }
  1007. Font* Package::loadFont(const char* id)
  1008. {
  1009. // Seek to the specified Font
  1010. Reference* ref = seekTo(id, PACKAGE_TYPE_FONT);
  1011. if (ref == NULL)
  1012. {
  1013. return NULL;
  1014. }
  1015. // Read font family
  1016. std::string family = readString(_file);
  1017. if (family.empty())
  1018. {
  1019. LOG_ERROR_VARG("Failed to read font family for font: %s", id);
  1020. return NULL;
  1021. }
  1022. // Read font style and size
  1023. unsigned int style, size;
  1024. if (fread(&style, 4, 1, _file) != 1 ||
  1025. fread(&size, 4, 1, _file) != 1)
  1026. {
  1027. LOG_ERROR_VARG("Failed to read style and/or size for font: %s", id);
  1028. return NULL;
  1029. }
  1030. // Read character set
  1031. std::string charset = readString(_file);
  1032. // Read font glyphs
  1033. unsigned int glyphCount;
  1034. if (fread(&glyphCount, 4, 1, _file) != 1 || glyphCount == 0)
  1035. {
  1036. LOG_ERROR_VARG("Failed to read glyph count for font: %s", id);
  1037. return NULL;
  1038. }
  1039. Font::Glyph* glyphs = new Font::Glyph[glyphCount];
  1040. if (fread(glyphs, sizeof(Font::Glyph), glyphCount, _file) != glyphCount)
  1041. {
  1042. LOG_ERROR_VARG("Failed to read %d glyphs for font: %s", glyphCount, id);
  1043. SAFE_DELETE_ARRAY(glyphs);
  1044. return NULL;
  1045. }
  1046. // Read texture
  1047. unsigned int width, height, textureByteCount;
  1048. if (fread(&width, 4, 1, _file) != 1 ||
  1049. fread(&height, 4, 1, _file) != 1 ||
  1050. fread(&textureByteCount, 4, 1, _file) != 1)
  1051. {
  1052. LOG_ERROR_VARG("Failed to read texture attributes for font: %s", id);
  1053. SAFE_DELETE_ARRAY(glyphs);
  1054. return NULL;
  1055. }
  1056. if (textureByteCount != (width * height))
  1057. {
  1058. LOG_ERROR_VARG("Invalid texture byte for font: %s", id);
  1059. SAFE_DELETE_ARRAY(glyphs);
  1060. return NULL;
  1061. }
  1062. unsigned char* textureData = new unsigned char[textureByteCount];
  1063. if (fread(textureData, 1, textureByteCount, _file) != textureByteCount)
  1064. {
  1065. LOG_ERROR_VARG("Failed to read %d texture bytes for font: %s", textureByteCount, id);
  1066. SAFE_DELETE_ARRAY(glyphs);
  1067. SAFE_DELETE_ARRAY(textureData);
  1068. return NULL;
  1069. }
  1070. // Load the texture for the font
  1071. Texture* texture = Texture::create(Texture::ALPHA, width, height, textureData, true);
  1072. // Free the texture data (no longer needed)
  1073. SAFE_DELETE_ARRAY(textureData);
  1074. if (texture == NULL)
  1075. {
  1076. LOG_ERROR_VARG("Failed to create texture for font: %s", id);
  1077. SAFE_DELETE_ARRAY(glyphs);
  1078. return NULL;
  1079. }
  1080. // Create the font
  1081. Font* font = Font::create(family.c_str(), Font::PLAIN, size, glyphs, glyphCount, texture);
  1082. // Free the glyph array
  1083. SAFE_DELETE_ARRAY(glyphs);
  1084. // Release the texture since the Font now owns it
  1085. SAFE_RELEASE(texture);
  1086. if (font)
  1087. {
  1088. font->_path = _path;
  1089. font->_id = id;
  1090. }
  1091. return font;
  1092. }
  1093. void Package::setTransform(const float* values, Transform* transform)
  1094. {
  1095. // Load array into transform
  1096. Matrix matrix(values);
  1097. Vector3 scale, translation;
  1098. Quaternion rotation;
  1099. matrix.decompose(&scale, &rotation, &translation);
  1100. transform->setScale(scale);
  1101. transform->setTranslation(translation);
  1102. transform->setRotation(rotation);
  1103. }
  1104. bool Package::contains(const char* id) const
  1105. {
  1106. return (find(id) != NULL);
  1107. }
  1108. unsigned int Package::getObjectCount() const
  1109. {
  1110. return _referenceCount;
  1111. }
  1112. const char* Package::getObjectID(unsigned int index) const
  1113. {
  1114. return (index >= _referenceCount ? NULL : _references[index].id.c_str());
  1115. }
  1116. Package::Reference::Reference() :
  1117. type(0), offset(0)
  1118. {
  1119. }
  1120. Package::Reference::~Reference()
  1121. {
  1122. }
  1123. }