Context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Core/EventProfiler.h"
  6. #include "../IO/Log.h"
  7. #ifndef MINI_URHO
  8. #include <SDL/SDL.h>
  9. #ifdef URHO3D_IK
  10. #include <ik/log.h>
  11. #include <ik/memory.h>
  12. #endif
  13. #endif
  14. #include "../DebugNew.h"
  15. namespace Urho3D
  16. {
  17. #ifndef MINI_URHO
  18. // Keeps track of how many times SDL was initialised so we know when to call SDL_Quit().
  19. static int sdlInitCounter = 0;
  20. // Keeps track of how many times IK was initialised
  21. static int ikInitCounter = 0;
  22. // Reroute all messages from the ik library to the Urho3D log
  23. static void HandleIKLog(const char* msg)
  24. {
  25. URHO3D_LOGINFOF("[IK] %s", msg);
  26. }
  27. #endif
  28. void EventReceiverGroup::BeginSendEvent()
  29. {
  30. ++inSend_;
  31. }
  32. void EventReceiverGroup::EndSendEvent()
  33. {
  34. assert(inSend_ > 0);
  35. --inSend_;
  36. if (inSend_ == 0 && dirty_)
  37. {
  38. /// \todo Could be optimized by erase-swap, but this keeps the receiver order
  39. for (unsigned i = receivers_.Size() - 1; i < receivers_.Size(); --i)
  40. {
  41. if (!receivers_[i])
  42. receivers_.Erase(i);
  43. }
  44. dirty_ = false;
  45. }
  46. }
  47. void EventReceiverGroup::Add(Object* object)
  48. {
  49. if (object)
  50. receivers_.Push(object);
  51. }
  52. void EventReceiverGroup::Remove(Object* object)
  53. {
  54. if (inSend_ > 0)
  55. {
  56. PODVector<Object*>::Iterator i = receivers_.Find(object);
  57. if (i != receivers_.End())
  58. {
  59. (*i) = nullptr;
  60. dirty_ = true;
  61. }
  62. }
  63. else
  64. receivers_.Remove(object);
  65. }
  66. void RemoveNamedAttribute(HashMap<StringHash, Vector<AttributeInfo>>& attributes, StringHash objectType, const char* name)
  67. {
  68. HashMap<StringHash, Vector<AttributeInfo>>::Iterator i = attributes.Find(objectType);
  69. if (i == attributes.End())
  70. return;
  71. Vector<AttributeInfo>& infos = i->second_;
  72. for (Vector<AttributeInfo>::Iterator j = infos.Begin(); j != infos.End(); ++j)
  73. {
  74. if (!j->name_.Compare(name, true))
  75. {
  76. infos.Erase(j);
  77. break;
  78. }
  79. }
  80. // If the vector became empty, erase the object type from the map
  81. if (infos.Empty())
  82. attributes.Erase(i);
  83. }
  84. Context::Context() :
  85. eventHandler_(nullptr)
  86. {
  87. #ifdef __ANDROID__
  88. // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs
  89. SetRandomSeed(1);
  90. #endif
  91. // Set the main thread ID (assuming the Context is created in it)
  92. Thread::SetMainThread();
  93. }
  94. Context::~Context()
  95. {
  96. // Remove subsystems that use SDL in reverse order of construction, so that Graphics can shut down SDL last
  97. /// \todo Context should not need to know about subsystems
  98. RemoveSubsystem("Audio");
  99. RemoveSubsystem("UI");
  100. RemoveSubsystem("Input");
  101. RemoveSubsystem("Renderer");
  102. RemoveSubsystem("Graphics");
  103. subsystems_.Clear();
  104. factories_.Clear();
  105. // Delete allocated event data maps
  106. for (PODVector<VariantMap*>::Iterator i = eventDataMaps_.Begin(); i != eventDataMaps_.End(); ++i)
  107. delete *i;
  108. eventDataMaps_.Clear();
  109. }
  110. SharedPtr<Object> Context::CreateObject(StringHash objectType)
  111. {
  112. HashMap<StringHash, SharedPtr<ObjectFactory>>::ConstIterator i = factories_.Find(objectType);
  113. if (i != factories_.End())
  114. return i->second_->CreateObject();
  115. else
  116. return SharedPtr<Object>();
  117. }
  118. void Context::RegisterFactory(ObjectFactory* factory)
  119. {
  120. if (!factory)
  121. return;
  122. factories_[factory->GetType()] = factory;
  123. }
  124. void Context::RegisterFactory(ObjectFactory* factory, const char* category)
  125. {
  126. if (!factory)
  127. return;
  128. RegisterFactory(factory);
  129. if (String::CStringLength(category))
  130. objectCategories_[category].Push(factory->GetType());
  131. }
  132. void Context::RegisterSubsystem(Object* object)
  133. {
  134. if (!object)
  135. return;
  136. subsystems_[object->GetType()] = object;
  137. }
  138. void Context::RemoveSubsystem(StringHash objectType)
  139. {
  140. HashMap<StringHash, SharedPtr<Object>>::Iterator i = subsystems_.Find(objectType);
  141. if (i != subsystems_.End())
  142. subsystems_.Erase(i);
  143. }
  144. AttributeHandle Context::RegisterAttribute(StringHash objectType, const AttributeInfo& attr)
  145. {
  146. // None or pointer types can not be supported
  147. if (attr.type_ == VAR_NONE || attr.type_ == VAR_VOIDPTR || attr.type_ == VAR_PTR
  148. || attr.type_ == VAR_CUSTOM_HEAP || attr.type_ == VAR_CUSTOM_STACK)
  149. {
  150. URHO3D_LOGWARNING("Attempt to register unsupported attribute type " + Variant::GetTypeName(attr.type_) + " to class " +
  151. GetTypeName(objectType));
  152. return AttributeHandle();
  153. }
  154. AttributeHandle handle;
  155. Vector<AttributeInfo>& objectAttributes = attributes_[objectType];
  156. objectAttributes.Push(attr);
  157. handle.attributeInfo_ = &objectAttributes.Back();
  158. if (attr.mode_ & AM_NET)
  159. {
  160. Vector<AttributeInfo>& objectNetworkAttributes = networkAttributes_[objectType];
  161. objectNetworkAttributes.Push(attr);
  162. handle.networkAttributeInfo_ = &objectNetworkAttributes.Back();
  163. }
  164. return handle;
  165. }
  166. void Context::RemoveAttribute(StringHash objectType, const char* name)
  167. {
  168. RemoveNamedAttribute(attributes_, objectType, name);
  169. RemoveNamedAttribute(networkAttributes_, objectType, name);
  170. }
  171. void Context::RemoveAllAttributes(StringHash objectType)
  172. {
  173. attributes_.Erase(objectType);
  174. networkAttributes_.Erase(objectType);
  175. }
  176. void Context::UpdateAttributeDefaultValue(StringHash objectType, const char* name, const Variant& defaultValue)
  177. {
  178. AttributeInfo* info = GetAttribute(objectType, name);
  179. if (info)
  180. info->defaultValue_ = defaultValue;
  181. }
  182. VariantMap& Context::GetEventDataMap()
  183. {
  184. unsigned nestingLevel = eventSenders_.Size();
  185. while (eventDataMaps_.Size() < nestingLevel + 1)
  186. eventDataMaps_.Push(new VariantMap());
  187. VariantMap& ret = *eventDataMaps_[nestingLevel];
  188. ret.Clear();
  189. return ret;
  190. }
  191. #ifndef MINI_URHO
  192. bool Context::RequireSDL(unsigned int sdlFlags)
  193. {
  194. // Always increment, the caller must match with ReleaseSDL(), regardless of
  195. // what happens.
  196. ++sdlInitCounter;
  197. // Need to call SDL_Init() at least once before SDL_InitSubsystem()
  198. if (sdlInitCounter == 1)
  199. {
  200. URHO3D_LOGDEBUG("Initialising SDL");
  201. if (SDL_Init(0) != 0)
  202. {
  203. URHO3D_LOGERRORF("Failed to initialise SDL: %s", SDL_GetError());
  204. return false;
  205. }
  206. }
  207. Uint32 remainingFlags = sdlFlags & ~SDL_WasInit(0);
  208. if (remainingFlags != 0)
  209. {
  210. if (SDL_InitSubSystem(remainingFlags) != 0)
  211. {
  212. URHO3D_LOGERRORF("Failed to initialise SDL subsystem: %s", SDL_GetError());
  213. return false;
  214. }
  215. }
  216. return true;
  217. }
  218. void Context::ReleaseSDL()
  219. {
  220. --sdlInitCounter;
  221. if (sdlInitCounter == 0)
  222. {
  223. URHO3D_LOGDEBUG("Quitting SDL");
  224. SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
  225. SDL_Quit();
  226. }
  227. if (sdlInitCounter < 0)
  228. URHO3D_LOGERROR("Too many calls to Context::ReleaseSDL()!");
  229. }
  230. #ifdef URHO3D_IK
  231. void Context::RequireIK()
  232. {
  233. // Always increment, the caller must match with ReleaseIK(), regardless of
  234. // what happens.
  235. ++ikInitCounter;
  236. if (ikInitCounter == 1)
  237. {
  238. URHO3D_LOGDEBUG("Initialising Inverse Kinematics library");
  239. ik_memory_init();
  240. ik_log_init(IK_LOG_NONE);
  241. ik_log_register_listener(HandleIKLog);
  242. }
  243. }
  244. void Context::ReleaseIK()
  245. {
  246. --ikInitCounter;
  247. if (ikInitCounter == 0)
  248. {
  249. URHO3D_LOGDEBUG("De-initialising Inverse Kinematics library");
  250. ik_log_unregister_listener(HandleIKLog);
  251. ik_log_deinit();
  252. ik_memory_deinit();
  253. }
  254. if (ikInitCounter < 0)
  255. URHO3D_LOGERROR("Too many calls to Context::ReleaseIK()");
  256. }
  257. #endif // ifdef URHO3D_IK
  258. #endif // ifndef MINI_URHO
  259. void Context::CopyBaseAttributes(StringHash baseType, StringHash derivedType)
  260. {
  261. // Prevent endless loop if mistakenly copying attributes from same class as derived
  262. if (baseType == derivedType)
  263. {
  264. URHO3D_LOGWARNING("Attempt to copy base attributes to itself for class " + GetTypeName(baseType));
  265. return;
  266. }
  267. const Vector<AttributeInfo>* baseAttributes = GetAttributes(baseType);
  268. if (baseAttributes)
  269. {
  270. for (unsigned i = 0; i < baseAttributes->Size(); ++i)
  271. {
  272. const AttributeInfo& attr = baseAttributes->At(i);
  273. attributes_[derivedType].Push(attr);
  274. if (attr.mode_ & AM_NET)
  275. networkAttributes_[derivedType].Push(attr);
  276. }
  277. }
  278. }
  279. Object* Context::GetSubsystem(StringHash type) const
  280. {
  281. HashMap<StringHash, SharedPtr<Object>>::ConstIterator i = subsystems_.Find(type);
  282. if (i != subsystems_.End())
  283. return i->second_;
  284. else
  285. return nullptr;
  286. }
  287. const Variant& Context::GetGlobalVar(StringHash key) const
  288. {
  289. VariantMap::ConstIterator i = globalVars_.Find(key);
  290. return i != globalVars_.End() ? i->second_ : Variant::EMPTY;
  291. }
  292. void Context::SetGlobalVar(StringHash key, const Variant& value)
  293. {
  294. globalVars_[key] = value;
  295. }
  296. Object* Context::GetEventSender() const
  297. {
  298. if (!eventSenders_.Empty())
  299. return eventSenders_.Back();
  300. else
  301. return nullptr;
  302. }
  303. const String& Context::GetTypeName(StringHash objectType) const
  304. {
  305. // Search factories to find the hash-to-name mapping
  306. HashMap<StringHash, SharedPtr<ObjectFactory>>::ConstIterator i = factories_.Find(objectType);
  307. return i != factories_.End() ? i->second_->GetTypeName() : String::EMPTY;
  308. }
  309. AttributeInfo* Context::GetAttribute(StringHash objectType, const char* name)
  310. {
  311. HashMap<StringHash, Vector<AttributeInfo>>::Iterator i = attributes_.Find(objectType);
  312. if (i == attributes_.End())
  313. return nullptr;
  314. Vector<AttributeInfo>& infos = i->second_;
  315. for (Vector<AttributeInfo>::Iterator j = infos.Begin(); j != infos.End(); ++j)
  316. {
  317. if (!j->name_.Compare(name, true))
  318. return &(*j);
  319. }
  320. return nullptr;
  321. }
  322. void Context::AddEventReceiver(Object* receiver, StringHash eventType)
  323. {
  324. SharedPtr<EventReceiverGroup>& group = eventReceivers_[eventType];
  325. if (!group)
  326. group = new EventReceiverGroup();
  327. group->Add(receiver);
  328. }
  329. void Context::AddEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  330. {
  331. SharedPtr<EventReceiverGroup>& group = specificEventReceivers_[sender][eventType];
  332. if (!group)
  333. group = new EventReceiverGroup();
  334. group->Add(receiver);
  335. }
  336. void Context::RemoveEventSender(Object* sender)
  337. {
  338. HashMap<Object*, HashMap<StringHash, SharedPtr<EventReceiverGroup>>>::Iterator i = specificEventReceivers_.Find(sender);
  339. if (i != specificEventReceivers_.End())
  340. {
  341. for (HashMap<StringHash, SharedPtr<EventReceiverGroup>>::Iterator j = i->second_.Begin(); j != i->second_.End(); ++j)
  342. {
  343. for (PODVector<Object*>::Iterator k = j->second_->receivers_.Begin(); k != j->second_->receivers_.End(); ++k)
  344. {
  345. Object* receiver = *k;
  346. if (receiver)
  347. receiver->RemoveEventSender(sender);
  348. }
  349. }
  350. specificEventReceivers_.Erase(i);
  351. }
  352. }
  353. void Context::RemoveEventReceiver(Object* receiver, StringHash eventType)
  354. {
  355. EventReceiverGroup* group = GetEventReceivers(eventType);
  356. if (group)
  357. group->Remove(receiver);
  358. }
  359. void Context::RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  360. {
  361. EventReceiverGroup* group = GetEventReceivers(sender, eventType);
  362. if (group)
  363. group->Remove(receiver);
  364. }
  365. void Context::BeginSendEvent(Object* sender, StringHash eventType)
  366. {
  367. #ifdef URHO3D_PROFILING
  368. if (EventProfiler::IsActive())
  369. {
  370. auto* eventProfiler = GetSubsystem<EventProfiler>();
  371. if (eventProfiler)
  372. eventProfiler->BeginBlock(eventType);
  373. }
  374. #endif
  375. eventSenders_.Push(sender);
  376. }
  377. void Context::EndSendEvent()
  378. {
  379. eventSenders_.Pop();
  380. #ifdef URHO3D_PROFILING
  381. if (EventProfiler::IsActive())
  382. {
  383. auto* eventProfiler = GetSubsystem<EventProfiler>();
  384. if (eventProfiler)
  385. eventProfiler->EndBlock();
  386. }
  387. #endif
  388. }
  389. }