Reprinted please note, original address: http://blog.csdn.net/jinble03/article/details/20006407
Introduction: If you want to gain an in-depth understanding of the entire framework and running process of the cocos2d-x, if you want to know the details of the entire startup process, if you want to know when and where the code you write is called, you can answer the following questions. Object: Suitable for beginners just getting started with the cocos2d-x, write and run a simple demo, and want to carefully explore the principle of the mechanism. 1. main. cpp
Int APIENTRY _ tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ){... // create the application instance AppDelegate app; // click here... return CCApplication: sharedApplication ()-> run (); // check here}The above two lines are the key code (1) code AppDelegate app; the constructor of AppDelegate is called, and its parent class is CCApplication, so the constructor of CCApplication is also called.
CCApplication::CCApplication(): m_hInstance(NULL), m_hAccelTable(NULL){ m_hInstance = GetModuleHandle(NULL); m_nAnimationInterval.QuadPart = 0; CC_ASSERT(! sm_pSharedApplication); sm_pSharedApplication = this;}The connection between AppDelegate and CCApplication is completed. Because AppDelegate is a subclass of CCApplication, the static Singleton pointer in CCApplication refers to the AppDelegate instance. Subsequent operations related to CCApplication: sharedApplication () are implemented based on AppDelegate. (2) code CCApplication: sharedApplication ()-> run (); the following code is called:
Int CCApplication: run () {... // Initialize instance and cocos2d. if (! ApplicationDidFinishLaunching () {return 0 ;}.. while (1) {if (! PeekMessage (& msg, NULL, 0, 0, PM_REMOVE) {// Get current time tick. queryPerformanceCounter (& nNow); // If it's the time to draw next frame, draw it, else sleep a while. if (nNow. quadPart-nLast. quadPart> m_nAnimationInterval.QuadPart) {nLast. quadPart = nNow. quadPart; CCDirector: shareddire()-> mainLoop (); // check here} else {Sleep (0);} continue;} if (WM_QUIT = msg. message) {// Quit message l Oop. break;} // Deal with windows message. if (! M_hAccelTable |! TranslateAccelerator (msg. hwnd, m_hAccelTable, & msg) {TranslateMessage (& msg); DispatchMessage (& msg) ;}return (int) msg. wParam ;}Here, the run () function contains a while endless loop, but the condition if (WM_QUIT = msg. message) can jump out of the loop and terminate the program. In the loop, m_nAnimationInterval calls CCDirector: sharedDirector ()-> mainLoop () to refresh the game. (3) let's take a look at what mainLoop () has done:
Void CCDisplayLinkDirector: mainLoop (void) {if (m_bPurgeDirecotorInNextLoop) {m_bPurgeDirecotorInNextLoop = false; purgeDirector ();} else if (! M_bInvalid) {drawScene (); // click here. // release the objects CCPoolManager: sharedPoolManager ()-> pop (); // Click Here }}First, explain why CCDisplayLinkDirector: mainLoop instead of CCDirector: mainLoop. The answer is in the CCDirector. h header file.
Class CC_DLL CCDirector: public CCObject, public TypeInfo {....... virtual void mainLoop (void) = 0; // here .......} class CCDisplayLinkDirector: public CCDirector {..........}In the CCDirector class, mainLoop is a pure virtual function, and CCDisplayLinkDirector is a subclass of CCDirector. Return to the mainLoop function implementation, and we find that drawScene () and CCPoolManager: sharedPoolManager ()-> pop () are the main content, that is, redraw and release the objects temporarily stored in the automatic memory pool manager, which is related to the Automatic Memory Management Mechanism of the cocos2d-x, all static object creation functions: create () all adopt an automatic hosting mechanism, such:
CCSprite * CCSprite: create (const char * pszFileName) {CCSprite * pobSprite = new CCSprite (); if (pobSprite & pobSprite-> initWithFile (pszFileName )) {pobSprite-> autorelease (); // click here to return pobSprite;} CC_SAFE_DELETE (pobSprite); return NULL ;}The autorelease () function is implemented as follows:
CCObject* CCObject::autorelease(void){ CCPoolManager::sharedPoolManager()->addObject(this); return this;}It can be seen that the automatic memory management object will be released by CCPoolManager: sharedPoolManager ()-> pop () after each frame is drawn, unless we create () the object uses retain (), and retain () is also very simple. The implementation is as follows:
Void CCObject: retain (void) {CCAssert (m_uReference> 0, "reference count shocould greater than 0"); ++ m_uReference; // check here}The reference count of the object is-1, which corresponds to the release () function of the object.
Void CCObject: release (void) {CCAssert (m_uReference> 0, "reference count shocould greater than 0"); -- m_uReference; // here if (m_uReference = 0) // here {delete this ;}}We can see that the object will be deleted only when its reference count m_uReference is 0. (4) let's take a look at what the drawScene () re-painting function is responsible for. After reading it, You can fully understand the entire framework.
// Draw the Scenevoid CCDirector: drawScene (void) {...... // tick before glClear: issue #533 if (! M_bPaused) {m_pScheduler-> update (m_fDeltaTime); // Click Here }..................... // draw the scene if (m_pRunningScene) {m_pRunningScene-> visit ();}..................... // swap buffers if (m_pobOpenGLView) {m_pobOpenGLView-> swapBuffers ();}................}Do you see m_pScheduler-> update (m_fDeltaTime) Think of the void update (float dt) that we often write in HelloWorldScene. h? What is the relationship between the two? First, let's recall that we are at HelloWorldScene. h. How to call this-> schedule (schedule_selector (HelloWorld: update) of the update function? (this is only one way to call it.) Check the implementation of the schedule function.
Void CCNode: schedule (SEL_SCHEDULE selector) {this-> schedule (selector, 0.0f, medium, 0.0f);} void CCNode: 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 "); m_pschedtor-> scheduleSelector (selector, this, interval, repeat, delay ,! M_bRunning); // here} class CC_DLL CCNode: public CCObject {...... CCScheduler * m_pScheduler; // here .......}Compare the drawScene () redraw function.
// Draw the Scenevoid CCDirector: drawScene (void) {...... // tick before glClear: issue #533 if (! M_bPaused) {m_pScheduler-> update (m_fDeltaTime); // see here }.....................} class CC_DLL CCDirector: public CCObject, public TypeInfo {............... CC_PROPERTY (CCScheduler *, m_pScheduler, Scheduler); // click here ..............} # define CC_PROPERTY (varType, varName, funName) \ // check protected: varType varName; \ public: virtual varType get # funName (void); \ public: virtual void set # funName (varType var );We found that both the CCNode and CCDirector classes declare CCScheduler * m_pScheduler, neither of which is the same. Not necessarily. Look at the CCNode constructor first.
CCNode: CCNode (void ):........... {CCDirector * director = CCDirector: shareddire ();............... m_pschedctor = director-> getScheduler (); // click here ................}The m_pschedctor in CCNode referenced the m_pschedctor of ccctor, and felt the charm of perseverance. Back to the previous question: CCDirector: m_pScheduler-> update (m_fDeltaTime) in drawScene and we often use HelloWorldScene. what is the relationship between the void update (float dt) written by h? As shown in the code above, this-> schedule (schedule_selector (HelloWorld: update) will actually save schedule_selector (HelloWorld: update) to m_pScheduler in CCNode, that is, m_pScheduler in ccdire, so the code in m_pScheduler-> update (m_fDeltaTime) in ccctor ctor: drawScene should be related to HelloWorld: update. Continue.
// Main loopvoid CCScheduler: update (float dt ){................ // Iterate over all the custom selectors for (tHashTimerEntry * elt = m_pHashForTimers; elt! = NULL;) {m_pCurrentTarget = elt; m_bCurrentTargetSalvaged = false; if (! M_pCurrentTarget-> paused) {// The 'Times' array may change while inside this loop for (elt-> timerIndex = 0; elt-> timerIndex <elt-> timers-> num; ++ (elt-> timerIndex) {elt-> currentTimer = (CCTimer *) (elt-> timers-> arr [elt-> timerIndex]); elt-> currentTimerSalvaged = false; elt-> currentTimer-> update (dt ); // check out ......................}}............ ......}...............}Focus on elt-> currentTimer-> update (dt); elt-> currentTimer is the CCTimer class. Let's see if the update function in it is a good idea.
Void CCTimer: update (float dt) {if (m_fElapsed =-1 ){....................} else {if (m_bRunForever &&! M_bUseDelay) {// standard timer usage ................... if (m_fElapsed> = m_fInterval) {if (m_pTarget & m_pfnSelector) {(m_pTarget-> * m_pfnSelector) (m_fElapsed ); // see here }...................}} else {// advanced usage ............... if (m_bUseDelay) {if (m_fElapsed> = m_fDelay) {if (m_pTarget & m_pfnSelector) {(m_pTarget-> * m_pfnSelector) (m_fElapsed ); // see here }...............}} else {if (m_fElapsed> = m_fInterval) {if (m_pTarget & m_pfnSelector) {(m_pTarget-> * m_pfnSelector) (m_fElapsed ); // see here }.......................}}.......... ....}}}You may not know (m_pTarget-> * m_pfnSelector) (m_fElapsed. h code for calling the update function: this-> schedule (schedule_selector (HelloWorld: update); The following is the implementation of schedule (as mentioned above)
Void CCNode: schedule (SEL_SCHEDULE selector) {this-> schedule (selector, 0.0f, medium, 0.0f);} void CCNode: 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 "); m_pschedtor-> scheduleSelector (selector, this, interval, repeat, delay ,! M_bRunning); // click here}The last step is to check m_pschedtor-> scheduleSelector (selector, this, interval, repeat, delay ,! M_bRunning) and (m_pTarget-> * m_pfnSelector) (m_fElapsed) are related. The selector is a function pointer pointing to HelloWorld: update. If you do not understand it, you can see the definition of schedule_selector. The following describes the implementation of the scheduleSelector function.
Void ccschedtor: scheduleSelector (SEL_SCHEDULE pfnSelector, CCObject * pTarget, float fInterval, unsigned int repeat, float delay, bool bPaused) {................ tHashTimerEntry * pElement = NULL; HASH_FIND_INT (m_pHashForTimers, & pTarget, pElement); if (! PElement ){...........................} else {CCAssert (pElement-> paused = bPaused, "");} if (pElement-> timers = NULL) {pElement-> timers = ccArrayNew (10 );} else {....................} CCTimer * pTimer = new CCTimer (); pTimer-> initWithTarget (pTarget, pfnSelector, fInterval, repeat, delay); // check the partition (pElement-> timers, pTimer) here ); pTimer-> release ();}Focus on pTimer-> initWithTarget (pTarget, pfnSelector, fInterval, repeat, delay). pTarget is the CCNode (corresponding to the HelloWorld class) object, and pfnSelector is the function pointer just mentioned, point to HelloWorld: update. The following is the implementation of the initWithTarget function.
bool CCTimer::initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, float fSeconds, unsigned int nRepeat, float fDelay){ m_pTarget = pTarget; m_pfnSelector = pfnSelector; ..................... return true;}So we can solve the problem we just raised: Look at m_pschedtor-> scheduleSelector (selector, this, interval, repeat, delay ,! M_bRunning) and (m_pTarget-> * m_pfnSelector) (m_fElapsed) are related, where selector is a function pointer pointing to HelloWorld: update. The answer is as follows: again, it means that pTarget is the CCNode (corresponding to the HelloWorld class) object, and pfnSelector is the function pointer just mentioned, pointing to HelloWorld: update, that is, the void update (float dt) defined by the HelloWorld class is called and is in the entire main loop ccctor ctor: shareddire()-> mainLoop (). (5) Conclusion: The entire cocos2d-x framework source code is like this, specific details are not involved, but we have understood the beginning of the program from the main function, and then how to call our own step by step is HelloWorld. h itself defined the implementation of the function, especially the update function, but also understand some of the cocos2d-x memory management mechanism and callback mechanism, also in the Framework Code, and how the entire framework controls the number of frames. Let's use a sentence in "one generation of Masters" to summarize the framework source code study journey-"Never forget, but it will echo".