CCScheduler.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2016 Chukong Technologies Inc.
  6. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  7. http://www.cocos2d-x.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. #include "base/CCScheduler.h"
  25. #include "base/ccMacros.h"
  26. #include "base/CCDirector.h"
  27. #include "base/utlist.h"
  28. #include "base/ccCArray.h"
  29. #include "base/CCScriptSupport.h"
  30. NS_CC_BEGIN
  31. // data structures
  32. // A list double-linked list used for "updates with priority"
  33. typedef struct _listEntry
  34. {
  35. struct _listEntry *prev, *next;
  36. ccSchedulerFunc callback;
  37. void *target;
  38. int priority;
  39. bool paused;
  40. bool markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick
  41. } tListEntry;
  42. typedef struct _hashUpdateEntry
  43. {
  44. tListEntry **list; // Which list does it belong to ?
  45. tListEntry *entry; // entry in the list
  46. void *target;
  47. ccSchedulerFunc callback;
  48. UT_hash_handle hh;
  49. } tHashUpdateEntry;
  50. // Hash Element used for "selectors with interval"
  51. typedef struct _hashSelectorEntry
  52. {
  53. ccArray *timers;
  54. void *target;
  55. int timerIndex;
  56. Timer *currentTimer;
  57. bool paused;
  58. UT_hash_handle hh;
  59. } tHashTimerEntry;
  60. // implementation Timer
  61. Timer::Timer()
  62. : _scheduler(nullptr)
  63. , _elapsed(-1)
  64. , _runForever(false)
  65. , _useDelay(false)
  66. , _timesExecuted(0)
  67. , _repeat(0)
  68. , _delay(0.0f)
  69. , _interval(0.0f)
  70. , _aborted(false)
  71. {
  72. }
  73. void Timer::setupTimerWithInterval(float seconds, unsigned int repeat, float delay)
  74. {
  75. _elapsed = -1;
  76. _interval = seconds;
  77. _delay = delay;
  78. _useDelay = (_delay > 0.0f) ? true : false;
  79. _repeat = repeat;
  80. _runForever = (_repeat == CC_REPEAT_FOREVER) ? true : false;
  81. _timesExecuted = 0;
  82. }
  83. void Timer::update(float dt)
  84. {
  85. if (_elapsed == -1)
  86. {
  87. _elapsed = 0;
  88. _timesExecuted = 0;
  89. return;
  90. }
  91. // accumulate elapsed time
  92. _elapsed += dt;
  93. // deal with delay
  94. if (_useDelay)
  95. {
  96. if (_elapsed < _delay)
  97. {
  98. return;
  99. }
  100. _timesExecuted += 1; // important to increment before call trigger
  101. trigger(_delay);
  102. _elapsed = _elapsed - _delay;
  103. _useDelay = false;
  104. // after delay, the rest time should compare with interval
  105. if (isExhausted())
  106. { //unschedule timer
  107. cancel();
  108. return;
  109. }
  110. }
  111. // if _interval == 0, should trigger once every frame
  112. float interval = (_interval > 0) ? _interval : _elapsed;
  113. while ((_elapsed >= interval) && !_aborted)
  114. {
  115. _timesExecuted += 1; // important to increment before call trigger
  116. trigger(interval);
  117. _elapsed -= interval;
  118. if (isExhausted())
  119. {
  120. cancel();
  121. break;
  122. }
  123. if (_elapsed <= 0.f)
  124. {
  125. break;
  126. }
  127. }
  128. }
  129. bool Timer::isExhausted() const
  130. {
  131. return !_runForever && _timesExecuted > _repeat;
  132. }
  133. // TimerTargetSelector
  134. TimerTargetSelector::TimerTargetSelector()
  135. : _target(nullptr)
  136. , _selector(nullptr)
  137. {
  138. }
  139. bool TimerTargetSelector::initWithSelector(Scheduler* scheduler, SEL_SCHEDULE selector, Ref* target, float seconds, unsigned int repeat, float delay)
  140. {
  141. _scheduler = scheduler;
  142. _target = target;
  143. _selector = selector;
  144. setupTimerWithInterval(seconds, repeat, delay);
  145. return true;
  146. }
  147. void TimerTargetSelector::trigger(float dt)
  148. {
  149. if (_target && _selector)
  150. {
  151. (_target->*_selector)(dt);
  152. }
  153. }
  154. void TimerTargetSelector::cancel()
  155. {
  156. _scheduler->unschedule(_selector, _target);
  157. }
  158. // TimerTargetCallback
  159. TimerTargetCallback::TimerTargetCallback()
  160. : _target(nullptr)
  161. , _callback(nullptr)
  162. {
  163. }
  164. bool TimerTargetCallback::initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay)
  165. {
  166. _scheduler = scheduler;
  167. _target = target;
  168. _callback = callback;
  169. _key = key;
  170. setupTimerWithInterval(seconds, repeat, delay);
  171. return true;
  172. }
  173. void TimerTargetCallback::trigger(float dt)
  174. {
  175. if (_callback)
  176. {
  177. _callback(dt);
  178. }
  179. }
  180. void TimerTargetCallback::cancel()
  181. {
  182. _scheduler->unschedule(_key, _target);
  183. }
  184. #if CC_ENABLE_SCRIPT_BINDING
  185. // TimerScriptHandler
  186. bool TimerScriptHandler::initWithScriptHandler(int handler, float seconds)
  187. {
  188. _scriptHandler = handler;
  189. _elapsed = -1;
  190. _interval = seconds;
  191. return true;
  192. }
  193. void TimerScriptHandler::trigger(float dt)
  194. {
  195. if (0 != _scriptHandler)
  196. {
  197. SchedulerScriptData data(_scriptHandler,dt);
  198. ScriptEvent event(kScheduleEvent,&data);
  199. ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
  200. }
  201. }
  202. void TimerScriptHandler::cancel()
  203. {
  204. }
  205. #endif
  206. // implementation of Scheduler
  207. // Priority level reserved for system services.
  208. const int Scheduler::PRIORITY_SYSTEM = INT_MIN;
  209. // Minimum priority level for user scheduling.
  210. const int Scheduler::PRIORITY_NON_SYSTEM_MIN = PRIORITY_SYSTEM + 1;
  211. Scheduler::Scheduler(void)
  212. : _timeScale(1.0f)
  213. , _updatesNegList(nullptr)
  214. , _updates0List(nullptr)
  215. , _updatesPosList(nullptr)
  216. , _hashForUpdates(nullptr)
  217. , _hashForTimers(nullptr)
  218. , _currentTarget(nullptr)
  219. , _currentTargetSalvaged(false)
  220. , _updateHashLocked(false)
  221. #if CC_ENABLE_SCRIPT_BINDING
  222. , _scriptHandlerEntries(20)
  223. #endif
  224. {
  225. // I don't expect to have more than 30 functions to all per frame
  226. _functionsToPerform.reserve(30);
  227. }
  228. Scheduler::~Scheduler(void)
  229. {
  230. unscheduleAll();
  231. }
  232. void Scheduler::removeHashElement(_hashSelectorEntry *element)
  233. {
  234. ccArrayFree(element->timers);
  235. HASH_DEL(_hashForTimers, element);
  236. free(element);
  237. }
  238. void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key)
  239. {
  240. this->schedule(callback, target, interval, CC_REPEAT_FOREVER, 0.0f, paused, key);
  241. }
  242. void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, unsigned int repeat, float delay, bool paused, const std::string& key)
  243. {
  244. CCASSERT(target, "Argument target must be non-nullptr");
  245. CCASSERT(!key.empty(), "key should not be empty!");
  246. tHashTimerEntry *element = nullptr;
  247. HASH_FIND_PTR(_hashForTimers, &target, element);
  248. if (! element)
  249. {
  250. element = (tHashTimerEntry *)calloc(sizeof(*element), 1);
  251. element->target = target;
  252. HASH_ADD_PTR(_hashForTimers, target, element);
  253. // Is this the 1st element ? Then set the pause level to all the selectors of this target
  254. element->paused = paused;
  255. }
  256. else
  257. {
  258. CCASSERT(element->paused == paused, "element's paused should be paused!");
  259. }
  260. if (element->timers == nullptr)
  261. {
  262. element->timers = ccArrayNew(10);
  263. }
  264. else
  265. {
  266. for (int i = 0; i < element->timers->num; ++i)
  267. {
  268. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  269. if (timer && !timer->isExhausted() && key == timer->getKey())
  270. {
  271. CCLOG("CCScheduler#schedule. Reiniting timer with interval %.4f, repeat %u, delay %.4f", interval, repeat, delay);
  272. timer->setupTimerWithInterval(interval, repeat, delay);
  273. return;
  274. }
  275. }
  276. ccArrayEnsureExtraCapacity(element->timers, 1);
  277. }
  278. TimerTargetCallback *timer = new (std::nothrow) TimerTargetCallback();
  279. timer->initWithCallback(this, callback, target, key, interval, repeat, delay);
  280. ccArrayAppendObject(element->timers, timer);
  281. timer->release();
  282. }
  283. void Scheduler::unschedule(const std::string &key, void *target)
  284. {
  285. // explicit handle nil arguments when removing an object
  286. if (target == nullptr || key.empty())
  287. {
  288. return;
  289. }
  290. //CCASSERT(target);
  291. //CCASSERT(selector);
  292. tHashTimerEntry *element = nullptr;
  293. HASH_FIND_PTR(_hashForTimers, &target, element);
  294. if (element)
  295. {
  296. for (int i = 0; i < element->timers->num; ++i)
  297. {
  298. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  299. if (timer && key == timer->getKey())
  300. {
  301. if (timer == element->currentTimer && (! timer->isAborted()))
  302. {
  303. timer->retain();
  304. timer->setAborted();
  305. }
  306. ccArrayRemoveObjectAtIndex(element->timers, i, true);
  307. // update timerIndex in case we are in tick:, looping over the actions
  308. if (element->timerIndex >= i)
  309. {
  310. element->timerIndex--;
  311. }
  312. if (element->timers->num == 0)
  313. {
  314. if (_currentTarget == element)
  315. {
  316. _currentTargetSalvaged = true;
  317. }
  318. else
  319. {
  320. removeHashElement(element);
  321. }
  322. }
  323. return;
  324. }
  325. }
  326. }
  327. }
  328. void Scheduler::priorityIn(tListEntry **list, const ccSchedulerFunc& callback, void *target, int priority, bool paused)
  329. {
  330. tListEntry *listElement = new (std::nothrow) tListEntry();
  331. listElement->callback = callback;
  332. listElement->target = target;
  333. listElement->priority = priority;
  334. listElement->paused = paused;
  335. listElement->next = listElement->prev = nullptr;
  336. listElement->markedForDeletion = false;
  337. // empty list ?
  338. if (! *list)
  339. {
  340. DL_APPEND(*list, listElement);
  341. }
  342. else
  343. {
  344. bool added = false;
  345. for (tListEntry *element = *list; element; element = element->next)
  346. {
  347. if (priority < element->priority)
  348. {
  349. if (element == *list)
  350. {
  351. DL_PREPEND(*list, listElement);
  352. }
  353. else
  354. {
  355. listElement->next = element;
  356. listElement->prev = element->prev;
  357. element->prev->next = listElement;
  358. element->prev = listElement;
  359. }
  360. added = true;
  361. break;
  362. }
  363. }
  364. // Not added? priority has the higher value. Append it.
  365. if (! added)
  366. {
  367. DL_APPEND(*list, listElement);
  368. }
  369. }
  370. // update hash entry for quick access
  371. tHashUpdateEntry *hashElement = (tHashUpdateEntry *)calloc(sizeof(*hashElement), 1);
  372. hashElement->target = target;
  373. hashElement->list = list;
  374. hashElement->entry = listElement;
  375. memset(&hashElement->hh, 0, sizeof(hashElement->hh));
  376. HASH_ADD_PTR(_hashForUpdates, target, hashElement);
  377. }
  378. void Scheduler::appendIn(_listEntry **list, const ccSchedulerFunc& callback, void *target, bool paused)
  379. {
  380. tListEntry *listElement = new (std::nothrow) tListEntry();
  381. listElement->callback = callback;
  382. listElement->target = target;
  383. listElement->paused = paused;
  384. listElement->priority = 0;
  385. listElement->markedForDeletion = false;
  386. DL_APPEND(*list, listElement);
  387. // update hash entry for quicker access
  388. tHashUpdateEntry *hashElement = (tHashUpdateEntry *)calloc(sizeof(*hashElement), 1);
  389. hashElement->target = target;
  390. hashElement->list = list;
  391. hashElement->entry = listElement;
  392. memset(&hashElement->hh, 0, sizeof(hashElement->hh));
  393. HASH_ADD_PTR(_hashForUpdates, target, hashElement);
  394. }
  395. void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused)
  396. {
  397. tHashUpdateEntry *hashElement = nullptr;
  398. HASH_FIND_PTR(_hashForUpdates, &target, hashElement);
  399. if (hashElement)
  400. {
  401. // change priority: should unschedule it first
  402. if (hashElement->entry->priority != priority)
  403. {
  404. unscheduleUpdate(target);
  405. }
  406. else
  407. {
  408. // don't add it again
  409. //CCLOG("warning: don't update it again");
  410. return;
  411. }
  412. }
  413. // most of the updates are going to be 0, that's way there
  414. // is an special list for updates with priority 0
  415. if (priority == 0)
  416. {
  417. appendIn(&_updates0List, callback, target, paused);
  418. }
  419. else if (priority < 0)
  420. {
  421. priorityIn(&_updatesNegList, callback, target, priority, paused);
  422. }
  423. else
  424. {
  425. // priority > 0
  426. priorityIn(&_updatesPosList, callback, target, priority, paused);
  427. }
  428. }
  429. bool Scheduler::isScheduled(const std::string& key, const void *target) const
  430. {
  431. CCASSERT(!key.empty(), "Argument key must not be empty");
  432. CCASSERT(target, "Argument target must be non-nullptr");
  433. tHashTimerEntry *element = nullptr;
  434. HASH_FIND_PTR(_hashForTimers, &target, element);
  435. if (!element)
  436. {
  437. return false;
  438. }
  439. if (element->timers == nullptr)
  440. {
  441. return false;
  442. }
  443. for (int i = 0; i < element->timers->num; ++i)
  444. {
  445. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  446. if (timer && !timer->isExhausted() && key == timer->getKey())
  447. {
  448. return true;
  449. }
  450. }
  451. return false;
  452. }
  453. void Scheduler::removeUpdateFromHash(struct _listEntry *entry)
  454. {
  455. tHashUpdateEntry *element = nullptr;
  456. HASH_FIND_PTR(_hashForUpdates, &entry->target, element);
  457. if (element)
  458. {
  459. // list entry
  460. DL_DELETE(*element->list, element->entry);
  461. if (!_updateHashLocked)
  462. CC_SAFE_DELETE(element->entry);
  463. else
  464. {
  465. element->entry->markedForDeletion = true;
  466. _updateDeleteVector.push_back(element->entry);
  467. }
  468. // hash entry
  469. HASH_DEL(_hashForUpdates, element);
  470. free(element);
  471. }
  472. }
  473. void Scheduler::unscheduleUpdate(void *target)
  474. {
  475. if (target == nullptr)
  476. {
  477. return;
  478. }
  479. tHashUpdateEntry *element = nullptr;
  480. HASH_FIND_PTR(_hashForUpdates, &target, element);
  481. if (element)
  482. this->removeUpdateFromHash(element->entry);
  483. }
  484. void Scheduler::unscheduleAll(void)
  485. {
  486. unscheduleAllWithMinPriority(PRIORITY_SYSTEM);
  487. }
  488. void Scheduler::unscheduleAllWithMinPriority(int minPriority)
  489. {
  490. // Custom Selectors
  491. tHashTimerEntry *element = nullptr;
  492. tHashTimerEntry *nextElement = nullptr;
  493. for (element = _hashForTimers; element != nullptr;)
  494. {
  495. // element may be removed in unscheduleAllSelectorsForTarget
  496. nextElement = (tHashTimerEntry *)element->hh.next;
  497. unscheduleAllForTarget(element->target);
  498. element = nextElement;
  499. }
  500. // Updates selectors
  501. tListEntry *entry, *tmp;
  502. if(minPriority < 0)
  503. {
  504. DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
  505. {
  506. if(entry->priority >= minPriority)
  507. {
  508. unscheduleUpdate(entry->target);
  509. }
  510. }
  511. }
  512. if(minPriority <= 0)
  513. {
  514. DL_FOREACH_SAFE(_updates0List, entry, tmp)
  515. {
  516. unscheduleUpdate(entry->target);
  517. }
  518. }
  519. DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
  520. {
  521. if(entry->priority >= minPriority)
  522. {
  523. unscheduleUpdate(entry->target);
  524. }
  525. }
  526. #if CC_ENABLE_SCRIPT_BINDING
  527. _scriptHandlerEntries.clear();
  528. #endif
  529. }
  530. void Scheduler::unscheduleAllForTarget(void *target)
  531. {
  532. // explicit nullptr handling
  533. if (target == nullptr)
  534. {
  535. return;
  536. }
  537. // Custom Selectors
  538. tHashTimerEntry *element = nullptr;
  539. HASH_FIND_PTR(_hashForTimers, &target, element);
  540. if (element)
  541. {
  542. if (ccArrayContainsObject(element->timers, element->currentTimer)
  543. && (! element->currentTimer->isAborted()))
  544. {
  545. element->currentTimer->retain();
  546. element->currentTimer->setAborted();
  547. }
  548. ccArrayRemoveAllObjects(element->timers);
  549. if (_currentTarget == element)
  550. {
  551. _currentTargetSalvaged = true;
  552. }
  553. else
  554. {
  555. removeHashElement(element);
  556. }
  557. }
  558. // update selector
  559. unscheduleUpdate(target);
  560. }
  561. #if CC_ENABLE_SCRIPT_BINDING
  562. unsigned int Scheduler::scheduleScriptFunc(unsigned int handler, float interval, bool paused)
  563. {
  564. SchedulerScriptHandlerEntry* entry = SchedulerScriptHandlerEntry::create(handler, interval, paused);
  565. _scriptHandlerEntries.pushBack(entry);
  566. return entry->getEntryId();
  567. }
  568. void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID)
  569. {
  570. for (ssize_t i = _scriptHandlerEntries.size() - 1; i >= 0; i--)
  571. {
  572. SchedulerScriptHandlerEntry* entry = _scriptHandlerEntries.at(i);
  573. if (entry->getEntryId() == (int)scheduleScriptEntryID)
  574. {
  575. entry->markedForDeletion();
  576. break;
  577. }
  578. }
  579. }
  580. #endif
  581. void Scheduler::resumeTarget(void *target)
  582. {
  583. CCASSERT(target != nullptr, "target can't be nullptr!");
  584. // custom selectors
  585. tHashTimerEntry *element = nullptr;
  586. HASH_FIND_PTR(_hashForTimers, &target, element);
  587. if (element)
  588. {
  589. element->paused = false;
  590. }
  591. // update selector
  592. tHashUpdateEntry *elementUpdate = nullptr;
  593. HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
  594. if (elementUpdate)
  595. {
  596. CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
  597. elementUpdate->entry->paused = false;
  598. }
  599. }
  600. void Scheduler::pauseTarget(void *target)
  601. {
  602. CCASSERT(target != nullptr, "target can't be nullptr!");
  603. // custom selectors
  604. tHashTimerEntry *element = nullptr;
  605. HASH_FIND_PTR(_hashForTimers, &target, element);
  606. if (element)
  607. {
  608. element->paused = true;
  609. }
  610. // update selector
  611. tHashUpdateEntry *elementUpdate = nullptr;
  612. HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
  613. if (elementUpdate)
  614. {
  615. CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
  616. elementUpdate->entry->paused = true;
  617. }
  618. }
  619. bool Scheduler::isTargetPaused(void *target)
  620. {
  621. CCASSERT( target != nullptr, "target must be non nil" );
  622. // Custom selectors
  623. tHashTimerEntry *element = nullptr;
  624. HASH_FIND_PTR(_hashForTimers, &target, element);
  625. if( element )
  626. {
  627. return element->paused;
  628. }
  629. // We should check update selectors if target does not have custom selectors
  630. tHashUpdateEntry *elementUpdate = nullptr;
  631. HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
  632. if ( elementUpdate )
  633. {
  634. return elementUpdate->entry->paused;
  635. }
  636. return false; // should never get here
  637. }
  638. std::set<void*> Scheduler::pauseAllTargets()
  639. {
  640. return pauseAllTargetsWithMinPriority(PRIORITY_SYSTEM);
  641. }
  642. std::set<void*> Scheduler::pauseAllTargetsWithMinPriority(int minPriority)
  643. {
  644. std::set<void*> idsWithSelectors;
  645. // Custom Selectors
  646. for(tHashTimerEntry *element = _hashForTimers; element != nullptr;
  647. element = (tHashTimerEntry*)element->hh.next)
  648. {
  649. element->paused = true;
  650. idsWithSelectors.insert(element->target);
  651. }
  652. // Updates selectors
  653. tListEntry *entry, *tmp;
  654. if(minPriority < 0)
  655. {
  656. DL_FOREACH_SAFE( _updatesNegList, entry, tmp )
  657. {
  658. if(entry->priority >= minPriority)
  659. {
  660. entry->paused = true;
  661. idsWithSelectors.insert(entry->target);
  662. }
  663. }
  664. }
  665. if(minPriority <= 0)
  666. {
  667. DL_FOREACH_SAFE( _updates0List, entry, tmp )
  668. {
  669. entry->paused = true;
  670. idsWithSelectors.insert(entry->target);
  671. }
  672. }
  673. DL_FOREACH_SAFE( _updatesPosList, entry, tmp )
  674. {
  675. if(entry->priority >= minPriority)
  676. {
  677. entry->paused = true;
  678. idsWithSelectors.insert(entry->target);
  679. }
  680. }
  681. return idsWithSelectors;
  682. }
  683. void Scheduler::resumeTargets(const std::set<void*>& targetsToResume)
  684. {
  685. for(const auto &obj : targetsToResume) {
  686. this->resumeTarget(obj);
  687. }
  688. }
  689. void Scheduler::performFunctionInCocosThread(std::function<void ()> function)
  690. {
  691. std::lock_guard<std::mutex> lock(_performMutex);
  692. _functionsToPerform.push_back(std::move(function));
  693. }
  694. void Scheduler::removeAllFunctionsToBePerformedInCocosThread()
  695. {
  696. std::unique_lock<std::mutex> lock(_performMutex);
  697. _functionsToPerform.clear();
  698. }
  699. // main loop
  700. void Scheduler::update(float dt)
  701. {
  702. _updateHashLocked = true;
  703. if (_timeScale != 1.0f)
  704. {
  705. dt *= _timeScale;
  706. }
  707. //
  708. // Selector callbacks
  709. //
  710. // Iterate over all the Updates' selectors
  711. tListEntry *entry, *tmp;
  712. // updates with priority < 0
  713. DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
  714. {
  715. if ((! entry->paused) && (! entry->markedForDeletion))
  716. {
  717. entry->callback(dt);
  718. }
  719. }
  720. // updates with priority == 0
  721. DL_FOREACH_SAFE(_updates0List, entry, tmp)
  722. {
  723. if ((! entry->paused) && (! entry->markedForDeletion))
  724. {
  725. entry->callback(dt);
  726. }
  727. }
  728. // updates with priority > 0
  729. DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
  730. {
  731. if ((! entry->paused) && (! entry->markedForDeletion))
  732. {
  733. entry->callback(dt);
  734. }
  735. }
  736. // Iterate over all the custom selectors
  737. for (tHashTimerEntry *elt = _hashForTimers; elt != nullptr; )
  738. {
  739. _currentTarget = elt;
  740. _currentTargetSalvaged = false;
  741. if (! _currentTarget->paused)
  742. {
  743. // The 'timers' array may change while inside this loop
  744. for (elt->timerIndex = 0; elt->timerIndex < elt->timers->num; ++(elt->timerIndex))
  745. {
  746. elt->currentTimer = (Timer*)(elt->timers->arr[elt->timerIndex]);
  747. CCASSERT
  748. ( !elt->currentTimer->isAborted(),
  749. "An aborted timer should not be updated" );
  750. elt->currentTimer->update(dt);
  751. if (elt->currentTimer->isAborted())
  752. {
  753. // The currentTimer told the remove itself. To prevent the timer from
  754. // accidentally deallocating itself before finishing its step, we retained
  755. // it. Now that step is done, it's safe to release it.
  756. elt->currentTimer->release();
  757. }
  758. elt->currentTimer = nullptr;
  759. }
  760. }
  761. // elt, at this moment, is still valid
  762. // so it is safe to ask this here (issue #490)
  763. elt = (tHashTimerEntry *)elt->hh.next;
  764. // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
  765. if (_currentTargetSalvaged && _currentTarget->timers->num == 0)
  766. {
  767. removeHashElement(_currentTarget);
  768. }
  769. }
  770. // delete all updates that are removed in update
  771. for (auto &e : _updateDeleteVector)
  772. delete e;
  773. _updateDeleteVector.clear();
  774. _updateHashLocked = false;
  775. _currentTarget = nullptr;
  776. #if CC_ENABLE_SCRIPT_BINDING
  777. //
  778. // Script callbacks
  779. //
  780. // Iterate over all the script callbacks
  781. if (!_scriptHandlerEntries.empty())
  782. {
  783. for (auto i = _scriptHandlerEntries.size() - 1; i >= 0; i--)
  784. {
  785. SchedulerScriptHandlerEntry* eachEntry = _scriptHandlerEntries.at(i);
  786. if (eachEntry->isMarkedForDeletion())
  787. {
  788. _scriptHandlerEntries.erase(i);
  789. }
  790. else if (!eachEntry->isPaused())
  791. {
  792. eachEntry->getTimer()->update(dt);
  793. }
  794. }
  795. }
  796. #endif
  797. //
  798. // Functions allocated from another thread
  799. //
  800. // Testing size is faster than locking / unlocking.
  801. // And almost never there will be functions scheduled to be called.
  802. if( !_functionsToPerform.empty() ) {
  803. _performMutex.lock();
  804. // fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock.
  805. auto temp = std::move(_functionsToPerform);
  806. _performMutex.unlock();
  807. for (const auto &function : temp) {
  808. function();
  809. }
  810. }
  811. }
  812. void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused)
  813. {
  814. CCASSERT(target, "Argument target must be non-nullptr");
  815. tHashTimerEntry *element = nullptr;
  816. HASH_FIND_PTR(_hashForTimers, &target, element);
  817. if (! element)
  818. {
  819. element = (tHashTimerEntry *)calloc(sizeof(*element), 1);
  820. element->target = target;
  821. HASH_ADD_PTR(_hashForTimers, target, element);
  822. // Is this the 1st element ? Then set the pause level to all the selectors of this target
  823. element->paused = paused;
  824. }
  825. else
  826. {
  827. CCASSERT(element->paused == paused, "element's paused should be paused.");
  828. }
  829. if (element->timers == nullptr)
  830. {
  831. element->timers = ccArrayNew(10);
  832. }
  833. else
  834. {
  835. for (int i = 0; i < element->timers->num; ++i)
  836. {
  837. TimerTargetSelector *timer = dynamic_cast<TimerTargetSelector*>(element->timers->arr[i]);
  838. if (timer && !timer->isExhausted() && selector == timer->getSelector())
  839. {
  840. CCLOG("CCScheduler#schedule. Reiniting timer with interval %.4f, repeat %u, delay %.4f", interval, repeat, delay);
  841. timer->setupTimerWithInterval(interval, repeat, delay);
  842. return;
  843. }
  844. }
  845. ccArrayEnsureExtraCapacity(element->timers, 1);
  846. }
  847. TimerTargetSelector *timer = new (std::nothrow) TimerTargetSelector();
  848. timer->initWithSelector(this, selector, target, interval, repeat, delay);
  849. ccArrayAppendObject(element->timers, timer);
  850. timer->release();
  851. }
  852. void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, bool paused)
  853. {
  854. this->schedule(selector, target, interval, CC_REPEAT_FOREVER, 0.0f, paused);
  855. }
  856. bool Scheduler::isScheduled(SEL_SCHEDULE selector, const Ref *target) const
  857. {
  858. CCASSERT(selector, "Argument selector must be non-nullptr");
  859. CCASSERT(target, "Argument target must be non-nullptr");
  860. tHashTimerEntry *element = nullptr;
  861. HASH_FIND_PTR(_hashForTimers, &target, element);
  862. if (!element)
  863. {
  864. return false;
  865. }
  866. if (element->timers == nullptr)
  867. {
  868. return false;
  869. }
  870. for (int i = 0; i < element->timers->num; ++i)
  871. {
  872. TimerTargetSelector *timer = dynamic_cast<TimerTargetSelector*>(element->timers->arr[i]);
  873. if (timer && !timer->isExhausted() && selector == timer->getSelector())
  874. {
  875. return true;
  876. }
  877. }
  878. return false;
  879. }
  880. void Scheduler::unschedule(SEL_SCHEDULE selector, Ref *target)
  881. {
  882. // explicit handle nil arguments when removing an object
  883. if (target == nullptr || selector == nullptr)
  884. {
  885. return;
  886. }
  887. tHashTimerEntry *element = nullptr;
  888. HASH_FIND_PTR(_hashForTimers, &target, element);
  889. if (element)
  890. {
  891. for (int i = 0; i < element->timers->num; ++i)
  892. {
  893. TimerTargetSelector *timer = dynamic_cast<TimerTargetSelector*>(element->timers->arr[i]);
  894. if (timer && selector == timer->getSelector())
  895. {
  896. if (timer == element->currentTimer && !timer->isAborted())
  897. {
  898. timer->retain();
  899. timer->setAborted();
  900. }
  901. ccArrayRemoveObjectAtIndex(element->timers, i, true);
  902. // update timerIndex in case we are in tick:, looping over the actions
  903. if (element->timerIndex >= i)
  904. {
  905. element->timerIndex--;
  906. }
  907. if (element->timers->num == 0)
  908. {
  909. if (_currentTarget == element)
  910. {
  911. _currentTargetSalvaged = true;
  912. }
  913. else
  914. {
  915. removeHashElement(element);
  916. }
  917. }
  918. return;
  919. }
  920. }
  921. }
  922. }
  923. NS_CC_END