Pages

Gin Rummy Indian Rummy Nine Men's Morris and more Air Attack

Monday 16 February 2015

Signature verification of android application

Get the SHA1 key for the signature

First step in verification of the signature is to retrieve the SHA1 key for the keystore.
This can be done using keytool.

The command to run on the debug keystore is given below,

keytool -list -v -keystore debug.keystore  -alias androiddebugkey -storepass android -keypass android

The keys will be listed under the Certificate fingerprints section.
Certificate fingerprints:
         MD5:  
         SHA1: 
         Signature algorithm name: SHA1withRSA
         Version: 3

Verification for the signature

Verification of the signature can be done in the main Activity class or Application class.
The verification is done by retrieving SHA1 for the application and comparing it against the one that we obtained by running the keytool command.


static final byte signatureSha1[] = { /* SHA1 key obtained from keytool */};

@Override
protected void onCreate(Bundle savedInstanceState)
{   super.onCreate(savedInstanceState);
    boolean validSignature = false;
    try
    {   // Retrieve the sha1 algorithm
        MessageDigest sha1Alg = MessageDigest.getInstance("SHA1");
        try
        {   // Retrieve the package info, package info contains the signatures
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),
                                      PackageManager.GET_SIGNATURES);
            // For all the signed signature check for the signature obtained using key tool
for (Signature signature : packageInfo.signatures)
            {   // Retrieve the hash for the signature
                byte[] hash = sha1Alg.digest(signature.toByteArray());
                // Compare it against the one obtained using keytool
                if (Arrays.equals(hash, signatureSha1))
                {   validSignature = true;
                    break;
                }
            }
        }
        catch (NameNotFoundException e)
        {   throw new RuntimeException(e);
        }
    }
    catch (NoSuchAlgorithmException e)
    {   throw new RuntimeException(e);
    }

    if (!validSignature)
    {   throw new RuntimeException("Invalid Signature");
    }

    // Complete the activity initialization here
}

Friday 13 February 2015

Color saturation or gray scale implementation in OpenGL



To implement gray scaling we need to modify slightly the fragment shader. 

Conversion equation that I am using is,


Red * 0.299 + Green * 0.587 + Blue 0.144


The fragment shader used to do gray scaling is shown below,
                                                           
uniform sampler2D u_sampler;
uniform int u_compliment;

varying vec2 v_texturecoord;

void main()
{
    vec4 clr = texture2D(u_sampler, v_texturecoord);
    float l = clr.r*0.299 + clr.g*0.587 + clr.b*0.114;
    l = clamp(l, 0.0, 1.0);
    if (u_compliment == 1) {
        l = 1.0 - l;
    }                   
    gl_FragColor = vec4(l, l, l, clr.a);
}


For complete source code visit https://github.com/trsquarelab/glexamples

Blur implementation in OpenGL using shader



Blur implementation is one of the simple thing to achieve in OpenGL.

The basic idea is to take the neighbour pixels as well while considering the pixel to draw. Say for example take average of the surrounding pixels.

Vertex shader


attribute vec3 a_position;                                 
attribute vec2 a_texturecoord;                             
                                                           
varying vec2 v_texturecoord;                               
                                                           
void main()                                                
{                                                          
   v_texturecoord = a_texturecoord;                        
                                                           
   gl_Position = vec4(a_position, 1.0);                    
}                                                          

Fragment shader

                                                                                                     
                                                           
uniform sampler2D u_sampler;                               
uniform float u_blurstep;                                  
                                                           
varying vec2 v_texturecoord;                               
                                                           
void main()                                                
{                                                          
    vec4 sample0;                                          
    vec4 sample1;                                          
    vec4 sample2;                                          
    vec4 sample3;                                          
                                                           
    float step = u_blurstep;                               
                                                           
    sample0 = texture2D(u_sampler,                         
                        vec2(v_texturecoord.x - step,      
                        v_texturecoord.y - step));         
                                                           
    sample1 = texture2D(u_sampler,                         
                        vec2(v_texturecoord.x + step,      
                        v_texturecoord.y - step));         
                                                           
    sample2 = texture2D(u_sampler,                         
                        vec2(v_texturecoord.x - step,      
                        v_texturecoord.y + step));         
                                                           
    sample3 = texture2D(u_sampler,                         
                        vec2(v_texturecoord.x + step,      
                        v_texturecoord.y + step));         
                                                           
    gl_FragColor = (sample0 + sample1 + sample2 + sample3) 
                               / 4.0;                      
}                                                          

Complete source code is available at https://github.com/trsquarelab/glexamples

Color picking or selection in OpenGL using shaders


Color picking is a simple method to implement the object selection.  It is very accurate as well, actually pixel accurate.

However since it involves read back the frame buffer data the performance won't be that good.

Steps involved in the implementation,

1. Draw your 2d or 3d object as you would normally do
2. Setup a frame buffer object
3. Assign unique ID and color to each object
4. Draw the object with the unique color assigned
5. Using the given screen coordinate retrieve the color.
6. Use the color to identify the object, and you are done

Frame buffer object creation 

            
glGenFramebuffers(1, &mChoose.mFrameBuffer);
glGenRenderbuffers(1, &mChoose.mDepthRenderbuffer);
glGenTextures(1, &mChoose.mTexture);

glBindTexture(GL_TEXTURE_2D, mChoose.mTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mW, mH,
                         0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glBindRenderbuffer(GL_RENDERBUFFER, mChoose.mDepthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, mW, mH);

glBindFramebuffer(GL_FRAMEBUFFER, mChoose.mFrameBuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                                   mChoose.mTexture, 0);

glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                                      GL_RENDERBUFFER, mChoose.mDepthRenderbuffer);

Object selection

Let the mesh to be drawn are stored in vector objects and let px and py be the screen coordinates.

unsigned char data[4] = {0.0f};
glReadPixels(px, mH-py, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data);
for (ObjectMapIter iter = objects.begin(); iter != objects.end(); ++iter) {
    if (iter->mR == data[0] &&
        iter->mG == data[1] &&
        iter->mB == data[2]) {
        clickedItem = iter->mObject;
        break;
    }
}

Complete source code is available at https://github.com/trsquarelab/glexamples

Tuesday 10 February 2015

Integrating Android UI controls in Unity3D applications by creating a Java plug-in




Let me show you how to add android controls on top of unity activity in the unity application.

The steps to achieve the same is given below,
1. layout xml file
2. jar library with a java class which adds the control on top of unity activity, this would also pass the event back to unity
3. Manifest file which forwards the events to java

The sample code

We will create a simple unity application with an android button and checkbox. Button will be used to change the background color
and checkbiox will be used to lock or unlock the background color chaning functionality.

The Layout file

Let me create a simple layout xml file with a button and a checkbox.
Button and checkbox will be displayed at the center of the screen.
Let me name the xml file as android_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal|center_vertical"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >
    
    <Button android:id="@+id/button_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Background"/>

    <CheckBox
        android:id="@+id/checkbox_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lock Background" />

</LinearLayout>

The java class

Java class does two thing.
1. Adds the above layout  in the activity
2. Receves the event from button and checkbox and then pass it back to unity.

The complete source code for the java class is show below,


package com.test.androidcontrols;

import android.app.Activity;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MyControls {
 
 public static interface Listner {
  public void onButtonClicked();
  public void onCheckBoxChanged(boolean state);
 }
 
 private Listner mListner;
 private Activity mActivity;
 
 public MyControls(Activity activity, Listner listner) {
  mActivity = activity;
  mListner = listner;
  
  mActivity.runOnUiThread(new Runnable() {
   @Override
   public void run() {
    LayoutInflater inflater = mActivity.getLayoutInflater();
    
    Resources resources =  mActivity.getResources();
    String pkgName = mActivity.getPackageName();
    
    // get the resource id for the layout xml file android_layout.xml
    int id = resources.getIdentifier("android_layout", "layout", pkgName);

    // inflate the layout xml file
    View view = inflater.inflate(id, null);
    
    LayoutParams param = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                                                            FrameLayout.LayoutParams.MATCH_PARENT);
    
    // add the view hierarchy in to the unity activity
    mActivity.addContentView(view, param);
    
    Button button = (Button)mActivity.findViewById(resources.getIdentifier("button_id", "id", pkgName));
    button.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      if (mListner != null) {
       mListner.onButtonClicked();
      }
     }
    });
    
    final CheckBox checkBox = (CheckBox)mActivity.findViewById(resources.getIdentifier("checkbox_id", "id", pkgName));
    checkBox.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      if (mListner != null) {
       mListner.onCheckBoxChanged(checkBox.isChecked());
      }
     }
    });
   }
  });
 }
}

Manifest file

Updated manifest file is shown below.
Please note the change for meta data unityplayer.ForwardNativeEventsToDalvik, it is set to true.


<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.androidcontrols"
 android:installLocation="preferExternal"
 android:theme="@android:style/Theme.NoTitleBar"
    android:versionCode="1"
    android:versionName="1.0">
    <supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        android:anyDensity="true"/>

    <application
  android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:debuggable="true">
        <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
            <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
        </activity>
    </application>
</manifest>


Integrating the android part in unity

The steps to integrate android specific artifacts is show below,
  1. Create plugin folder for android, Assets\Plugins\Android. 
  2. Copy the layout xml file, android_layout.xml, in to  Assets\Plugins\Android\res\layout folder.
  3. Create a jar file for our java class and copy it to Assets\Plugins\Android
  4. Copy the manifest file to Assets\Plugins\Android

Using the android ui from unity

The source code to display and receive event from the android ui is shown below.

using UnityEngine;
using System.Collections;

public class AndroidUIControls : MonoBehaviour {

 private bool mLockBackgroundColor = false;

 void Start () {
  init();
 }
 
 void Update () {
 }

 void onButtonClicked() {
  if (!mLockBackgroundColor) {
   float red = Random.value;
   float green = Random.value;
   float blue = Random.value;
   float alpha = 1.0f;

   Camera.main.backgroundColor = new Color(red, green, blue, alpha);
  }
 }

 void onCheckBoxChanged(bool state) {
  mLockBackgroundColor  = state;
 }

#if UNITY_ANDROID
 AndroidJavaObject mUI;

 // create the listner implementation
 // To derive from a java class use AndroidJavaProxy and pass the class name to base class as done below
 private sealed class EventListner: AndroidJavaProxy {
  private AndroidUIControls mReceiver;

  public EventListner(AndroidUIControls receiver)
   : base("com.test.androidcontrols.MyControls$Listner") {
   mReceiver = receiver;
  }

  public void onButtonClicked() {
   mReceiver.onButtonClicked();
  }

  public void onCheckBoxChanged(bool state) {
   mReceiver.onCheckBoxChanged(state);
  }
 }

 void init() {
     // obtain the android activity of the unity application
  AndroidJavaClass unityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
  AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject> ("currentActivity");
  
  // Create an instance of the java class com.test.androidcontrols.MyControls
  // pass the activity and the listner as argument to its constructor
  mUI = new AndroidJavaObject("com.test.androidcontrols.MyControls", activity, new EventListner(this));
 }
#else
 void init() {}
#endif

}


Detecting swipe from Unity3D c# scripts


Let me share a simple code to detect swipe from Unity 3D application. The sample code is written in c#, but it can easily be ported to other languages.

Please find the code below, I guess the code is documented enough to understand.

This implementation detects swipe using angle of swipe from X and Y axis.



using UnityEngine;
using System.Collections;

public class SwipeDetector : MonoBehaviour {

    private const int mMessageWidth  = 200;
    private const int mMessageHeight = 64;

    private readonly Vector2 mXAxis = new Vector2(1, 0);
    private readonly Vector2 mYAxis = new Vector2(0, 1);

    private readonly string [] mMessage = {
        "",
        "Swipe Left",
        "Swipe Right",
        "Swipe Top",
        "Swipe Bottom"
    };

    private int mMessageIndex = 0;

    // The angle range for detecting swipe
    private const float mAngleRange = 30;

    // To recognize as swipe user should at lease swipe for this many pixels
    private const float mMinSwipeDist = 50.0f;

    // To recognize as a swipe the velocity of the swipe
    // should be at least mMinVelocity
    // Reduce or increase to control the swipe speed
    private const float mMinVelocity  = 2000.0f;

    private Vector2 mStartPosition;
    private float mSwipeStartTime;

    // Use this for initialization
    void Start () {
    }
    
    // Update is called once per frame
    void Update () {

        // Mouse button down, possible chance for a swipe
        if (Input.GetMouseButtonDown(0)) {
            // Record start time and position
            mStartPosition = new Vector2(Input.mousePosition.x,
                                         Input.mousePosition.y);
            mSwipeStartTime = Time.time;
        }

        // Mouse button up, possible chance for a swipe
        if (Input.GetMouseButtonUp(0)) {
            float deltaTime = Time.time - mSwipeStartTime;

            Vector2 endPosition  = new Vector2(Input.mousePosition.x,
                                               Input.mousePosition.y);
            Vector2 swipeVector = endPosition - mStartPosition;

            float velocity = swipeVector.magnitude/deltaTime;

            if (velocity > mMinVelocity &&
                swipeVector.magnitude > mMinSwipeDist) {
                // if the swipe has enough velocity and enough distance

                swipeVector.Normalize();

                float angleOfSwipe = Vector2.Dot(swipeVector, mXAxis);
                angleOfSwipe = Mathf.Acos(angleOfSwipe) * Mathf.Rad2Deg;

                // Detect left and right swipe
                if (angleOfSwipe < mAngleRange) {
                    OnSwipeRight();
                } else if ((180.0f - angleOfSwipe) < mAngleRange) {
                    OnSwipeLeft();
                } else {
                    // Detect top and bottom swipe
                    angleOfSwipe = Vector2.Dot(swipeVector, mYAxis);
                    angleOfSwipe = Mathf.Acos(angleOfSwipe) * Mathf.Rad2Deg;
                    if (angleOfSwipe < mAngleRange) {
                        OnSwipeTop();
                    } else if ((180.0f - angleOfSwipe) < mAngleRange) {
                        OnSwipeBottom();
                    } else {
                        mMessageIndex = 0;
                    }
                }
            }
        }
    }

    void OnGUI() {
        // Display the appropriate message
        GUI.Label(new Rect((Screen.width-mMessageWidth)/2,
                           (Screen.height-mMessageHeight)/2,
                            mMessageWidth, mMessageHeight),
                  mMessage[mMessageIndex]);
    }

    private void OnSwipeLeft() {
        mMessageIndex = 1;
    }

    private void OnSwipeRight() {
        mMessageIndex = 2;
    }

    private void OnSwipeTop() {
        mMessageIndex = 3;
    }

    private void OnSwipeBottom() {
        mMessageIndex = 4;
    }
}

Friday 6 February 2015

Accessing android java classes from Unity 3D; launching an android alert dialog from Unity 3D



Introduction


Let me share a sample code in C# which communicates with android java classes.

What I will do is open an AlertDialog from unity c# scripts.

In the process I will show you how to access android classes, derive from an android java class, override its methods, also how to execute task in android main thread.

You can use the technique used in the document to access anything that is accessible in android.

If you want to say create a custom dialog you can create a jar library which has the required code and access the classes in the jar by using the same technique.

The jar library and the resources of course should be kept in the Assets/Plugins/Android folder.

Accessing the activity class

In unity AndroidJavaClass represents the java.lang.Class and AndroidJavaObject the java.lang.Object. We will use both of these classes to get the instance of Activity class.

  // Obtain activity
  AndroidJavaClass unityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
  AndroidJavaObject activity = unityPlayer.GetStatic<  AndroidJavaObject >  ("currentActivity");

Running code on UI thread

We will use the method runOnUiThread of the activity to run on UI thread. Here we will use AndroidJavaRunnable class which represents java.lang.Runnable.

    // Here we are using lambda expression you can also pass a function as argument to the AndroidJavaRunnable class
    activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>  {
        // put your code there
    }

Deriving from a Java interface

AndroidJavaProxy will be used to derive from a java interface. To derive from a java interface first derive from AndroidJavaProxy and then call the java interface from the constructor as show below,
private class PositiveButtonListner : AndroidJavaProxy {

  public PositiveButtonListner()
   : base("android.content.DialogInterface$OnClickListener") {
  }

  public void onClick(AndroidJavaObject obj, int value ) {
     // do your stuff here, it will be overridden from DialogInterface.OnClickListener
  }
 }

Complete source code



using UnityEngine;
using System.Collections;

public class AndroidDialog : MonoBehaviour {

 const int ButtonWidth = 256;
 const int ButtonHeight = 64;

 private string mMessage = "See My Android Dialog";

 private bool mYesPressed = false;
 private bool mNoPressed = false;

 // Use this for initialization
 void Start () {
 }
 
 // Update is called once per frame
 void Update () {
 }

 void OnGUI() {

  if (GUI.Button(new Rect((Screen.width-ButtonWidth)/2, (Screen.height-ButtonHeight)/2,
                           ButtonWidth, ButtonHeight),
                 "ShowDialog")) {
   showDialog();
  }

  if (mYesPressed) {
   GUI.Label(new Rect((Screen.width-ButtonWidth)/2, (Screen.height-ButtonHeight)/2 + 2 * ButtonHeight,
                      ButtonWidth, ButtonHeight), "You Pressed Yes");
  }

  if (mNoPressed) {
   GUI.Label(new Rect((Screen.width-ButtonWidth)/2, (Screen.height-ButtonHeight)/2 + 2 * ButtonHeight,
                      ButtonWidth, ButtonHeight), "You Pressed No");
  }
 }

 // Lets put our android specific code under the macro UNITY_ANDROID
#if UNITY_ANDROID
 // Lets create some listners.
 // These listners will be passed to android 

 // Create the postive action listner class
 // It has to be derived from the AndroidJavaProxy class
 // Make the methods as same as that of DialogInterface.OnClickListener
 private class PositiveButtonListner : AndroidJavaProxy {
  private AndroidDialog mDialog;

  public PositiveButtonListner(AndroidDialog d)
   : base("android.content.DialogInterface$OnClickListener") {
   mDialog = d;
  }

  public void onClick(AndroidJavaObject obj, int value ) {
   mDialog.mYesPressed = true;
   mDialog.mNoPressed = false;
  }
 }

 // Create the postive action listner class
 // It has to be derived from the AndroidJavaProxy class
 // Make the methods as same as that of DialogInterface.OnClickListener
 private class NegativeButtonListner : AndroidJavaProxy {
  private AndroidDialog mDialog;

  public NegativeButtonListner(AndroidDialog d)
  : base("android.content.DialogInterface$OnClickListener") {
   mDialog = d;
  }
  
  public void onClick(AndroidJavaObject obj, int value ) {
   mDialog.mYesPressed = false;
   mDialog.mNoPressed = true;
  }
 }


#endif

 private void showDialog() {

#if UNITY_ANDROID
  // Obtain activity
  AndroidJavaClass unityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
  AndroidJavaObject activity = unityPlayer.GetStatic< AndroidJavaObject>  ("currentActivity");

  // Lets execute the code in the UI thread
  activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>  {

   // Create an AlertDialog.Builder object
   AndroidJavaObject alertDialogBuilder = new AndroidJavaObject("android/app/AlertDialog$Builder", activity);

   // Call setMessage on the builder
   alertDialogBuilder.Call< AndroidJavaObject> ("setMessage", mMessage);

   // Call setCancelable on the builder
   alertDialogBuilder.Call< AndroidJavaObject> ("setCancelable", true);

   // Call setPositiveButton and set the message along with the listner
   // Listner is a proxy class
   alertDialogBuilder.Call< AndroidJavaObject> ("setPositiveButton", "Yes", new PositiveButtonListner(this));

   // Call setPositiveButton and set the message along with the listner
   // Listner is a proxy class
   alertDialogBuilder.Call< AndroidJavaObject> ("setNegativeButton", "No", new NegativeButtonListner(this));

   // Finally get the dialog instance and show it
   AndroidJavaObject dialog = alertDialogBuilder.Call< AndroidJavaObject> ("create");
   dialog.Call("show");
  }));
#endif

 }
}


Thursday 5 February 2015

Shared and smart pointer implementation in c++


Introduction

Shared pointer is a class which can share the underlying data between object. This avoids deep copying and improves performance. It is also called as shallow copying.

Smart pointer is a class which manages the life time of the underlying pointer.

A simple smart pointer class

Lets create a simple base class for smart pointer class using c++ template so that we can store any type of data.
The basic idea of a shared pointer or a smart pointer is that actual data is stored separately and the shared pointer or smart pointer class will have a pointer to it.


For a very basic shared pointer class will have the data class as,
    class Data
    {
    public:
        int mRefCount;
        T mData;
    }; 

Let our class name be RSharedObject. Now lets declare the copy constructor and assignment operator function. The template parameter T is the actual pointer.

template < typename T >
class RSharedObject
{
protected:
    class Data
    {
    public:
        int mRefCount;
        T mData;
    };

public:
    RSharedObject()
     : mData(0)
    {}

    RSharedObject(RSharedObject const & o)
    {
        mData = 0;
        copy(o);
    }

    RSharedObject& operator=(RSharedObject const & o)
    {
        copy(o);
        return *this;
    }
    // ...
};

Let add referencing and dereferencing logic now to complete the implementation,
template <typename T >
class RSharedObject
{
protected:
    class Data
    {
    public:
        int mRefCount;
        T mData;
    };

public:
    RSharedObject()
     : mData(0)
    {}

    RSharedObject(RSharedObject const & o)
    {
        mData = 0;
        copy(o);
    }

    RSharedObject& operator=(RSharedObject const & o)
    {
        copy(o);
        return *this;
    }

    virtual ~RSharedObject()
    {
        dispose();
    }

protected:
    virtual T & data_p()
    {
        if (!mData) {
            create();
        }
        return mData->mData;
    }

    virtual const T & data_p() const
    {
        if (!mData) {
            const_cast *>(this)->create();
        }
        return mData->mData;
    }
    void copy(RSharedObject const & oth)
    {
        dispose();
        mData = oth.mData;
        ref();
    }

   void detach()
    {
        if (mData && mData->mRefCount > 1) {
            deref();
            mData = new Data(*mData);
            mData->mRefCount = 1;
        }
    }

private:
    void create()
    {
        mData = new Data();
        ref();
    }

    void dispose()
    {
        if (mData) {
            deref();
            if (mData->mRefCount == 0) {
                delete mData;
                mData = 0;
            }
        }
    }

    void ref()
    {
        if (mData) {
            ++mData->mRefCount;
        }
    }

    void deref()
    {
        if (mData) {
            --mData->mRefCount;
        }
    }

private:
    Data * mData;
};



Function data_p will be used to access the actual data from the derived classes.

Lets create a detachable shared object class. Detachable shared object class detaches itself from the underlying pointer data if required.

template <typename T >
class RDetachableRSharedObject: RSharedObject
{
protected:
    T & data_p()
    {
        this->detach();
        return RSharedObject::data_p();
    }

    const T & data_p() const
    {
        return RSharedObject::data_p();
    }
};

Then smart pointer class

We will create a base class for smart pointer so that we can have smart pointer class for both object and array.

This smart pointer base class will derive from our RSharedObject class.

template <typename A, typename D >
class RSmartPointerBase: public RSharedObject < A >
{
public:
    RSmartPointerBase(D * p)
    {
        this->data_p().mPtr = p;
        this->data_p().mOwn = true;
    }

    bool isNull() const
    {
        return data() == 0;
    }

    D * data()
    {
        return this->data_p().mPtr;
    }

    const D * data() const
    {
        return this->data_p().mPtr;
    }

    D * take()
    {
        this->data_p().mOwn = false;
        return this->data_p().mPtr;
    }

    D * operator->()
    {
        return data();
    }

    const D * operator->() const
    {
        return data();
    }

    D & operator*()
    {
        return *(data());
    }
    const D * operator*() const
    {
        return *(data());
    }
};
Lets now create the actual smart pointer,

template < typename D >
class RSmartPointerData
{
public:
    RSmartPointerData()
     : mOwn(true),
       mPtr(0)
    {}

    ~RSmartPointerData()
    {
        if (mOwn) {
            delete mPtr;
        }
    }

private:
    RSmartPointerData(RSmartPointerData const &);
    RSmartPointerData & operator=(RSmartPointerData const &);

public:
    bool mOwn;
    D * mPtr;
};

template < typename D >
class RSmartPointer: public RSmartPointerBase<RSmartPointerData<D>, D>
{
public:
    RSmartPointer(D * p=0)
     : RSmartPointerBase, D>(p)
    {}

    operator D*()
    {
        return this->data();
    }

    operator const D*() const
    {
        return this->data();
    }
};


Lets now create the actual smart array pointer,

template < typename D >
class SmartArrayPointerData
{
public:
    SmartArrayPointerData()
     : mOwn(true),
       mPtr(0)
    {}

    ~SmartArrayPointerData()
    {
        if (mOwn) {
            delete [] mPtr;
        }
    }

private:
    SmartArrayPointerData(SmartArrayPointerData const &);
    SmartArrayPointerData & operator=(SmartArrayPointerData const &);

public:
    bool mOwn;
    D * mPtr;
};

template <typename D >
class SmartArrayPointer: public RSmartPointerBase< SmartArrayPointerData<D>, D>
{
public:
    SmartArrayPointer(D * p=0)
     : RSmartPointerBase, D>(p)
    {}

    operator D*()
    {
        return this->data();
    }

    operator const D*() const
    {
        return this->data();
    }
};
I know it is more code and less document, but hopefully it helps.

Complete implementation can be found at https://github.com/trsquarelab/glexamples/blob/master/src/common/rsmart_pointer.h

Custom mesh rendering with texture in cocos2d-x


Introduction

Custom drawing can be done in cocos2dx by deriving from Node class and using the shaders available in cocos2dx or by creating shader by our self.

Create a base class for Mesh

Lets create a class which will act as a base for mesh. You would be deriving from this class and providing required information to get the mesh drawn.

Class skeleton is show below,
class CustomShape
{
public:
    virtual ~CustomShape();

    virtual void init() = 0;

    virtual float * vertices() = 0;
    virtual float * texCoords() = 0;
    virtual float * colors() = 0;

    virtual int primitive() = 0;

    virtual int verticesCount() = 0;

    virtual int coordSize() = 0;
};



Create a Node class implementation

Create a class called TexturedMeshNode which is deriving from Node class.  

Class sekeleton is show below,

class TexturedMeshNode: public Node
{
public:
    bool init();

    void setShape(CustomShape *shape)
    {
        mShape = shape;
    }

    void draw(Renderer *renderer, const Mat4& transform, uint32_t flags);
    void onDraw(const Mat4 &transform, uint32_t flags);

    void setTexture(Texture2D *texture)
    {
        mTexture = texture;
    }

    CREATE_FUNC(TexturedMeshNode);

private:
    CustomShape *mShape;
    Texture2D * mTexture;
    CustomCommand mCustomCommand;
};

Method implementation

init

In the init method will set the shader for the class.
bool TexturedMeshNode::init()
{
    setGLProgram(ShaderCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE));
}

draw


void TexturedMeshNode::draw(Renderer *renderer, const Mat4& transform, uint32_t flags)
{
    if (mShape) {
        mCustomCommand.init(_globalZOrder);
        mCustomCommand.func = CC_CALLBACK_0(TexturedMeshNode::onDraw, this, transform, flags);
        renderer->addCommand(&mCustomCommand);
    }
}

onDraw


void TexturedMeshNode::onDraw(const Mat4 &transform, uint32_t flags)
{
    auto glProgram = getGLProgram();
    glProgram->use();
    glProgram->setUniformsForBuiltins(transform);
    if (mShape) {
        GL::bindTexture2D(mTexture->getName());
        GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORD);
        glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, mShape->coordSize(), GL_FLOAT, GL_FALSE, 0, mShape->vertices());
        glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, mShape->texCoords());
        glDrawArrays(mShape->primitive(), 0, mShape->verticesCount());
    }
    CC_INCREMENT_GL_DRAWS(1);
}

A simple rectangle mesh implementation

Class declaration

class Rectangle : public CustomShape
{
private:
    float mX;
    float mY;
    float mWidth;
    float mHeight;
    std::vector mVertices;
    std::vector mTexCoords;
public:
    Rectangle(float x, float y, float w, float h)
     : mX(x),
       mY(y),
       mWidth(w),
       mHeight(h)
    {}
    float * vertices()
    {
        return mVertices.data();
    }
    float * texCoords()
    {
        if (mTexCoords.empty()) {
            return 0;
        }
        return mTexCoords.data();
    }
    float * colors()
    {
        return 0;
    }
    int verticesCount()
    {
        return mVertices.size() / coordSize();
    }
    int primitive();
    void init();
    int coordSize()
    {
        return 3;
    }
};

Class implementation

void Rectangle::init()
{
    mVertices.clear();
    mTexCoords.clear();

    float v[] = {
        mX, mY, 0.0f,
        mX+mWidth, mY, 0.0f,
        mX+mWidth, mY+mHeight, 0.0f,
        mX, mY+mHeight, 0.0f
    };
    float t[] = {
        0, 1,
        1, 1,
        1, 0,
        0, 0
    };

    mVertices.insert(mVertices.begin(), v, v + sizeof(v)/sizeof(v[0]));
    mTexCoords.insert(mTexCoords.begin(), t, t + sizeof(t)/sizeof(t[0]));
}

int Rectangle::primitive()
{
    return GL_TRIANGLE_FAN;
}

Using the textured mesh class

The TexturedMeshNode can be used from other classes as shwo below,
CustomShape *shape = new Rectangle(10, 10, 100, 200);

TexturedMeshNode *texturedMeshNode = TexturedMeshNode::create();
texturedMeshNode->setShape(shape);
texturedMeshNode->setTexture(texture);

this->addChild(texturedMeshNode);