Entity.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Log.h"
  25. #include "Scene.h"
  26. #include "StringUtils.h"
  27. #include "DebugNew.h"
  28. Entity::Entity(EntityID id, const std::string& name) :
  29. mID(id),
  30. mName(name),
  31. mNameHash(name),
  32. mNetFlags(NET_SYNCTOALL),
  33. mScene(0),
  34. mOwner(0),
  35. mNextComponentName(0x30),
  36. mNetUpdateDistance(0.0f),
  37. mPredictionTimer(0.0f)
  38. {
  39. }
  40. Entity::~Entity()
  41. {
  42. removeAllComponents();
  43. }
  44. void Entity::handleEvent(StringHash eventType, VariantMap& eventData)
  45. {
  46. // Special-case event handling: send to all components that are event listeners
  47. for (std::vector<EventListener*>::const_iterator i = mEventListeners.begin(); i != mEventListeners.end(); ++i)
  48. {
  49. // Note: we do not check if the component actually subscribes to the event, because handleEvent() does this check
  50. (*i)->handleEvent(eventType, eventData);
  51. }
  52. }
  53. void Entity::save(Serializer& dest)
  54. {
  55. // Write ID & name
  56. dest.writeUInt(mID);
  57. dest.writeString(mName);
  58. // Write netflags and update distance
  59. dest.writeUByte(mNetFlags);
  60. dest.writeFloat(mNetUpdateDistance);
  61. // Write properties
  62. dest.writeVLE(mProperties.size());
  63. for (PropertyMap::const_iterator i = mProperties.begin(); i != mProperties.end(); ++i)
  64. {
  65. dest.writeShortStringHash(i->first);
  66. dest.writeVariant(i->second.mValue);
  67. dest.writeBool(i->second.mSync);
  68. }
  69. // Write components
  70. dest.writeVLE(mComponents.size());
  71. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  72. (*i)->save(dest);
  73. }
  74. void Entity::load(Deserializer& source, ResourceCache* cache)
  75. {
  76. // ID and name are handled at the Scene level
  77. // Load should only be called for new entities, but remove components just to be sure
  78. removeAllComponents();
  79. // Read netflags and update distance
  80. mNetFlags = source.readUByte();
  81. mNetUpdateDistance = source.readFloat();
  82. // Read properties
  83. mProperties.clear();
  84. unsigned numProperties = source.readVLE();
  85. for (unsigned i = 0; i < numProperties; ++i)
  86. {
  87. ShortStringHash key = source.readShortStringHash();
  88. Property newProperty;
  89. newProperty.mValue = source.readVariant();
  90. newProperty.mSync = source.readBool();
  91. mProperties[key] = newProperty;
  92. }
  93. // Create and read components
  94. unsigned numComponents = source.readVLE();
  95. for (unsigned i = 0; i < numComponents; ++i)
  96. {
  97. ShortStringHash type = source.readShortStringHash();
  98. std::string name = source.readString();
  99. Component* newComponent = createComponent(type, name);
  100. newComponent->load(source, cache);
  101. }
  102. }
  103. void Entity::saveXML(XMLElement& dest)
  104. {
  105. // Write ID & name
  106. dest.setInt("id", mID);
  107. if (!mName.empty())
  108. dest.setString("name", mName);
  109. // Write netflags & netupdate distance
  110. dest.setInt("netflags", mNetFlags);
  111. dest.setFloat("netdistance", mNetUpdateDistance);
  112. // Write properties
  113. for (PropertyMap::const_iterator i = mProperties.begin(); i != mProperties.end(); ++i)
  114. {
  115. XMLElement propertyElem = dest.createChildElement("property");
  116. // Use name if possible, or hash if reverse mapping is unavailable
  117. std::string name = shortHashToString(i->first);
  118. if (name.empty())
  119. propertyElem.setInt("hash", i->first.mData);
  120. else
  121. propertyElem.setString("name", name);
  122. propertyElem.setVariant(i->second.mValue);
  123. propertyElem.setBool("sync", i->second.mSync);
  124. }
  125. // Write components
  126. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  127. {
  128. XMLElement componentElem = dest.createChildElement("component");
  129. (*i)->saveXML(componentElem);
  130. }
  131. }
  132. void Entity::loadXML(const XMLElement& source, ResourceCache* cache)
  133. {
  134. // ID and name are handled at the Scene level
  135. // Load should only be called for new entities, but remove components just to be sure
  136. removeAllComponents();
  137. // Read netflags
  138. mNetFlags = source.getInt("netflags");
  139. mNetUpdateDistance = source.getFloat("netdistance");
  140. // Read properties
  141. mProperties.clear();
  142. XMLElement propertyElem = source.getChildElement("property");
  143. while (propertyElem)
  144. {
  145. ShortStringHash key;
  146. if (propertyElem.hasAttribute("hash"))
  147. key.mData = propertyElem.getInt("hash");
  148. else
  149. key = ShortStringHash(propertyElem.getString("name"));
  150. Property newProperty;
  151. newProperty.mValue = propertyElem.getVariant();
  152. newProperty.mSync = propertyElem.getBool("sync");
  153. mProperties[key] = newProperty;
  154. propertyElem = propertyElem.getNextElement("property");
  155. }
  156. // Create and read components
  157. XMLElement componentElem = source.getChildElement("component");
  158. while (componentElem)
  159. {
  160. std::string type = componentElem.getString("type");
  161. std::string name = componentElem.getString("name");
  162. Component* newComponent = createComponent(ShortStringHash(type), name);
  163. newComponent->loadXML(componentElem, cache);
  164. componentElem = componentElem.getNextElement("component");
  165. }
  166. }
  167. void Entity::postLoad(ResourceCache* cache)
  168. {
  169. // Perform post-load on all components (resolve entity & component references)
  170. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  171. (*i)->postLoad(cache);
  172. }
  173. bool Entity::writeNetUpdate(Serializer& dest, Serializer& destRevision, Deserializer& baseRevision, const NetUpdateInfo& info)
  174. {
  175. // Note: this function only builds a delta-update of entity properties, not components
  176. VariantMap baseProperties;
  177. if (baseRevision.getSize())
  178. {
  179. // We read the base properties as an ordinary variantmap, because only synced properties are stored,
  180. // and therefored storing the sync bool would be redundant
  181. baseProperties = baseRevision.readVariantMap();
  182. }
  183. unsigned syncedProperties = 0;
  184. std::set<ShortStringHash> changedProperties;
  185. for (PropertyMap::iterator i = mProperties.begin(); i != mProperties.end(); ++i)
  186. {
  187. if (i->second.mSync)
  188. {
  189. VariantMap::const_iterator j = baseProperties.find(i->first);
  190. if ((j == baseProperties.end()) || (i->second.mValue != j->second))
  191. changedProperties.insert(i->first);
  192. ++syncedProperties;
  193. }
  194. }
  195. // Write all synced properties to the dest.revision buffer, and delta to network stream
  196. destRevision.writeVLE(syncedProperties);
  197. dest.writeVLE(changedProperties.size());
  198. for (PropertyMap::iterator i = mProperties.begin(); i != mProperties.end(); ++i)
  199. {
  200. if (i->second.mSync)
  201. {
  202. destRevision.writeShortStringHash(i->first);
  203. destRevision.writeVariant(i->second.mValue);
  204. if (changedProperties.find(i->first) != changedProperties.end())
  205. {
  206. dest.writeShortStringHash(i->first);
  207. dest.writeVariant(i->second.mValue);
  208. }
  209. }
  210. }
  211. return changedProperties.size() > 0;
  212. }
  213. void Entity::postNetUpdate(ResourceCache* cache)
  214. {
  215. // Perform post-network update on all components (resolve entity & component references)
  216. // Note: does not track which components actually got updated. For most components this is a no-op
  217. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  218. {
  219. if ((*i)->isProxy())
  220. (*i)->postNetUpdate(cache);
  221. }
  222. }
  223. void Entity::interpolate(bool snapToEnd)
  224. {
  225. // Interpolate all proxy components
  226. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  227. {
  228. if ((*i)->isProxy())
  229. (*i)->interpolate(snapToEnd);
  230. }
  231. }
  232. void Entity::getComponentRefs(std::vector<ComponentRef>& dest)
  233. {
  234. dest.clear();
  235. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  236. (*i)->getComponentRefs(dest);
  237. }
  238. void Entity::setName(const std::string& name)
  239. {
  240. mName = name;
  241. mNameHash = StringHash(name);
  242. }
  243. void Entity::setNetFlags(unsigned char flags)
  244. {
  245. // Respect the authority and proxy flags if they have been set already
  246. if (mNetFlags & NET_MODEFLAGS)
  247. mNetFlags = (mNetFlags & NET_MODEFLAGS) | (flags & ~NET_MODEFLAGS);
  248. else
  249. mNetFlags = flags;
  250. }
  251. void Entity::setOwner(Connection* owner)
  252. {
  253. if (mID >= LOCAL_ENTITY)
  254. {
  255. LOGERROR("Owner can not be set for local entities");
  256. return;
  257. }
  258. mOwner = owner;
  259. }
  260. void Entity::setProperty(ShortStringHash key, const Variant& value)
  261. {
  262. mProperties[key].mValue = value;
  263. }
  264. void Entity::setProperty(ShortStringHash key, const Variant& value, bool sync)
  265. {
  266. mProperties[key].mValue = value;
  267. mProperties[key].mSync = sync;
  268. }
  269. void Entity::setPropertySync(ShortStringHash key, bool enable)
  270. {
  271. mProperties[key].mSync = enable;
  272. }
  273. void Entity::setProperties(const PropertyMap& properties)
  274. {
  275. mProperties = properties;
  276. }
  277. void Entity::setProperties(const VariantMap& properties, bool sync)
  278. {
  279. mProperties.clear();
  280. for (VariantMap::const_iterator i = properties.begin(); i != properties.end(); ++i)
  281. {
  282. Property newProperty;
  283. newProperty.mValue = i->second;
  284. newProperty.mSync = sync;
  285. mProperties[i->first] = newProperty;
  286. }
  287. }
  288. void Entity::setNetUpdateDistance(float distance)
  289. {
  290. mNetUpdateDistance = max(distance, 0.0f);
  291. }
  292. void Entity::setPredictionTimer(float time)
  293. {
  294. if (!isTransientPredicted())
  295. return;
  296. mPredictionTimer = time;
  297. }
  298. void Entity::setPredictionFrom(Entity* other)
  299. {
  300. if (!isTransientPredicted())
  301. return;
  302. // If the other entity is owner-predicted, set full prediction period. Otherwise propagate the higher timer value
  303. if (other->isOwnerPredicted())
  304. mPredictionTimer = mScene->getTransientPredictionTime();
  305. if (other->isTransientPredicted())
  306. mPredictionTimer = max(mPredictionTimer, other->getPredictionTimer());
  307. }
  308. void Entity::updatePredictionTimer(float timeStep)
  309. {
  310. // Decrement prediction timer if necessary
  311. if (mPredictionTimer > 0.0f)
  312. mPredictionTimer = max(mPredictionTimer - timeStep, 0.0f);
  313. }
  314. void Entity::removeProperty(ShortStringHash key)
  315. {
  316. PropertyMap::iterator i = mProperties.find(key);
  317. if (i != mProperties.end())
  318. mProperties.erase(i);
  319. }
  320. void Entity::removeAllProperties()
  321. {
  322. mProperties.clear();
  323. }
  324. void Entity::addComponent(Component* component)
  325. {
  326. if (!component)
  327. {
  328. LOGERROR("Null component for addComponent");
  329. return;
  330. }
  331. ShortStringHash combinedHash = component->getCombinedHash();
  332. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  333. {
  334. // Make sure component is not already added
  335. if (component == *i)
  336. {
  337. LOGWARNING("Component " + component->getTypeName() + " already added to entity " + mName);
  338. return;
  339. }
  340. // Check the same combined hash does not already exist (can not replicate or load/save parent references)
  341. if (combinedHash == (*i)->getCombinedHash())
  342. {
  343. // If types differ, it is a more insiduous hash collision
  344. if (component->getType() != (*i)->getType())
  345. {
  346. SAFE_EXCEPTION("Component hash collision between " + component->getTypeName() + " name " + component->getName() +
  347. " and " + (*i)->getTypeName() + " name " + (*i)->getName() + " in entity " + mName);
  348. }
  349. // The more common cause is adding several components with the same type and name
  350. else
  351. {
  352. LOGERROR("Component with type " + component->getTypeName() + " name " + component->getName() +
  353. "already exists in entity " + mName);
  354. }
  355. }
  356. }
  357. component->mEntity = this;
  358. mComponents.push_back(SharedPtr<Component>(component));
  359. updateEventListeners();
  360. }
  361. Component* Entity::createComponent(ShortStringHash type, const std::string& name)
  362. {
  363. if (!mScene)
  364. EXCEPTION("Entity not in scene, can not create components");
  365. SharedPtr<Component> newComponent = mScene->createComponent(type, name);
  366. addComponent(newComponent);
  367. return newComponent;
  368. }
  369. void Entity::removeComponent(Component* component)
  370. {
  371. if (!component)
  372. return;
  373. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  374. {
  375. if ((*i) == component)
  376. {
  377. removeComponent(i);
  378. return;
  379. }
  380. }
  381. LOGWARNING("Component " + component->getTypeName() + " not found in entity " + mName);
  382. }
  383. void Entity::removeComponent(ShortStringHash type, const std::string& name)
  384. {
  385. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  386. {
  387. if (((*i)->getType() == type) && ((name.empty()) || ((*i)->getName() == name)))
  388. {
  389. removeComponent(i);
  390. return;
  391. }
  392. }
  393. LOGWARNING("Component type " + toString(type) + " name " + name + " not found in entity " + mName);
  394. }
  395. void Entity::removeComponent(ShortStringHash type, StringHash nameHash)
  396. {
  397. for (std::vector<SharedPtr<Component> >::iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  398. {
  399. if (((*i)->getType() == type) && ((!nameHash) || ((*i)->getNameHash() == nameHash)))
  400. {
  401. removeComponent(i);
  402. return;
  403. }
  404. }
  405. LOGWARNING("Component type " + toString(type) + " name hash " + toString(nameHash) + " not found in entity " + mName);
  406. }
  407. void Entity::removeAllComponents()
  408. {
  409. while (mComponents.size())
  410. removeComponent(mComponents.end() - 1, true);
  411. mEventListeners.clear();
  412. }
  413. bool Entity::hasProperty(ShortStringHash key) const
  414. {
  415. PropertyMap::const_iterator i = mProperties.find(key);
  416. if (i == mProperties.end())
  417. return false;
  418. return i->second.mValue.getType() != VAR_NONE;
  419. }
  420. const Variant& Entity::getProperty(ShortStringHash key) const
  421. {
  422. static const Variant empty;
  423. PropertyMap::const_iterator i = mProperties.find(key);
  424. if (i == mProperties.end())
  425. return empty;
  426. else
  427. return i->second.mValue;
  428. }
  429. bool Entity::getPropertySync(ShortStringHash key) const
  430. {
  431. PropertyMap::const_iterator i = mProperties.find(key);
  432. if (i == mProperties.end())
  433. return false;
  434. else
  435. return i->second.mSync;
  436. }
  437. std::string Entity::getUniqueComponentName()
  438. {
  439. std::string ret;
  440. ret += mNextComponentName;
  441. ++mNextComponentName;
  442. // Use only 0-9, @-Z and a-z to be sure component survives XML serialization
  443. if (mNextComponentName == 0x3a)
  444. mNextComponentName = 0x40;
  445. if (mNextComponentName == 0x5b)
  446. mNextComponentName = 0x61;
  447. if (mNextComponentName == 0x7b)
  448. mNextComponentName = 0x30;
  449. return ret;
  450. }
  451. bool Entity::hasComponent(ShortStringHash type) const
  452. {
  453. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  454. {
  455. if ((*i)->getType() == type)
  456. return true;
  457. }
  458. return false;
  459. }
  460. bool Entity::hasComponent(ShortStringHash type, const std::string& name) const
  461. {
  462. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  463. {
  464. if (((*i)->getType() == type) && ((*i)->getName() == name))
  465. return true;
  466. }
  467. return false;
  468. }
  469. bool Entity::hasComponent(ShortStringHash type, StringHash nameHash) const
  470. {
  471. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  472. {
  473. if (((*i)->getType() == type) && ((*i)->getNameHash() == nameHash))
  474. return true;
  475. }
  476. return false;
  477. }
  478. bool Entity::hasComponent(unsigned short combinedHash) const
  479. {
  480. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  481. {
  482. if ((*i)->getCombinedHash().mData == combinedHash)
  483. return true;
  484. }
  485. return false;
  486. }
  487. Component* Entity::getComponent(ShortStringHash type) const
  488. {
  489. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  490. {
  491. if ((*i)->getType() == type)
  492. return *i;
  493. }
  494. return 0;
  495. }
  496. Component* Entity::getComponent(ShortStringHash type, const std::string& name) const
  497. {
  498. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  499. {
  500. if (((*i)->getType() == type) && ((*i)->getName() == name))
  501. return *i;
  502. }
  503. return 0;
  504. }
  505. Component* Entity::getComponent(ShortStringHash type, StringHash nameHash) const
  506. {
  507. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  508. {
  509. if (((*i)->getType() == type) && ((*i)->getNameHash() == nameHash))
  510. return *i;
  511. }
  512. return 0;
  513. }
  514. Component* Entity::getComponent(unsigned short combinedHash) const
  515. {
  516. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  517. {
  518. if ((*i)->getCombinedHash().mData == combinedHash)
  519. return *i;
  520. }
  521. return 0;
  522. }
  523. std::vector<Component*> Entity::getComponents(ShortStringHash type) const
  524. {
  525. std::vector<Component*> ret;
  526. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  527. {
  528. if ((*i)->getType() == type)
  529. ret.push_back(*i);
  530. }
  531. return ret;
  532. }
  533. bool Entity::isPlayback() const
  534. {
  535. if (!mScene)
  536. return false;
  537. return mScene->isPlayback();
  538. }
  539. bool Entity::checkSync(Connection* connection) const
  540. {
  541. if (mNetFlags & NET_SYNCTONONE)
  542. return false;
  543. if (mNetFlags & NET_SYNCTOOWNER)
  544. return mOwner == connection;
  545. return true;
  546. }
  547. bool Entity::checkPrediction(Connection* connection) const
  548. {
  549. if (isOwnerPredicted())
  550. {
  551. // On server need to check the actual owner. On client need only check if owner is non-null
  552. if (isAuthority())
  553. {
  554. if ((mOwner) && (mOwner == connection))
  555. return true;
  556. }
  557. else
  558. {
  559. if (mOwner)
  560. return true;
  561. }
  562. }
  563. if (isTransientPredicted())
  564. return mPredictionTimer > 0.0f;
  565. return false;
  566. }
  567. void Entity::removeComponent(std::vector<SharedPtr<Component> >::iterator i, bool removeAll)
  568. {
  569. (*i)->mEntity = 0;
  570. mComponents.erase(i);
  571. if (!removeAll)
  572. updateEventListeners();
  573. }
  574. void Entity::updateEventListeners()
  575. {
  576. mEventListeners.clear();
  577. for (std::vector<SharedPtr<Component> >::const_iterator i = mComponents.begin(); i != mComponents.end(); ++i)
  578. {
  579. EventListener* listener = dynamic_cast<EventListener*>(i->getPtr());
  580. if (listener)
  581. mEventListeners.push_back(listener);
  582. }
  583. }