Preliminary Analysis of Cocos2d-x 3.1 ctor actionmanger Scheduler

Source: Internet
Author: User
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, throughsetAnimationIntervalSet 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()ScenevisitMethod.

// draw the scene    if (_runningScene)    {        _runningScene->visit(_renderer, Mat4::IDENTITY, false);        _eventDispatcher->dispatchEvent(_eventAfterVisit);    }

InvisitMethod, 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,_transformUpdatedIstrue.
That's why node automatically changes when node attributes are set in the cocos2d-x.

Then, node will call the children'svisitMethod.

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._actionManagerUsed to manage actions.

Provided by actionmangeraddActionTo manage actions and call the node'srunAction()The method is actually called by actionmanager.addActionPut the action in actionmanger andnodePut the key in the hash table.

Actionmanager is a singleton.initIn 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 hasSchedulerPointer_scheduler, Call the nodescheduleIn 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'sdrawSceneThe SchedulerupdateMethod.

if (! _paused)    {        _scheduler->update(_deltaTime);        _eventDispatcher->dispatchEvent(_eventAfterUpdate);    }

SchedulerupdateThe method is equivalent to the main loop of scheduler.

SchedulerselectorFunction, one is the defaultupdate(float dt)The other is user-defined, with time intervals or number of callsselectorFunction.

Scheduler uses a linked list to store the first type.selectorTo store the second type with a hash table.selector.

Defaultupdate selectorEach frame of the function is called once. Here we mainly analyze the User-DefinedselectorFunction.

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;
  1. Timers is the timer array. Each time the target calls schedule, timers adds a timer.
  2. Target object pointer
  3. Timerindex timers subscript
  4. Currenttimer current Timer
  5. Whether the current timer of currenttimersalvaged is retained to prevent the timer from finishing work but being deleted.
  6. Paused paused?
  7. 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 tabletargetIskeySearch.valueTo createtHashTimerEntryObject, 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. IfselectorAlready exists. Skip to 5.

4. Create a timertargetselector object and add ittimersArray.

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_hashForTimersHash table. Then, call timer'supdateMethod. In the timer update method, DT is accumulated. If the accumulated time is greater than the previously setintervalTo triggerselectorMethod.

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 classmainLoopIt is the main loop function of the game. Each loop calls scene.visitFunction 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 updateselectorFunctions and user-definedselectorFunction,mainLoopSchedulerupdateFunction, then scheduler and then call otherselectorFunction.

The actionmanager class manages all the actions in the game. Actionmanger relies on schedger to update actions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.