Box2D – porting to Android NDK

INTRODUCTION

Box2D is a wonderful physics engine for game developers(but not only). Its usability is proven by the fact that Angry Birds is basing on it(http://www.geek.com/articles/mobile/box2d-creator-asks-rovio-for-angry-birds-credit-at-gdc-2011032/). How to leverage from this easy-to-use and very robust engine in Android? There are already some java libraries for android which port Box2D like androidbox2d or jbox2d. But I think(maybe I’m wrong) that most of game developers want to write a Android Game in c/c++ using NDK. This article is about how to do it. A few weeks ago I decided to write a game(AirHockey) and to use Box2D(for learning reasons) and spent a some time to properly compile it to make it available from JNI code. It was hard to find any info about it in google, one book describe it but after following it step-by-step It didn’t work. After some research and attempts I finally forced it to work and decided to share complete solution with others.

LET’S GO

First you need to download Box2D from here: http://code.google.com/p/box2d/downloads/list. I have version 2.1.2 and don’t know if further steps is right for newer version(should be). Then unpack .zip file. You should get Box2D_vX.Y.Z folder. Inside this directory you have 2 dirs – Box2D and Contributions. Please copy the first folder(Box2D) to android-ndk-rX/sources. Now you should have a folder android-ndk-rX/sources/Box2D. Go inside it. You should see next bunch of directories: Box2D, Build, Building.txt, CMakeLists.txt, Documentation, freeglut, glui, HelloWorld, License.txt, Readme.txt, Testbed.
Now you need to add Android.mk file under above dir(Android-ndk-rX/sources/Box2D) with exactly this content:

LOCAL_PATH:= $(call my-dir)

LS_CPP:= $(subst $(1)/,,$(wildcard $(1)/$(2)/*.cpp))
BOX2D_CPP:= $(call LS_CPP, $(LOCAL_PATH), Box2D/Collision) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Collision/Shapes) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Common) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Dynamics) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Dynamics/Contacts) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Dynamics/Joints) \
            $(call LS_CPP, $(LOCAL_PATH), Box2D/Rope)

include $(CLEAR_VARS)

LOCAL_MODULE:= box2d_static
LOCAL_SRC_FILES := Box2D \
Box2D/Collision/Shapes/b2CircleShape.cpp \
Box2D/Collision/Shapes/b2PolygonShape.cpp \
Box2D/Collision/b2BroadPhase.cpp \
Box2D/Collision/b2CollideCircle.cpp \
Box2D/Collision/b2CollidePolygon.cpp \
Box2D/Collision/b2Collision.cpp \
Box2D/Collision/b2Distance.cpp \
Box2D/Collision/b2DynamicTree.cpp \
Box2D/Collision/b2TimeOfImpact.cpp \
Box2D/Common/b2BlockAllocator.cpp \
Box2D/Common/b2Math.cpp \
Box2D/Common/b2Settings.cpp \
Box2D/Common/b2StackAllocator.cpp \
Box2D/Dynamics/Contacts/b2CircleContact.cpp \
Box2D/Dynamics/Contacts/b2Contact.cpp \
Box2D/Dynamics/Contacts/b2ContactSolver.cpp \
Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp \
Box2D/Dynamics/Contacts/b2PolygonContact.cpp \
Box2D/Dynamics/Contacts/b2TOISolver.cpp \
Box2D/Dynamics/Joints/b2DistanceJoint.cpp \
Box2D/Dynamics/Joints/b2FrictionJoint.cpp \
Box2D/Dynamics/Joints/b2GearJoint.cpp \
Box2D/Dynamics/Joints/b2Joint.cpp \
Box2D/Dynamics/Joints/b2LineJoint.cpp \
Box2D/Dynamics/Joints/b2MouseJoint.cpp \
Box2D/Dynamics/Joints/b2PrismaticJoint.cpp \
Box2D/Dynamics/Joints/b2PulleyJoint.cpp \
Box2D/Dynamics/Joints/b2RevoluteJoint.cpp \
Box2D/Dynamics/Joints/b2WeldJoint.cpp \
Box2D/Dynamics/b2Body.cpp \
Box2D/Dynamics/b2ContactManager.cpp \
Box2D/Dynamics/b2Fixture.cpp \
Box2D/Dynamics/b2Island.cpp \
Box2D/Dynamics/b2World.cpp \
Box2D/Dynamics/b2WorldCallbacks.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
LOCAL_C_INCLUDES := $(LOCAL_EXPORT_C_INCLUDES)

include $(BUILD_STATIC_LIBRARY)

Ok, we have done everything by Box2D side. Now it will be attached to your project if you care of join this library. How?

Inside Android.mk of your project(in JNI directory) you need to 2 lines:
-LOCAL_STATIC_LIBRARIES := box2d_static – before “include $(BUILD_SHARED_LIBRARY)”
and
-$(call import-module,box2d) – after “”include $(BUILD_SHARED_LIBRARY)”).
For instance my Android.mk looks like:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := game_shared

LOCAL_MODULE_FILENAME := libgame

LOCAL_SRC_FILES := main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/GameLayer.cpp \
                   ../../Classes/Objects/Table.cpp \
                   ../../Classes/Objects/Player.cpp \
                   ../../Classes/Objects/Puck.cpp \
                   ../../Classes/Objects/GameObject.cpp
                   
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes                   

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static
LOCAL_STATIC_LIBRARIES := box2d_static
            
include $(BUILD_SHARED_LIBRARY)

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

Now you can use Box2D in your project!:) Just include it: #include <Box2D/Box2D.h> in .h or .cpp files where you want to use Box2D objects;)

Here is API docs of Box2D: http://programanddesign.com/box2d/annotated.html

Enjoy your adventure with Box2D in Android NDK;)

Posted in Android programming | Tagged , , , | Leave a comment

Unit of work

Recently, I often meet with interesting pattern(design pattern) – unit of work. I liked this pattern quickly and I get used to implementing it in my programs. This is why I considered to share few words about this pattern and my implementation of it.

Unit of Work is great pattern intended to create an abstraction layer between the DAL(data access layer) and BLL(bussiness logic layer). Simply, Unit of Work is container for repositories, where Repository(next pattern) is provider of set of operations on single entity(usually CRUD operations but it can be extend). Thanks for its abstracition we can write program independent from DAL(I mean from concrete implementation of access to DB), so we can use next great pattern – Dependency Injection. More, Unit of Work can facilitate writing unit tests or use TDD.

For more information about UoW I strongly recommend below article(above image comes from it):

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

When I was writing UoW second time in my application I thought that I should create reusable library – and I created. My implementation of UoW is based on Entity Framework(for now). Some people can say now – what for? If Entity Framework isn’t Unit of Work on its own?

Entity Framework can resamble Unit of Work – DbContext as UoW and DbSet as Repository. But Entity Framework classes are concrete implementation – there’s lack of abstraction which is more important in UoW – I think.

In my library I decided to hide Repositories against client. Thanks for this methods responsible for access to DB are very simple e.g. to insert entity of type Employee in DB we only write it: UoW.Insert<Employee>(myEmployee). Important part of my implementation is also take care of two important principles connected to access to DB(open connection as late as possible and close as soon as possible). We wrtie UoW.Query(() => …and here we call one or few methods from UoW) -> and UoW will open connection by first method in Query and close after last method in query – additionaly every methods are involved by transaction(cause SaveChanges from DbContext use transacion).

So, at last word I encourage to test and use my library. It’s published as open source on codeplex here:

http://unitofwork.codeplex.com/

 

Posted in .NET programming | Leave a comment

Dynamic XML

One of the newcomer in C# 4.0 – great newcomer is new keyword ‘dynamic’. Dynamic variables are run-time binded which is very helpful many times e.g. it simplify access to COM objects. I don’t want to explain in more details about ‘dynamic’. I want to show useful usage of this. For more details about dynamic keyword I send here – http://msdn.microsoft.com/en-us/library/dd264741.aspx.

Recently, I must have read complex xml and I thought that maybe I can use dynamic and I mustn’t read xml by LINQ or other technics.
Take this xml as example:
<root>
    <shop>
        <book>
            <author>John Savacki</author>
           <title>E.G.Title</title>
          <price>20.50</price>
        </book>
        <book>
            <author>Tom Curly</author>
           <title>E.G.Title 2</title>
        </book>
    </shop>
</root>
I wanted to read it like that:
dynamic xml = ……
string author = xml.shop.book[0].author
Is not pretty?
It is – but unfortunately such library doesn’t exist.
So, I was finding existing solutions but none of these was sufficient for me so I decided to write own DynamicXML class and I wanna share with you my solution and by the way show usage of new ‘dynamic’ feature.
Cause I will be use exactly this base class – DynamicObject. It is base class for new type which we can bind to dynamic variable and thanks for this we can capture every references to our variable like properties, like methods etc.
So this is header of my class:
public class DynamicXml : DynamicObject, IEnumerable
{
}


I leverage IEnumerable interace to give possibility of going through collection but about this will be later.
To read XML I override only two methods of our base class:
TryGetMember and TryGetIndex.
As you expected first method is call when client write sth like this dynamicXML.Something and second when client type sth like this dynamicXML.Something[i].
Simply Idea is that: when client demand property(node) we find if actual node include this. If yes then we check if this node include children or not. If include children then we should return new DynamicXML with changed current node, else we should return string with value. When actual node doesn’t include finding property we can return null – but here appear problem. What with optional fields. Look on our sample xml – when client type xml.shop.book[1].price we should return null – of course, it is good, but what if price can also include optional fields? eg. ‘discount’.
Now, when client call xml.shop.book[1].price.discount he get NullPointerException. We must avoid this but we haven’t possibility to check if client type sth after actual checking property(in TryGetMember), so I decided to return always new DynamicXml object and carry additional method like eval() which return finally result.
So to get author from second book we must type xml.shop.book[1].author.eval().
Next option is when we retrive more than one element eg. we type xml.shop.book.eval() – this should return DynamicXml with list of book elements. To attend to this all option I use list of XElement and and string variable of actual value.
Our class look like this now:
public class DynamicXml : DynamicObject, IEnumerable
{
    private string value = null;

    public IList Elements { get; set; }
}


Now we need some constructors – public and private. Public for client to create our DynamicXml from few source like filename or from stream. Private will be used for returning new DynamicXml in reply of property demand(it simple recursion).
public class DynamicXml : DynamicObject, IEnumerable
{
    private string value = null;
    public IList Elements { get; set; }

    public DynamicXml(Stream input) { Elements = new List { XDocument.Load(input).Root }; }

    public DynamicXml(TextReader input)
    {
        Elements = new
            List { XDocument.Load(input).Root };
    }

    public DynamicXml(string input)
    {
        Elements = new
            List { XDocument.Load(input).Root };
    }

    private DynamicXml() { Elements = null; }

    private DynamicXml(XElement input)
    {
        Elements = new
            List { input };
    }

    private DynamicXml(IEnumerable<XElement> input)
    {
        Elements =
            new List(input);
    }

    private DynamicXml CreateValueDynamicXml(string value)
    {
        DynamicXml result = new DynamicXml();
        result.value = value;

        return result;
    }
}


Last method is sth like pseudo-constructor – I write it as method to avoid conflict with previous string-parameter constructor.
So, almost last step is attend to client demands for properties. Firstly, I comment TryGetValue:
public override bool TryGetMember(GetMemberBinder binder, out
object result)
    {
        if (Elements != null)
        {
            var elements = Elements.Descendants().Where(q =>
            q.Name == binder.Name);
            if (elements.Count() == 1)
            {
                if (elements.First().HasElements)
                {
                    result = new DynamicXml(elements.First());
                }
                else
                {
                    result = CreateValueDynamicXml(elements.First().Value);
                }
            }
            else if (elements.Count() > 1)
            {
                result = new DynamicXml(elements);
            }
            else
            {
                result =

                CreateValueDynamicXml(null);
                return false;
            }
            return true;
        }
        else
        {

            result = CreateValueDynamicXml(null); ;
            return false;
        }
    }

If list of actual elements is empty we return next DynamicXml object with null value – it’s our protection for optional nodes as I mentioned earlier. If list has elements then we find every elements of this list of node name equal name of demanding properties which is carry through GetMemberBinder object. If we find one element so we check if this element has children if yes then we return new DynamicXml with Elements list including one found element(next we can retrive child elements from this). If found element doesn’t include any child we know that this is ‘leaf’ so we return new DynamicXml with empty Elements list but with proper value. If we found more than one matching element we return new DynamicXml with Elements filled of all previously found elements. If we didn’t find any matching elements is the same to case of null Elements property.

public override bool TryGetIndex(GetIndexBinder binder,
object[] indexes, out object result)
    {
        int index = 0;
        if (int.TryParse(indexes[0].ToString(), out index) && Elements != null)
        {
            if (Elements[index].HasElements)
            {
                result = new DynamicXml(Elements[index]);
            }
            else
            {
                result = CreateValueDynamicXml(Elements[index].Value);
            }
            return true;
        }
        else
        {
            result = CreateValueDynamicXml(null);
            return false;
        }
    }



This method is always calling afterTryGetMember so must keeping result from TryGetMember to service this method. Obviously, we keep our previous result in Elements list, so now we check if this list is not null and if we can get back number from index element, cause it not must be number, we can type sth like this: dynamicVar.property[“key”]. Indexes is table cause we can demand more than one dimension e.g.dynamicVar.property[0,1,”key”]. I assume that we demand only number-one dimension index, so if we has not null Elements and we can retrive index we return new DynamicXml with value or with new actual node.
Eval() method look like this:

public string Eval()
    {
        return string.IsNullOrEmpty(value) ? null : value;
    }


I think that it’s so easy and don’t need any comment.
Last method I attend to is GetEnumerator() as implementation of IEnumerable interface:
public IEnumerator GetEnumerator()
    {
        foreach (var element in Elements)
        {
            if (element.HasElements)
            {
                yield return new DynamicXml(element);
            }
            else
            {
                yield return CreateValueDynamicXml(element.Value);
            }
        }
    }

I wrote this method to service demand like this:

foreach (var book in xml.shop.book.eval())
        {
            Console.WriteLine(book.author.eval());
        }


I think that above method is also easy to understand. Exception may be yield keyword. To understand this I suggest this article:
Below I present whole ready to use code of DynamicXml class:
public class DynamicXml : DynamicObject, IEnumerable
{
    private string value = null;
    public IList Elements { get; set; }

    public DynamicXml(Stream input)
    {
        Elements = new
            List { XDocument.Load(input).Root };
    }

    public DynamicXml(TextReader input)
    {
        Elements = new
            List { XDocument.Load(input).Root };
    }

    public DynamicXml(string input)
    {
        Elements = new
            List { XDocument.Load(input).Root };
    }

    private DynamicXml() { Elements = null; }

    private DynamicXml(XElement input)
    {
        Elements = new
            List { input };
    }

    private DynamicXml(IEnumerable<XElement> input)
    {
        Elements =
            new List(input);
    }

    private DynamicXml CreateValueDynamicXml(string value)
    {
        DynamicXml result = new DynamicXml();
        result.value = value;

        return result;
    }

    public override bool TryGetMember(GetMemberBinder binder, out
object result)
    {
        if (Elements != null)
        {
            var elements = Elements.Descendants().Where(q =>
            q.Name == binder.Name);

            if (elements.Count() == 1)
            {
                if (elements.First().HasElements)
                {
                    result = new DynamicXml(elements.First());
                }
                else
                {
                    result = CreateValueDynamicXml(elements.First().Value);
                }
            }
            else if (elements.Count() > 1)
            {
                result = new DynamicXml(elements);
            }
            else
            {
                result =

                CreateValueDynamicXml(null);
                return false;
            }
            return true;
        }
        else
        {
            result = CreateValueDynamicXml(null);
            return false;
        }
    }

    public override bool TryGetIndex(GetIndexBinder binder,
    object[] indexes, out object result)
    {
        int index = 0;
        if (int.TryParse(indexes[0].ToString(), out index) &&
        Elements != null)
        {
            if (Elements[index].HasElements)
            {
                result = new DynamicXml(Elements[index]);
            }
            else
            {
                result = CreateValueDynamicXml(Elements[index].Value);
            }
            return true;
        }
        else
        {
            result = CreateValueDynamicXml(null)

            ;
            return false;
        }
    }
    public IEnumerator GetEnumerator()
    {
        foreach (var element in Elements)
        {
            if (element.HasElements)
            {
                yield return new DynamicXml(element);
            }
            else
            {
                yield return CreateValueDynamicXml(element.Value);
            }
        }
    }

    public string Eval()
    {
        return string.IsNullOrEmpty(value) ? null : value;
    }
}


At the end I wanna sorry for my english.
I hope that this class can be helpfully for you.
Posted in .NET programming | 5 Comments