SceneLoader.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "Package.h"
  4. #include "SceneLoader.h"
  5. namespace gameplay
  6. {
  7. // Static member variables.
  8. std::map<std::string, Properties*> SceneLoader::_propertiesFromFile;
  9. std::vector<SceneLoader::SceneAnimation> SceneLoader::_animations;
  10. std::vector<SceneLoader::SceneNodeProperty> SceneLoader::_nodeProperties;
  11. std::vector<std::string> SceneLoader::_nodesWithMeshRB;
  12. std::map<std::string, SceneLoader::MeshRigidBodyData>* SceneLoader::_meshRigidBodyData = NULL;
  13. Scene* SceneLoader::load(const char* filePath)
  14. {
  15. assert(filePath);
  16. // Load the scene properties from file.
  17. Properties* properties = Properties::create(filePath);
  18. assert(properties);
  19. if (properties == NULL)
  20. {
  21. WARN_VARG("Failed to load scene file: %s", filePath);
  22. return NULL;
  23. }
  24. // Check if the properties object is valid and has a valid namespace.
  25. Properties* sceneProperties = properties->getNextNamespace();
  26. assert(sceneProperties);
  27. if (!sceneProperties || !(strcmp(sceneProperties->getNamespace(), "scene") == 0))
  28. {
  29. WARN("Failed to load scene from properties object: must be non-null object and have namespace equal to 'scene'.");
  30. SAFE_DELETE(properties);
  31. return NULL;
  32. }
  33. // Build the node URL/property and animation reference tables and load the referenced files.
  34. buildReferenceTables(sceneProperties);
  35. loadReferencedFiles();
  36. // Calculate the node IDs that need to be loaded with mesh rigid body support.
  37. calculateNodesWithMeshRigidBodies(sceneProperties);
  38. // Set up for storing the mesh rigid body data.
  39. if (_nodesWithMeshRB.size() > 0)
  40. {
  41. // We do not currently support loading more than one scene simultaneously.
  42. if (_meshRigidBodyData)
  43. {
  44. WARN("Attempting to load multiple scenes simultaneously; mesh rigid bodies will not load properly.");
  45. }
  46. _meshRigidBodyData = new std::map<std::string, MeshRigidBodyData>();
  47. }
  48. // Load the main scene data from GPB and apply the global scene properties.
  49. Scene* scene = loadMainSceneData(sceneProperties);
  50. if (!scene)
  51. {
  52. SAFE_DELETE(properties);
  53. return NULL;
  54. }
  55. // First apply the node url properties. Following that,
  56. // apply the normal node properties and create the animations.
  57. applyNodeUrls(scene);
  58. applyNodeProperties(scene, sceneProperties);
  59. createAnimations(scene);
  60. // Find the physics properties object.
  61. Properties* physics = NULL;
  62. Properties* ns = NULL;
  63. sceneProperties->rewind();
  64. while (true)
  65. {
  66. Properties* ns = sceneProperties->getNextNamespace();
  67. if (ns == NULL || strcmp(ns->getNamespace(), "physics") == 0)
  68. {
  69. physics = ns;
  70. break;
  71. }
  72. }
  73. // Load physics properties and constraints.
  74. if (physics)
  75. loadPhysics(physics, scene);
  76. // Clean up all loaded properties objects.
  77. std::map<std::string, Properties*>::iterator iter = _propertiesFromFile.begin();
  78. for (; iter != _propertiesFromFile.end(); iter++)
  79. {
  80. SAFE_DELETE(iter->second);
  81. }
  82. // Clean up the .scene file's properties object.
  83. SAFE_DELETE(properties);
  84. // Clean up mesh rigid body data.
  85. if (_meshRigidBodyData)
  86. {
  87. std::map<std::string, MeshRigidBodyData>::iterator iter = _meshRigidBodyData->begin();
  88. for (; iter != _meshRigidBodyData->end(); iter++)
  89. {
  90. for (unsigned int i = 0; i < iter->second.indexData.size(); i++)
  91. {
  92. SAFE_DELETE_ARRAY(iter->second.indexData[i]);
  93. }
  94. SAFE_DELETE_ARRAY(iter->second.vertexData);
  95. }
  96. SAFE_DELETE(_meshRigidBodyData);
  97. }
  98. // Clear all temporary data stores.
  99. _propertiesFromFile.clear();
  100. _animations.clear();
  101. _nodeProperties.clear();
  102. _nodesWithMeshRB.clear();
  103. return scene;
  104. }
  105. void SceneLoader::addMeshRigidBodyData(std::string id, Mesh* mesh, unsigned char* vertexData, unsigned int vertexByteCount)
  106. {
  107. if (!_meshRigidBodyData)
  108. {
  109. WARN("Attempting to add mesh rigid body data outside of scene loading; ignoring request.");
  110. return;
  111. }
  112. (*_meshRigidBodyData)[id].mesh = mesh;
  113. (*_meshRigidBodyData)[id].vertexData = new unsigned char[vertexByteCount];
  114. memcpy((*_meshRigidBodyData)[id].vertexData, vertexData, vertexByteCount);
  115. }
  116. void SceneLoader::addMeshRigidBodyData(std::string id, unsigned char* indexData, unsigned int indexByteCount)
  117. {
  118. if (!_meshRigidBodyData)
  119. {
  120. WARN("Attempting to add mesh rigid body data outside of scene loading; ignoring request.");
  121. return;
  122. }
  123. unsigned char* indexDataCopy = new unsigned char[indexByteCount];
  124. memcpy(indexDataCopy, indexData, indexByteCount);
  125. (*_meshRigidBodyData)[id].indexData.push_back(indexDataCopy);
  126. }
  127. void SceneLoader::addSceneAnimation(const char* animationID, const char* targetID, const char* url)
  128. {
  129. // Calculate the file and id from the given url.
  130. std::string file;
  131. std::string id;
  132. splitURL(url, &file, &id);
  133. // If there is a file that needs to be loaded later, add an
  134. // empty entry to the properties table to signify it.
  135. if (file.length() > 0 && _propertiesFromFile.count(file) == 0)
  136. _propertiesFromFile[file] = NULL;
  137. // Add the animation to the list of animations to be resolved later.
  138. _animations.push_back(SceneAnimation(animationID, targetID, file, id));
  139. }
  140. void SceneLoader::addSceneNodeProperty(SceneNodeProperty::Type type, const char* nodeID, const char* url)
  141. {
  142. // Calculate the file and id from the given url.
  143. std::string file;
  144. std::string id;
  145. splitURL(url, &file, &id);
  146. // If there is a non-GPB file that needs to be loaded later, add an
  147. // empty entry to the properties table to signify it.
  148. if (file.length() > 0 && file.find(".gpb") == file.npos && _propertiesFromFile.count(file) == 0)
  149. _propertiesFromFile[file] = NULL;
  150. // Add the node property to the list of node properties to be resolved later.
  151. _nodeProperties.push_back(SceneNodeProperty(type, nodeID, file, id));
  152. }
  153. void SceneLoader::applyNodeProperties(const Scene* scene, const Properties* sceneProperties)
  154. {
  155. // Apply all of the remaining scene node properties except rigid body (we apply that last).
  156. for (unsigned int i = 0; i < _nodeProperties.size(); i++)
  157. {
  158. // If the referenced node doesn't exist in the scene, then we
  159. // can't do anything so we skip to the next scene node property.
  160. Node* node = scene->findNode(_nodeProperties[i]._nodeID);
  161. if (!node)
  162. {
  163. WARN_VARG("Attempting to set a property for node '%s', which does not exist in the scene.", _nodeProperties[i]._nodeID);
  164. continue;
  165. }
  166. if (_nodeProperties[i]._type == SceneNodeProperty::AUDIO ||
  167. _nodeProperties[i]._type == SceneNodeProperty::MATERIAL ||
  168. _nodeProperties[i]._type == SceneNodeProperty::PARTICLE ||
  169. _nodeProperties[i]._type == SceneNodeProperty::RIGIDBODY)
  170. {
  171. // Check to make sure the referenced properties object was loaded properly.
  172. Properties* p = _propertiesFromFile[_nodeProperties[i]._file];
  173. if (!p)
  174. {
  175. WARN_VARG("The referenced node data in file '%s' failed to load.", _nodeProperties[i]._file.c_str());
  176. continue;
  177. }
  178. // If a specific namespace within the file was specified, load that namespace.
  179. if (_nodeProperties[i]._id.size() > 0)
  180. {
  181. p = p->getNamespace(_nodeProperties[i]._id.c_str());
  182. if (!p)
  183. {
  184. WARN_VARG("The referenced node data at '%s#%s' failed to load.", _nodeProperties[i]._file.c_str(), _nodeProperties[i]._id.c_str());
  185. continue;
  186. }
  187. }
  188. else
  189. {
  190. // Otherwise, use the first namespace.
  191. p->rewind();
  192. p = p->getNextNamespace();
  193. }
  194. switch (_nodeProperties[i]._type)
  195. {
  196. case SceneNodeProperty::AUDIO:
  197. {
  198. AudioSource* audioSource = AudioSource::create(p);
  199. node->setAudioSource(audioSource);
  200. SAFE_RELEASE(audioSource);
  201. break;
  202. }
  203. case SceneNodeProperty::MATERIAL:
  204. if (!node->getModel())
  205. WARN_VARG("Attempting to set a material on node '%s', which has no model.", _nodeProperties[i]._nodeID);
  206. else
  207. {
  208. Material* material = Material::create(p);
  209. node->getModel()->setMaterial(material);
  210. SAFE_RELEASE(material);
  211. }
  212. break;
  213. case SceneNodeProperty::PARTICLE:
  214. {
  215. ParticleEmitter* particleEmitter = ParticleEmitter::create(p);
  216. node->setParticleEmitter(particleEmitter);
  217. SAFE_RELEASE(particleEmitter);
  218. break;
  219. }
  220. case SceneNodeProperty::RIGIDBODY:
  221. // Process this last in a separate loop to allow scale, translate, rotate to be applied first.
  222. break;
  223. default:
  224. // This cannot happen.
  225. break;
  226. }
  227. }
  228. else
  229. {
  230. Properties* np = sceneProperties->getNamespace(_nodeProperties[i]._nodeID);
  231. const char* name = NULL;
  232. switch (_nodeProperties[i]._type)
  233. {
  234. case SceneNodeProperty::TRANSLATE:
  235. {
  236. Vector3 t;
  237. if (np && np->getVector3("translate", &t))
  238. node->setTranslation(t);
  239. break;
  240. }
  241. case SceneNodeProperty::ROTATE:
  242. {
  243. Quaternion r;
  244. if (np && np->getQuaternionFromAxisAngle("rotate", &r))
  245. node->setRotation(r);
  246. break;
  247. }
  248. case SceneNodeProperty::SCALE:
  249. {
  250. Vector3 s;
  251. if (np && np->getVector3("scale", &s))
  252. node->setScale(s);
  253. break;
  254. }
  255. default:
  256. WARN_VARG("Unsupported node property type: %d.", _nodeProperties[i]._type);
  257. break;
  258. }
  259. }
  260. }
  261. // Process rigid body properties.
  262. for (unsigned int i = 0; i < _nodeProperties.size(); i++)
  263. {
  264. if (_nodeProperties[i]._type == SceneNodeProperty::RIGIDBODY)
  265. {
  266. // If the referenced node doesn't exist in the scene, then we
  267. // can't do anything so we skip to the next scene node property.
  268. Node* node = scene->findNode(_nodeProperties[i]._nodeID);
  269. if (!node)
  270. {
  271. WARN_VARG("Attempting to set a property for node '%s', which does not exist in the scene.", _nodeProperties[i]._nodeID);
  272. continue;
  273. }
  274. // Check to make sure the referenced properties object was loaded properly.
  275. Properties* p = _propertiesFromFile[_nodeProperties[i]._file];
  276. if (!p)
  277. {
  278. WARN_VARG("The referenced node data in file '%s' failed to load.", _nodeProperties[i]._file.c_str());
  279. continue;
  280. }
  281. // If a specific namespace within the file was specified, load that namespace.
  282. if (_nodeProperties[i]._id.size() > 0)
  283. {
  284. p = p->getNamespace(_nodeProperties[i]._id.c_str());
  285. if (!p)
  286. {
  287. WARN_VARG("The referenced node data at '%s#%s' failed to load.", _nodeProperties[i]._file.c_str(), _nodeProperties[i]._id.c_str());
  288. continue;
  289. }
  290. }
  291. else
  292. {
  293. // Otherwise, use the first namespace.
  294. p->rewind();
  295. p = p->getNextNamespace();
  296. }
  297. // If the scene file specifies a rigid body model, use it for creating the rigid body.
  298. Properties* np = sceneProperties->getNamespace(_nodeProperties[i]._nodeID);
  299. const char* name = NULL;
  300. if (np && (name = np->getString("rigidbodymodel")))
  301. {
  302. Node* modelNode = scene->findNode(name);
  303. if (!modelNode)
  304. WARN_VARG("Node '%s' does not exist; attempting to use its model for rigid body creation.", name);
  305. else
  306. {
  307. if (!modelNode->getModel())
  308. WARN_VARG("Node '%s' does not have a model; attempting to use its model for rigid body creation.", name);
  309. else
  310. {
  311. // Set the specified model during physics rigid body creation.
  312. Model* model = node->getModel();
  313. node->setModel(modelNode->getModel());
  314. node->setPhysicsRigidBody(p);
  315. node->setModel(model);
  316. }
  317. }
  318. }
  319. else if (!node->getModel())
  320. WARN_VARG("Attempting to set a rigid body on node '%s', which has no model.", _nodeProperties[i]._nodeID);
  321. else
  322. node->setPhysicsRigidBody(p);
  323. }
  324. }
  325. }
  326. void SceneLoader::applyNodeUrls(Scene* scene)
  327. {
  328. // Apply all URL node properties so that when we go to apply
  329. // the other node properties, the node is in the scene.
  330. for (unsigned int i = 0; i < _nodeProperties.size(); )
  331. {
  332. if (_nodeProperties[i]._type == SceneNodeProperty::URL)
  333. {
  334. // Make sure that the ID we are using to insert the node into the scene with is unique.
  335. if (scene->findNode(_nodeProperties[i]._nodeID) != NULL)
  336. WARN_VARG("Attempting to insert or rename a node to an ID that already exists: ID='%s'", _nodeProperties[i]._nodeID);
  337. else
  338. {
  339. // If a file was specified, load the node from file and then insert it into the scene with the new ID.
  340. if (_nodeProperties[i]._file.size() > 0)
  341. {
  342. Package* tmpPackage = Package::create(_nodeProperties[i]._file.c_str());
  343. if (!tmpPackage)
  344. WARN_VARG("Failed to load GPB file '%s' for node stitching.", _nodeProperties[i]._file.c_str());
  345. else
  346. {
  347. bool loadWithMeshRBSupport = false;
  348. for (unsigned int j = 0; j < _nodesWithMeshRB.size(); j++)
  349. {
  350. if (_nodeProperties[i]._id == _nodesWithMeshRB[j])
  351. {
  352. loadWithMeshRBSupport = true;
  353. break;
  354. }
  355. }
  356. Node* node = tmpPackage->loadNode(_nodeProperties[i]._id.c_str(), loadWithMeshRBSupport);
  357. if (!node)
  358. WARN_VARG("Could not load node '%s' in GPB file '%s'.", _nodeProperties[i]._id.c_str(), _nodeProperties[i]._file.c_str());
  359. else
  360. {
  361. node->setId(_nodeProperties[i]._nodeID);
  362. scene->addNode(node);
  363. SAFE_RELEASE(node);
  364. }
  365. SAFE_RELEASE(tmpPackage);
  366. }
  367. }
  368. else
  369. {
  370. // TODO: Should we do all nodes with this case first to allow users to stitch in nodes with
  371. // IDs equal to IDs that were in the original GPB file but were changed in the scene file?
  372. // Otherwise, the node is from the main GPB and should just be renamed.
  373. Node* node = scene->findNode(_nodeProperties[i]._id.c_str());
  374. if (!node)
  375. WARN_VARG("Could not find node '%s' in main scene GPB file.", _nodeProperties[i]._id.c_str());
  376. else
  377. node->setId(_nodeProperties[i]._nodeID);
  378. }
  379. }
  380. // Remove the node property since we are done applying it.
  381. _nodeProperties.erase(_nodeProperties.begin() + i);
  382. }
  383. else
  384. i++;
  385. }
  386. }
  387. void SceneLoader::buildReferenceTables(Properties* sceneProperties)
  388. {
  389. // Go through the child namespaces of the scene.
  390. Properties* ns;
  391. const char* name = NULL;
  392. while (ns = sceneProperties->getNextNamespace())
  393. {
  394. if (strcmp(ns->getNamespace(), "node") == 0)
  395. {
  396. if (strlen(ns->getId()) == 0)
  397. {
  398. WARN("Nodes must have an ID; skipping the current node.");
  399. continue;
  400. }
  401. while (name = ns->getNextProperty())
  402. {
  403. if (strcmp(name, "url") == 0)
  404. {
  405. addSceneNodeProperty(SceneNodeProperty::URL, ns->getId(), ns->getString());
  406. }
  407. else if (strcmp(name, "audio") == 0)
  408. {
  409. addSceneNodeProperty(SceneNodeProperty::AUDIO, ns->getId(), ns->getString());
  410. }
  411. else if (strcmp(name, "material") == 0)
  412. {
  413. addSceneNodeProperty(SceneNodeProperty::MATERIAL, ns->getId(), ns->getString());
  414. }
  415. else if (strcmp(name, "particle") == 0)
  416. {
  417. addSceneNodeProperty(SceneNodeProperty::PARTICLE, ns->getId(), ns->getString());
  418. }
  419. else if (strcmp(name, "rigidbody") == 0)
  420. {
  421. addSceneNodeProperty(SceneNodeProperty::RIGIDBODY, ns->getId(), ns->getString());
  422. }
  423. else if (strcmp(name, "rigidbodymodel") == 0)
  424. {
  425. // Ignore this for now. We process this when we do rigid body creation.
  426. }
  427. else if (strcmp(name, "translate") == 0)
  428. {
  429. addSceneNodeProperty(SceneNodeProperty::TRANSLATE, ns->getId());
  430. }
  431. else if (strcmp(name, "rotate") == 0)
  432. {
  433. addSceneNodeProperty(SceneNodeProperty::ROTATE, ns->getId());
  434. }
  435. else if (strcmp(name, "scale") == 0)
  436. {
  437. addSceneNodeProperty(SceneNodeProperty::SCALE, ns->getId());
  438. }
  439. else
  440. {
  441. WARN_VARG("Unsupported node property: %s = %s", name, ns->getString());
  442. }
  443. }
  444. }
  445. else if (strcmp(ns->getNamespace(), "animations") == 0)
  446. {
  447. // Load all the animations.
  448. Properties* animation;
  449. while (animation = ns->getNextNamespace())
  450. {
  451. if (strcmp(animation->getNamespace(), "animation") == 0)
  452. {
  453. const char* animationID = animation->getId();
  454. if (strlen(animationID) == 0)
  455. {
  456. WARN("Animations must have an ID; skipping the current animation.");
  457. continue;
  458. }
  459. const char* url = animation->getString("url");
  460. if (!url)
  461. {
  462. WARN_VARG("Animations must have a URL; skipping animation '%s'.", animationID);
  463. continue;
  464. }
  465. const char* targetID = animation->getString("target");
  466. if (!targetID)
  467. {
  468. WARN_VARG("Animations must have a target; skipping animation '%s'.", animationID);
  469. continue;
  470. }
  471. addSceneAnimation(animationID, targetID, url);
  472. }
  473. else
  474. {
  475. WARN_VARG("Unsupported child namespace (of 'animations'): %s", ns->getNamespace());
  476. }
  477. }
  478. }
  479. else if (strcmp(ns->getNamespace(), "physics") == 0)
  480. {
  481. // Note: we don't load physics until the whole scene file has been
  482. // loaded so that all node references (i.e. for constraints) can be resolved.
  483. }
  484. else
  485. {
  486. WARN_VARG("Unsupported child namespace (of 'scene'): %s", ns->getNamespace());
  487. }
  488. }
  489. }
  490. void SceneLoader::calculateNodesWithMeshRigidBodies(const Properties* sceneProperties)
  491. {
  492. const char* name = NULL;
  493. // Make a list of all nodes with triangle mesh rigid bodies.
  494. for (unsigned int i = 0; i < _nodeProperties.size(); i++)
  495. {
  496. if (_nodeProperties[i]._type == SceneNodeProperty::RIGIDBODY)
  497. {
  498. Properties* p = _propertiesFromFile[_nodeProperties[i]._file];
  499. if (p)
  500. {
  501. if (_nodeProperties[i]._id.size() > 0)
  502. {
  503. p = p->getNamespace(_nodeProperties[i]._id.c_str());
  504. }
  505. else
  506. {
  507. p = p->getNextNamespace();
  508. }
  509. if (p && strcmp(p->getNamespace(), "rigidbody") == 0 &&
  510. strcmp(p->getString("type"), "MESH") == 0)
  511. {
  512. // If the node specifies a rigidbodymodel, then use
  513. // that node's ID; otherwise, use its ID.
  514. Properties* p = sceneProperties->getNamespace(_nodeProperties[i]._nodeID);
  515. if (p && (name = p->getString("rigidbodymodel")))
  516. _nodesWithMeshRB.push_back(name);
  517. else
  518. _nodesWithMeshRB.push_back(_nodeProperties[i]._nodeID);
  519. }
  520. }
  521. }
  522. }
  523. }
  524. void SceneLoader::createAnimations(const Scene* scene)
  525. {
  526. // Create the scene animations.
  527. for (unsigned int i = 0; i < _animations.size(); i++)
  528. {
  529. // If the target node doesn't exist in the scene, then we
  530. // can't do anything so we skip to the next animation.
  531. Node* node = scene->findNode(_animations[i]._targetID);
  532. if (!node)
  533. {
  534. WARN_VARG("Attempting to create an animation targeting node '%s', which does not exist in the scene.", _animations[i]._targetID);
  535. continue;
  536. }
  537. // Check to make sure the referenced properties object was loaded properly.
  538. Properties* p = _propertiesFromFile[_animations[i]._file];
  539. if (!p)
  540. {
  541. WARN_VARG("The referenced animation data in file '%s' failed to load.", _animations[i]._file.c_str());
  542. continue;
  543. }
  544. if (_animations[i]._id.size() > 0)
  545. {
  546. p = p->getNamespace(_animations[i]._id.c_str());
  547. if (!p)
  548. {
  549. WARN_VARG("The referenced animation data at '%s#%s' failed to load.", _animations[i]._file.c_str(), _animations[i]._id.c_str());
  550. continue;
  551. }
  552. }
  553. Game::getInstance()->getAnimationController()->createAnimation(_animations[i]._animationID, node, p);
  554. }
  555. }
  556. const SceneLoader::MeshRigidBodyData* SceneLoader::getMeshRigidBodyData(std::string id)
  557. {
  558. if (!_meshRigidBodyData)
  559. {
  560. WARN("Attempting to get mesh rigid body data, but none has been loaded; ignoring request.");
  561. return NULL;
  562. }
  563. return (_meshRigidBodyData->count(id) > 0) ? &(*_meshRigidBodyData)[id] : NULL;
  564. }
  565. PhysicsConstraint* SceneLoader::loadGenericConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  566. {
  567. PhysicsGenericConstraint* physicsConstraint;
  568. // Create the constraint from the specified properties.
  569. Quaternion roA;
  570. Vector3 toA;
  571. bool offsetSpecified = constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  572. offsetSpecified |= constraint->getVector3("translationOffsetA", &toA);
  573. if (offsetSpecified)
  574. {
  575. if (rbB)
  576. {
  577. Quaternion roB;
  578. Vector3 toB;
  579. constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  580. constraint->getVector3("translationOffsetB", &toB);
  581. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, roA, toB, rbB, roB, toB);
  582. }
  583. else
  584. {
  585. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, roA, toA);
  586. }
  587. }
  588. else
  589. {
  590. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, rbB);
  591. }
  592. // Set the optional parameters that were specified.
  593. Vector3 v;
  594. if (constraint->getVector3("angularLowerLimit", &v))
  595. physicsConstraint->setAngularLowerLimit(v);
  596. if (constraint->getVector3("angularUpperLimit", &v))
  597. physicsConstraint->setAngularUpperLimit(v);
  598. if (constraint->getVector3("linearLowerLimit", &v))
  599. physicsConstraint->setLinearLowerLimit(v);
  600. if (constraint->getVector3("linearUpperLimit", &v))
  601. physicsConstraint->setLinearUpperLimit(v);
  602. return physicsConstraint;
  603. }
  604. PhysicsConstraint* SceneLoader::loadHingeConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  605. {
  606. PhysicsHingeConstraint* physicsConstraint = NULL;
  607. // Create the constraint from the specified properties.
  608. Quaternion roA;
  609. Vector3 toA;
  610. constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  611. constraint->getVector3("translationOffsetA", &toA);
  612. if (rbB)
  613. {
  614. Quaternion roB;
  615. Vector3 toB;
  616. constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  617. constraint->getVector3("translationOffsetB", &toB);
  618. physicsConstraint = Game::getInstance()->getPhysicsController()->createHingeConstraint(rbA, roA, toB, rbB, roB, toB);
  619. }
  620. else
  621. {
  622. physicsConstraint = Game::getInstance()->getPhysicsController()->createHingeConstraint(rbA, roA, toA);
  623. }
  624. // Attempt to load the hinge limits first as a Vector3 and if that doesn't work, try loading as a Vector2.
  625. // We do this because the user can specify just the min and max angle, or both angle along with bounciness.
  626. Vector3 fullLimits;
  627. Vector2 angleLimits;
  628. if (constraint->getVector3("limits", &fullLimits))
  629. physicsConstraint->setLimits(MATH_DEG_TO_RAD(fullLimits.x), MATH_DEG_TO_RAD(fullLimits.y), fullLimits.z);
  630. else if (constraint->getVector2("limits", &angleLimits))
  631. physicsConstraint->setLimits(angleLimits.x, angleLimits.y);
  632. return physicsConstraint;
  633. }
  634. Scene* SceneLoader::loadMainSceneData(const Properties* sceneProperties)
  635. {
  636. // Load the main scene from the specified path.
  637. const char* path = sceneProperties->getString("path");
  638. Package* package = Package::create(path);
  639. if (!package)
  640. {
  641. WARN_VARG("Failed to load scene GPB file '%s'.", path);
  642. return NULL;
  643. }
  644. Scene* scene = package->loadScene(NULL, &_nodesWithMeshRB);
  645. if (!scene)
  646. {
  647. WARN_VARG("Failed to load scene from '%s'.", path);
  648. SAFE_RELEASE(package);
  649. return NULL;
  650. }
  651. // Go through the supported scene properties and apply them to the scene.
  652. const char* name = sceneProperties->getString("activeCamera");
  653. if (name)
  654. {
  655. Node* camera = scene->findNode(name);
  656. if (camera && camera->getCamera())
  657. scene->setActiveCamera(camera->getCamera());
  658. }
  659. SAFE_RELEASE(package);
  660. return scene;
  661. }
  662. void SceneLoader::loadPhysics(Properties* physics, Scene* scene)
  663. {
  664. // Go through the supported global physics properties and apply them.
  665. Vector3 gravity;
  666. if (physics->getVector3("gravity", &gravity))
  667. Game::getInstance()->getPhysicsController()->setGravity(gravity);
  668. Properties* constraint;
  669. const char* name;
  670. while (constraint = physics->getNextNamespace())
  671. {
  672. if (strcmp(constraint->getNamespace(), "constraint") == 0)
  673. {
  674. // Get the constraint type.
  675. std::string type = constraint->getString("type");
  676. // Attempt to load the first rigid body. If the first rigid body cannot
  677. // be loaded or found, then continue to the next constraint (error).
  678. name = constraint->getString("rigidBodyA");
  679. if (!name)
  680. {
  681. WARN_VARG("Missing property 'rigidBodyA' for constraint %s", constraint->getId());
  682. continue;
  683. }
  684. Node* rbANode = scene->findNode(name);
  685. if (!rbANode)
  686. {
  687. WARN_VARG("Node '%s' to be used as 'rigidBodyA' for constraint %s cannot be found.", name, constraint->getId());
  688. continue;
  689. }
  690. PhysicsRigidBody* rbA = rbANode->getPhysicsRigidBody();
  691. if (!rbA)
  692. {
  693. WARN_VARG("Node '%s' to be used as 'rigidBodyA' does not have a rigid body.", name);
  694. continue;
  695. }
  696. // Attempt to load the second rigid body. If the second rigid body is not
  697. // specified, that is usually okay (only spring constraints require both and
  698. // we check that below), but if the second rigid body is specified and it doesn't
  699. // load properly, then continue to the next constraint (error).
  700. name = constraint->getString("rigidBodyB");
  701. PhysicsRigidBody* rbB = NULL;
  702. if (name)
  703. {
  704. Node* rbBNode = scene->findNode(name);
  705. if (!rbBNode)
  706. {
  707. WARN_VARG("Node '%s' to be used as 'rigidBodyB' for constraint %s cannot be found.", name, constraint->getId());
  708. continue;
  709. }
  710. rbB = rbBNode->getPhysicsRigidBody();
  711. if (!rbB)
  712. {
  713. WARN_VARG("Node '%s' to be used as 'rigidBodyB' does not have a rigid body.", name);
  714. continue;
  715. }
  716. }
  717. PhysicsConstraint* physicsConstraint = NULL;
  718. // Load the constraint based on its type.
  719. if (type == "FIXED")
  720. {
  721. physicsConstraint = Game::getInstance()->getPhysicsController()->createFixedConstraint(rbA, rbB);
  722. }
  723. else if (type == "GENERIC")
  724. {
  725. physicsConstraint = loadGenericConstraint(constraint, rbA, rbB);
  726. }
  727. else if (type == "HINGE")
  728. {
  729. physicsConstraint = loadHingeConstraint(constraint, rbA, rbB);
  730. }
  731. else if (type == "SOCKET")
  732. {
  733. physicsConstraint = loadSocketConstraint(constraint, rbA, rbB);
  734. }
  735. else if (type == "SPRING")
  736. {
  737. physicsConstraint = loadSpringConstraint(constraint, rbA, rbB);
  738. }
  739. // If the constraint failed to load, continue on to the next one.
  740. if (!physicsConstraint)
  741. continue;
  742. // If the breaking impulse was specified, apply it to the constraint.
  743. if (constraint->getString("breakingImpulse"))
  744. physicsConstraint->setBreakingImpulse(constraint->getFloat("breakingImpulse"));
  745. }
  746. else
  747. {
  748. WARN_VARG("Unsupported child namespace (of 'physics'): %s", physics->getNamespace());
  749. }
  750. }
  751. }
  752. void SceneLoader::loadReferencedFiles()
  753. {
  754. // Load all referenced properties files.
  755. std::map<std::string, Properties*>::iterator iter = _propertiesFromFile.begin();
  756. for (; iter != _propertiesFromFile.end(); iter++)
  757. {
  758. Properties* p = Properties::create(iter->first.c_str());
  759. assert(p);
  760. if (p == NULL)
  761. WARN_VARG("Failed to load referenced file: %s", iter->first.c_str());
  762. iter->second = p;
  763. }
  764. }
  765. PhysicsConstraint* SceneLoader::loadSocketConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  766. {
  767. PhysicsSocketConstraint* physicsConstraint = NULL;
  768. Vector3 toA;
  769. bool offsetSpecified = constraint->getVector3("translationOffsetA", &toA);
  770. if (offsetSpecified)
  771. {
  772. if (rbB)
  773. {
  774. Vector3 toB;
  775. constraint->getVector3("translationOffsetB", &toB);
  776. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, toA, rbB, toB);
  777. }
  778. else
  779. {
  780. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, toA);
  781. }
  782. }
  783. else
  784. {
  785. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, rbB);
  786. }
  787. return physicsConstraint;
  788. }
  789. PhysicsConstraint* SceneLoader::loadSpringConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  790. {
  791. if (!rbB)
  792. {
  793. WARN("Spring constraints require two rigid bodies.");
  794. return NULL;
  795. }
  796. PhysicsSpringConstraint* physicsConstraint = NULL;
  797. // Create the constraint from the specified properties.
  798. Quaternion roA, roB;
  799. Vector3 toA, toB;
  800. bool offsetsSpecified = constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  801. offsetsSpecified |= constraint->getVector3("translationOffsetA", &toA);
  802. offsetsSpecified |= constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  803. offsetsSpecified |= constraint->getVector3("translationOffsetB", &toB);
  804. if (offsetsSpecified)
  805. {
  806. physicsConstraint = Game::getInstance()->getPhysicsController()->createSpringConstraint(rbA, roA, toB, rbB, roB, toB);
  807. }
  808. else
  809. {
  810. physicsConstraint = Game::getInstance()->getPhysicsController()->createSpringConstraint(rbA, rbB);
  811. }
  812. // Set the optional parameters that were specified.
  813. Vector3 v;
  814. if (constraint->getVector3("angularLowerLimit", &v))
  815. physicsConstraint->setAngularLowerLimit(v);
  816. if (constraint->getVector3("angularUpperLimit", &v))
  817. physicsConstraint->setAngularUpperLimit(v);
  818. if (constraint->getVector3("linearLowerLimit", &v))
  819. physicsConstraint->setLinearLowerLimit(v);
  820. if (constraint->getVector3("linearUpperLimit", &v))
  821. physicsConstraint->setLinearUpperLimit(v);
  822. if (constraint->getString("angularDampingX"))
  823. physicsConstraint->setAngularDampingX(constraint->getFloat("angularDampingX"));
  824. if (constraint->getString("angularDampingY"))
  825. physicsConstraint->setAngularDampingY(constraint->getFloat("angularDampingY"));
  826. if (constraint->getString("angularDampingZ"))
  827. physicsConstraint->setAngularDampingZ(constraint->getFloat("angularDampingZ"));
  828. if (constraint->getString("angularStrengthX"))
  829. physicsConstraint->setAngularStrengthX(constraint->getFloat("angularStrengthX"));
  830. if (constraint->getString("angularStrengthY"))
  831. physicsConstraint->setAngularStrengthY(constraint->getFloat("angularStrengthY"));
  832. if (constraint->getString("angularStrengthZ"))
  833. physicsConstraint->setAngularStrengthZ(constraint->getFloat("angularStrengthZ"));
  834. if (constraint->getString("linearDampingX"))
  835. physicsConstraint->setLinearDampingX(constraint->getFloat("linearDampingX"));
  836. if (constraint->getString("linearDampingY"))
  837. physicsConstraint->setLinearDampingY(constraint->getFloat("linearDampingY"));
  838. if (constraint->getString("linearDampingZ"))
  839. physicsConstraint->setLinearDampingZ(constraint->getFloat("linearDampingZ"));
  840. if (constraint->getString("linearStrengthX"))
  841. physicsConstraint->setLinearStrengthX(constraint->getFloat("linearStrengthX"));
  842. if (constraint->getString("linearStrengthY"))
  843. physicsConstraint->setLinearStrengthY(constraint->getFloat("linearStrengthY"));
  844. if (constraint->getString("linearStrengthZ"))
  845. physicsConstraint->setLinearStrengthZ(constraint->getFloat("linearStrengthZ"));
  846. return physicsConstraint;
  847. }
  848. void SceneLoader::splitURL(const char* url, std::string* file, std::string* id)
  849. {
  850. if (!url)
  851. return;
  852. std::string urlString = url;
  853. // Check if the url references a file (otherwise, it only references a node within the main GPB).
  854. unsigned int loc = urlString.rfind(".");
  855. if (loc != urlString.npos)
  856. {
  857. // If the url references a specific namespace within the file,
  858. // set the id out parameter appropriately. Otherwise, set the id out
  859. // parameter to the empty string so we know to load the first namespace.
  860. loc = urlString.rfind("#");
  861. if (loc != urlString.npos)
  862. {
  863. *file = urlString.substr(0, loc);
  864. *id = urlString.substr(loc + 1);
  865. }
  866. else
  867. {
  868. *file = url;
  869. *id = std::string();
  870. }
  871. }
  872. else
  873. {
  874. *file = std::string();
  875. *id = url;
  876. }
  877. }
  878. }