Cocos2d-x learning logs (18) -- how is the program started to run and ended?

Source: Internet
Author: User

Origin
How to Use Cocos2d-x to quickly develop the game, the method is very simple, you can look at its own routines, or from the online search tutorial, run the first HelloWorld, and then write the relevant logic code in HelloWorld, add layers, Genie, etc ~ We do not need to know how Cocos2d-x is running or running on a variety of platforms, do not know how the Cocos2d-x game is running, it is how to render the interface ~~~

Two Portals

The concept of program entry is relative. As a cross-platform program entry, AppDelegate encapsulates another layer and encapsulates different implementations of different platforms, for example, we usually think that a program runs from the main function, so we can look for it. We can see it in proj. main. cpp file, which is what we want to see, as follows:

int APIENTRY _tWinMain(HINSTANCE hInstance,                       HINSTANCE hPrevInstance,                       LPTSTR    lpCmdLine,                       int       nCmdShow){    UNREFERENCED_PARAMETER(hPrevInstance);    UNREFERENCED_PARAMETER(lpCmdLine);#ifdef USE_WIN32_CONSOLE    AllocConsole();    freopen("CONIN$", "r", stdin);    freopen("CONOUT$", "w", stdout);    freopen("CONOUT$", "w", stderr);#endif    // create the application instance    AppDelegate app;    CCEGLView* eglView = CCEGLView::sharedOpenGLView();    eglView->setViewName("HelloLua");    eglView->setFrameSize(480, 320);    int ret = CCApplication::sharedApplication()->run();#ifdef USE_WIN32_CONSOLE    FreeConsole();#endif    return ret;}


Here we see the real entry of the program, including a main function, from which to execute the cocos2d-x program.

Android:

We can find the equivalent entry point of the Android platform and above, proj. android \ jni \ hellolua \ main. cpp

void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv*  env, jobject thiz, jint w, jint h){    if (!CCDirector::sharedDirector()->getOpenGLView())    {        CCEGLView *view = CCEGLView::sharedOpenGLView();        view->setFrameSize(w, h);        AppDelegate *pAppDelegate = new AppDelegate();        CCApplication::sharedApplication()->run();    }    else    {        ccGLInvalidateStateCache();        CCShaderCache::sharedShaderCache()->reloadDefaultShaders();        ccDrawInit();        CCTextureCache::reloadAllTextures();        CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_FOREGROUND, NULL);        CCDirector::sharedDirector()->setGLDefaultValues();     }}

We didn't see the so-called main function. This is because different platforms have different implementations for encapsulation. On the Android platform, Java is used by default, java can be used to call the C ++ program through Jni, which is also officially used here. Now we only need to know, started by Android an application, through a variety of peaks and turns, finally executed to Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit function, thus, began our cocos2d-x Android platform program entrance. For cross-platform cocos2d-x, unless necessary, otherwise you do not have to go into the details, for example, to use the inherent features of the Android platform, then need to learn more about the Jni use method, and more details about the Android operating system.


Program process (Here we mainly implement Win32, and other platforms can bypass the class)


Note:

From main. CCApplication: sharedApplication ()-> run (); in cpp, this statement indicates that the cocos2d-x program is officially started to run, start to analyze a little bit, we can find the implementation of the sharedApplication () method.

CCApplication. cpp: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48cD48cHJlIGNsYXNzPQ = "brush: java;"> int CCApplication: run () {PVRFrameEnableControlWindow (false); // Main message loop: MSG msg; LARGE_INTEGER nFreq; LARGE_INTEGER nLast; LARGE_INTEGER nNow; QueryPerformanceFrequency (& nFreq); QueryPerformanceCounter (& nLast); // Initialize instance and cocos2d. if (! Returns () {return 0;} CCEGLView * pMainWnd = CCEGLView: Export dopenglview (); pMainWnd-> centerWindow (); ShowWindow (pMainWnd-> getHWnd (), SW_SHOW ); 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 ();} else {Sleep (0);} continue;} if (WM_QUIT = msg. message) {// Quit message loop. Break;} // Deal with windows message. if (! M_hAccelTable |! TranslateAccelerator (msg. hwnd, m_hAccelTable, & msg) {TranslateMessage (& msg); DispatchMessage (& msg) ;}} return (int) msg. wParam;} void CCApplication: setAnimationInterval (double interval) {LARGE_INTEGER nFreq; QueryPerformanceFrequency (& nFreq); m_nAnimationInterval.QuadPart = (LONGLONG) (interval * nFreq. quadPart );} //////////////////////////////////////// /// // static member function/ //////////////////////////////////////// /// // CCApplication * CCApplication:: sharedApplication () {CC_ASSERT (sm_pSharedApplication); return sm_pSharedApplication ;}
From the sharedApplication () method to the run () method, before that, we need to call its constructor; otherwise, it cannot be run, which is why in the CCApplication: sharedApplication () -> run ();

Previously, we first used the AppDelegate app; the reason for creating the AppDelegate variable!

What is the relationship between AppDelegate and CCAppliation!

We can know from the definition of AppDelegate that it is a subclass of CCApplication. When a subclass object is created and its constructor is called, the parent constructor will also execute, then, the object of AppDelegate is assigned to the static variable of CCApplication. In AppDelegate, The applicationDidFinishLaunching method is implemented, therefore, the implementation in AppDelegate is called at the beginning of the run method in CCApplication. In this method, we initialize some variables, create the first CCScene scenario, and then assign the control to CCDirector: shareddire()-> mainLoop (); method.


The cocos2d-x program from CCApplication to CCDirector has been running, and we proceed to the next step, mainLoop function:
CCDirector* CCDirector::sharedDirector(void){    if (!s_SharedDirector)    {        s_SharedDirector = new CCDisplayLinkDirector();        s_SharedDirector->init();    }    return s_SharedDirector;}void CCDisplayLinkDirector::mainLoop(void){    if (m_bPurgeDirecotorInNextLoop)    {        m_bPurgeDirecotorInNextLoop = false;        purgeDirector();    }    else if (! m_bInvalid)     {         drawScene();              // release the objects         CCPoolManager::sharedPoolManager()->pop();             }}
The running of the game is based on the scenario. Every moment, a scenario is running. There is a scenario stack in it, which follows the principle of "going forward and going out". When we call the end () method, or when the current scenario is displayed, the end () method is triggered to indicate the end of the scenario if no scenario exists, just as the stage is absent, the program enters the final stage and calls the purgeDirector method within the mainLoop method of the program by modifying the m_bPurgeDirecotorInNextLoop variable.

The last step is to see if CCEGLView is responsible for finishing the work:
void CCEGLView::end(){    if (m_hWnd)    {#if(_MSC_VER >= 1600)        if(m_bSupportTouch){    s_pfUnregisterTouchWindowFunction(m_hWnd);}#endif /* #if(_MSC_VER >= 1600) */        DestroyWindow(m_hWnd);        m_hWnd = NULL;    }    s_pMainWindow = NULL;    UnregisterClass(kWindowClassName, GetModuleHandle(NULL));    delete this;}

The end () method is very simple. You only need to see the last delete this; to understand.
Reference blog: http://blog.leafsoar.com/archives/2013/05-05.html

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.