CCScheduler.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. #ifndef __CCSCHEDULER_H__
  25. #define __CCSCHEDULER_H__
  26. #include <functional>
  27. #include <mutex>
  28. #include <set>
  29. #include "base/CCRef.h"
  30. #include "base/CCVector.h"
  31. #include "base/uthash.h"
  32. NS_CC_BEGIN
  33. class Scheduler;
  34. typedef std::function<void(float)> ccSchedulerFunc;
  35. /**
  36. * @cond
  37. */
  38. class CC_DLL Timer : public Ref
  39. {
  40. protected:
  41. Timer();
  42. public:
  43. void setupTimerWithInterval(float seconds, unsigned int repeat, float delay);
  44. void setAborted() { _aborted = true; }
  45. bool isAborted() const { return _aborted; }
  46. bool isExhausted() const;
  47. virtual void trigger(float dt) = 0;
  48. virtual void cancel() = 0;
  49. /** triggers the timer */
  50. void update(float dt);
  51. protected:
  52. Scheduler* _scheduler; // weak ref
  53. float _elapsed;
  54. bool _runForever;
  55. bool _useDelay;
  56. unsigned int _timesExecuted;
  57. unsigned int _repeat; //0 = once, 1 is 2 x executed
  58. float _delay;
  59. float _interval;
  60. bool _aborted;
  61. };
  62. class CC_DLL TimerTargetSelector : public Timer
  63. {
  64. public:
  65. TimerTargetSelector();
  66. /** Initializes a timer with a target, a selector and an interval in seconds, repeat in number of times to repeat, delay in seconds. */
  67. bool initWithSelector(Scheduler* scheduler, SEL_SCHEDULE selector, Ref* target, float seconds, unsigned int repeat, float delay);
  68. SEL_SCHEDULE getSelector() const { return _selector; }
  69. virtual void trigger(float dt) override;
  70. virtual void cancel() override;
  71. protected:
  72. Ref* _target;
  73. SEL_SCHEDULE _selector;
  74. };
  75. class CC_DLL TimerTargetCallback : public Timer
  76. {
  77. public:
  78. TimerTargetCallback();
  79. // Initializes a timer with a target, a lambda and an interval in seconds, repeat in number of times to repeat, delay in seconds.
  80. bool initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay);
  81. const ccSchedulerFunc& getCallback() const { return _callback; }
  82. const std::string& getKey() const { return _key; }
  83. virtual void trigger(float dt) override;
  84. virtual void cancel() override;
  85. protected:
  86. void* _target;
  87. ccSchedulerFunc _callback;
  88. std::string _key;
  89. };
  90. #if CC_ENABLE_SCRIPT_BINDING
  91. class CC_DLL TimerScriptHandler : public Timer
  92. {
  93. public:
  94. bool initWithScriptHandler(int handler, float seconds);
  95. int getScriptHandler() const { return _scriptHandler; }
  96. virtual void trigger(float dt) override;
  97. virtual void cancel() override;
  98. private:
  99. int _scriptHandler;
  100. };
  101. #endif
  102. /**
  103. * @endcond
  104. */
  105. /**
  106. * @addtogroup base
  107. * @{
  108. */
  109. struct _listEntry;
  110. struct _hashSelectorEntry;
  111. struct _hashUpdateEntry;
  112. #if CC_ENABLE_SCRIPT_BINDING
  113. class SchedulerScriptHandlerEntry;
  114. #endif
  115. /** @brief Scheduler is responsible for triggering the scheduled callbacks.
  116. You should not use system timer for your game logic. Instead, use this class.
  117. There are 2 different types of callbacks (selectors):
  118. - update selector: the 'update' selector will be called every frame. You can customize the priority.
  119. - custom selector: A custom selector will be called every frame, or with a custom interval of time
  120. The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'.
  121. */
  122. class CC_DLL Scheduler : public Ref
  123. {
  124. public:
  125. /** Priority level reserved for system services.
  126. * @lua NA
  127. * @js NA
  128. */
  129. static const int PRIORITY_SYSTEM;
  130. /** Minimum priority level for user scheduling.
  131. * Priority level of user scheduling should bigger then this value.
  132. *
  133. * @lua NA
  134. * @js NA
  135. */
  136. static const int PRIORITY_NON_SYSTEM_MIN;
  137. /**
  138. * Constructor
  139. *
  140. * @js ctor
  141. */
  142. Scheduler();
  143. /**
  144. * Destructor
  145. *
  146. * @js NA
  147. * @lua NA
  148. */
  149. virtual ~Scheduler();
  150. /**
  151. * Gets the time scale of schedule callbacks.
  152. * @see Scheduler::setTimeScale()
  153. */
  154. float getTimeScale() { return _timeScale; }
  155. /** Modifies the time of all scheduled callbacks.
  156. You can use this property to create a 'slow motion' or 'fast forward' effect.
  157. Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
  158. To create a 'fast forward' effect, use values higher than 1.0.
  159. @since v0.8
  160. @warning It will affect EVERY scheduled selector / action.
  161. */
  162. void setTimeScale(float timeScale) { _timeScale = timeScale; }
  163. /** 'update' the scheduler.
  164. * You should NEVER call this method, unless you know what you are doing.
  165. * @lua NA
  166. */
  167. void update(float dt);
  168. /////////////////////////////////////
  169. // schedule
  170. /** The scheduled method will be called every 'interval' seconds.
  171. If paused is true, then it won't be called until it is resumed.
  172. If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdate' instead.
  173. If the 'callback' is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
  174. repeat let the action be repeated repeat + 1 times, use CC_REPEAT_FOREVER to let the action run continuously
  175. delay is the amount of time the action will wait before it'll start.
  176. @param callback The callback function.
  177. @param target The target of the callback function.
  178. @param interval The interval to schedule the callback. If the value is 0, then the callback will be scheduled every frame.
  179. @param repeat repeat+1 times to schedule the callback.
  180. @param delay Schedule call back after `delay` seconds. If the value is not 0, the first schedule will happen after `delay` seconds.
  181. But it will only affect first schedule. After first schedule, the delay time is determined by `interval`.
  182. @param paused Whether or not to pause the schedule.
  183. @param key The key to identify the callback function, because there is not way to identify a std::function<>.
  184. @since v3.0
  185. */
  186. void schedule(const ccSchedulerFunc& callback, void *target, float interval, unsigned int repeat, float delay, bool paused, const std::string& key);
  187. /** The scheduled method will be called every 'interval' seconds for ever.
  188. @param callback The callback function.
  189. @param target The target of the callback function.
  190. @param interval The interval to schedule the callback. If the value is 0, then the callback will be scheduled every frame.
  191. @param paused Whether or not to pause the schedule.
  192. @param key The key to identify the callback function, because there is not way to identify a std::function<>.
  193. @since v3.0
  194. */
  195. void schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key);
  196. /** The scheduled method will be called every `interval` seconds.
  197. If paused is true, then it won't be called until it is resumed.
  198. If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdate' instead.
  199. If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
  200. repeat let the action be repeated repeat + 1 times, use CC_REPEAT_FOREVER to let the action run continuously
  201. delay is the amount of time the action will wait before it'll start
  202. @param selector The callback function.
  203. @param target The target of the callback function.
  204. @param interval The interval to schedule the callback. If the value is 0, then the callback will be scheduled every frame.
  205. @param repeat repeat+1 times to schedule the callback.
  206. @param delay Schedule call back after `delay` seconds. If the value is not 0, the first schedule will happen after `delay` seconds.
  207. But it will only affect first schedule. After first schedule, the delay time is determined by `interval`.
  208. @param paused Whether or not to pause the schedule.
  209. @since v3.0
  210. */
  211. void schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused);
  212. /** The scheduled method will be called every `interval` seconds for ever.
  213. @param selector The callback function.
  214. @param target The target of the callback function.
  215. @param interval The interval to schedule the callback. If the value is 0, then the callback will be scheduled every frame.
  216. @param paused Whether or not to pause the schedule.
  217. */
  218. void schedule(SEL_SCHEDULE selector, Ref *target, float interval, bool paused);
  219. /** Schedules the 'update' selector for a given target with a given priority.
  220. The 'update' selector will be called every frame.
  221. The lower the priority, the earlier it is called.
  222. @since v3.0
  223. @lua NA
  224. */
  225. template <class T>
  226. void scheduleUpdate(T *target, int priority, bool paused)
  227. {
  228. this->schedulePerFrame([target](float dt){
  229. target->update(dt);
  230. }, target, priority, paused);
  231. }
  232. #if CC_ENABLE_SCRIPT_BINDING
  233. // Schedule for script bindings.
  234. /** The scheduled script callback will be called every 'interval' seconds.
  235. If paused is true, then it won't be called until it is resumed.
  236. If 'interval' is 0, it will be called every frame.
  237. return schedule script entry ID, used for unscheduleScriptFunc().
  238. @warn Don't invoke this function unless you know what you are doing.
  239. @js NA
  240. @lua NA
  241. */
  242. unsigned int scheduleScriptFunc(unsigned int handler, float interval, bool paused);
  243. #endif
  244. /////////////////////////////////////
  245. // unschedule
  246. /** Unschedules a callback for a key and a given target.
  247. If you want to unschedule the 'callbackPerFrame', use unscheduleUpdate.
  248. @param key The key to identify the callback function, because there is not way to identify a std::function<>.
  249. @param target The target to be unscheduled.
  250. @since v3.0
  251. */
  252. void unschedule(const std::string& key, void *target);
  253. /** Unschedules a selector for a given target.
  254. If you want to unschedule the "update", use `unscheduleUpdate()`.
  255. @param selector The selector that is unscheduled.
  256. @param target The target of the unscheduled selector.
  257. @since v3.0
  258. */
  259. void unschedule(SEL_SCHEDULE selector, Ref *target);
  260. /** Unschedules the update selector for a given target
  261. @param target The target to be unscheduled.
  262. @since v0.99.3
  263. */
  264. void unscheduleUpdate(void *target);
  265. /** Unschedules all selectors for a given target.
  266. This also includes the "update" selector.
  267. @param target The target to be unscheduled.
  268. @since v0.99.3
  269. @lua NA
  270. */
  271. void unscheduleAllForTarget(void *target);
  272. /** Unschedules all selectors from all targets.
  273. You should NEVER call this method, unless you know what you are doing.
  274. @since v0.99.3
  275. */
  276. void unscheduleAll();
  277. /** Unschedules all selectors from all targets with a minimum priority.
  278. You should only call this with `PRIORITY_NON_SYSTEM_MIN` or higher.
  279. @param minPriority The minimum priority of selector to be unscheduled. Which means, all selectors which
  280. priority is higher than minPriority will be unscheduled.
  281. @since v2.0.0
  282. */
  283. void unscheduleAllWithMinPriority(int minPriority);
  284. #if CC_ENABLE_SCRIPT_BINDING
  285. /** Unschedule a script entry.
  286. * @warning Don't invoke this function unless you know what you are doing.
  287. * @js NA
  288. * @lua NA
  289. */
  290. void unscheduleScriptEntry(unsigned int scheduleScriptEntryID);
  291. #endif
  292. /////////////////////////////////////
  293. // isScheduled
  294. /** Checks whether a callback associated with 'key' and 'target' is scheduled.
  295. @param key The key to identify the callback function, because there is not way to identify a std::function<>.
  296. @param target The target of the callback.
  297. @return True if the specified callback is invoked, false if not.
  298. @since v3.0.0
  299. */
  300. bool isScheduled(const std::string& key, const void *target) const;
  301. /** Checks whether a selector for a given target is scheduled.
  302. @param selector The selector to be checked.
  303. @param target The target of the callback.
  304. @return True if the specified selector is invoked, false if not.
  305. @since v3.0
  306. */
  307. bool isScheduled(SEL_SCHEDULE selector, const Ref *target) const;
  308. /////////////////////////////////////
  309. /** Pauses the target.
  310. All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed.
  311. If the target is not present, nothing happens.
  312. @param target The target to be paused.
  313. @since v0.99.3
  314. */
  315. void pauseTarget(void *target);
  316. /** Resumes the target.
  317. The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.
  318. If the target is not present, nothing happens.
  319. @param target The target to be resumed.
  320. @since v0.99.3
  321. */
  322. void resumeTarget(void *target);
  323. /** Returns whether or not the target is paused.
  324. * @param target The target to be checked.
  325. * @return True if the target is paused, false if not.
  326. * @since v1.0.0
  327. * @lua NA
  328. */
  329. bool isTargetPaused(void *target);
  330. /** Pause all selectors from all targets.
  331. You should NEVER call this method, unless you know what you are doing.
  332. @since v2.0.0
  333. */
  334. std::set<void*> pauseAllTargets();
  335. /** Pause all selectors from all targets with a minimum priority.
  336. You should only call this with PRIORITY_NON_SYSTEM_MIN or higher.
  337. @param minPriority The minimum priority of selector to be paused. Which means, all selectors which
  338. priority is higher than minPriority will be paused.
  339. @since v2.0.0
  340. */
  341. std::set<void*> pauseAllTargetsWithMinPriority(int minPriority);
  342. /** Resume selectors on a set of targets.
  343. This can be useful for undoing a call to pauseAllSelectors.
  344. @param targetsToResume The set of targets to be resumed.
  345. @since v2.0.0
  346. */
  347. void resumeTargets(const std::set<void*>& targetsToResume);
  348. /** Calls a function on the cocos2d thread. Useful when you need to call a cocos2d function from another thread.
  349. This function is thread safe.
  350. @param function The function to be run in cocos2d thread.
  351. @since v3.0
  352. @js NA
  353. */
  354. void performFunctionInCocosThread(std::function<void()> function);
  355. /**
  356. * Remove all pending functions queued to be performed with Scheduler::performFunctionInCocosThread
  357. * Functions unscheduled in this manner will not be executed
  358. * This function is thread safe
  359. * @since v3.14
  360. * @js NA
  361. */
  362. void removeAllFunctionsToBePerformedInCocosThread();
  363. /////////////////////////////////////
  364. // Deprecated methods:
  365. /** The scheduled method will be called every 'interval' seconds.
  366. If paused is true, then it won't be called until it is resumed.
  367. If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead.
  368. If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
  369. repeat let the action be repeated repeat + 1 times, use CC_REPEAT_FOREVER to let the action run continuously
  370. delay is the amount of time the action will wait before it'll start
  371. @deprecated Please use `Scheduler::schedule` instead.
  372. @since v0.99.3, repeat and delay added in v1.1
  373. @js NA
  374. */
  375. CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused)
  376. {
  377. schedule(selector, target, interval, repeat, delay, paused);
  378. }
  379. /** Calls scheduleSelector with CC_REPEAT_FOREVER and a 0 delay.
  380. * @deprecated Please use `Scheduler::schedule` instead.
  381. * @js NA
  382. */
  383. CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused)
  384. {
  385. schedule(selector, target, interval, paused);
  386. }
  387. /** Schedules the 'update' selector for a given target with a given priority.
  388. The 'update' selector will be called every frame.
  389. The lower the priority, the earlier it is called.
  390. @deprecated Please use 'Scheduler::scheduleUpdate' instead.
  391. @since v0.99.3
  392. */
  393. template <class T>
  394. CC_DEPRECATED_ATTRIBUTE void scheduleUpdateForTarget(T* target, int priority, bool paused) { scheduleUpdate(target, priority, paused); };
  395. /** Unschedule a selector for a given target.
  396. If you want to unschedule the "update", use unscheduleUpdateForTarget.
  397. @deprecated Please use 'Scheduler::unschedule' instead.
  398. @since v0.99.3
  399. @js NA
  400. */
  401. CC_DEPRECATED_ATTRIBUTE void unscheduleSelector(SEL_SCHEDULE selector, Ref *target) { unschedule(selector, target); };
  402. /** Checks whether a selector for a given target is scheduled.
  403. @deprecated Please use 'Scheduler::isScheduled' instead.
  404. @since v0.99.3
  405. @js NA
  406. */
  407. CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduled(selector, target); };
  408. /** Unschedules the update selector for a given target
  409. @deprecated Please use 'Scheduler::unscheduleUpdate' instead.
  410. @since v0.99.3
  411. */
  412. CC_DEPRECATED_ATTRIBUTE void unscheduleUpdateForTarget(Ref *target) { return unscheduleUpdate(target); };
  413. protected:
  414. /** Schedules the 'callback' function for a given target with a given priority.
  415. The 'callback' selector will be called every frame.
  416. The lower the priority, the earlier it is called.
  417. @note This method is only for internal use.
  418. @since v3.0
  419. @js _schedulePerFrame
  420. */
  421. void schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused);
  422. void removeHashElement(struct _hashSelectorEntry *element);
  423. void removeUpdateFromHash(struct _listEntry *entry);
  424. // update specific
  425. void priorityIn(struct _listEntry **list, const ccSchedulerFunc& callback, void *target, int priority, bool paused);
  426. void appendIn(struct _listEntry **list, const ccSchedulerFunc& callback, void *target, bool paused);
  427. float _timeScale;
  428. //
  429. // "updates with priority" stuff
  430. //
  431. struct _listEntry *_updatesNegList; // list of priority < 0
  432. struct _listEntry *_updates0List; // list priority == 0
  433. struct _listEntry *_updatesPosList; // list priority > 0
  434. struct _hashUpdateEntry *_hashForUpdates; // hash used to fetch quickly the list entries for pause,delete,etc
  435. std::vector<struct _listEntry *> _updateDeleteVector; // the vector holds list entries that needs to be deleted after update
  436. // Used for "selectors with interval"
  437. struct _hashSelectorEntry *_hashForTimers;
  438. struct _hashSelectorEntry *_currentTarget;
  439. bool _currentTargetSalvaged;
  440. // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
  441. bool _updateHashLocked;
  442. #if CC_ENABLE_SCRIPT_BINDING
  443. Vector<SchedulerScriptHandlerEntry*> _scriptHandlerEntries;
  444. #endif
  445. // Used for "perform Function"
  446. std::vector<std::function<void()>> _functionsToPerform;
  447. std::mutex _performMutex;
  448. };
  449. // end of base group
  450. /** @} */
  451. NS_CC_END
  452. #endif // __CCSCHEDULER_H__