Director the game's main cycle shows that node displaylinkdireinherits Director
Override:
virtual void mainLoop() override;virtual void setAnimationInterval(double value) override;virtual void startAnimation() override;virtual void stopAnimation() override;
mainLoop()
Is the main loop of the game, throughsetAnimationInterval
Set the number of calls of the Main Loop per second.
mainLoop()
Code:
void DisplayLinkDirector::mainLoop(){ if (_purgeDirectorInNextLoop) { _purgeDirectorInNextLoop = false; purgeDirector(); } else if (! _invalid) { drawScene(); // release the objects PoolManager::getInstance()->getCurrentPool()->clear(); }}
IndrawScene()
Scenevisit
Method.
// draw the scene if (_runningScene) { _runningScene->visit(_renderer, Mat4::IDENTITY, false); _eventDispatcher->dispatchEvent(_eventAfterVisit); }
Invisit
Method, if the node is invisible, return directly, and then determine whether the node needs to be deformed.
bool dirty = _transformUpdated || parentTransformUpdated; if(dirty) _modelViewTransform = this->transform(parentTransform); _transformUpdated = false;
When you call methods such as node setscale () and setposition,_transformUpdated
Istrue
.
That's why node automatically changes when node attributes are set in the cocos2d-x.
Then, node will call the children'svisit
Method.
if(!_children.empty()) { sortAllChildren(); // draw children zOrder < 0 for( ; i < _children.size(); i++ ) { auto node = _children.at(i); if ( node && node->_localZOrder < 0 ) node->visit(renderer, _modelViewTransform, dirty); else break; } // self draw this->draw(renderer, _modelViewTransform, dirty); for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) (*it)->visit(renderer, _modelViewTransform, dirty); } else { this->draw(renderer, _modelViewTransform, dirty); }
Actionmanager management action
Node contains a member variable of actionmanager._actionManager
Used to manage actions.
Provided by actionmangeraddAction
To manage actions and call the node'srunAction()
The method is actually called by actionmanager.addAction
Put the action in actionmanger andnode
Put the key in the hash table.
Actionmanager is a singleton.init
In the function, call _ schedupdate-> scheduleupdate ():
_actionManager = new ActionManager(); _scheduler->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
Each schedmanager frame uses the UPDATE function of actionmanager.
In the UPDATE function of actionmanager, traverse all actions and callaction->step(dt)
To set the action.
Useaction->isDone()
To determine whether the action is completed. If the action is completed, the action is removed from actionmanager.
Scheduler
Scheduler is used to regularly trigger callback functions.
Node also hasScheduler
Pointer_scheduler
, Call the nodeschedule
In fact, the method is to call the corresponding method of scheduler and add the node and callback function to the scheduler linked list.
Scheduler has two priorities: system priority and non-system lowest priority.
// Priority level reserved for system services.const int Scheduler::PRIORITY_SYSTEM = INT_MIN;// Minimum priority level for user scheduling.const int Scheduler::PRIORITY_NON_SYSTEM_MIN = PRIORITY_SYSTEM + 1;
The author's note is displayed in the scheduler constructor:
// I don‘t expect to have more than 30 functions to all per frame
All, each frame should not exceed 30 scheduled callback functions.
In director'sdrawScene
The Schedulerupdate
Method.
if (! _paused) { _scheduler->update(_deltaTime); _eventDispatcher->dispatchEvent(_eventAfterUpdate); }
Schedulerupdate
The method is equivalent to the main loop of scheduler.
Schedulerselector
Function, one is the defaultupdate(float dt)
The other is user-defined, with time intervals or number of callsselector
Function.
Scheduler uses a linked list to store the first type.selector
To store the second type with a hash table.selector
.
Defaultupdate selector
Each frame of the function is called once. Here we mainly analyze the User-Definedselector
Function.
The following struct is used to save a customselector
// Hash Element used for "selectors with interval"typedef struct _hashSelectorEntry{ ccArray *timers; void *target; int timerIndex; Timer *currentTimer; bool currentTimerSalvaged; bool paused; UT_hash_handle hh;} tHashTimerEntry;
- Timers is the timer array. Each time the target calls schedule, timers adds a timer.
- Target object pointer
- Timerindex timers subscript
- Currenttimer current Timer
- Whether the current timer of currenttimersalvaged is retained to prevent the timer from finishing work but being deleted.
- Paused paused?
- HH hash table Node
Analyze the node schedule Function
void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay){ CCASSERT( selector, "Argument must be non-nil"); CCASSERT( interval >=0, "Argument must be positive"); _scheduler->schedule(selector, this, interval , repeat, delay, !_running);}
Let's look at the schedule method corresponding to schedle.
void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused){ CCASSERT(target, "Argument target must be non-nullptr"); tHashTimerEntry *element = nullptr; HASH_FIND_PTR(_hashForTimers, &target, element); if (! element) { element = (tHashTimerEntry *)calloc(sizeof(*element), 1); element->target = target; HASH_ADD_PTR(_hashForTimers, target, element); // Is this the 1st element ? Then set the pause level to all the selectors of this target element->paused = paused; } else { CCASSERT(element->paused == paused, ""); } if (element->timers == nullptr) { element->timers = ccArrayNew(10); } else { for (int i = 0; i < element->timers->num; ++i) { TimerTargetSelector *timer = static_cast<TimerTargetSelector*>(element->timers->arr[i]); if (selector == timer->getSelector()) { CCLOG("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer->getInterval(), interval); timer->setInterval(interval); return; } } ccArrayEnsureExtraCapacity(element->timers, 1); } TimerTargetSelector *timer = new TimerTargetSelector(); timer->initWithSelector(this, selector, target, interval, repeat, delay); ccArrayAppendObject(element->timers, timer); timer->release();}
1. From the hash tabletarget
Iskey
Search.value
To createtHashTimerEntry
Object, and then add it to the hash table.
2. If the timers array of element is empty, allocate 10 spaces to timers. To 4.
3. If the timers array of the element is not empty, traverse the timer array to determine whether it already exists. Ifselector
Already exists. Skip to 5.
4. Create a timertargetselector object and add ittimers
Array.
5. End.
PS: This timertargetselector class is not analyzed here.
Finally, let's look at the UPDATE function of scheduler.
Here we only focus on customselector
.
// main loopvoid Scheduler::update(float dt){ // Iterate over all the custom selectors for (tHashTimerEntry *elt = _hashForTimers; elt != nullptr; ) { _currentTarget = elt; _currentTargetSalvaged = false; if (! _currentTarget->paused) { // The ‘timers‘ array may change while inside this loop for (elt->timerIndex = 0; elt->timerIndex < elt->timers->num; ++(elt->timerIndex)) { elt->currentTimer = (Timer*)(elt->timers->arr[elt->timerIndex]); elt->currentTimerSalvaged = false; elt->currentTimer->update(dt); if (elt->currentTimerSalvaged) { // The currentTimer told the remove itself. To prevent the timer from // accidentally deallocating itself before finishing its step, we retained // it. Now that step is done, it‘s safe to release it. elt->currentTimer->release(); } elt->currentTimer = nullptr; } } // elt, at this moment, is still valid // so it is safe to ask this here (issue #490) elt = (tHashTimerEntry *)elt->hh.next; // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if (_currentTargetSalvaged && _currentTarget->timers->num == 0) { removeHashElement(_currentTarget); } }}
Traversal_hashForTimers
Hash table. Then, call timer'supdate
Method. In the timer update method, DT is accumulated. If the accumulated time is greater than the previously setinterval
To triggerselector
Method.
Void Timer: Update (float DT) {// omit if (_ runforever &&! _ Usedelay) {// standard timer usage _ elapsed + = DT; If (_ elapsed >=_ interval) {trigger (); _ elapsed = 0 ;}/// omitted}
Trigger Function
void TimerTargetSelector::trigger(){ if (_target && _selector) { (_target->*_selector)(_elapsed); }}
This is the process for customizing schedule.
Summary
The Cocos2d-x engine is single-threaded, director classmainLoop
It is the main loop function of the game. Each loop calls scene.visit
Function to display or update elements on the interface.
Scheduler class is the scheduling class of the Cocos2d-x, used to trigger the callback function regularly, the callback function has the default updateselector
Functions and user-definedselector
Function,mainLoop
Schedulerupdate
Function, then scheduler and then call otherselector
Function.
The actionmanager class manages all the actions in the game. Actionmanger relies on schedger to update actions.