Cocos2d-x program in the Android startup process, cocos2d-xandroid

Source: Internet
Author: User
Tags android games

Cocos2d-x program in the Android startup process, cocos2d-xandroid
Note: The original text is also posted on the internal forum of the company.This article analyzes the example program HelloLua provided by the cocos2d-x (the analytics version is the cocos2d-x-2.2.1) itself (under the $ (sourcedir) \ samples \ Lua \ HelloLua \ directory) to analyze the specific Startup Process of cocos2d-x In the android platform. We know that games on the android platform start with an Activity. The startup Activity of HelloLua is defined in the HelloLua. java file. The related code is as follows:

public class HelloLua extends Cocos2dxActivity{protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);}public Cocos2dxGLSurfaceView onCreateGLSurfaceView() {return new LuaGLSurfaceView(this);}static {        System.loadLibrary("hellolua");   }}

From the above Code, the startup Activity inherits Cocos2dxActivity. When the game starts, the Activity first executes the static code block and loads libhellolua. so library, this dynamic link library is generated when NDK is compiled; then the onCreate method is executed. Here the onCreate method of the parent class Cocos2dxActivity is called. Cocos2dxActivity in

$(sourcedir)\cocos2dx\platform\android\java\src\org\cocos2dx\lib\Cocos2dxActivity.java

The OnCreate method code is as follows:

protected void onCreate(final Bundle savedInstanceState) {super.onCreate(savedInstanceState);sContext = this;this.mHandler = new Cocos2dxHandler(this);this.init();Cocos2dxHelper.init(this, this);}

Here we mainly execute the initialization process. Cocos2dxHandler mainly processes messages displaying Dialog. Cocos2dxHelper is a helper class. We mainly look at the init () method and the code is as follows:

public void init() {    // FrameLayout        ViewGroup.LayoutParams framelayout_params =            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,                                       ViewGroup.LayoutParams.FILL_PARENT);        FrameLayout framelayout = new FrameLayout(this);        framelayout.setLayoutParams(framelayout_params);        // Cocos2dxEditText layout        ViewGroup.LayoutParams edittext_layout_params =            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,                                       ViewGroup.LayoutParams.WRAP_CONTENT);        Cocos2dxEditText edittext = new Cocos2dxEditText(this);        edittext.setLayoutParams(edittext_layout_params);        // ...add to FrameLayout        framelayout.addView(edittext);        // Cocos2dxGLSurfaceView        this.mGLSurfaceView = this.onCreateView();        // ...add to FrameLayout        framelayout.addView(this.mGLSurfaceView);        // Switch to supported OpenGL (ARGB888) mode on emulator        if (isAndroidEmulator())           this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);        this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());        this.mGLSurfaceView.setCocos2dxEditText(edittext);        // Set framelayout as the content view        setContentView(framelayout);}
The init () method is to bind the View Hierarchy to the Activity. The FrameLayout here is the root View, and FrameLayout contains a Cocos2dxEditText and a Cocos2dxGLSurfaceView. the instance of Cocos2dxGLSurfaceView is created in, the code is very simple, as follows:
public Cocos2dxGLSurfaceView onCreateView() {return new Cocos2dxGLSurfaceView(this);}
Cocos2dxGLSurfaceView itself is
$(sourcedir)\cocos2dx\platform\android\java\src\org\cocos2dx\lib\Cocos2dxGLSurfaceView.java

It inherits from GLSurfaceView in opengl. The core of GLSurfaceView is Renderer. during initialization, The onSurfaceCreated method of Renderer is called. Each frame is drawn by calling the onDrawFrame method of Renderer. Cocos2dxGLSurfaceView Renderer is a Cocos2dxRenderer object, class Cocos2dxRenderer in

$(sourcedir)\cocos2dx\platform\android\java\src\org\cocos2dx\lib\Cocos2dxRenderer.java

The onSurfaceCreated method code is as follows:

public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);this.mLastTickInNanoSeconds = System.nanoTime();}

Here we call a method nativeInit, which is declared:

private static native void nativeInit(final int pWidth, final int pHeight);

That is, it is a native function, that is, it is implemented in C ++ code. To put it simply, it is a function implemented by calling C ++ code in java, JNI technology is required (it can be considered a protocol for Java to interact with C ++ ~). The C ++ implementation corresponding to nativeInit is in (sourcedir) \ samples \ Lua \ HelloLua \ 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    {.....    }}
The function name Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit follows the naming rules of the JNI implementation method. CCDirector is the director class in the cocos2d-x, which is implemented in $ (sourcedir) \ cocos2dx \ CCDirector. cpp. Method sharedDirector is a static method of CCDirector. This method is used to create a unique CCDirector object in the game. The Code is as follows:
CCDirector* CCDirector::sharedDirector(void){    if (!s_SharedDirector)    {        s_SharedDirector = new CCDisplayLinkDirector();        s_SharedDirector->init();    }    return s_SharedDirector;}

The CCCCDisplayLinkDirector is a subclass of CCDirector. The init () method performs initialization:

Bool CCDirector: init (void) {setdefavaluvalues (); // scenario related ...... // array stack m_pobScenesStack = new CCArray (); m_pobScenesStack-> init (); // initialization of some FPS and other related member variables ...... // initialize the scheduler object m_pScheduler = new CCScheduler (); // Action Manager object m_pActionManager = new CCActionManager (); m_pScheduler-> scheduleUpdateForTarget (m_pActionManager, kCCPrioritySystem, false ); // touchDispatcher, KeypadDispatcher, Accelerometer, and other object initialization ...... // The Memory Management Mechanism of the cocos2d-x CCObject object is implemented in CCPoolManager: sharedPoolManager ()-> push (); return true ;}

After the Director object is created, the getOpenGLView method of the object is called in Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit:

inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; }

This method returns the CCEGLView used for game plotting. In init (), m_pobOpenGLView is copied to NULL. On the Android platform, this CCEGLView does not actually play any role, because the games are all drawn on Cocos2dxGLSurfaceView. Therefore, the Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit method then executes the if Branch:

CCEGLView *view = CCEGLView::sharedOpenGLView();view->setFrameSize(w, h);

The unique instance of the CCEGLView class in the game is also created here. The class is implemented in $ (sourcedir) \ cocos2dx \ platform \ android \ CCEGLView. cpp. Then execute

AppDelegate *pAppDelegate = new AppDelegate();CCApplication::sharedApplication()->run();

An AppDelegate object is created, which is implemented in $ (sourcedir) \ samples \ Lua \ HelloLua \ Classes \ AppDelegate. cpp. AppDelegate is shared among platforms:

class  AppDelegate : private cocos2d::CCApplication{public:    AppDelegate();    virtual ~AppDelegate();    virtual bool applicationDidFinishLaunching();    virtual void applicationDidEnterBackground();    virtual void applicationWillEnterForeground();};

This class is inherited from CCApplication. Note that the CCApplication class is implemented in $ (sourcedir) \ cocos2dx \ platform \ android \ CCApplication. cpp, and its implementation is platform-related. The essence of creating an AppDelegate instance is to instantiate CCApplication. Its constructor code is as follows:

CCApplication::CCApplication(){    CCAssert(! sm_pSharedApplication, "");    sm_pSharedApplication = this;}

Therefore, when instantiating AppDelegate, the main task is to use the AppDelegate object to initialize the global variable sm_pSharedApplication. Next, call CCApplication: sharedApplication ()-> run (). The related code is as follows:

CCApplication* CCApplication::sharedApplication(){    CCAssert(sm_pSharedApplication, "");    return sm_pSharedApplication;}int CCApplication::run(){    // Initialize instance and cocos2d.    if (! applicationDidFinishLaunching())    {        return 0;    }        return -1;}

The virtual function applicationDidFinishLaunching called in run essentially calls applicationDidFinishLaunching In the subclass AppDelegate. The Code is as follows:

Bool AppDelegate: applicationDidFinishLaunching () {// initialize director CCDirector * pDirector = CCDirector: shareddire(); pDirector-> setOpenGLView (CCEGLView: sharedOpenGLView (); CCEGLView :: export dopenglview ()-> setDesignResolutionSize (480,320, kResolutionNoBorder); // display FPS pDirector-> setDisplayStats (true); // set FPS pDirector-> setAnimationInterval (1.0/60 ); // create Lua Script Engine CCLuaEngine * pEngine = CCLuaEngine: defaultEngine (); CCScriptEngineManager: sharedManager ()-> setScriptEngine (pEngine); // load and execute the lua script std :: string path = CCFileUtils: sharedFileUtils ()-> fullPathForFilename ("hello. lua "); pEngine-> executeScriptFile (path. c_str (); return true ;}
Now the game is started, but we did not see something similar to the while loop (btw, analysis of windows and Linux platform on the cocos2d-x startup process can clearly see similar while LOOP stuff ~), This is because on the android platform, the main loop is initiated by the rendering thread and is driven by constant calls to render. Specifically, the onDrawFrame method in the Java Cocos2dxRenderer class is called:
public void onDrawFrame(final GL10 gl) {Cocos2dxRenderer.nativeRender();}

The only task is to call the nativeRender method, which is native and its implementation is:

JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env) {cocos2d::CCDirector::sharedDirector()->mainLoop();}

That is, execute the mainLoop method in the Director object:

Void CCDisplayLinkDirector: mainLoop (void) {// This variable determines whether the program ends if (m_bPurgeDirecotorInNextLoop) {m_bPurgeDirecotorInNextLoop = false; purgeDirector ();} else if (! M_bInvalid) {// screen painting, and perform some corresponding logic processing drawScene (); // release the CCObject object CCPoolManager: sharedPoolManager () in the object manager () -> pop ();}}

This method is the loop body actually executed by all platforms.

References

Http://blog.csdn.net/cjj7905150/article/details/22587021http://www.dapps.net/dev/gamedev/cocos2d-x-dev-the-game-loop-4.htmlhttp://blog.leafsoar.com/archives/2013/05-05.html

Small android game process with Cocos2d-x C ++ Engine

This is a bit complicated and you need to have android sdk, ndk, cocos2d-x package, eclipse.
First I use programming tools to write code that can run, I am a cocos2d-x program written in xcode on mac
Then create a work android project with the cocos2d-x (need to configure the android sdk and ndk), and then write your own cocos2d-x program class files put in the class directory of android, cocos2d-x resources put in the resource Directory of android, and then set the Good Luck line android program to compile the file, and then in the terminal bulid_native.sh to compile this file, if the compilation is successful, open this directory in eclipse to implement this small android program.

To write android games with cocos2d-x, you must go back to c ++

Cocos2d-x itself is C ++ written ah, so must be c ++, in the windows platform with cocos2d-x to write android Games first with visual stdio programming cocos2d-x game, and then run successfully, then, use eclipse to add the generated program framework. In this way, you can generate an android game.

Related Article

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.