Porting and Maintaining your C++ Game on Android without losing your mind

100 %
0 %
Information about Porting and Maintaining your C++ Game on Android without losing your mind

Published on March 5, 2014

Author: bemyapp

Source: slideshare.net


Presentation from David Wingrove & Katie Merrill from Golden Hammer Software http://www.goldenhammersoftware.com/

From the Barcelona Android User Group meetup: http://www.meetup.com/Barcelona-Android-User-Group/events/166734982/

Porting and Maintaining Your C++ Game on Android (without losing your mind)

Why C++  Cross-Platform support    (Some lesser platforms don’t have a JVM) Don’t want to use Unity, etc Existing C++ Codebase

Overview    NDK recap What goes where? C++ vs Java Streamlining packaged app data     Eliminating Data Duplication Compiling multiple architectures Other quirks we’ve run into Some downloads info about our apps

NDK Application.mk APP_PROJECT_PATH := $(call my-dir) APP_BUILD_SCRIPT := $(call my-dir)/Android.mk APP_MODULES := GHEngine APP_OPTIM := release APP_STL := stlport_static APP_PLATFORM := android-8

NDK (static lib) Android.mk LOCAL_PATH := $(call my-dir) LOCAL_CFLAGS := -Wno-psabi LOCAL_CFLAGS += -D ANDROID LOCAL_MODULE := GHEngine LOCAL_MODULE_FILENAME := libGHEngine LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../../../Base LOCAL_SRC_FILES += ../../../../Base/GHAppRunner.cpp include $(BUILD_STATIC_LIBRARY)

NDK Android.mk (shared lib – loaded by java) LOCAL_MODULE := libGHEngine LOCAL_SRC_FILES := ../../GHEngine/obj/local/armeabi/libGHEngine.a include $(PREBUILT_STATIC_LIBRARY) LOCAL_STATIC_LIBRARIES += libGHEngine include $(BUILD_SHARED_LIBRARY) $(shell cp libs/armeabi/libGHBowling.so ../../../GHBowlingBase/libs/armeabi)

NDK JNI Loading the C++ Library public class GHBowlingBaseActivity extends Activity { static { System.loadLibrary("GHBowling"); } }  Loads the file named libGHBowling.so

NDK JNI Java (calling C++) public class GHEngineInterface { public native void runNativeFrame(); public native void launchNativeApp(int windowWidth, int windowHeight, String externalStoragePath, int isTablet,int iapIsOn); //resizeWindow, handleTouchStart, handleTouchEnd, handleTouchPos //handleAcceleration, handleJavaPause, handleJavaResume, //handleJavaShutdown,handleBackPressed, calculatePublicKey, //onInterstitialRewardGranted,onRewardInterstitialAvailabilityChange, //onInterstitialDismiss, loadFile,handleTextureLoadConfirmed, //onAdActivation, onAdDeactivation, onIAPPurchase }

NDK JNI C++ (called by Java) static jobject globalEngineInterface = 0; extern "C“ __attribute__((visibility("default"))) void Java_goldenhammer_ghbowlingbase_GHEngineInterface_launchNativeApp (JNIEnv* env, jobject engineInterface, jint windowWidth, jint windowHeight, jstring jExternalStoragePath, jint isTablet, jint useIAP) { globalEngineInterface = env->NewGlobalRef(engineInterface); //Engine/Game Initialization goes here. }  When you shut down: env->DeleteGlobalRef(globalEngineInterface);

NDK JNI Java (called by C++) public class GHEngineInterface { public void showInterstitialAd() { if (mInterstitialHandler != null) { mInterstitialHandler.showInterstitial(); } else { onInterstitialDismiss(); } } };

NDK JNI C++ (calling Java)  GHAndroidInterstitialAd class declaration: JNIEnv& mJNIEnv; jobject mEngineInterface; jmethodID mShowAdMethod;  GHAndroidInterstitialAd ctor: jclass cls = mJNIEnv.GetObjectClass(mEngineInterface); mShowAdMethod = mJNIEnv.GetMethodID(cls, "showInterstitialAd", "()V");  GHAndroidInterstitialAd::activate: mJNIEnv.CallVoidMethod(mJavaObj, mShowAdMethod);

What goes Where? C++ or Java  C++    Java    All your platform-independent/pre-existing code Bare minimum wrapper for Android implementation of platform services Typical Android platform code Middleware integration  Can swap middleware vendors of the same service without touching C++ Exceptions:   OpenGL (initialization in Java, most code in C++ or GLSL) File I/O (mix of Java, C++)

What Goes Where Java       OpenGL initialization Sound through SoundPool File handle loading through AssetManager Image loading through BitmapFactory Google Play, In-App Billing, etc Ads and other middleware integration   AdMob, AdColony, Chartboost, PlayHaven, Facebook, etc Input Handling  (touches, accelerometer, buttons/gamepad)

What Goes Where C++  All your game code   OpenGL rendering code    Ideally 90% of your app Need to handle reinit after lost device fopen using file handle from Java Thin wrapper over JNI calls for everything else

What Goes Where Our code distribution.  2800 lines Java   1600 in base project 1200 in master project   Includes middleware integration 50k-150k lines C++   Varies depending on game 6400 Android-specific C++

Eliminating Data Duplication Problem    Eclipse wants all data underneath project We want to reuse data (between projects) in our own directory structure We hate maintaining multiple copies of the same data files.

Eliminating Data Duplication Solution   Batch file/shell script to copy data On Mac cp ../../../../../data/GHBowling/ballrollloop.wav ../../../GHBowling/assets/ballrollloop.wav cp ../../../../../data/Bowling/GHBowlingAndroid/backwall.jpg ../. ./../GHBowling/assets/backwall.jpg  On Windows copy ..........dataGHBowlingballrollloop.wav ......GHBowlingassetsballrollloop.wav copy ..........dataBowlingGHBowlingAndroidbackwall.jpg ... ...GHBowlingassetsbackwall.jpg

Eliminating Data Duplication Batch File Generation  Tool for initial generation  Looks through set of directories with a specified order of preference      Some files are different per-platform We may have Android-specific files We may not, but we prefer iOS-specific to generic Downside: some unnecessary files get copied Maintenance usually done by hand

Packaged App Data Problem    Data is packaged through Android build process All files except those with certain excluded file extensions (precompressed file types) are automatically compressed. Platform-agnostic file reading code doesn’t know to uncompress: sees garbage

Excluded file extensions  Source: Android Asset Packaging Tool /* these formats are already compressed, or don't compress well */ static const char* kNoCompressExt[] = { ".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".amr", ".awb", ".wma", ".wmv" };

App Data Compression Solution   One option: forgo Eclipse and pass –0 to the AAPT via command line (universally or for certain extensions) What we do cp ../../../../../data/GHBowlingiOS/arrowpixel.glsl ../ ../../GHBowling/assets/arrowpixel.glsl.mp3

Compiling for x86 (or other architectures)  In Application.mk: APP_ABI := x86 armeabi  Supported values:      armeabi armeabi-v7a x86 mips all

Compiling for x86 Problem  Shared library Android.mk needs to include the correct static library for each architecture   For arm: /armeabi/libGHEngine.a For x86: /x86/libGHEngine.a

Compiling for x86 Solution include $(CLEAR_VARS) LOCAL_MODULE := libGHEngine LOCAL_SRC_FILES := ../../GHEngine/obj/local/$(TARGET_ARCH_ABI)/libGHEngine.a include $(PREBUILT_STATIC_LIBRARY)

Building on Windows Problem  We really like verbose filenames     GHBowlingYellowBallThrowWith190Degre eSpinTransitionXMLLoaderTransition.cpp Our GHEngine project has lots of files Linker includes all of those filenames in one shell command Exceeds maximum line length on Windows cmd (8191 characters)

Building on Windows Problem  We really like verbose filenames     Ok, more like GHGUIPopTransitionXMLLoader.cpp Our GHEngine project has lots of files Linker includes all of those filenames in one shell command Exceeds maximum line length on Windows cmd (8191 characters)

Building on Windows Solution     In Android.mk: LOCAL_SHORT_COMMANDS := true Build system generates intermediate list file and then invokes it with a much shorter command line Downside: slower compiles Can use only in projects that need it.

Add a comment


GeorgeKr | 12/11/14
http://satinet.info/sputnikovoe-televidenie-v-minske/ - спутниковое тв в минске Сейчас в РФ имеется уже немало компаний, которые предоставляют официально сервисы- цифрового спутникового TV для частных абонентов. Спутниковое тв стало широкопопулярно и зарекомендовало себя только с отличной стороны, в основном это касается тех регионов, где простое эфирное вещание осуществлялось c большими помехами. В последнее время прослеживалось развитие и крупный рост данного направления. Все это, в первую очередь, самым положительно сказалось на потребителях. Улучшилась и финансовая составляющая, и появился громадный выбор хорошей фирмы для установки ТВ и спутникового Интернета. http://satinet.info/pakety-sputnikovogo-televideniya/ - пакеты спутникового телевидения Ещё недавно спутниковые антенны были показателем статуса, позволяя уже с девяностых годов наслаждаться широким выбором и отечественных, и зарубежных каналов со всего мира. Именно посредством спутникового ТВ немногие могли узнать последние новости, которые происходили в мире, могли смотреть самые новые видеофильмы и самые знаменитые музыкальные клипы. http://satinet.info/sputnikovoe-televidenie-v-ekaterinburge/ - спутниковое тв в екатеринбурге Вебсайт satinet.info представляет подробную информацию о всех российских провайдерах, которые дают возможность воспользоваться спутниковым ТВ и интернетом в квартире, на даче, в самых плоходоступных районах.

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

Porting and Maintaining your C++ Game on Android without ...

Porting and Maintaining your C++ Game on Android without losing your mind ...
Read more

Gamasutra - In-depth: Porting your game from iOS to Android

... the challenges you'll face when porting your game from ... So you created a C/C++ game for iOS that ... OpenGL when porting to Android is ...
Read more

Porting your game from iOS to Android | Thoughts Serializer

Porting your game from iOS to Android. ... So you created a C/C++ game for iOS that gives joy to iPhone and ... Porting your iOS game to Blackberry ...
Read more

objective c - Porting an iOS app to OSX and maintaining ...

Help Center Detailed answers to any questions you might have ... Answer and help your peers ... Porting an iOS app to OSX and maintaining one code set?
Read more

Embedded Android - O'Reilly Media

... can adapt it to fit your needs. You’ll delve into Android’s ... Android; Apple; C/C++; C#; Design Patterns; ... prototype your embedded Android ...
Read more

Feed your real hunger: Getting off the emotional treadmill ...

Do thoughts of food and weight occupy your mind more than you’d ... maintaining a weight loss is harder than losing ... mind and spirit without ...
Read more

Several Standard Desktop Apps Ported to Windows RT

How to Change Your Android Encryption Password Without Changing Your ... Game Would You Like to See on Android? ... Standard Desktop Apps Ported to ...
Read more

The future of scripting in Unity – Unity Blog

The future of scripting in Unity. ... the game logic/ mesh creationg, whatever changes without losing ... Do you want your game made in 10 ...
Read more

How to RedirectToAction in ASP.NET MVC without losing ...

Using ASP.NET MVC there are situations ... How to RedirectToAction in ASP.NET MVC without losing request data. ... Then in your "Form" action you can go:
Read more