顯示具有 Cpp 標籤的文章。 顯示所有文章
顯示具有 Cpp 標籤的文章。 顯示所有文章

2013-11-07

Cocos2d-x JNI 筆記

底下整理幾個常用的情況 :
  1. 新增 C++ 檔案
  2. 查看 Java Method Signature
  3. Java 呼叫 C++ 函數
  4. C++ 呼叫 Java 函數
  5. Java 呼叫 C++ 時傳遞數字變數
  6. C++ 呼叫 Java 時傳遞數字變數
  7. Java 呼叫 C++ 時傳遞字串
  8. C++ 呼叫 Java 時傳遞字串
  9. Java 呼叫 C++ 時傳遞矩陣
  10. C++ 呼叫 Java 時傳遞矩陣
  11. Java 呼叫 C++ 時傳遞回呼函數
  12. C++ 呼叫 Java 時傳遞回呼函數

1. C++ 新增 .h/.cpp 檔案 :
   i. 在 Classes 資料夾內新增 .h/.cpp 檔案
   ii. 編輯 proj.android/jni/Android.mk :
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := cocos2dcpp_shared

LOCAL_MODULE_FILENAME := libcocos2dcpp

#新增的檔案加在 LOCAL_SRC_FILES
LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/HelloWorldScene.cpp \
                   ../../Classes/AMGamebarUtil.cpp

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes

LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static
LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static

include $(BUILD_SHARED_LIBRARY)

$(call import-module,cocos2dx)
$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl)
$(call import-module,CocosDenshion/android)
$(call import-module,extensions)
$(call import-module,external/Box2D)
$(call import-module,external/chipmunk)
2. 查看 Java Method Signature :
javap -s -classpath <path to jar file> <package name>.<class name>
javap -s -classpath ./AMGameBar.jar com.appmaster.AMCocos2dxInterface
javap -s com.appmaster.AMCocos2dxInterface (尚未壓縮成jar, 相對路徑 com/appmaster/AMCocos2dxInterface.class)
3. Java 呼叫 C++ 函數 :
   i. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  //1.定義
  private static native void nativeLoginHandler();
  ...
  
  static public void callNative(){
    //2. 呼叫 c method
    nativeLoginHandler();
  }
}
   ii. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

extern "C"
{
  //c method 定義 :
  //Java_<package name (replace point with under line)>_<class>_<method>
  void Java_com_appmaster_AMCocos2dxInterface_nativeLoginHandler(JNIEnv* env, jobject thiz)
  {
    CCLOG("I HAVE BEEN TRIGGERED BY JAVA !");
  }

  ...
}
4. C++ 呼叫 Java 函數 :
   i. C++  檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

  JNIEnv *env  =NULL;
  jclass classid;
  jmethodID methodid;

  JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
  if (NULL == jvm) {
      return;
  }

  //setup env
  jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
  if (ret !=JNI_OK) {
      env =NULL;
      return;
  }

  classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
  if (!classid){
      return;
  }

  methodid =env->GetStaticMethodID(classid, "initGameBarLib", "()V");
  if (!methodid){
      return;
  }

  env->CallStaticObjectMethod(classid, methodid);
   ii. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  static public void initGameBarLib(){
    ...
  }
}

5. Java 呼叫 C++ 時傳遞數字變數 :
   i. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  private static native void nativeMethod(int val);
  ...

  static public void run(){
    nativeMethod(9527);
  }
}
   ii. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

extern "C"
{
  void Java_com_appmaster_AMCocos2dxInterface_ nativeMethod(JNIEnv* env, jobject thiz, jint val)
  {
    int nval =(int)val;
    CCLOG("val=%d", nval);

    ...

  }

  ...
}
6. C++ 呼叫 Java 時傳遞數字變數 :
   i. C++  檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

  JNIEnv *env  =NULL;
  jclass classid;
  jmethodID methodid;

  JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
  if (NULL == jvm) {
      return;
  }

  //setup env
  jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
  if (ret !=JNI_OK) {
      env =NULL;
      return;
  }

  classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
  if (!classid){
      return;
  }

  methodid =env->GetStaticMethodID(classid, "magicNumber", "(I)V");
  if (!methodid){
      return;
  }

  env->CallStaticObjectMethod(classid, methodid, (jint)9527);
   ii. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  static public void magicNumber(int val){
    ...
  }
}
7. Java 呼叫 C++ 時傳遞字串 :
   i. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  private static native void nativeMethod(final string data);
  ...

  static public void run(){
    nativeMethod("hello C++");
  }
}
   ii. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

extern "C"
{
  void Java_com_appmaster_AMCocos2dxInterface_ nativeMethod(JNIEnv* env, jobject thiz, jstring data)
  {
    const char* pData =env->GetStringUTFChars(data, 0);
    CCLOG("data=%s", pData);

    ...

    env->ReleaseStringUTFChars(data, pData);
  }

  ...
}
8. C++ 呼叫 Java 時傳遞字串 :
   i. C++  檔案如下 :
#include <jni/JniHelper.h>
#include <jni.h>

...

  JNIEnv *env  =NULL;
  jclass classid;
  jmethodID methodid;

  JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
  if (NULL == jvm) {
      return;
  }

  //setup env
  jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
  if (ret !=JNI_OK) {
      env =NULL;
      return;
  }

  classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
  if (!classid){
      return;
  }

  methodid =env->GetStaticMethodID(classid, "initGameBarLib", "(Ljava/lang/String;Ljava/lang/String;)V");
  if (!methodid){
      return;
  }

  jstring arg0 =env->NewStringUTF(pArg0); //char* pArg0
  jstring arg1 =env->NewStringUTF(pArg1); //char* pArg1
  env->CallStaticObjectMethod(classid, methodid, arg0, arg1);
  env->DeleteLocalRef(arg0);
  env->DeleteLocalRef(arg1);
   ii. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  static public void initGameBarLib(String arg0, String arg1){
    ...
  }
}
9. Java 呼叫 C++ 時傳遞矩陣 :
   i. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  private static native void nativeLoginHandler(int[] array);
  ...
  
  static public void run(){
    int[] array ={9, 5, 2, 7};
    nativeLoginHandler(array);
  }
}
   ii. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

extern "C"
{
  void Java_com_appmaster_AMCocos2dxInterface_nativeLoginHandler(JNIEnv* env, jobject thiz, jintArray ptr)
  {
      jsize length =env->GetArrayLength(ptr);
      if (length>0){
          jint* intarr =env->GetIntArrayElements(ptr, 0);
          for (int i=0;i<length;++i){
              printf("val[%d] =%d", i, intarr[i]);
          }

          env->ReleaseIntArrayElements(ptr, intarr, 0); 
      }
  }

  ...
}
10. C++ 呼叫 Java 時傳遞矩陣 :
   i. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

  ...

  int* praw_int =new int[4];
  praw_int[0] =9;
  praw_int[1] =5;
  praw_int[2] =2;
  praw_int[3] =7;

  jintArray arrdata =env->NewIntArray(4);
  env->SetIntArrayRegion(arrdata, 0, 4, (jint*)praw_int);

  ...

  JNIEnv *env  =NULL;
  jclass classid;
  jmethodID methodid;

  JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
  if (NULL == jvm) {
      return;
  }

  //setup env
  jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
  if (ret !=JNI_OK) {
      env =NULL;
      return;
  }

  classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
  if (!classid){
      return;
  }

  methodid =env->GetStaticMethodID(classid, "initGameBarLib", "([II)V");
  if (!methodid){
      return;
  }

  env->CallStaticObjectMethod(classid, methodid, arrdata, 4);

  delete [] praw_int;

}
   ii. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  
  static public void initGameBarLib(int[] data, int num){

    ...

  }

}
11. Java 呼叫 C++ 時傳遞回呼函數 :
   i. JAVA 檔案如下 :
package com.appmaster;

import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.Activity;

public class AMCocos2dxInterface
{
  //傳遞回呼函數名稱 (字串)
  private static native void nativeAsyncMethod(final string funcString);
  ...
  
  static public void callbackFunc(){
    //i will be callback from c++
  }

  static public void run(){
    nativeAsyncMethod("callbackFunc");
  }
}
   ii. C++ 檔案如下 :
#include "cocos2d.h"
#include <jni/JniHelper.h>
#include <jni.h>

...

extern "C"
{
  void Java_com_appmaster_AMCocos2dxInterface_ nativeAsyncMethod(JNIEnv* env, jobject thiz, jstring funcString)
  {
    const char* pFuncString =env->GetStringUTFChars(funcString, 0);
    
    ...

    //callback
    JNIEnv *env  =NULL;
    jclass classid;
    jmethodID methodid;

    JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
    if (NULL == jvm) {
        env->ReleaseStringUTFChars(funcString, pFuncString);
        return;
    }

    //setup env
    jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
    if (ret !=JNI_OK) {
        env =NULL;
        env->ReleaseStringUTFChars(funcString, pFuncString);
        return;
    }

    classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
    if (!classid){
        env->ReleaseStringUTFChars(funcString, pFuncString);
        return;
    }

    methodid =env->GetStaticMethodID(classid, pFuncString, "()V");
    if (!methodid){
        env->ReleaseStringUTFChars(funcString, pFuncString);
        return;
    }

    env->CallStaticObjectMethod(classid, methodid);

    env->ReleaseStringUTFChars(funcString, pFuncString);
  }

  ...
}
12. C++ 呼叫 Java 時傳遞回呼函數 :
(ps. 底下的實作並未真正的把 C function pointer 傳遞到 java 環境)
   i. C++ (AMGamebarUtil.h)檔案如下 :
#include "cocos2d.h"

 ...

//定義回呼函數
typedef void (*onLoginCallback)(const cocos2d::CCString* pStrAccountID, const cocos2d::CCString* pStrNickname);

class AMGamebarUtil
{
public:
  static void initGameBarLib(onLoginCallback pCBFunc1);

}

 ...

   i. C++ (AMGamebarUtil.cpp)檔案如下 :
#include <jni/JniHelper.h>
#include <jni.h>
#include "AMGamebarUtil.h"

 ...

onLoginCallback pLC =NULL;

//預先建立 function 讓 java 回呼
extern "C"
{
  void Java_com_appmaster_AMCocos2dxInterface_nativeLoginHandler(JNIEnv*  env, jobject thiz, jstring aid, jstring nickname)
  {
    const char* pAid =env->GetStringUTFChars(aid, 0);
    const char* pNick =env->GetStringUTFChars(nickname, 0);

    //若是回呼函數已指定則回呼之
    if (pLC !=NULL){
      pLC(
        cocos2d::CCString::createWithFormat("%s", pAid),
        cocos2d::CCString::createWithFormat("%s", pNick)
      );
    }

    env->ReleaseStringUTFChars(aid, pAid);
    env->ReleaseStringUTFChars(nickname, pNick);
  }
}

void AMGamebarUtil::initGameBarLib(onLoginCallback pCBFunc1)
{

  //呼叫 JAVA
  JNIEnv *env  =NULL;
  jclass classid;
  jmethodID methodid;

  JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
  if (NULL == jvm) {
      CCLOG("Unity - AMGamebarUtil.cpp, Failed to get JNIEnv. JniHelper::getJavaVM() is NULL");
      return;
  }

  //setup env
  jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
  if (ret !=JNI_OK) {
      env =NULL;
      return;
  }

  if (env ==NULL){
    return;
  }

  classid =env->FindClass("com/appmaster/AMCocos2dxInterface");
  if (!classid){
      return;
  }

  methodid =env->GetStaticMethodID(classid, "initGameBarLib", "()V");
  if (!methodid){
      return;
  }

  //REGISTER CALLBACK FUNCTION
  pLC   =pCBFunc1;

  //CALLING METHOD
  env->CallStaticObjectMethod(classid, methodid);

}
   i. C++ (.cpp)執行如下 :
//實作回呼函數
void onLoginCallbackHandler(const cocos2d::CCString* pStrAccountID, const cocos2d::CCString* pStrNickname)
{
    CCLOG("onLoginCallbackHandler(), aid=%s, nickname=%s", pStrAccountID->getCString(), pStrNickname->getCString());
}

 ...

//實際呼叫 initGameBarLib 並傳遞回呼函數指標
AMGamebarUtil::initGameBarLib(&onLoginCallbackHandler);


   ii. JAVA 檔案如下 :

public class AMCocos2dxInterface
{
    //預先定義回呼之 c++ method
    private static native void nativeLoginHandler(final String aid, final String nickname);

    static public void initGameBarLib(){
       ...
       
       //回呼 c++ method
       nativeLoginHandler("THIS_IS_AID", "THIS_IS_NICKNAME");
    }
   
    ...
}

ref:http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
ref:http://stackoverflow.com/questions/1232236/retrieving-byte-array-of-unknow-length-from-java-store
ref:http://www.lyceemermoz.com/iris/jlp/util/java/jdk/graphic/graphic.cpp
ref:http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/types.html

2013-07-24

Create Android Live Wallpaper with Cocos2d-x

底下敘述使用 Cocos2d-x 製作 Android Live Wallpaper 的方法。(建構環境 : OSX ML,cocos2d-2.1rc0-x-2.1.3,Android NDK r8e,Android SDK r22。執行環境 : Sony Xperia TX with Android 4.1.2)

A. 程式架構 :
Cocos2d-x 本身提供一個便利的方法建立 Android Project ( 執行 Cocos2d-x 裡的 create-android-project.sh 即可 ),從自動建立的 Android Project 大概可以了解 App 模式之 Cocos2d-x 與 Android 作業系統間的關係,目前 Cocos2d-x 的程式架構在 Android 環境下,單一 Process 只能同時擁有及處理單一 GL Context 及 GLSurface,若要直接把 Cocos2dxRenderer 及 Cocos2dxGLSurfaceView 整合至 WallpaperService.Engine 內會衍生不少問題。因此這裡實作把它們整合在 WallpaperService。各別 Engine 在進行繪圖時 ( onDrawFrame ),只實作貼圖 ( Texture ) 的動作 ( 使用 Android 系統提供的 GL Function ),其中圖片的來源則是向 WallpaperService 的 Cocos2dxRenderer 取得 ( 此處的 Cocos2dxRenderer 是以 off-screen rendering 方式產生貼圖 )。

在不同的 GL Context 之間分享貼圖的方法,這裡選擇使用 EGL_KHR_gl_texture_2D_image Extension 的功能來實作,可避免因為使用 glReadPixles 及 glTexImage2D 造成效能低落的問題。

B. 實作程式 :

1. 建立 Android Project
從 cocos2d-x 網站下載檔案 cocos2d-2.1rc0-x-2.1.3.zip ,將壓縮檔解開並編輯檔案 create-android-project.sh,找到 :
# set environment paramters
NDK_ROOT_LOCAL="/home/laschweinski/android/android-ndk-r5"
ANDROID_SDK_ROOT_LOCAL="/home/laschweinski/android/android-sdk-linux_86"
將它們修改成自己電腦裡 NDK 及 Android SDK 的路徑,例如 :
# set environment paramters
NDK_ROOT_LOCAL="/Users/macaronics/Downloads/android-ndk-r8e"
ANDROID_SDK_ROOT_LOCAL="/Users/macaronics/android-sdks"
完成之後執行這個 sh 檔案,執行畫面如下 :
執行 create-android-project.sh

輸入 package path (com.macaronics.cclw) 之後,畫面會出現目前 Android SDK 已安裝的 API (依照各電腦情況不同),此範例選擇的是 id:1 (API Level 10),最後輸入專案名稱 (cclw),就完成了。

打開 eclipse 並匯入 cclw 這個專案,完成之後會發現幾個錯誤回報,那是因為找不到 cocos2dx package,此時匯入 cocos2dx 專案即可解決 ( cocos2dx 專案的路徑為 cocos2d-2.1rc0-x-2.1.3/cocos2dx/platform/android/java )。

匯入 cclw 及 cocos2dx 專案

本專案建立時選擇之 API Level 為 10,因此匯入完成之後檢查 AndroidManifest.xml 檔案,將 :
<uses-sdk android:minSdkVersion="8"/>
改為
<uses-sdk android:minSdkVersion="10"/>
到目前為止已經可以正常編譯並執行 cclw 專案,首先在資料夾 cocos2d-2.1rc0-x-2.1.3/cclw/proj.android 底下執行 build_native.sh,完成之後會看到專案裡的 lib 資料夾多出檔案 libgame.so,接著在 eclipse 點選 cclw 專案,並於功能表上選擇 Run --> Run As --> Android Application 即可實際編譯執行。此外也可直接在 Terminal 裡輸入 :
ant release -Dsdk.dir=/Users/macaronics/android-sdks/
編譯 apk 檔案 (/Users/macaronics/android-sdks/ 為 Android SDK 之路徑)。

2. 新增 PixelBuffer
如圖所示,在 cclw/src/com/macaronics/cclw 資料夾底下增加檔案 PixelBuffer.java :
新增檔案 PixelBuffer.java

PixelBuffer 的作用是向系統要求建立 GL Context 與 Surface Buffer ,它和 GLSurfaceView 的功能幾乎一樣,只是它所建立的 Surface Buffer 是 PBuffer (作為 off-screen rendering 使用),與 GLSurfaceView 建立的 Window Surface Buffer 不同。此段程式碼參考的來源在此,但 EGL Config Chooser 的部分參考 GLSurfaceView 做了一些修改,程式碼內容如下 :
public class PixelBuffer
{
    final static String TAG = "PixelBuffer";
    final static boolean LIST_CONFIGS = true;

    GLSurfaceView.Renderer mRenderer; // borrow this interface
    int mWidth, mHeight;
    Bitmap mBitmap;
        
    EGL10 mEGL; 
    EGLDisplay mEGLDisplay;
    EGLConfig[] mEGLConfigs;
    EGLConfig mEGLConfig;
    EGLContext mEGLContext;
    EGLSurface mEGLSurface;
    GL10 mGL;

    EGLConfigChooser mEGLConfigChooser;
    int mEGLContextClientVersion;
    
    String mThreadOwner;
    private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
    private static int EGL_LARGEST_PBUFFER        = 0x3058;
    private static int EGL_OPENGL_ES2_BIT          = 4;


    public PixelBuffer(int width, int height) {
        mWidth = width;
        mHeight = height;
        mEGLContextClientVersion =2;
                
        int[] version = new int[2];
        int[] attribList = new int[] {
            EGL_WIDTH,              mWidth,
            EGL_HEIGHT,             mHeight,
            EGL_LARGEST_PBUFFER,    1,
            EGL_NONE
        };

        int [] context_attribList =new int[] {
            EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion, 
            EGL_NONE
        };
                
        // No error checking performed, minimum required code to elucidate logic
        mEGL = (EGL10) EGLContext.getEGL();
        mEGLDisplay = mEGL.eglGetDisplay(EGL_DEFAULT_DISPLAY);
        mEGL.eglInitialize(mEGLDisplay, version);
        Log.i("cclw", "eglInitialized, version ="+version[0]+"."+version[1]);
        Log.i("cclw", "EGL Extension : "+mEGL.eglQueryString(mEGLDisplay, EGL_EXTENSIONS));

        mEGLConfigChooser =new SimpleEGLConfigChooser(8, 8, 8, 0, true);
        mEGLConfig =mEGLConfigChooser.chooseConfig(mEGL, mEGLDisplay);
        if (mEGLConfig ==null)
        {
            mEGLConfigChooser =new SimpleEGLConfigChooser(5, 8, 5, 0, true);
            mEGLConfig =mEGLConfigChooser.chooseConfig(mEGL, mEGLDisplay);
        }
        
        mEGLContext = mEGL.eglCreateContext(mEGLDisplay, mEGLConfig, EGL_NO_CONTEXT, context_attribList);
        mEGLSurface = mEGL.eglCreatePbufferSurface(mEGLDisplay, mEGLConfig, attribList);
        mEGL.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
        mGL = (GL10) mEGLContext.getGL();
        
        // Record thread owner of OpenGL context
        mThreadOwner = Thread.currentThread().getName();
        Log.i("cclw", "PixelBuffer created. mThreadOwner ="+mThreadOwner);

    }

    public void dispose()
    {
        if (mEGLDisplay !=EGL_NO_DISPLAY)
        {
            mEGL.eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
            if (mEGLContext !=EGL_NO_CONTEXT)
                mEGL.eglDestroyContext(mEGLDisplay, mEGLContext);

            if (mEGLSurface !=EGL_NO_SURFACE)
                mEGL.eglDestroySurface(mEGLDisplay, mEGLSurface);
            mEGL.eglTerminate(mEGLDisplay);
        }
    }
    
    public void setRenderer(GLSurfaceView.Renderer renderer) {
        mRenderer = renderer;
        
        // Does this thread own the OpenGL context?
        if (!Thread.currentThread().getName().equals(mThreadOwner)) {
            Log.e(TAG, "setRenderer: This thread does not own the OpenGL context.");
            return;
        }
        
        // Call the renderer initialization routines
        mRenderer.onSurfaceCreated(mGL, mEGLConfig);
        mRenderer.onSurfaceChanged(mGL, mWidth, mHeight);
    }

    public void drawFrame()
    {
        makeCurrent();
        mRenderer.onDrawFrame(mGL);
    }

    public void makeCurrent()
    {
        // Do we have a renderer?
        if (mRenderer == null) {
            Log.e(TAG, "getBitmap: Renderer was not set.");
            return;
        }
        
        // Does this thread own the OpenGL context?
        if (!Thread.currentThread().getName().equals(mThreadOwner)) {
            Log.e(TAG, "getBitmap: This thread does not own the OpenGL context.");
            return;
        }
                
        // Call the renderer draw routine
        mEGL.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
    } 

    public interface EGLConfigChooser {
        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
    }

    private abstract class BaseConfigChooser implements EGLConfigChooser {
        public BaseConfigChooser(int[] configSpec) {
            mConfigSpec =configSpec;
        }

        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
            int[] num_config = new int[1];
            if (!egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config)) {
                throw new IllegalArgumentException("eglChooseConfig failed");
            }

            int numConfigs = num_config[0];

            if (numConfigs <= 0) {
                throw new IllegalArgumentException("No configs match configSpec");
            }

            EGLConfig[] configs = new EGLConfig[numConfigs];
            if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config)) {
                throw new IllegalArgumentException("eglChooseConfig#2 failed");
            }

            //list configs
            listConfig(configs);

            EGLConfig config = chooseConfig(egl, display, configs);
            if (config == null) {
                throw new IllegalArgumentException("No config chosen");
            }
            return config;
        }

        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs);
        protected int[] mConfigSpec;
    }

    private class ComponentSizeChooser extends BaseConfigChooser {
        public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) {
            super(new int[] {
                    EGL10.EGL_RENDERABLE_TYPE,  EGL_OPENGL_ES2_BIT,
                    EGL10.EGL_SURFACE_TYPE,     EGL_WINDOW_BIT | EGL_PBUFFER_BIT,

                    EGL10.EGL_RED_SIZE,         redSize,
                    EGL10.EGL_GREEN_SIZE,       greenSize,
                    EGL10.EGL_BLUE_SIZE,        blueSize,
                    EGL10.EGL_ALPHA_SIZE,       alphaSize,
                    EGL10.EGL_DEPTH_SIZE,       depthSize,
                    EGL10.EGL_STENCIL_SIZE,     stencilSize,

                    EGL10.EGL_NONE});

            mValue = new int[1];
            mRedSize = redSize;
            mGreenSize = greenSize;
            mBlueSize = blueSize;
            mAlphaSize = alphaSize;
            mDepthSize = depthSize;
            mStencilSize = stencilSize;
        }

        @Override
        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
                EGLConfig[] configs) {
            for (EGLConfig config : configs) {
                int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
                int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
                if ((d >= mDepthSize) && (s >= mStencilSize)) {
                    int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
                    int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
                    int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
                    int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
                    if ((r == mRedSize) && (g == mGreenSize) && (b == mBlueSize) && (a == mAlphaSize)) {
                        return config;
                    }
                }
            }
            return null;
        }

        private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) {

            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
                return mValue[0];
            }
            return defaultValue;
        }

        private int[] mValue;
        // Subclasses can adjust these values:
        protected int mRedSize;
        protected int mGreenSize;
        protected int mBlueSize;
        protected int mAlphaSize;
        protected int mDepthSize;
        protected int mStencilSize;
        }

    private class SimpleEGLConfigChooser extends ComponentSizeChooser {
        public SimpleEGLConfigChooser(int red, int green, int blue, int alpha, boolean withDepthBuffer) {
            super(red, green, blue, alpha, withDepthBuffer ? 16 : 0, 0);
        }
    }    
    
    private void listConfig(EGLConfig[] tmpConfig) {
        Log.i("cclw", "Config List {");

        for (EGLConfig config : tmpConfig) {
            int d, s, r, g, b, a;
                    
            // Expand on this logic to dump other attributes        
            d = getConfigAttrib(config, EGL_DEPTH_SIZE);
            s = getConfigAttrib(config, EGL_STENCIL_SIZE);
            r = getConfigAttrib(config, EGL_RED_SIZE);
            g = getConfigAttrib(config, EGL_GREEN_SIZE);
            b = getConfigAttrib(config, EGL_BLUE_SIZE);
            a = getConfigAttrib(config, EGL_ALPHA_SIZE);
            Log.i("cclw", "    <d,s,r,g,b,a> = <" + d + "," + s + "," +  r + "," + g + "," + b + "," + a + ">");
        }

        Log.i("cclw", "}");
    }
        
    private int getConfigAttrib(EGLConfig config, int attribute) {
        int[] value = new int[1];
        return mEGL.eglGetConfigAttrib(mEGLDisplay, config,
                        attribute, value)? value[0] : 0;
    }
}
3. EGL_KHR_gl_texture_2D_image Extension 的部分 :
WallpaperService.Engine 命令 Cocos2d-x 以 off-screen rendering 的方式將圖案畫在 PBuffer 裡,然後將 PBuffer 裡的資料複製到自己的 GL Context,此處複製 PBuffer 資料的步驟使用 EGL_KHR_gl_texture_2D_image Extension 以 C 語言來實作,讓 WallpaperService.Engine 以 JNI 的方式呼叫。實作時,直接將函數寫在檔案 cclw/jni/hellocpp/main.cpp 內,底下列出修改後的結果 :
#include "AppDelegate.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>

#include "cocos2d.h"
#include "HelloWorldScene.h"

#define EGL_EGLEXT_PROTOTYPES

#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2ext.h>

#define  LOG_TAG    "main"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

using namespace cocos2d;

extern "C"
{

jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JniHelper::setJavaVM(vm);

    return JNI_VERSION_1_4;
}

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
    {
        ccDrawInit();
        ccGLInvalidateStateCache();
        
        CCShaderCache::sharedShaderCache()->reloadDefaultShaders();
        CCTextureCache::reloadAllTextures();
        CCNotificationCenter::sharedNotificationCenter()->postNotification(EVNET_COME_TO_FOREGROUND, NULL);
        CCDirector::sharedDirector()->setGLDefaultValues(); 
    }
    */
}

EGLImageKHR eglImage =NULL;
EGLDisplay eglDisplay =NULL;

void Java_com_macaronics_cclw_cclwservice_nativeAttachEGLImageKHR(JNIEnv*  env, jobject thiz)
{
    if (eglImage !=NULL)
    {
        glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, eglImage);
    }
}

void Java_com_macaronics_cclw_cclwservice_nativeDestroyEGLImageKHR(JNIEnv*  env, jobject thiz)
{
    if (eglImage !=NULL && eglDisplay !=NULL)
    {
        bool ret =eglDestroyImageKHR(eglDisplay, eglImage);
        LOGD("cclw, nativeDestroyEGLImageKHR ret val =%d", ret);

        eglImage =NULL;
        eglDisplay =NULL;
    }
}

void Java_com_macaronics_cclw_cclwservice_nativeRenderToTexture(JNIEnv*  env, jobject thiz)
{
    int textureID =HelloWorld::renderToTexture();

    if (eglImage ==NULL)
    {
        LOGD("cclw, nativeRenderToTexture - Generate EGLImageKHR ...");
        EGLint imageAttributes[] = {
            EGL_GL_TEXTURE_LEVEL_KHR,   0, // mip map level to reference
            EGL_IMAGE_PRESERVED_KHR,    EGL_FALSE,
            EGL_NONE,                   EGL_NONE
        };

        eglDisplay =eglGetCurrentDisplay();
        EGLContext eglContext =eglGetCurrentContext();
        LOGD("cclw, eglDisplay=%d, eglContext=%d, textureID=%d", eglDisplay, eglContext, textureID);

        eglImage =
            eglCreateImageKHR(
                eglDisplay,
                eglContext,
                EGL_GL_TEXTURE_2D_KHR,
                reinterpret_cast<EGLClientBuffer>(textureID),
                imageAttributes
            );
    }
}

}
其中值得注意的是,並不是所有的 GPU 都支援 EGL_GL_TEXTURE_2D_KHR (例如: Adreno 205 GPU 不支援),此外,函數 :
HelloWorld::renderToTexture();
利用 Cocos2d-x 提供的 CCRenderTexture 物件將圖案畫在 Texture 裡,實作內容如下 (檔案 HelloWorldScene.cpp) :
CCRenderTexture* g_RT =NULL;
int HelloWorld::renderToTexture()
{
    if (g_RT==NULL)
    {
        g_RT =CCRenderTexture::create(720, 1184, kCCTexture2DPixelFormat_RGBA8888);
        g_RT->retain();
        g_RT->setPosition(ccp(720 / 2, 1184 / 2));
        CCLOG("cclw, create RenderTexture (id=%d)...", g_RT->getSprite()->getTexture()->getName());
    }

    g_RT->beginWithClear(0.0f, 0.0f, 0.0f, 1.0f);
    CCDirector::sharedDirector()->mainLoop();
    g_RT->end();

    return g_RT->getSprite()->getTexture()->getName();
}
其中的 720 是畫面寬度,1184 是畫面高度。

4. WallpaperService 的部分 :
新增檔案 cclwservice.java 於資料夾 cclw/src/com/macaronics/cclw 。檔案的程式碼如底下所示,其中 WallpaperService 主要分為 Engine、Renderer 及 Service (負責創造 Engine Instance 、 Cocos2d-x Renderer 執行緒及收拾殘局) :
public class cclwservice extends WallpaperService {
 
    public final static long NANOSECONDSPERSECOND = 1000000000L;
    public final static long NANOSECONDSPERMICROSECOND = 1000000;
 
    public static native void nativeAttachEGLImageKHR();
    public static native void nativeDestroyEGLImageKHR();
    public static native void nativeRenderToTexture();

    //----------------------
    // LIBRARY
    //
        static {
            System.loadLibrary("game");
        }

    //----------------------
    // VARIABLES
    //
        public static cclwservice inst =null;

        public static PixelBuffer pb =null;
        public static Handler ph =null;
        public static HandlerThread mThread;

        private Cocos2dxRenderer pc2r =null;

    //----------------------
    // MAIN FUNCTION
    //
        @Override
        public Engine onCreateEngine() {

            Log.i("cclw", "cclw - onCreateEngine");
            Engine retEng =null;
            retEng =new GLEngine();

            return retEng;
        }

        @Override
        public void onCreate(){
            Log.i("cclw", "cclw - onCreate");
            super.onCreate();
            inst =this;

            mThread =new HandlerThread("Rendering Thread");
            mThread.start();
            ph =new Handler(mThread.getLooper());
            ph.post(new Runnable(){
                @Override
                public void run(){
                    Log.i("cclw", "cclw - calling Cocos2dxHelper.init...");
                    Cocos2dxHelper.init(cclwservice.inst, null);

                    //prepare offscreen buffer
                    Log.i("cclw", "cclw - prepare offscreen buffer...");
                    if (pb ==null)
                        pb =new PixelBuffer(720, 1184);

                    Log.i("cclw", "cclw - create native renderer...");

                    pc2r =new Cocos2dxRenderer();
                    pc2r.setScreenWidthAndHeight(720, 1184);
                    pb.setRenderer(pc2r);
                }
            });
                    
        }

        @Override
        public void onDestroy(){
            Log.i("cclw", "cclw - onDestroy");
            super.onDestroy();

            //dispose handler
            ph =null;

            //dispose thread
            Log.i("cclw", "cclw - dispose Rendering Thread...");
            mThread.quit();

            cclwservice.nativeDestroyEGLImageKHR();

            Log.i("cclw", "cclw - dispose PixelBuffer");
            if (pb !=null){
                pb.dispose();
            }
            pb =null;

        }

        synchronized static public void renderToTexture(){
            pb.makeCurrent();
            cclwservice.nativeRenderToTexture();
        }

}
函數 renderToTexture 執行時,會透過 JNI 呼叫 cclw/jni/hellocpp/main.cpp 檔案裡的函數 Java_com_macaronics_cclw_cclwservice_nativeRenderToTexture 讓 Cocos2d-x 將圖案畫在 PixelBuffer 所建立之 PBuffer 的 Texture 裡,並將此 Texture 設定為 KHR_image。

底下為 Engine 部分的程式 ( Engine 負責建立自己的 Renderer、接收系統訊息,及乎如同一般的 Activity ) :
//----------------------
// GL Engine
//
private class GLEngine extends Engine
{

    //----------------------
    // VARIABLES
    //
        private WallpaperGLSurfaceView glSurfaceView;
        private boolean rendererHasBeenSet;

        private WallpaperGLRenderer glRenderer;
         
    //----------------------
    // FUNCTION
    //                 
        @Override
        public Bundle onCommand(String action, int x, int y, int z, Bundle extras, boolean resultRequested) {
            Log.i("cclw", "onCommand");
            return super.onCommand(action, x, y, z, extras, resultRequested);
        }

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);

            setTouchEventsEnabled(true);

            Log.i("cclw", "onCreate");
            glSurfaceView = new WallpaperGLSurfaceView(cclwservice.this);

            setEGLContextClientVersion(2);
            glRenderer =new WallpaperGLRenderer();
            setRenderer(glRenderer);

        }

        @Override
        public void onDestroy() {
            super.onDestroy();

            glRenderer.onDestroy();
            glRenderer =null;

            Log.i("cclw", "onDestroy");
            glSurfaceView.onDestroy();
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
         
            Log.i("cclw", "onVisibilityChanged, visible ="+visible);
            if (rendererHasBeenSet) {
                if (visible) {
                    Log.i("cclw", "calling onResume...");
                    glSurfaceView.onResume();
                } else {
                    Log.i("cclw", "calling onPause...");
                    glSurfaceView.onPause();
                }
            }
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset)
        {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            //Log.i("cclw", "onOffsetsChanged, xOffset="+xOffset+", yOffset="+yOffset+", xOffsetStep="+xOffsetStep+", yOffsetStep="+yOffsetStep+", xPixelOffset="+xPixelOffset+", yPixelOffset="+yPixelOffset);
        }

        protected void setRenderer(Renderer renderer){
            glSurfaceView.setRenderer(renderer);
            rendererHasBeenSet =true;
        }

        protected void setEGLContextClientVersion(int version) {
              glSurfaceView.setEGLContextClientVersion(version);
        }


    //------------------------
    // Custom SurfaceView for WallpaperService.engine
    //
        private class WallpaperGLSurfaceView extends GLSurfaceView {
         
            WallpaperGLSurfaceView(Context context) {
                super(context);
            }
         
            @Override
            public SurfaceHolder getHolder() {
                return getSurfaceHolder();
            }
        }

}
值得注意的是 WallpaperGLSurfaceView 類別裡的函數 getHolder,是透過 Engine 類別的函數 getSurfaceHolder 來取得 SurfaceHolder。此外,Engine 所建立的 Renderer 與 Cocos2d-x Renderer 無關,它擁有自己的 GL Context 及 Window Surface Buffer。

WallpaperGLRenderer 的部分 : (底下的程式如同一般的 GL 程式,使用 OpenGL ES 2.0 來顯示一張 Texture,只是這個 Texture 的資料是 PixelBuffer 的 PBuffer 的資料 )
//----------------------
// RENDERER
//
private class WallpaperGLRenderer implements GLSurfaceView.Renderer{

    private String TAG ="cclw";
    
    int[] mTextureNameWorkspace =new int[] {0};

    private final float[] mTriangleVerticesData = { -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f };
    private final float[] mTriangleNormalData ={0.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,0.0f};
    private final float[] mTriangleTexCoordData ={0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f };
    private final float[] mTriangleTexCoordData2 ={1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };

    private FloatBuffer mTriangleVertices;
    private FloatBuffer mTriangleNormal;
    private FloatBuffer mTriangleTexCoord;
    private FloatBuffer mTriangleTexCoord2;

    private final String mVertexShader = "attribute vec4 a_position;   \n"+
        "attribute vec3 a_normal;     \n"+
        "attribute vec2 a_texCoord;   \n"+
        "varying vec2 v_texCoord;     \n"+
        "varying vec3 v_normal;       \n"+
        "void main()                  \n"+
        "{                            \n"+
        "   gl_Position =a_position;  \n"+
        "   v_normal = a_normal;      \n"+
        "   v_texCoord = a_texCoord;  \n"+
        "}                            \n";

    private final String mFragmentShader = "precision mediump float; \n"+
                "varying vec2 v_texCoord;                            \n"+
                "varying vec3 v_normal;                              \n"+
                "uniform sampler2D s_texture;                        \n"+
                "void main()                                         \n"+
                "{                                                   \n"+
                "  gl_FragColor = texture2D( s_texture, v_texCoord );\n"+
                "}                                                   \n";
    
    private int mProgram;
    private int mvPositionHandle;
    private int mvNormalHandle;
    private int mvTexCoordHandle;
    private int mvSamplerHandle;

    private long mLastTickInNanoSeconds;
    public long aniInterval;

    public int mOrientation =0;

    public boolean onDestroyCalled =false;

    public WallpaperGLRenderer() {
        mTriangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mTriangleVertices.put(mTriangleVerticesData).position(0);

        mTriangleNormal = ByteBuffer.allocateDirect(mTriangleNormalData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mTriangleNormal.put(mTriangleNormalData).position(0);

        mTriangleTexCoord = ByteBuffer.allocateDirect(mTriangleTexCoordData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mTriangleTexCoord.put(mTriangleTexCoordData).position(0);

        mTriangleTexCoord2 =ByteBuffer.allocateDirect(mTriangleTexCoordData2.length *4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        mTriangleTexCoord2.put(mTriangleTexCoordData2).position(0);

        this.mLastTickInNanoSeconds =System.nanoTime();
        aniInterval =(long) (1.0 / 30 * NANOSECONDSPERSECOND);
    }

    public void onDestroy(){
        Log.i("cclw", "onDestroy called...");
        onDestroyCalled =true;
    }
    
    protected class WorkerRunnable implements Runnable{
        private final CountDownLatch doneSignal;
        WorkerRunnable(CountDownLatch doneSignal){
            this.doneSignal =doneSignal;
        }

        public void run(){
            try{
                cclwservice.renderToTexture();
                this.doneSignal.countDown();
            }catch(Exception ex){
                Log.i("cclw", "Error : Runnable return exception : "+ex);

            }                    
        }
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        try{
                final long nowInNanoSeconds = System.nanoTime();
                final long interval = nowInNanoSeconds - this.mLastTickInNanoSeconds;

                //------------------------
                // FETCH DATA
                //
                    EGL10 mEGL = (EGL10) EGLContext.getEGL();
                    EGLSurface mEGLSurface =mEGL.eglGetCurrentSurface(EGL10.EGL_DRAW);
                    EGLDisplay mEGLDisplay =mEGL.eglGetCurrentDisplay();
                    EGLContext mEGLContext =mEGL.eglGetCurrentContext();

                    CountDownLatch doneSignal =new CountDownLatch(1);
                    cclwservice.ph.post(new WorkerRunnable(doneSignal));

                    doneSignal.await();

                //------------------------
                // SETUP BASIC ENVIRONMENT
                //
                    mEGL.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
                    if (onDestroyCalled==true)
                    {
                        Log.i("cclw", "onDestroyCalled==true, ignore drawing...");
                        return;
                    }

                //------------------------
                // UPDATE TEXTURE
                //
                    if (mTextureNameWorkspace[0]==0){                                                            
                        //Load texture
                        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
                        gl.glGenTextures(1, mTextureNameWorkspace, 0);
                        Log.i("cclw", "mTextureNameWorkspace[0]="+mTextureNameWorkspace[0]);

                    }

                    gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureNameWorkspace[0]);

                    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
                    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

                    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
                    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);

                    cclwservice.nativeAttachEGLImageKHR();

                    gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);


                //------------------------
                // RENDER SCENE
                //
                    GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                    GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
                    GLES20.glUseProgram(mProgram);

                    GLES20.glVertexAttribPointer(mvPositionHandle, 3, GLES20.GL_FLOAT, false, 0, mTriangleVertices);
                    GLES20.glVertexAttribPointer(mvNormalHandle, 3, GLES20.GL_FLOAT, false, 0, mTriangleNormal);

                    if (mOrientation ==1)
                        GLES20.glVertexAttribPointer(mvTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, mTriangleTexCoord);
                    else if(mOrientation ==0)
                        GLES20.glVertexAttribPointer(mvTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, mTriangleTexCoord2);

                    GLES20.glEnableVertexAttribArray(mvPositionHandle);
                    GLES20.glEnableVertexAttribArray(mvNormalHandle);
                    GLES20.glEnableVertexAttribArray(mvTexCoordHandle);

                    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
                    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureNameWorkspace[0]);
                    GLES20.glUniform1i(mvSamplerHandle, 0);

                    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);

                //------------------------
                // FPS Limitation
                //
                    final long val =(aniInterval - interval) / NANOSECONDSPERMICROSECOND;
                    if (val >0)
                    {
                        try{
                            Thread.sleep(val);
                        }catch(final Exception e){}
                    }

                    this.mLastTickInNanoSeconds = nowInNanoSeconds;

        }
        catch(Exception e){

        }
    }

    @Override
    public void onSurfaceChanged(GL10 arg0, int arg1, int arg2) { //arg1:width, arg2:height
        // TODO Auto-generated method stub
        Log.i("cclw", "WallpaperGLRenderer::onSurfaceChanged, arg1="+arg1+", arg2="+arg2);

        float myRatio =1184.0f/720.0f;
        mOrientation =0;
        if (arg2>=arg1)
        {
            myRatio =720.0f/1184.0f;
            mOrientation =1;
        }

        int targetHeight =arg2;
        int targetWidth =(int)((float)arg2*myRatio);

        if (targetWidth >arg1)
        {
            targetWidth =arg1;
            targetHeight =(int)((float)arg1/myRatio);
        }

        Log.i("cclw", "WallpaperGLRenderer::onSurfaceChanged, fit targetWidth="+targetWidth+", targetHeight="+targetHeight);
        GLES20.glViewport((int)((arg1-targetWidth)*0.5f), (int)((arg2-targetHeight)*0.5f), targetWidth, targetHeight);
    }

    @Override
    public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
        // TODO Auto-generated method stub
        Log.i("cclw", "WallpaperGLRenderer::onSurfaceCreated");

        mProgram =createProgram(mVertexShader, mFragmentShader);
        if (mProgram ==0)
            return;

        mvPositionHandle =GLES20.glGetAttribLocation(mProgram, "a_position");
        if (mvPositionHandle ==-1)
            return;
        
        mvNormalHandle =GLES20.glGetAttribLocation(mProgram, "a_normal");
        mvTexCoordHandle =GLES20.glGetAttribLocation(mProgram, "a_texCoord");
        mvSamplerHandle =GLES20.glGetUniformLocation(mProgram, "s_texture");

        GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
    }

    ...

其中值得注意的是函數 onDrawFrame 被系統呼叫之後,會產生一個實體 WorkerRunnable ,讓負責 cocos2d-x 繪圖的執行緒去執行,目的是讓 cocos2d-x 更新 PBuffer 裡的資料,更新完成之後,onDrawFrame 才繼續執行貼圖的動作。

5. 設定 AndroidManifest.xml
為 WallpaperService 新增 service 標籤,如底下所示 :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.macaronics.cclw"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="10"/>
    <uses-feature android:glEsVersion="0x00020000" />

    <application android:label="@string/app_name"
        android:icon="@drawable/icon">

        <activity android:name=".cclw"
                  android:label="@string/app_name"
                  android:screenOrientation="landscape"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:process="com.macaronics.cclw.cclw"
                  android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service
            android:name=".cclwservice"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:permission="android.permission.BIND_WALLPAPER"
            android:process="com.macaronics.cclw.cclwservice">
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>
            <meta-data android:name="android.service.wallpaper" android:resource="@xml/cclw_res" />
        </service>
                
    </application>
    <supports-screens android:largeScreens="true"
                      android:smallScreens="true"
                      android:anyDensity="true"
                      android:normalScreens="true"/>
</manifest> 
其中的 xml/cclw_res.xml 表示 Live Wallpaper 選單列表時所顯示之資訊,需要額外手動建立,步驟是首先建立資料夾 xml 於 cclw/res,然後建立檔案 cclw_res.xml,並設定內容如下 :
<?xml version="1.0" encoding="utf-8"?>
<wallpaper 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:thumbnail="@drawable/icon" 
/>

6. 設定 jni/Android.mk :
此時若執行 native_build.sh 會顯示一些錯誤,那是因為尚未設定連結 EGL Library,將 jni/Android.mk 修改如下即可正常編譯 :
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := game_shared

LOCAL_MODULE_FILENAME := libgame

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/HelloWorldScene.cpp
                   
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes                   

LOCAL_LDLIBS := -lEGL

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static
            
include $(BUILD_SHARED_LIBRARY)

$(call import-module,CocosDenshion/android) \
$(call import-module,cocos2dx) \
$(call import-module,extensions)

7. 執行結果 :
動態桌布選單多出了 cocos2d-x 建立的 cclw


將 cclw 設定成動態桌布

完整範例程式碼可以到 Git 下載: http://github.com/phardera/cocos2dx_android_livewallpaper

2012-09-17

Convert char** (string array) to C# string[]

底下範例是將 C/C++ 的字串陣列指標 (char**) 轉成 C# 內部使用的 string[] :

C/C++ 端的函數指標為 :
typedef void (* pCBFunc)(int, char**);

對應的 C# 端的函數為 :
public static void callback(int nArrsz, IntPtr pStringArray)
{
    string[] data = new string[nArrsz];
    IntPtr tmpPtr = pStringArray;
 
    for (int i = 0; i < nArrsz; ++i)
    {
        IntPtr strPtr = 
            (IntPtr)Marshal.PtrToStructure(tmpPtr, typeof(IntPtr));
        data[i] = Marshal.PtrToStringAuto(strPtr);
 
        tmpPtr = new IntPtr(tmpPtr.ToInt64() + IntPtr.Size);
    }
}
其中的 int nArrsz 為字串數目,IntPtr pStringArray 為字串陣列 ( 對應至 C 的 char** ) ,string[] data 是轉型後的資料。

2011-11-13

Objective-C 執行緒同步 ( NSCondition )

撰寫多執行緒程式都會碰到資料同步問題,objc 在這邊可使用 NSCondition 來達成,底下是 NSCondition 與 C#,C++用法比較:
Objective-C 的用法如下: 
NSCondition* pLock =[NSCondition new];
[pLock lock];
{ 
    //...
}
[pLock unlock];
[pLock release];



C++ 的用法如下:  HANDLE m_Handle =CreateSemaphore( NULL, 1, 1, L"SemaphoreName" );

WaitForSingleObject( m_Handle, nWaitTime );
{ 
    //...
}
ReleaseSemaphore( m_Handle, 1, NULL );
CloseHandle( m_Handle );



C# 的用法如下: 
private static AutoResetEvent m_Handle =new AutoResetEvent( true ); 
m_Handle.WaitOne(); 
{ 
    //...
}
m_Handle.Set();
其它有關執行緒同步的文章參考這篇。

2011-07-23

freeimage + DDS ( nvidia texture tools )

前段時間遇到一個需求是把 bmp, png 轉成 dds 格式,且在過程中自動把 bmp, png 的圖形放大到二的冪次方大小。 

後來使用兩套工具解決這個需求:
  • Freeimage 來做圖檔的讀取工具,
  • nvidia 提供的 texture tools 來做圖檔的格式轉換及壓縮工具,
freeimage library 提供方便快速的圖形讀取和寫入功能,但對(DirectX Surface)DDS 格式的支援只有到讀取的程度,致使無法儲存 DDS 格式檔案。texture tools 則是提供簡單的圖檔讀取及完整的 DDS 檔案格式支援,其 DDS 支援的部分剛好可以補足 freeimage 在支援 DDS 格式不足之處。

底下為把圖片轉成 DDS 格式的簡單實作:

1) 載入圖檔  (src.jpg):
std::string filename("src.jpg");
FREE_IMAGE_FORMAT fif =FreeImage_GetFileType( filename.c_str() );
FIBITMAP* dib =NULL;
dib = FreeImage_Load( fif, filename.c_str() );

2) 將圖檔轉成 RGBA 32bit 格式:
FIBITMAP* dib32 = FreeImage_ConvertTo32Bits(dib);

3) 取得圖形資料:
int nWidth =FreeImage_GetWidth(dib);
int nHeight =FreeImage_GetHeight(dib);
BYTE* pSrcDIB =FreeImage_GetBits(dib32);

4) 設定欲壓縮的圖形資料格式
nvtt::InputOptions inputOptions;
inputOptions.setTextureLayout(nvtt::TextureType_2D, nWidth, nHeight);
inputOptions.setMipmapData(pSrcDIB, nWidth, nHeight);
inputOptions.setFormat(nvtt::InputFormat_BGRA_8UB);

inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
inputOptions.setAlphaMode(nvtt::AlphaMode_Transparency);

inputOptions.setNormalMap(false);
inputOptions.setConvertToNormalMap(false);
inputOptions.setGamma(2.2f, 2.2f);
inputOptions.setNormalizeMipmaps(false);

inputOptions.setMipmapGeneration(false);

5) 設定 DDS 檔格式,此處使用的是 DXT1a 格式
nvtt::CompressionOptions compressionOptions;
compressionOptions.setFormat(nvtt::Format_DXT1a);
//compressionOptions.setQuality(nvtt::Quality_Fastest);
//compressionOptions.setQuality(nvtt::Quality_Normal);
//compressionOptions.setQuality(nvtt::Quality_Production);
compressionOptions.setQuality(nvtt::Quality_Highest);

6) 壓縮並儲存成 DDS 檔 (dst.dds):
nvtt::OutputOptions outputOptions;
outputOptions.setFileName("dst.dds");

nvtt::Compressor compressor;
compressor.enableCudaAcceleration(false);
compressor.process(inputOptions, compressionOptions, outputOptions);

7) 最後不忘刪除記憶體:
FreeImage_Unload(dib32);
FreeImage_Unload(dib);

2011-01-05

Windows Message in the Unity3D : WndProc

先前提到可以用 Hooks 的方法在 Unity 裡監控 Windows Message,但是使用 Hooks 這個方法我們沒辦法更改 Message 的內容。因此這邊提出第二個方式。Windows 傳送 Message 給 Unity 時,會呼叫 Unity 預設的 Message 處理函數,但透過函數:

pOldWndProc =(WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)SubWndProc);

我們可以將原本 Windows 呼叫 Unity 預設的 Message 處理函數改為呼叫我們指定的函數,指定的函數把我們想要處理的 Message 處理完,再把剩下的 Message 丟回給 Unity 來處理。

原本實作是使用 dllimport 讓 SetWindowLong function 可以在 C# 裡呼叫, 並把整個 callback function 及流程實作出來,且測試時運作都相當正常,但程式在關閉時會出現 Access Violation 的錯誤,後來將整個實作改成 C DLL 之後錯誤才沒有出現,不知道是什麼原因?底下是 DLL 部分的原始碼:
#include "stdafx.h"
LRESULT CALLBACK SubWndProc(
 HWND hWnd, 
 UINT nMessage, 
 WPARAM wParam, LPARAM lParam); 
 
 WNDPROC  gOldWndProc = NULL; 
 HWND  gUnityWnd = NULL; 
 
 #ifdef    __cplusplus
 extern "C" {
 #endif    /*    __cplusplus    */
 
 __declspec(dllexport) bool __stdcall init(HWND hWnd)
 {
  gOldWndProc =(WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)SubWndProc);
  gUnityWnd =hWnd;
 
  if (gOldWndProc !=NULL)
   return true;
 
  return false;
 }
 
 __declspec(dllexport) void __stdcall release()
 {
  SetWindowLong(gUnityWnd, GWL_WNDPROC, (LONG)gOldWndProc);
  gOldWndProc =0;
  gUnityWnd =0;
 }
 
#ifdef    __cplusplus
}
#endif    /*    __cplusplus    */
 
 
LRESULT CALLBACK SubWndProc(
 HWND hWnd, 
 UINT nMessage, 
 WPARAM wParam, LPARAM lParam)
 {
  switch(nMessage)
  {
   case WM_IME_SETCONTEXT:
   case WM_IME_STARTCOMPOSITION:
   case WM_IME_ENDCOMPOSITION:
   case WM_IME_COMPOSITION:
   case WM_IME_REQUEST:
   {
    //...
   }
   break;
 }
 return CallWindowProc(gOldWndProc, hWnd, nMessage, wParam, lParam);
}

Unity 可以透過呼叫 DLL 提供的 init() 函數,讓 Windows 改為呼叫我們指定的函數 (SubWndProc) 來處理 Message,透過 release() 函數讓 Message 處理流程復原。底下是 Unity 部分的原始碼(DLL 檔名為 UnityIMEDLL.dll 且檔案放在 Assets/Plugins 目錄下)
using UnityEngine;
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
 
public class IMEInputBox : MonoBehaviour
{
    //-----------------------------------------------------------
    [DllImport("UnityIMEDLL")]
    protected static extern bool init(IntPtr hWnd);
 
    [DllImport("UnityIMEDLL")]
    protected static extern void release();
 
    [DllImport("user32")]
    protected static extern IntPtr GetActiveWindow();
 
    //-----------------------------------------------------------
    // Use this for initialization
    void Start ()
    {
        Debug.Log("init UnityIMEDLL.");
        try
        {
            init(GetActiveWindow());
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }
 
    void OnDisable()
    {
        Debug.Log("release UnityIMEDLL.");
        try
        {
            release();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }
}

2010-12-17

Hermite Curve (Hermite Spline)

參考 這個連結 ,Hermite Curve 可以寫成一個 2D Hermite Curve Function 如下:

void hermiteCurve(
 const float t, 
 const float* vPt, 
 const float* vTangent, 
 float* pOutPt)
{
    float tt = t * t;
    float ttt = tt * t;
 
 for (int i=0;i<2;++i)
 {
    pOutPt[i] =(2.0f * ttt - 3.0f * tt + 1.0f) * vPt[0*2+i] + 
       (ttt - 2.0f * tt + t) * vTangent[0*2+i] + 
       (-2.0f * ttt + 3.0f * tt) * vPt[1*2+i] + 
       (ttt - tt) * vTangent[1*2+i];
 }
 
}

其中 t 表示欲內插的點在曲線上的比例值(區間從 0~1)。vPt 表示曲線的起點跟終點位置,是一個 float[4] 的變數,其中起點是(vPt[0], vPt[1]),終點是(vPt[2], vPt[3])。vTangent 表示曲線起點跟終點的切線向量,其中起點的切線向量是(vTangent[0], vTangent[1]),終點的切線向量是(vTangent[2], vTangent[3])。pOutPt 是比例值 t 內插出來的位置,是一個 float[2] 的變數。

2010-08-31

擷取 std::cout 字串

std::cout 方便我們把資料列印到 console 視窗,擷取這些字串可以拿來做其它用途,例如另存成 Log file、以其它方式顯示等...。底下的方法是當 cout 呼叫時, 會將 cout 的字串以 callback 的方式傳給 callback function。

1. 建立 cout wrapper class 繼承
std::basic_streambuf< char, std::char_traits< char > >

2. 在 class 的 constructor 加入(其中  m_pBuf 為暫存的 cout buffer):
m_pBuf = std::cout.rdbuf( this );

3.在 class 的 destructor 加入下列(還原原來的 cout buffer):
m_Stream.rdbuf( m_pBuf );

4. 利用此 class override 兩個 function 分別為 xsputn 及 overflow:
/**
* Override xsputn and make it forward data to the callback function.
*/
std::streamsize xsputn( const char* _Ptr, std::streamsize _Count )
{
 m_pCbFunc( _Ptr, _Count ); //m_pCbFunc 為使用者定義的 callback function
 return _Count;
}

/**
* Override overflow and make it forward data to the callback function.
*/
std::char_traits< char >::int_type overflow( std::char_traits< char >::int_type v )
{
 char ch = std::char_traits< char >::to_char_type( v );
 m_pCbFunc( &ch, 1 ); //m_pCbFunc 為使用者定義的 callback function

 return std::char_traits< char >::not_eof( v );
}

5. 程式建立此 class 之後,所有的 cout 呼叫都會將字串以 callback 方式傳給使用者定義的 callback function 了!

2010-06-22

C# 的執行緒同步

用 C++ 寫多執行緒同步程式時常用到的功能有 InterlockedIncrement、CRITICAL_SECTION 和 Semaphore,其對照在 C# 下的使用方式為:

1. InterlockedIncrement

    C++ 的用法如下:
    UINT nCt =0;
    InterlockedIncrement( &nCt );

    C# 的用法如下:
    int nCt =0;
    System.Threading.Interlocked.Increment( ref uCt );

2. CRITICAL_SECTION

    C++ 的用法如下:
    CRITICAL_SECTION g_cs;
    EnterCriticalSection( &g_cs );
    {
        //...
    }
    LeaveCriticalSection( &g_cs );

    C# 的用法如下:
    Object cs = new Object();
    lock (cs)
    {
        //...
    }

3. Semaphore

    C++ 的用法如下:
    HANDLE m_Handle =CreateSemaphore( NULL, 1, 1, L"SemaphoreName" );
    WaitForSingleObject( m_Handle, nWaitTime );
    {
        //...
    }
    ReleaseSemaphore( m_Handle, 1, NULL );
    CloseHandle( m_Handle );

    C# 的用法如下:
    private static AutoResetEvent m_Handle =new AutoResetEvent( true );
    m_Handle.WaitOne();
    {
        //...
    }
    m_Handle.Set();

2010-06-17

C# 的 delegate

delegate 大致類似 C++ 的函數指標。

C++ 的用法如下:

void ShowPercentage( int nPercentage );
typedef void (* CALLBACK) (int);
CALLBACK =showPercentage;

呼叫 ShowPercentage 函數:
CALLBACK( 100 );
或
ShowPercentage( 100 );


C# 的用法如下:

void ShowPercentage( int nPercentage );
delegate void ShowPercentageDelegate( int nPercentage );
ShowPercentageDelegate CALLBACK = ShowPercentage;

呼叫 ShowPercentage 函數:
CALLBACK( 100 );
或
ShowPercentage( 100 );

2010-06-01

Collada 模型檢視器 + 擴增實境 AR



HK416

Robot

F430

A6M3

SBD3

Titanic

Taipei 101

YZF-R1


小弟利用工作閒餘寫了一個具有擴增實境 (AR) 的 Collada 模型檢視器, 主要開啟的是 Google 3D Warehouse 裡的 collada 模型, render 的部分接下來會增強光線和陰影效果 (例如 HDR, SSAO 之類的), 但想要問各位對程式接下去的發展有沒有什麼建議 ? (例如增加場景編輯, 物理運算, 人物遊覽場景, 寵物飼養等....,)

程式下載

ps. 

  1. 因為用 media foundation library 來擷取 webcam 畫面, 所以程式目前只能在 vista 或 win7 上跑, 過些時候再把 xp 的版本放上來.
  2. 執行路徑在 bin/DAELoader.exe
  3. 從 3D warehouse 下載的 Collada 檔為 zip 格式, 將它解壓縮之後可以在 models 目錄下找到副檔名 dae 的檔案, 開啟此檔即可載入模型.
  4. 將副檔名 dae 檔關聯到 DAEViewer.exe, 以後只要連點 dae 檔, 系統就會自動呼叫 DAEViewer 來開啟之.

2010-05-12

boost 編譯筆記

1.編譯bjam
利用Visual Studio Command Prompt開啟DOS視窗,將目錄 cd 到 C:\boost_1_34_1\tools\jam\src下,執行build.bat,然後會在C:\boost_1_34_1\tools\jam\src\bin.ntx86\產生bjam.exe,將bjam.exe複製到c:\boost_1_34_1\下。

2.修改user-config.jam
(C:\boost_1_34_1\tools\build\v2\user-config.jam) 的MSVC configuration,以 vc9 為例

msvc (default version
# -------------------
# MSVC configuration.
# -------------------
# Configure
, searched for in standard locations and PATH).
# using msvc ;
# Configure specific msvc version (searched for in standard locations and PATH).
# using msvc : 8.0 ;
using msvc : 9.0 : : /wd4819 /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0 /D_ITERATOR_DEBUGGING=0 ;

3.編譯boost
bjam --toolset=msvc-9.0 --build-type=complete install