소스 검색

More todo changes converted over to android code

Tim Newell 12 년 전
부모
커밋
cccba8be6e

+ 1 - 0
engine/compilers/android/AndroidManifest.xml

@@ -6,6 +6,7 @@
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
     <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+    <uses-permission android:name="android.permission.VIBRATE"/>
 
 
     <uses-sdk
     <uses-sdk
         android:minSdkVersion="9"
         android:minSdkVersion="9"

+ 0 - 2
engine/compilers/android/jni/Android.mk

@@ -451,7 +451,6 @@ LOCAL_SRC_FILES :=  ../../../lib/ljpeg/jcapimin.c \
 					../../../source/platformAndroid/AndroidInput.cpp \
 					../../../source/platformAndroid/AndroidInput.cpp \
 					../../../source/platformAndroid/AndroidMath.cpp \
 					../../../source/platformAndroid/AndroidMath.cpp \
 					../../../source/platformAndroid/AndroidMemory.cpp \
 					../../../source/platformAndroid/AndroidMemory.cpp \
-					../../../source/platformAndroid/AndroidMotionManager.cpp \
 					../../../source/platformAndroid/AndroidMutex.cpp \
 					../../../source/platformAndroid/AndroidMutex.cpp \
 					../../../source/platformAndroid/AndroidNet.cpp \
 					../../../source/platformAndroid/AndroidNet.cpp \
 					../../../source/platformAndroid/AndroidOGLVideo.cpp \
 					../../../source/platformAndroid/AndroidOGLVideo.cpp \
@@ -467,7 +466,6 @@ LOCAL_SRC_FILES :=  ../../../lib/ljpeg/jcapimin.c \
 					../../../source/platformAndroid/AndroidUtil.cpp \
 					../../../source/platformAndroid/AndroidUtil.cpp \
 					../../../source/platformAndroid/AndroidWindow.cpp \
 					../../../source/platformAndroid/AndroidWindow.cpp \
 					../../../source/platformAndroid/main.cpp \
 					../../../source/platformAndroid/main.cpp \
-					../../../source/platformAndroid/SoundEngine.cpp \
 					../../../source/platformAndroid/T2DActivity.cpp \
 					../../../source/platformAndroid/T2DActivity.cpp \
 					../../../source/platformAndroid/menus/popupMenu.cpp \
 					../../../source/platformAndroid/menus/popupMenu.cpp \
 					../../../source/sim/scriptGroup.cc \
 					../../../source/sim/scriptGroup.cc \

+ 4 - 0
engine/source/platformAndroid/AndroidAlerts.cpp

@@ -26,11 +26,13 @@
 void Platform::AlertOK(const char *windowTitle, const char *message)
 void Platform::AlertOK(const char *windowTitle, const char *message)
 {
 {
 	//TODO: alertok
 	//TODO: alertok
+	adprintf("Alert OK!");
 }
 }
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 bool Platform::AlertOKCancel(const char *windowTitle, const char *message)
 bool Platform::AlertOKCancel(const char *windowTitle, const char *message)
 {
 {
 	//TODO: AlertOKCancel
 	//TODO: AlertOKCancel
+	adprintf("Alert OK CANCEL!");
 	return false;
 	return false;
 }
 }
 
 
@@ -39,6 +41,7 @@ bool Platform::AlertRetry(const char *windowTitle, const char *message)
 {//retry/cancel
 {//retry/cancel
 	
 	
 	//TODO: alertRetry
 	//TODO: alertRetry
+	adprintf("Alert OK RETRY!");
 	return false;
 	return false;
 }
 }
 
 
@@ -46,5 +49,6 @@ bool Platform::AlertRetry(const char *windowTitle, const char *message)
 bool Platform::AlertYesNo(const char *windowTitle, const char *message)
 bool Platform::AlertYesNo(const char *windowTitle, const char *message)
 {
 {
 	//TODO: alertYesNo
 	//TODO: alertYesNo
+	adprintf("Alert Yes No");
 	return false;
 	return false;
 }
 }

+ 0 - 5
engine/source/platformAndroid/AndroidAudio.cpp

@@ -24,11 +24,6 @@
 #include "platformAndroid/AndroidUtil.h"
 #include "platformAndroid/AndroidUtil.h"
 #include "platform/platformAL.h"
 #include "platform/platformAL.h"
 
 
-ConsoleFunction(doDeviceVibrate, void, 1, 1, "Makes the device do a quick vibration. Only works on the iPhone line of devices - the iPod Touch line does not have vibration functionality.")  
-{  
-	//TODO: vibrate
-}  
-
 namespace Audio
 namespace Audio
 {
 {
 	
 	

+ 5 - 73
engine/source/platformAndroid/AndroidFileio.cpp

@@ -541,69 +541,17 @@ static bool isMainDotCsPresent(char *dir)
 /// Since you probably don't want to copy the game files into the app every time
 /// Since you probably don't want to copy the game files into the app every time
 /// you build, you will want to leave them outside the bundle for development.
 /// you build, you will want to leave them outside the bundle for development.
 ///
 ///
-/// Placing all content inside the application bundle gives a much better user
-/// experience when you distribute your app.
+/// Android reads all assets out of compressed bundle so we dont realy have an executable path
 StringTableEntry Platform::getExecutablePath()
 StringTableEntry Platform::getExecutablePath()
 {
 {
    if(platState.mainDotCsDir) 
    if(platState.mainDotCsDir) 
       return platState.mainDotCsDir;
       return platState.mainDotCsDir;
       
       
-   char cwd_buf[MAX_MAC_PATH_LONG];
-   //TODO: android
-   /*
-   CFBundleRef mainBundle = CFBundleGetMainBundle();
-   CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
-   
-   bool inside = true;
-   bool outside = false;
-   bool done = false;
-   
-   while(!done)
-   {
-      // first look for game content inside the application bundle.
-      // then we look outside the bundle
-      // then we assume it's a tool, and the "bundle" = the binary file.
-      CFURLRef workingUrl;
-      if(inside)
-         workingUrl = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault,bundleUrl,CFSTR("Contents/Resources"),true);
-      else if(outside)
-         workingUrl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, bundleUrl);
-      else
-      {
-         workingUrl = bundleUrl;
-         CFRetain(workingUrl); // so that we can release bundleUrl twice.
-      }
-      
-      CFStringRef workingString = CFURLCopyFileSystemPath(workingUrl, kCFURLPOSIXPathStyle);
-      CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
-      CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
-      CFStringGetCString(normalizedString, cwd_buf, sizeof(cwd_buf)-1, kCFStringEncodingUTF8);
-      
-      // if we dont see main.cs inside the bundle, try again looking outside
-      // we're done if we find it, or if we find it neither inside or outside.
-      if( isMainDotCsPresent(cwd_buf) || ( !inside && !outside))
-         done = true;
-      
-      if(inside)
-         inside = false, outside = true;
-      else if(outside)
-         outside = false;
-         
-      CFRelease(workingUrl);
-      CFRelease(workingString);
-      CFRelease(normalizedString);   
-   }
-   
-   //CFRelease(mainBundle);   // apple docs say to release this, but that causes a sigsegv(11)
-   CFRelease(bundleUrl);
-   */
-//   chdir(cwd_buf);            // set the current working directory.
-   
    char* ret = NULL;
    char* ret = NULL;
    if(StringTable)
    if(StringTable)
-      platState.mainDotCsDir = StringTable->insert(cwd_buf);
+      platState.mainDotCsDir = StringTable->insert(".");
    else
    else
-      ret = dStrdup(cwd_buf);
+      ret = dStrdup(".");
    
    
    return ret ? ret : platState.mainDotCsDir;
    return ret ? ret : platState.mainDotCsDir;
 }
 }
@@ -611,24 +559,8 @@ StringTableEntry Platform::getExecutablePath()
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 StringTableEntry Platform::getExecutableName()
 StringTableEntry Platform::getExecutableName()
 {
 {
-   char path_buf[MAX_MAC_PATH_LONG];
-   //TODO: android
-   /*
-   // get a cfurl to the executable name
-   CFBundleRef mainBundle = CFBundleGetMainBundle();
-   CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
-
-   // get a cfstring of just the app name
-   CFStringRef workingString = CFURLCopyLastPathComponent(bundleUrl);
-   CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
-   CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
-   CFStringGetCString(normalizedString, path_buf, sizeof(path_buf)-1, kCFStringEncodingUTF8);
-   
-   CFRelease(bundleUrl);
-   CFRelease(workingString);
-   CFRelease(normalizedString);
-   */
-   return StringTable->insert(path_buf);   
+   //TODO: does this need anything further?
+   return StringTable->insert("Torque2D");
 }
 }
 
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------

+ 1 - 1
engine/source/platformAndroid/AndroidGL.cpp

@@ -59,7 +59,7 @@ void glFreeVertexBufferEXT(GLint handle) {}
 // Find out which extensions are available for this renderer. 
 // Find out which extensions are available for this renderer. 
 void getGLCapabilities( )
 void getGLCapabilities( )
 {
 {
-   AssertFatal(platState.ctx, "getGLCapabilities() was called before a monitor was chosen!");
+   AssertFatal(platState.engine, "getGLCapabilities() was called before a monitor was chosen!");
 
 
    // silently create an opengl context on the current display,
    // silently create an opengl context on the current display,
    // so that we can get valid renderer and capability info.
    // so that we can get valid renderer and capability info.

+ 1 - 310
engine/source/platformAndroid/AndroidInput.cpp

@@ -401,281 +401,6 @@ InputManager* Input::getManager()
    return( smManager );
    return( smManager );
 }
 }
 
 
-//TODO: is this table right for android too?
-//--------------------------------------------------------------------------
-//#pragma message("input remap table might need tweaking - rumors of ibooks having diff virt keycodes, might need intermediate remap...")
-static U8 VcodeRemap[256] =
-{
-KEY_A,                     // 0x00 
-KEY_S,                     // 0x01 
-KEY_D,                     // 0x02 
-KEY_F,                     // 0x03 
-KEY_H,                     // 0x04 
-KEY_G,                     // 0x05 
-KEY_Z,                     // 0x06 
-KEY_X,                     // 0x07 
-KEY_C,                     // 0x08 
-KEY_V,                     // 0x09 
-KEY_Y,                     // 0x0A       // this is questionable - not normal Y code
-KEY_B,                     // 0x0B 
-KEY_Q,                     // 0x0C 
-KEY_W,                     // 0x0D 
-KEY_E,                     // 0x0E 
-KEY_R,                     // 0x0F 
-KEY_Y,                     // 0x10 
-KEY_T,                     // 0x11 
-KEY_1,                     // 0x12 
-KEY_2,                     // 0x13 
-KEY_3,                     // 0x14 
-KEY_4,                     // 0x15 
-KEY_6,                     // 0x16 
-KEY_5,                     // 0x17 
-KEY_EQUALS,                // 0x18 
-KEY_9,                     // 0x19 
-KEY_7,                     // 0x1A 
-KEY_MINUS,                 // 0x1B 
-KEY_8,                     // 0x1C 
-KEY_0,                     // 0x1D 
-KEY_RBRACKET,              // 0x1E 
-KEY_O,                     // 0x1F 
-KEY_U,                     // 0x20 
-KEY_LBRACKET,              // 0x21 
-KEY_I,                     // 0x22 
-KEY_P,                     // 0x23 
-KEY_RETURN,                // 0x24 
-KEY_L,                     // 0x25 
-KEY_J,                     // 0x26 
-KEY_APOSTROPHE,            // 0x27 
-KEY_K,                     // 0x28 
-KEY_SEMICOLON,             // 0x29 
-KEY_BACKSLASH,             // 0x2A 
-KEY_COMMA,                 // 0x2B 
-KEY_SLASH,                 // 0x2C 
-KEY_N,                     // 0x2D 
-KEY_M,                     // 0x2E 
-KEY_PERIOD,                // 0x2F 
-KEY_TAB,                   // 0x30 
-KEY_SPACE,                 // 0x31 
-KEY_TILDE,                 // 0x32 
-KEY_BACKSPACE,             // 0x33 
-0,                         // 0x34 //?
-KEY_ESCAPE,                // 0x35 
-0,                         // 0x36 //?
-KEY_ALT,                   // 0x37 // best mapping for mac Cmd key
-KEY_LSHIFT,                // 0x38 
-KEY_CAPSLOCK,              // 0x39 
-KEY_MAC_OPT,               // 0x3A // direct map mac Option key -- better than KEY_WIN_WINDOWS
-KEY_CONTROL,               // 0x3B 
-KEY_RSHIFT,                // 0x3C 
-0,                         // 0x3D 
-0,                         // 0x3E 
-0,                         // 0x3F 
-0,                         // 0x40 
-KEY_DECIMAL,               // 0x41 
-0,                         // 0x42 
-KEY_MULTIPLY,              // 0x43 
-0,                         // 0x44 
-KEY_ADD,                   // 0x45 
-KEY_SUBTRACT,              // 0x46 // secondary code?
-KEY_NUMLOCK,               // 0x47 // also known as Clear on mac...
-KEY_SEPARATOR,             // 0x48 // secondary code? for KPEqual
-0,                         // 0x49 
-0,                         // 0x4A 
-KEY_DIVIDE,                // 0x4B 
-KEY_NUMPADENTER,           // 0x4C 
-KEY_DIVIDE,                // 0x4D // secondary code?
-KEY_SUBTRACT,              // 0x4E 
-0,                         // 0x4F 
-0,                         // 0x50 
-KEY_SEPARATOR,             // 0x51 // WHAT IS SEP?  This is KPEqual on mac.
-KEY_NUMPAD0,               // 0x52 
-KEY_NUMPAD1,               // 0x53 
-KEY_NUMPAD2,               // 0x54 
-KEY_NUMPAD3,               // 0x55 
-KEY_NUMPAD4,               // 0x56 
-KEY_NUMPAD5,               // 0x57 
-KEY_NUMPAD6,               // 0x58 
-KEY_NUMPAD7,               // 0x59 
-0,                         // 0x5A 
-KEY_NUMPAD8,               // 0x5B 
-KEY_NUMPAD9,               // 0x5C 
-0,                         // 0x5D 
-0,                         // 0x5E 
-0,                         // 0x5F 
-KEY_F5,                    // 0x60 
-KEY_F6,                    // 0x61 
-KEY_F7,                    // 0x62 
-KEY_F3,                    // 0x63 
-KEY_F8,                    // 0x64 
-KEY_F9,                    // 0x65 
-0,                         // 0x66 
-KEY_F11,                   // 0x67 
-0,                         // 0x68 
-KEY_PRINT,                 // 0x69 
-0,                         // 0x6A 
-KEY_SCROLLLOCK,            // 0x6B 
-0,                         // 0x6C 
-KEY_F10,                   // 0x6D 
-0,                         // 0x6E 
-KEY_F12,                   // 0x6F 
-0,                         // 0x70 
-KEY_PAUSE,                 // 0x71 
-KEY_INSERT,                // 0x72 // also known as mac Help
-KEY_HOME,                  // 0x73 
-KEY_PAGE_UP,               // 0x74 
-KEY_DELETE,                // 0x75 // FwdDel
-KEY_F4,                    // 0x76 
-KEY_END,                   // 0x77 
-KEY_F2,                    // 0x78 
-KEY_PAGE_DOWN,             // 0x79 
-KEY_F1,                    // 0x7A 
-KEY_LEFT,                  // 0x7B 
-KEY_RIGHT,                 // 0x7C 
-KEY_DOWN,                  // 0x7D 
-KEY_UP,                    // 0x7E 
-0,                         // 0x7F 
-0,                         // 0x80 
-0,                         // 0x81 
-0,                         // 0x82 
-0,                         // 0x83 
-0,                         // 0x84 
-0,                         // 0x85 
-0,                         // 0x86 
-0,                         // 0x87 
-0,                         // 0x88 
-0,                         // 0x89 
-0,                         // 0x8A 
-0,                         // 0x8B 
-0,                         // 0x8C 
-0,                         // 0x8D 
-0,                         // 0x8E 
-0,                         // 0x8F 
-
-0,                         // 0x90 
-0,                         // 0x91 
-0,                         // 0x92 
-0,                         // 0x93 
-0,                         // 0x94 
-0,                         // 0x95 
-0,                         // 0x96 
-0,                         // 0x97 
-0,                         // 0x98 
-0,                         // 0x99 
-0,                         // 0x9A 
-0,                         // 0x9B 
-0,                         // 0x9C 
-0,                         // 0x9D 
-0,                         // 0x9E 
-0,                         // 0x9F 
-
-0,                         // 0xA0 
-0,                         // 0xA1 
-0,                         // 0xA2 
-0,                         // 0xA3 
-0,                         // 0xA4 
-0,                         // 0xA5 
-0,                         // 0xA6 
-0,                         // 0xA7 
-0,                         // 0xA8 
-0,                         // 0xA9 
-0,                         // 0xAA 
-0,                         // 0xAB 
-0,                         // 0xAC 
-0,                         // 0xAD 
-0,                         // 0xAE 
-0,                         // 0xAF 
-0,                         // 0xB0 
-0,                         // 0xB1 
-0,                         // 0xB2 
-0,                         // 0xB3 
-0,                         // 0xB4 
-0,                         // 0xB5 
-0,                         // 0xB6 
-0,                         // 0xB7 
-0,                         // 0xB8 
-0,                         // 0xB9 
-0,                         // 0xBA 
-0,                         // 0xBB 
-0,                         // 0xBC 
-0,                         // 0xBD 
-0,                         // 0xBE 
-0,                         // 0xBF 
-0,                         // 0xC0 
-0,                         // 0xC1 
-0,                         // 0xC2 
-0,                         // 0xC3 
-0,                         // 0xC4 
-0,                         // 0xC5 
-0,                         // 0xC6 
-0,                         // 0xC7 
-0,                         // 0xC8 
-0,                         // 0xC9 
-0,                         // 0xCA 
-0,                         // 0xCB 
-0,                         // 0xCC 
-0,                         // 0xCD 
-0,                         // 0xCE 
-0,                         // 0xCF 
-0,                         // 0xD0 
-0,                         // 0xD1 
-0,                         // 0xD2 
-0,                         // 0xD3 
-0,                         // 0xD4 
-0,                         // 0xD5 
-0,                         // 0xD6 
-0,                         // 0xD7 
-0,                         // 0xD8 
-0,                         // 0xD9 
-0,                         // 0xDA 
-0,                         // 0xDB 
-0,                         // 0xDC 
-0,                         // 0xDD 
-0,                         // 0xDE 
-0,                         // 0xDF 
-0,                         // 0xE0 
-0,                         // 0xE1 
-0,                         // 0xE2 
-0,                         // 0xE3 
-0,                         // 0xE4 
-
-0,                         // 0xE5 
-
-0,                         // 0xE6 
-0,                         // 0xE7 
-0,                         // 0xE8 
-0,                         // 0xE9 
-0,                         // 0xEA 
-0,                         // 0xEB 
-0,                         // 0xEC 
-0,                         // 0xED 
-0,                         // 0xEE 
-0,                         // 0xEF 
-   
-0,                         // 0xF0 
-0,                         // 0xF1 
-0,                         // 0xF2 
-0,                         // 0xF3 
-0,                         // 0xF4 
-0,                         // 0xF5 
-   
-0,                         // 0xF6 
-0,                         // 0xF7 
-0,                         // 0xF8 
-0,                         // 0xF9 
-0,                         // 0xFA 
-0,                         // 0xFB 
-0,                         // 0xFC 
-0,                         // 0xFD 
-0,                         // 0xFE 
-0                          // 0xFF 
-};   
-
-
-U8 TranslateOSKeyCode(U8 vcode)
-{
-   return VcodeRemap[vcode];   
-}   
-
 #pragma mark ---- Clipboard functions ----
 #pragma mark ---- Clipboard functions ----
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 const char* Platform::getClipboard()
 const char* Platform::getClipboard()
@@ -779,11 +504,7 @@ bool activateKeyboard()
    if ( !gInputEnabled || !Input::isActive() || !gKBEnabled )
    if ( !gInputEnabled || !Input::isActive() || !gKBEnabled )
       return( false );
       return( false );
 
 
-   //TODO: android
-   /*OSStatus status = noErr;
-   if (status==noErr)
-      gKBActive = true;
-      */
+   gKBActive = true;
 
 
    return( gKBActive );
    return( gKBActive );
 }
 }
@@ -1234,33 +955,3 @@ void createMouseTapEvent( S32 nbrTaps, S32 x, S32 y ) {
 	TouchTapEvents.push_back( touchEvent( nbrTaps, x, y ) );
 	TouchTapEvents.push_back( touchEvent( nbrTaps, x, y ) );
 }
 }
 
 
-
-// 0 = x, 1 = y, 2 = z
-//TODO: android
-//UIAccelerationValue g_lastAccel[3];
-
-// PUAP -Mat this is polled at AccelerometerUpdateMS, which should be set at around 33 
-/*
-bool createAccelMoveEvent( UIAccelerationValue *accel ) {
-	bool returnVal = false;
-	
-	U32 axis[3] = { SI_XAXIS, SI_YAXIS, SI_ZAXIS }; 
-	
-	for( int i = 0; i < 3; i++ ) {
-		if(accel[i]  != g_lastAccel[i] ) {
-			InputEvent event;
-			event.deviceInst = 0;//joystick number
-			event.fValue = accel[i];
-			event.deviceType = JoystickDeviceType;
-			event.objType = axis[i];
-			event.objInst = i;//axis number
-			event.action = SI_MOVE;
-			event.modifier = 0;
-			Game->postEvent(event);
-			g_lastAccel[i]  = accel[i];
-			returnVal = true;
-		}
-	}
-	return false;
-}
-*/

+ 0 - 500
engine/source/platformAndroid/AndroidMotionManager.cpp

@@ -1,500 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2013 GarageGames, LLC
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-// IN THE SOFTWARE.
-//-----------------------------------------------------------------------------
-
-#include "AndroidMotionManager.h"
-
-#include "platformAndroid.h"
-#include "string/stringBuffer.h"
-#include "sim/simBase.h"
-#include "game/gameInterface.h"
-
-extern AndroidPlatState platState;
-
-static const double kFilterConst = 0.1;
-
-static const double kUpdateInterval = 0.2;
-
-//TODO: convert objc to c++
-/*
-@implementation AndroidMotionManager
-
-
-@synthesize referenceAttitude;
-@synthesize accelerometerEnabled;
-@synthesize gyroscopeEnabled;
-
-- (id)init
-{
-    if (!(self = [super init])) return nil;
-    
-    if(self != NULL)
-    {
-        accelerometerEnabled = NO;
-        gyroscopeEnabled = NO;
-        
-        motionManager = [[CMMotionManager alloc] init];
-        
-        if(motionManager.deviceMotionAvailable)
-        {
-            [motionManager setDeviceMotionUpdateInterval:kUpdateInterval];
-        }
-        else
-        {
-            [motionManager setAccelerometerUpdateInterval:kUpdateInterval];
-        }
-    }
-    else
-    {
-        Con::printf("Could not initialized AndroidMotionManager!");
-        return 0;
-    }
-        
-    return self;
-}
-
-
-
-double accelAxes[6];
-
-
-- (void)enableAccelerometer
-{
-    accelerometerEnabled = YES;
-}
-
-- (void)disableAccelerometer
-{
-    accelerometerEnabled = NO;
-}
-
-- (bool)isAccelerometerActive
-{
-    return motionManager.accelerometerActive;
-}
-
-- (bool)enableGyroscope
-{
-    if(motionManager.gyroAvailable)
-        gyroscopeEnabled = YES;
-    else
-    {
-        Con::errorf("Gyroscope not supported on this device");
-        return false;
-    }
-    
-    return true;    
-}
-
-- (bool)disableGyroscope
-{
-    if(motionManager.gyroAvailable)
-        gyroscopeEnabled = NO;
-    else
-    {
-        Con::errorf("Gyroscope not supported on this device");
-        return false;
-    }
-    
-    return true;
-}
-
-- (bool)isGyroAvailable
-{
-    return motionManager.gyroAvailable;
-}
-
-- (bool)isGyroActive
-{
-    return motionManager.gyroActive;
-}
-
-static double filteredAccel[3] = {0, 0, 0};
-
-void (^accelerometerHandler)(CMAccelerometerData*, NSError*) = ^(CMAccelerometerData *accelData, NSError *)
-{
-    if(gMotionManager.accelerometerEnabled)
-    {
-        U32 accelAxes[6] = { SI_ACCELX, SI_ACCELY, SI_ACCELZ, SI_GRAVX, SI_GRAVY, SI_GRAVZ };
-        
-        double userAcc[6];
-        
-        if(platState.portrait)
-        {
-        
-            filteredAccel[0] = (accelData.acceleration.x * kFilterConst) + (filteredAccel[0] * (1.0 - kFilterConst));
-            filteredAccel[1] = (accelData.acceleration.y * kFilterConst) + (filteredAccel[1] * (1.0 - kFilterConst));
-            filteredAccel[2] = (accelData.acceleration.z * kFilterConst) + (filteredAccel[2] * (1.0 - kFilterConst));
-            
-            userAcc[0] = accelData.acceleration.x - filteredAccel[0];
-            userAcc[1] = accelData.acceleration.y - filteredAccel[1];
-            userAcc[2] = accelData.acceleration.z - filteredAccel[2];
-            
-            // Assign the non-filtered data to gravity
-            userAcc[3] = accelData.acceleration.x;
-            userAcc[4] = accelData.acceleration.y;
-            userAcc[5] = accelData.acceleration.z;
-        }
-        else 
-        {
-            filteredAccel[0] = (accelData.acceleration.y * kFilterConst) + (filteredAccel[0] * (1.0 - kFilterConst));
-            filteredAccel[1] = (accelData.acceleration.x * kFilterConst) + (filteredAccel[1] * (1.0 - kFilterConst));
-            filteredAccel[2] = (accelData.acceleration.z * kFilterConst) + (filteredAccel[2] * (1.0 - kFilterConst));
-
-            userAcc[0] = accelData.acceleration.y - filteredAccel[0];
-            userAcc[1] = accelData.acceleration.x - filteredAccel[1];
-            userAcc[2] = accelData.acceleration.z - filteredAccel[2];
-            
-            // Assign the non-filtered data to gravity
-            userAcc[3] = accelData.acceleration.y;
-            userAcc[4] = accelData.acceleration.x;
-            userAcc[5] = accelData.acceleration.z;
-        }
-        
-        for( int i = 0; i < 6; i++)
-        {
-            InputEvent event;
-            
-            event.deviceInst = 0;
-            event.fValue = userAcc[i];
-            event.deviceType = AccelerometerDeviceType;
-            event.objType = accelAxes[i];
-            event.objInst = i;
-            event.action = SI_MOTION;
-            event.modifier = 0;
-            
-            Game->postEvent(event);
-        }
-    }
-};
-
-void (^motionHandler)(CMDeviceMotion*, NSError*) = ^(CMDeviceMotion *motionData, NSError *error)
-{
-    if(gMotionManager.referenceAttitude == NULL)
-        [gMotionManager resetDeviceMotionReference];
-    
-    CMAttitude* currentAttitude = motionData.attitude;
-  
-    [currentAttitude multiplyByInverseOfAttitude:gMotionManager.referenceAttitude];
-  
-    if(gMotionManager.accelerometerEnabled)
-    {
-        U32 accelAxes[6] = { SI_ACCELX, SI_ACCELY, SI_ACCELZ, SI_GRAVX, SI_GRAVY, SI_GRAVZ };
-        
-        double userAcc[6];
-        if(platState.portrait)
-        {
-            userAcc[0] = motionData.userAcceleration.x; 
-            userAcc[1] = motionData.userAcceleration.y;
-            userAcc[2] = motionData.userAcceleration.z;
-            userAcc[3] = motionData.gravity.x; 
-            userAcc[4] = motionData.gravity.y;
-            userAcc[5] = motionData.gravity.z;
-        }
-        else 
-        {
-            userAcc[0] = motionData.userAcceleration.y; 
-            userAcc[1] = motionData.userAcceleration.x;
-            userAcc[2] = motionData.userAcceleration.z;
-            userAcc[3] = motionData.gravity.y; 
-            userAcc[4] = motionData.gravity.x;
-            userAcc[5] = motionData.gravity.z;            
-        }
-
-        for( int i = 0; i < 6; i++)
-        {
-            InputEvent event;
-        
-            event.deviceInst = 0;
-            event.fValue = userAcc[i];
-            event.deviceType = AccelerometerDeviceType;
-            event.objType = accelAxes[i];
-            event.objInst = i;
-            event.action = SI_MOTION;
-            event.modifier = 0;
-        
-            Game->postEvent(event);
-        }
-    }
-    
-    if(gMotionManager.gyroscopeEnabled)
-    {
-        double gyroData[6] = { currentAttitude.pitch, 
-                               currentAttitude.yaw, 
-                               currentAttitude.roll, 
-                               motionData.rotationRate.x, 
-                               motionData.rotationRate.y, 
-                               motionData.rotationRate.z };
-        
-        U32 gyroAxes[6] = { SI_PITCH, SI_YAW, SI_ROLL, SI_GYROX, SI_GYROY, SI_GYROZ };
-        
-        for( int i = 0; i < 6; i++)
-        {
-            InputEvent event;
-            
-            event.deviceInst = 0;
-            event.fValue = gyroData[i];
-            event.deviceType = GyroscopeDeviceType;
-            event.objType = gyroAxes[i];
-            event.objInst = i;
-            event.action = SI_MOTION;
-            event.modifier = 0;
-            
-            Game->postEvent(event);
-        }
-    }
-    
-};
-
-- (bool)startDeviceMotion
-{
-    if(motionManager.deviceMotionAvailable)
-    {
-        if(referenceAttitude == NULL)
-            referenceAttitude = motionManager.deviceMotion.attitude;
-        
-        [motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:motionHandler];
-    }
-    else
-    {
-        [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:accelerometerHandler];
-    }
-    
-    return true;
-}
-
-- (bool)stopDeviceMotion
-{
-    if(motionManager.deviceMotionAvailable)
-        [motionManager stopDeviceMotionUpdates];
-    else
-    {
-        [motionManager stopAccelerometerUpdates];
-    }
-    return true;
-}
-
-- (bool)resetDeviceMotionReference
-{
-    if(motionManager.deviceMotionAvailable)
-    {
-        referenceAttitude = motionManager.deviceMotion.attitude;
-        return true;
-    }
-    
-    Con::errorf("Device Motion not supported on this device (check OS)");
-    return false;
-}
-
-- (bool)isDeviceMotionAvailable
-{
-    return motionManager.deviceMotionAvailable;
-}
-
-- (bool)isDeviceMotionActive
-{
-    return motionManager.deviceMotionActive;
-}
-
-@end
-*/
-ConsoleFunction(initMotionManager, void, 1, 1, "() Initialize the AndroidMotionManager")
-{
-	//TODO: convert objc
-   /* if(gMotionManager != NULL)
-    {
-        Con::printf("Motion Manager already initialized");
-    }
-    else
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        */
-}
-
-ConsoleFunction(enableAccelerometer, void, 1, 1, "() Allow accelerometer tracking during device motion updates")
-{
-	//TODO: convert objc
-    /*if(gMotionManager == NULL)
-        gMotionManager = [[AndroidMotionManager alloc] init];
-    
-    gMotionManager.accelerometerEnabled = YES;
-    [gMotionManager startDeviceMotion];
-    */
-}
-
-ConsoleFunction(disableAccelerometer, void, 1, 1, "() Stop accelerometer tracking")
-{
-	//TODO: convert objc
-    /*if(gMotionManager != NULL)
-        gMotionManager.accelerometerEnabled = NO;
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-    }*/
-}
-
-ConsoleFunction(isAccelerometerActive, bool, 1, 1, "() Check to see if Accelerometer is being polled\n"
-                "@return True if accelerometer is on, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager isAccelerometerActive];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager isAccelerometerActive];
-    }
-    */
-	return false;
-}
-
-ConsoleFunction(isGyroAvailable, bool, 1, 1, "() Check to see if this Android device has a gyroscope\n"
-                                             "@return True if gyro is on the device, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager isGyroAvailable];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager isGyroAvailable];
-    }
-    */
-	return false;
-}
-
-ConsoleFunction(isGyroActive, bool, 1, 1, "() Check to see if this Android device has a gyroscope\n"
-                "@return True if gyro is on the device, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager isGyroActive];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager isGyroActive];
-    }
-    */
-	return false;
-}
-ConsoleFunction(enableGyroscope, void, 1, 1, "() Start the gyroscope tracking\n"
-                "@return True if gyroscope is supported, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        gMotionManager.gyroscopeEnabled = YES;
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        gMotionManager.gyroscopeEnabled = YES;
-        [gMotionManager startDeviceMotion];
-    }
-    */
-}
-
-ConsoleFunction(stopGyroscope, void, 1, 1, "() Stop gyroscope tracking\n"
-                "@return True if gyroscope is supported, false otherwise")
-{
-	//TODO: convert objc
-	    /*if(gMotionManager != NULL)
-        gMotionManager.gyroscopeEnabled = NO;
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        
-        gMotionManager = [[AndroidMotionManager alloc] init];
-    }
-    */
-}
-
-ConsoleFunction(isDeviceMotionAvailable, bool, 1, 1, "() Check to see if this Android device supports advanced device motion (requires gyroscope\n"
-                "@return True if Device Motion is supported, false otherwise")
-{
-	//TODO: convert objc
-	    /*if(gMotionManager != NULL)
-        return [gMotionManager isDeviceMotionAvailable];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager isDeviceMotionAvailable];
-    }
-    */
-	return false;
-}
-
-ConsoleFunction(isDeviceMotionActive, bool, 1, 1, "() Check to see if the device motion is running\n"
-                                                  "@return True if device motion is being tracked, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager isDeviceMotionActive];
-    
-    Con::warnf("Motion Manager was not initialized. Initializing now");
-    gMotionManager = [[AndroidMotionManager alloc] init];
-    return [gMotionManager isDeviceMotionActive];
-    */
-	return false;
-}
-ConsoleFunction(startDeviceMotion, bool, 1, 1, "() Start Device motion tracking\n"
-                                               "@return True if device motion is supported, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager startDeviceMotion];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager startDeviceMotion];
-    }
-    */
-	return false;
-}
-
-ConsoleFunction(stopDeviceMotion, bool, 1, 1, "() Stop Device Motion tracking\n"
-                                              "@return True if device motion is supported, false otherwise")
-{
-	//TODO: convert objc
-	    /*
-    if(gMotionManager != NULL)
-        return [gMotionManager stopDeviceMotion];
-    else
-    {
-        Con::warnf("Motion Manager was not initialized. Initializing now");
-        gMotionManager = [[AndroidMotionManager alloc] init];
-        return [gMotionManager stopDeviceMotion];
-    }
-    */
-	return false;
-}
-

+ 0 - 70
engine/source/platformAndroid/AndroidMotionManager.h

@@ -1,70 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2013 GarageGames, LLC
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-// IN THE SOFTWARE.
-//-----------------------------------------------------------------------------
-
-#ifndef _CONSOLEINTERNAL_H_
-#include "console/consoleInternal.h"
-#endif
-//TODO: convert objc
-/*
-#import <Foundation/Foundation.h>
-#import <GameKit/GameKit.h>
-#import <CoreMotion/CoreMotion.h>
-
-@interface AndroidMotionManager: NSObject
-{
-    // The sole CMMotionManager reference
-    CMMotionManager* motionManager;
-    
-    // The starting attitude reference DeviceMotion will use
-    CMAttitude* referenceAttitude;
-    
-    bool accelerometerEnabled;
-    bool gyroscopeEnabled;
-}
-
-@property (readwrite, assign) bool accelerometerEnabled;
-@property (readwrite, assign) bool gyroscopeEnabled;
-
-@property (strong) CMAttitude* referenceAttitude;
-
-// Accelerometer related functions
-- (void) enableAccelerometer;
-- (void) disableAccelerometer;
-- (bool) isAccelerometerActive;
-
-// Gyroscope related functions
-- (bool) enableGyroscope;
-- (bool) disableGyroscope;
-- (bool) isGyroAvailable;
-- (bool) isGyroActive;
-
-// Motion device related functions
-- (bool) startDeviceMotion;
-- (bool) stopDeviceMotion;
-- (bool) resetDeviceMotionReference;
-- (bool) isDeviceMotionAvailable;
-- (bool) isDeviceMotionActive;
-
-@end
-
-static AndroidMotionManager* gMotionManager;
-*/

+ 1 - 2
engine/source/platformAndroid/AndroidOGLVideo.cpp

@@ -45,7 +45,6 @@ extern void createMouseTapEvent(S32 nbrTaps, S32 x, S32 y);
 
 
 //extern bool createAccelMoveEvent( UIAccelerationValue *accel );
 //extern bool createAccelMoveEvent( UIAccelerationValue *accel );
 
 
-extern bool setScreenOrientation(bool, bool);
 // TODO: Card Profiling code isn't doing anything.
 // TODO: Card Profiling code isn't doing anything.
 extern StringTableEntry gScreenOrientation;
 extern StringTableEntry gScreenOrientation;
 extern bool gScreenUpsideDown;
 extern bool gScreenUpsideDown;
@@ -233,7 +232,7 @@ bool OpenGLDevice::setScreenMode(U32 width, U32 height, U32 bpp, bool fullScreen
 //------------------------------------------------------------------------------
 //------------------------------------------------------------------------------
 void OpenGLDevice::swapBuffers()
 void OpenGLDevice::swapBuffers()
 {
 {
-	 eglSwapBuffers(engine.display, engine.surface);
+	 eglSwapBuffers(platState.engine->display, platState.engine->surface);
 }
 }
 
 
 
 

+ 7 - 97
engine/source/platformAndroid/AndroidPlatform.cpp

@@ -19,9 +19,6 @@
 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 // IN THE SOFTWARE.
 // IN THE SOFTWARE.
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-
-
-
 #include <unistd.h>
 #include <unistd.h>
 #include "platform/platform.h"
 #include "platform/platform.h"
 #include "console/console.h"
 #include "console/console.h"
@@ -34,38 +31,22 @@
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 const char* Platform::getUserDataDirectory() 
 const char* Platform::getUserDataDirectory() 
 {
 {
-   // application support directory is most in line with the current usages of this function.
-   // this may change with later usage
-   // perhaps the user data directory should be pref-controlled?
-   //NSString *nsDataDir = [@"~/Library/Application Support/" stringByStandardizingPath];
-    //-Mat using Documents directory in same folder as .app 
-   //TODO: replace objc
-	/*NSString *nsDataDir = [@"~/Documents/" stringByStandardizingPath];
-   return StringTable->insert([nsDataDir UTF8String]);
-   */
-	return StringTable->insert("");
+    //on android we will be using the cache dir to store user data
+	return StringTable->insert(activity.getCacheDir());
 
 
 }
 }
 
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 const char* Platform::getUserHomeDirectory() 
 const char* Platform::getUserHomeDirectory() 
 {
 {
-	//TODO: replace objc
-		/*
-   return StringTable->insert([[@"~/" stringByStandardizingPath] UTF8String]);
-   */
-	return StringTable->insert("");
+	return StringTable->insert("~/");
 }
 }
 
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 StringTableEntry Platform::osGetTemporaryDirectory()
 StringTableEntry Platform::osGetTemporaryDirectory()
 {
 {
-	//TODO: replace objc
-   /*NSString *tdir = NSTemporaryDirectory();
-   const char *path = [tdir UTF8String];
-   return StringTable->insert(path);
-   */
-	return StringTable->insert("");
+	//Android has no global temp folder, each application is expected to use cache dir
+	return StringTable->insert(activity.getCacheDir());
 }
 }
 
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -79,52 +60,7 @@ S32 Platform::messageBox(const UTF8 *title, const UTF8 *message, MBButtons butto
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 bool Platform::pathCopy(const char* source, const char* dest, bool nooverwrite)
 bool Platform::pathCopy(const char* source, const char* dest, bool nooverwrite)
 {
 {
-	//TODO: replace objc
-	/*
-   NSFileManager *manager = [NSFileManager defaultManager];
-   @autoreleasepool {
-   
-      NSString *nsource = [@(source) stringByStandardizingPath];
-      NSString *ndest   = [@(dest) stringByStandardizingPath];
-      NSString *ndestFolder = [ndest stringByDeletingLastPathComponent];
-      
-      if(! [manager fileExistsAtPath:nsource])
-      {
-         Con::errorf("Platform::pathCopy: no file exists at %s",source);
-         return false;
-      }
-       
-       //Catcher for the errors.
-       NSError* returnValue = nil;
-      
-      if( [manager fileExistsAtPath:ndest] )
-      {
-         if(nooverwrite)
-         {
-            Con::errorf("Platform::pathCopy file already exists at %s",dest);
-            return false;
-         }
-          
-         Con::warnf("Deleting files at path: %s", dest);
-         bool deleted = [manager removeItemAtPath:ndest error:&returnValue];
-         if(!deleted)
-         {
-            Con::errorf("Copy failed! Could not delete files at path: %s", dest);
-            return false;
-         }
-      }
-      
-      if([manager fileExistsAtPath:ndestFolder] == NO)
-      {
-         ndestFolder = [ndestFolder stringByAppendingString:@"/"]; // createpath requires a trailing slash
-         Platform::createPath([ndestFolder UTF8String]);
-      }
-      
-      bool ret = [manager copyItemAtPath:nsource toPath:ndest error:&returnValue];
-      
-      return ret;
-   }
-   */
+	//TODO: Not used on android?
 	return false;
 	return false;
    
    
 }
 }
@@ -132,33 +68,7 @@ bool Platform::pathCopy(const char* source, const char* dest, bool nooverwrite)
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 bool Platform::fileRename(const char *source, const char *dest)
 bool Platform::fileRename(const char *source, const char *dest)
 {
 {
-	//TODO: replace objc
-	/*
-   if(source == NULL || dest == NULL)
-      return false;
-      
-   NSFileManager *manager = [NSFileManager defaultManager];
-   
-   NSString *nsource = [manager stringWithFileSystemRepresentation:source length:dStrlen(source)];
-   NSString *ndest   = [manager stringWithFileSystemRepresentation:dest length:dStrlen(dest)];
-   
-   if(! [manager fileExistsAtPath:nsource])
-   {
-      Con::errorf("Platform::fileRename: no file exists at %s",source);
-      return false;
-   }
-   
-   if( [manager fileExistsAtPath:ndest] )
-   {
-      Con::warnf("Platform::fileRename: Deleting files at path: %s", dest);
-   }
-    
-    NSError* returnValue = NULL;
-   
-   bool ret = [manager moveItemAtPath:nsource toPath:ndest error:&returnValue];
-  
-   return ret;
-   */
+   //TODO: not used on android?
    return false;
    return false;
 }
 }
 
 

+ 1 - 1
engine/source/platformAndroid/AndroidProcessControl.cpp

@@ -56,7 +56,7 @@ void Platform::restartInstance()
       Con::errorf("The game is still running, we cant relaunch now!");
       Con::errorf("The game is still running, we cant relaunch now!");
       return;
       return;
    }
    }
-   //TODO: replace
+   //TODO: is this needed on android?
    /*
    /*
    // get the path to the torque executable
    // get the path to the torque executable
    CFBundleRef mainBundle =  CFBundleGetMainBundle();
    CFBundleRef mainBundle =  CFBundleGetMainBundle();

+ 0 - 5
engine/source/platformAndroid/AndroidProfiler.cpp

@@ -39,7 +39,6 @@ bool g_AndroidProfilerReady = false;
 void AndroidProfilerResetAll() {
 void AndroidProfilerResetAll() {
 	for(int i=0; i<ANDROID_PROFILER_MAX_CALLS; i++){
 	for(int i=0; i<ANDROID_PROFILER_MAX_CALLS; i++){
 		g_AndroidProfilerData[i].name = NULL;
 		g_AndroidProfilerData[i].name = NULL;
-		g_AndroidProfilerData[i].timeMach = 0;
 		g_AndroidProfilerData[i].timeMS = 0;
 		g_AndroidProfilerData[i].timeMS = 0;
 		g_AndroidProfilerData[i].type = 0;
 		g_AndroidProfilerData[i].type = 0;
 		g_AndroidProfilerData[i].invokes = 0;
 		g_AndroidProfilerData[i].invokes = 0;
@@ -61,8 +60,6 @@ void AndroidProfilerStart( const char *name ) {
 
 
 		int i = g_AndroidProfilerCount++;
 		int i = g_AndroidProfilerCount++;
 		g_AndroidProfilerData[i].name = name;
 		g_AndroidProfilerData[i].name = name;
-		//TODO: android
-		//g_AndroidProfilerData[i].timeMach = mach_absolute_time();
 		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
 		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
 		g_AndroidProfilerData[i].type = 0;
 		g_AndroidProfilerData[i].type = 0;
 		g_AndroidProfilerData[i].invokes = 0;
 		g_AndroidProfilerData[i].invokes = 0;
@@ -78,8 +75,6 @@ void AndroidProfilerEnd( const char *name ) {
 
 
 		int i = g_AndroidProfilerCount++;
 		int i = g_AndroidProfilerCount++;
 		g_AndroidProfilerData[i].name = name;
 		g_AndroidProfilerData[i].name = name;
-		//TODO: android
-		//g_AndroidProfilerData[i].timeMach = mach_absolute_time();
 		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
 		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
 		g_AndroidProfilerData[i].type = 1;
 		g_AndroidProfilerData[i].type = 1;
 		g_AndroidProfilerData[i].invokes = 0;
 		g_AndroidProfilerData[i].invokes = 0;

+ 5 - 4
engine/source/platformAndroid/AndroidStreamSource.cc

@@ -21,7 +21,6 @@
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 
 
 #include "AndroidStreamSource.h"
 #include "AndroidStreamSource.h"
-#include "SoundEngine.h"
 
 
 #define BUFFERSIZE 32768
 #define BUFFERSIZE 32768
 
 
@@ -30,12 +29,14 @@ AndroidStreamSource::AndroidStreamSource(const char *filename)  {
 	int len = dStrlen( filename );
 	int len = dStrlen( filename );
 	mFilename = new char[len + 1];
 	mFilename = new char[len + 1];
 	dStrcpy( mFilename, filename );
 	dStrcpy( mFilename, filename );
+	//TODO: streaming music
 	//SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
 	//SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
 }
 }
 
 
 AndroidStreamSource::~AndroidStreamSource() {
 AndroidStreamSource::~AndroidStreamSource() {
 	stop();
 	stop();
 	delete [] mFilename;
 	delete [] mFilename;
+	//TODO: streaming music
 	//SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
 	//SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
 }
 }
 
 
@@ -44,7 +45,7 @@ bool AndroidStreamSource::isPlaying() {
 }
 }
 
 
 bool AndroidStreamSource::start( bool loop ) {
 bool AndroidStreamSource::start( bool loop ) {
-	//TODO: android
+	//TODO: streaming music
 	/*
 	/*
 	SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
 	SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
 	SoundEngine::SoundEngine_StartBackgroundMusic();
 	SoundEngine::SoundEngine_StartBackgroundMusic();
@@ -59,7 +60,7 @@ bool AndroidStreamSource::start( bool loop ) {
 
 
 bool AndroidStreamSource::stop() {
 bool AndroidStreamSource::stop() {
 	//false == stop now
 	//false == stop now
-	//TODO: android
+	//TODO: streaming music
 	/*
 	/*
 	SoundEngine::SoundEngine_StopBackgroundMusic( false );
 	SoundEngine::SoundEngine_StopBackgroundMusic( false );
 	SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
 	SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
@@ -68,7 +69,7 @@ bool AndroidStreamSource::stop() {
 }
 }
     
     
 bool AndroidStreamSource::setVolume( F32 volume) {
 bool AndroidStreamSource::setVolume( F32 volume) {
-	//TODO: android
+	//TODO: streaming music
 	/*
 	/*
     SoundEngine::SoundEngine_SetBackgroundMusicVolume(volume);
     SoundEngine::SoundEngine_SetBackgroundMusicVolume(volume);
     */
     */

+ 4 - 38
engine/source/platformAndroid/AndroidTime.cpp

@@ -27,8 +27,6 @@
 //--------------------------------------
 //--------------------------------------
 void Platform::getLocalTime(LocalTime &lt)
 void Platform::getLocalTime(LocalTime &lt)
 {
 {
-   //TODO: android
-	/*
 	struct tm systime;
 	struct tm systime;
    time_t long_time;
    time_t long_time;
 
 
@@ -47,61 +45,29 @@ void Platform::getLocalTime(LocalTime &lt)
    lt.year     = systime.tm_year;
    lt.year     = systime.tm_year;
    lt.yearday  = systime.tm_yday;
    lt.yearday  = systime.tm_yday;
    lt.isdst    = systime.tm_isdst;
    lt.isdst    = systime.tm_isdst;
-   */
 }   
 }   
 
 
 /// Gets the time in seconds since the Epoch
 /// Gets the time in seconds since the Epoch
 U32 Platform::getTime()
 U32 Platform::getTime()
 {
 {
    time_t epoch_time;
    time_t epoch_time;
-   //TODO: android
-   //time( &epoch_time );
+   time( &epoch_time );
    return epoch_time;
    return epoch_time;
 }   
 }   
 
 
-//TODO: mach?
-//TODO: android
-/*static mach_timebase_info_data_t InitTimebaseInfo();
-/static mach_timebase_info_data_t timebase_info = InitTimebaseInfo();
-*/
 static double absolute_to_seconds;
 static double absolute_to_seconds;
 static double seconds_to_absolute;
 static double seconds_to_absolute;
 static double absolute_to_millis;
 static double absolute_to_millis;
 static double millis_to_absolute;
 static double millis_to_absolute;
 
 
-//TODO: android
-/*
-mach_timebase_info_data_t InitTimebaseInfo()
-{
-	mach_timebase_info_data_t timebase_info;
-	mach_timebase_info(&timebase_info);
-	absolute_to_seconds = timebase_info.numer / (1000000000.0 * timebase_info.denom);
-	seconds_to_absolute = 1.0 / absolute_to_seconds;
-	absolute_to_millis = timebase_info.numer / (1000000.0 * timebase_info.denom);
-	millis_to_absolute = 1.0 / absolute_to_millis;
-	
-	return timebase_info;
-}*/
-
 /// Gets the time in milliseconds since some epoch. In this case, system start time.
 /// Gets the time in milliseconds since some epoch. In this case, system start time.
 /// Storing milisec in a U32 overflows every 49.71 days
 /// Storing milisec in a U32 overflows every 49.71 days
 U32 Platform::getRealMilliseconds()
 U32 Platform::getRealMilliseconds()
 {
 {
-   // Duration is a S32 value.
-   // if negative, it is in microseconds.
-   // if positive, it is in milliseconds.
-	//TODO: android
-	/*
-	Duration durTime = mach_absolute_time() * absolute_to_millis;
-   U32 ret;
-   if( durTime < 0 )
-      ret = durTime / -1000;
-   else 
-      ret = durTime;
+   struct timeval  tv;
+   gettimeofday(&tv, NULL);
 
 
-   return ret;
-   */
-	return 0;
+   return ((tv.tv_sec) * 1000.0 + (tv.tv_usec) / 1000.0);
 }   
 }   
 
 
 U32 Platform::getVirtualMilliseconds()
 U32 Platform::getVirtualMilliseconds()

+ 0 - 208
engine/source/platformAndroid/AndroidUtil.cpp

@@ -36,12 +36,6 @@
 #include <sys/socket.h>
 #include <sys/socket.h>
 #include <arpa/inet.h>
 #include <arpa/inet.h>
 
 
-
-
-
-//Luma:	Orientation support
-//TODO: android
-//int gAndroidGameCurrentOrientation = UIDeviceOrientationLandscapeRight;
 TCPObject* gpTCPObject = NULL;
 TCPObject* gpTCPObject = NULL;
 char gszTCPAddress[256];
 char gszTCPAddress[256];
 
 
@@ -52,205 +46,3 @@ void Platform::outputDebugString( const char *string )
     fprintf(stderr, "\n" );
     fprintf(stderr, "\n" );
     fflush(stderr);
     fflush(stderr);
 }
 }
-
-//--------------------------------------
-//TODO: android
-/*
-bool GBitmap::readPNGiPhone(Stream& io_rStream)
-{
-    int filesize = io_rStream.getStreamSize();
-    U8 *buff = new U8[filesize+1024];
-    
-    CGDataProviderRef data_provider = CGDataProviderCreateWithData(nil, buff, filesize, nil);
-    CGImageRef apple_image = CGImageCreateWithPNGDataProvider(data_provider, nil, false, kCGRenderingIntentDefault);
-    
-    // Choose alpha strategy based on whether the source image has alpha or not.
-    int width = CGImageGetWidth(apple_image);
-    int height = CGImageGetHeight(apple_image);
-    U32 rowBytes = width * 4;
-    
-    // Set up the row pointers...
-    AssertISV(width <= 1024, "Error, cannot load images wider than 1024 pixels!");
-    AssertISV(height <= 1024, "Error, cannot load images taller than 1024 pixels!");
-
-    BitmapFormat format = RGBA;
-    // actually allocate the bitmap space...
-    allocateBitmap(width, height,
-                   false,            // don't extrude miplevels...
-                   format);          // use determined format...
-
-    U8 *pBase = (U8*)getBits();
-    
-    CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
-    CGContextRef texture_context = CGBitmapContextCreate(pBase, width, height, 8, rowBytes, color_space, kCGImageAlphaPremultipliedLast);
-    
-    CGContextDrawImage(texture_context, CGRectMake(0.0, 0.0, width, height), apple_image);
-    
-    
-    CGImageRelease(apple_image);
-    CGDataProviderRelease(data_provider);
-
-    delete [] buff;
-    return true;
-}*/
-
-
-//Luma:	Orientation support
-int _AndroidGameGetOrientation()
-{
-	//TODO: android
-    //return gAndroidGameCurrentOrientation;
-	return 0;
-}
-void _AndroidGameSetCurrentOrientation(int iOrientation)
-{
-	//TODO: android
-    //gAndroidGameCurrentOrientation = iOrientation;
-}
-
-S32 _AndroidGetPortraitTouchoffset()
-{
-    S32 offset = 0;
-    
-    S32 deviceType = Con::getIntVariable("$pref::Android::DeviceType");
-    
-    bool retinaEnabled = Con::getBoolVariable("$pref::Android::RetinaEnabled");
-    
-    if (deviceType == 2)
-        offset = 500;
-    else if (deviceType == 1)
-        offset = retinaEnabled ? 500 : 250;
-    else
-        offset = retinaEnabled ? 320 : 160;
-    
-    return offset;
-}
-
-//Luma: Ability to get the Local IP (Internal IP) for an Android as opposed to it's External one
-void _AndroidGetLocalIP(unsigned char *pcIPString)
-{
-	//TODO: android
-	/*
-    int a,b,c,d ; 
-    struct ifaddrs* interface;
-    char* addr;
-    
-    if (getifaddrs(&interface) == 0) 
-    {
-        struct ifaddrs* allInterfaces = interface;
-        while (interface != NULL) 
-        {
-            const struct sockaddr_in* address = (const struct sockaddr_in*) interface->ifa_addr;
-            addr = inet_ntoa(address->sin_addr);
-            if ((address->sin_family == AF_INET) && (strcmp(addr, "127.0.0.1" )))
-            {
-                break;
-            }
-            interface = interface->ifa_next;
-        }
-        freeifaddrs(allInterfaces);
-    }
-    
-    if(interface)
-    {
-        sscanf( addr, "%i.%i.%i.%i", &a, &b, &c, &d);
-    }
-    else
-    {
-        a = 0;
-        b = 0;
-        c = 0;
-        d = 0;
-        
-    }
-    pcIPString[0] = (unsigned char)a;
-    pcIPString[1] = (unsigned char)b;
-    pcIPString[2] = (unsigned char)c;
-    pcIPString[3] = (unsigned char)d;
-    */
-}
-
-
-//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
-//TODO: android
-/*
-static void TCPObjectConnectCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *dataIn, void *info)
-{
-    if(type == kCFSocketConnectCallBack) 
-    {
-        if(dataIn) 
-        {
-            SInt32 error = *((SInt32*)dataIn);
-            Con::printf("Error connecting with CFSocker: Error code %d\n",error);
-        }
-    }
-    
-    //regardless, we want to connect to the TCPObject if we opened the socket or not so that it can continue its process properly
-    if(gpTCPObject)
-    {
-        gpTCPObject->connect(gszTCPAddress);
-        gpTCPObject = NULL;
-    }
-}
- 
-
-//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
-CFSocketRef CreateCFSocketToURLAndPort(const char *ipAddress, U16 port)
-{
-    CFSocketContext context;
-    context.version = 0;
-    context.info = NULL;
-    context.retain = NULL;
-    context.release = NULL;
-    context.copyDescription = NULL;
-                                    
-    CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault,
-                                        PF_INET,
-                                        SOCK_STREAM,
-                                        IPPROTO_TCP,
-                                        kCFSocketConnectCallBack,
-                                        TCPObjectConnectCallback,
-                                        &context);
-
-    struct sockaddr_in addr4;
-    memset(&addr4, 0, sizeof(addr4));
-
-    addr4.sin_family = AF_INET;
-    addr4.sin_len = sizeof(addr4);
-    addr4.sin_port = htons(port);
-    inet_aton(ipAddress, &addr4.sin_addr);
-
-    
-
-    return socket;
-}
-
-
-//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
-void OpenAndroidNetworkingAndConnectToTCPObject(TCPObject *psTCPObject, const char *pcAddress)
-{
-    
-    char remoteAddr[256];
-    //store TCPObject and Port in globals
-    gpTCPObject = psTCPObject;
-    if(psTCPObject)
-    {
-        dStrcpy(gszTCPAddress, pcAddress);
-    }
-    
-    //break up url / port to pass in	
-    dStrcpy(remoteAddr, pcAddress);
-    U16		port = 80;
-    char	*portString = dStrchr(remoteAddr, ':');
-    if(portString)
-    {
-        *portString++ = 0;
-        port = dAtoi(portString);
-    }
-
-    //call socket create function
-    CreateCFSocketToURLAndPort(remoteAddr, port);
-}
-*/
-
-

+ 0 - 4
engine/source/platformAndroid/AndroidUtil.h

@@ -26,10 +26,6 @@
 
 
 #include "network/tcpObject.h"
 #include "network/tcpObject.h"
 
 
-int _AndroidGameGetOrientation();
-void _AndroidGameSetCurrentOrientation(int iOrientation);
-S32 _AndroidGetPortraitTouchoffset();
-
 //Luma: Ability to get the Local IP (Internal IP) for an Android as opposed to it's External one
 //Luma: Ability to get the Local IP (Internal IP) for an Android as opposed to it's External one
 void _AndroidGetLocalIP(unsigned char *pcIPString);
 void _AndroidGetLocalIP(unsigned char *pcIPString);
 
 

+ 18 - 142
engine/source/platformAndroid/AndroidWindow.cpp

@@ -36,7 +36,6 @@
 
 
 #include "platformAndroid/platformGL.h"
 #include "platformAndroid/platformGL.h"
 
 
-bool setScreenOrientation(bool, bool);
 bool getStatusBarHidden();
 bool getStatusBarHidden();
 bool setStatusBarHidden(bool);
 bool setStatusBarHidden(bool);
 void setStatusBarType(S32);
 void setStatusBarType(S32);
@@ -75,9 +74,6 @@ AndroidPlatState::AndroidPlatState()
     // directory that contains main.cs . This will help us detect whether we are
     // directory that contains main.cs . This will help us detect whether we are
     // running with the scripts in the bundle or not.
     // running with the scripts in the bundle or not.
     mainDotCsDir = NULL;
     mainDotCsDir = NULL;
-
-    //TODO: android
-    //mainLoopTimer = NULL;
 }
 }
 
 
 
 
@@ -160,96 +156,30 @@ void Platform::shutdown()
 S32 gStatusBarType = 0;
 S32 gStatusBarType = 0;
 bool gStatusBarHidden = true;
 bool gStatusBarHidden = true;
 
 
-//Landscape by default. 0 Landscape, 1 Portrait
-S32 gScreenOrientation = 0;
-bool gScreenUpsideDown = true;
-
-
 //------------------------------------------------------------------------------
 //------------------------------------------------------------------------------
 void Platform::initWindow(const Point2I &initialSize, const char *name)
 void Platform::initWindow(const Point2I &initialSize, const char *name)
 {
 {
-    S32 resolutionWidth = ANDROID_DEFAULT_RESOLUTION_X;
-    S32 resolutionHeight = ANDROID_DEFAULT_RESOLUTION_Y;
-
-    // First fetch the values from the prefs.
-    U32 iDeviceOrientation = (U32) Con::getIntVariable("$pref::Android::ScreenOrientation");
-
-    // 0: iPhone
-    // 1: iPad
-    // 2: iPhone 5
-    //TODO: android
-    /*
-    if (iDeviceType == 2)
-    {
-        resolutionWidth = 1136;
-        resolutionHeight = 640;
-    }
-    else
-    {
-        U32 scaleFactor = retinaEnabled ? 2 : 1;
+    S32 resolutionWidth = _AndroidGetScreenWidth();
+    S32 resolutionHeight = _AndroidGetScreenHeight();
 
 
-        resolutionWidth = iDeviceType ? (1024 * scaleFactor) : (480 * scaleFactor);
-        resolutionHeight = iDeviceType ? (768 * scaleFactor) : (320 * scaleFactor);
-    }
+    dSprintf(platState.appWindowTitle, sizeof(platState.appWindowTitle), name);
 
 
-    Point2I startRes;
+    platState.windowSize.x = _AndroidGetScreenWidth();
+    platState.windowSize.y = _AndroidGetScreenHeight();
 
 
-    if (!iDeviceOrientation)
+    //Default to landscape, and run into portrait if requested.
+    S32 orientation = _AndroidGameGetOrientation();
+    if (orientation == ACONFIGURATION_ORIENTATION_PORT)
     {
     {
-        startRes.x = resolutionWidth;
-        startRes.y = resolutionHeight;
+    	gScreenOrientation = 1;
+    	platState.portrait = true;
     }
     }
     else
     else
     {
     {
-        //portrait, swap width height.
-        startRes.x = resolutionHeight;
-        startRes.y = resolutionWidth;
-    }
-
-    dSprintf(platState.appWindowTitle, sizeof(platState.appWindowTitle), name);
-
-    platState.windowSize.x = startRes.x;
-    platState.windowSize.y = startRes.y;
-
-    //Get screen orientation prefs //Based on 0 Landscape, 1 Portrait
-    gScreenOrientation = iDeviceOrientation;
-    gScreenUpsideDown = Con::getBoolVariable("$pref::Android::ScreenUpsideDown");
-
-    //Default to landscape, and run into portrait if requested.
-    platState.portrait = false;
-
-    if (gScreenOrientation != 0) //fuzzytodo :add a constant
-    {
-        //Could handle other options here, later.
-        platState.portrait = true;
+    	gScreenOrientation = 0;
+    	platState.portrait = false;
     }
     }
 
 
-    //We should now have a good windowSize, it will be default if initial size was bad
-    T2DView * glView;
-    CGRect rect;
-
-    rect.origin.x = 0;
-    rect.origin.y = 0;
-
-    rect.size.width = platState.windowSize.x;
-    rect.size.height = platState.windowSize.y;
-
-    glView = (T2DView *) platState.Window;
-    
-    //TODO: android
-    //if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2)
-    //    glView.contentScaleFactor = [[UIScreen mainScreen] scale];
-    
-    platState.ctx = glView;
-    
-    //get status bar pref // 0 Hidden , 1 BlackOpaque , 2 BlackTranslucent
-    
-    S32 tempType = Con::getIntVariable("$pref::Android::StatusBarType");
-    setStatusBarType(tempType);
-    
-    //set screen orientation
-    setScreenOrientation(platState.portrait, gScreenUpsideDown);
-    
     bool fullScreen;
     bool fullScreen;
     U32 bpp = Con::getIntVariable("$pref::Android::ScreenDepth"); //ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH;
     U32 bpp = Con::getIntVariable("$pref::Android::ScreenDepth"); //ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH;
     if (!bpp)
     if (!bpp)
@@ -273,7 +203,6 @@ void Platform::initWindow(const Point2I &initialSize, const char *name)
     //NOTE:	This should probably be set by the user to be the color closest to Default.png in order to minimize any popping effect... $pref:: anyone? Are $pref::s even valid at this point in the Init process?
     //NOTE:	This should probably be set by the user to be the color closest to Default.png in order to minimize any popping effect... $pref:: anyone? Are $pref::s even valid at this point in the Init process?
     glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
     glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
     glClear(GL_COLOR_BUFFER_BIT);
     glClear(GL_COLOR_BUFFER_BIT);
-    */
 }
 }
 
 
 //--------------------------------------
 //--------------------------------------
@@ -292,69 +221,16 @@ bool appIsRunning(int batchId)
 
 
 bool Platform::openWebBrowser(const char *webAddress)
 bool Platform::openWebBrowser(const char *webAddress)
 {
 {
-	//TODO: android
-    /*NSString *string = [[NSString alloc] initWithUTF8String:webAddress];
-    NSURL *url = [[NSURL alloc] initWithString:string];
-    bool ret = [platState.application openURL:url];
+	//TODO: convert to JNI code
+	//Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
+	//startActivity(browserIntent);
 
 
-    return ret;// this bails on the application, switching to Safari
-    */
-	return false;
-}
 
 
-bool setScreenOrientation(bool portrait, bool upsidedown)
-{
-    bool success = false;
-    //TODO: android
-    /*
-    CGPoint point;
-    if (platState.portrait)
-    {
-        point.x = platState.windowSize.x / 2;
-        point.y = platState.windowSize.y / 2;
-    }
-    else
-    {
-        point.x = platState.windowSize.y / 2;
-        point.y = platState.windowSize.x / 2;
-    }
-*/
-
-    //TODO: android
-    /*[platState.ctx centerOnPoint:point];
-
-    if (portrait)
-    {//normal upright
-        if (upsidedown)
-        {//button on top
-            [platState.ctx rotateToAngle:M_PI + (M_PI / 2.0)];//rotate to 90 degrees
-            platState.application.statusBarOrientation = UIInterfaceOrientationPortraitUpsideDown;
-            success = true;
-        } else
-        {//button on bottom
-            [platState.ctx rotateToAngle:(M_PI / 2.0)];//rotate to 270 degrees
-            platState.application.statusBarOrientation = UIInterfaceOrientationPortrait;
-            success = true;
-        }
-    } else
-    {//landscape/ sideways
-        if (upsidedown)
-        {//button on left
-            [platState.ctx rotateToAngle:0];//rotate to -180 (0) degrees
-            platState.application.statusBarOrientation = UIInterfaceOrientationLandscapeLeft;
-            success = true;
-        } else
-        {//button on right
-            [platState.ctx rotateToAngle:(M_PI)];//rotate to 180 degrees
-            platState.application.statusBarOrientation = UIInterfaceOrientationLandscapeRight;
-            success = true;
-        }
-    }
-*/
-    return success;
+	return true;
 }
 }
 
 
 ConsoleFunction(setScreenOrientation, bool, 3, 3, "Sets the orientation of the screen ( portrait/landscape, upside down or right-side up )\n"
 ConsoleFunction(setScreenOrientation, bool, 3, 3, "Sets the orientation of the screen ( portrait/landscape, upside down or right-side up )\n"
         "@(bool portrait, bool upside_down)"){
         "@(bool portrait, bool upside_down)"){
-    return setScreenOrientation(dAtob(argv[1]), dAtob(argv[2]));
+    adprintf("screen orientation is set via the manifest file on android");
+	return false;
 }
 }

+ 0 - 1599
engine/source/platformAndroid/SoundEngine.cpp

@@ -1,1599 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2013 GarageGames, LLC
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-// IN THE SOFTWARE.
-//-----------------------------------------------------------------------------
-
-/*
- 
- ===== IMPORTANT =====
- 
- This is sample code demonstrating API, technology or techniques in development.
- Although this sample code has been reviewed for technical accuracy, it is not
- final. Apple is supplying this information to help you plan for the adoption of
- the technologies and programming interfaces described herein. This information
- is subject to change, and software implemented based on this sample code should
- be tested with final operating system software and final documentation. Newer
- versions of this sample code may be provided with future seeds of the API or
- technology. For information about updates to this and other developer
- documentation, view the New & Updated sidebars in subsequent documentation
- seeds.
- 
- =====================
- 
- File: SoundEngine.cpp
- Abstract: These functions play background music tracks, multiple sound effects,
- and support stereo panning with a low-latency response.
- 
- Version: 1.6
- 
- Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
- ("Apple") in consideration of your agreement to the following terms, and your
- use, installation, modification or redistribution of this Apple software
- constitutes acceptance of these terms.  If you do not agree with these terms,
- please do not use, install, modify or redistribute this Apple software.
- 
- In consideration of your agreement to abide by the following terms, and subject
- to these terms, Apple grants you a personal, non-exclusive license, under
- Apple's copyrights in this original Apple software (the "Apple Software"), to
- use, reproduce, modify and redistribute the Apple Software, with or without
- modifications, in source and/or binary forms; provided that if you redistribute
- the Apple Software in its entirety and without modifications, you must retain
- this notice and the following text and disclaimers in all such redistributions
- of the Apple Software.
- Neither the name, trademarks, service marks or logos of Apple Inc. may be used
- to endorse or promote products derived from the Apple Software without specific
- prior written permission from Apple.  Except as expressly stated in this notice,
- no other rights or licenses, express or implied, are granted by Apple herein,
- including but not limited to any patent rights that may be infringed by your
- derivative works or by other works in which the Apple Software may be
- incorporated.
- 
- The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
- WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
- WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
- COMBINATION WITH YOUR PRODUCTS.
- 
- IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
- GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
- DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
- CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
- APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- 
- Copyright (C) 2008 Apple Inc. All Rights Reserved.
- 
- */
-//TODO: android
-/*
-//==================================================================================================
-//	Includes
-//==================================================================================================
-//	System Includes
-#include <map>
-#include <vector>
-#include <pthread.h>
-
-// Local Includes
-#include "SoundEngine.h"
-
-namespace SoundEngine {
-
-
-#define	AssertNoError(inMessage, inHandler) \
-if(result != noErr) \
-{	 \
-printf("%s: %d\n", inMessage, (int)result);	 \
-}
-
-#define AssertNoOALError(inMessage, inHandler)					\
-if((result = alGetError()) != AL_NO_ERROR)			\
-{													\
-printf("%s: %x\n", inMessage, (int)result);		\
-goto inHandler;									\
-}
-
-#define kNumberBuffers 3
-
-class OpenALObject;
-class BackgroundTrackMgr;
-
-static OpenALObject			*sOpenALObject = NULL;
-static BackgroundTrackMgr	*sBackgroundTrackMgr = NULL;
-static Float32				gMasterVolumeGain = 1.0;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-typedef ALvoid	AL_APIENTRY	(*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq);
-ALvoid  alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq)
-{
-    static	alBufferDataStaticProcPtr	proc = NULL;
-    
-    if (proc == NULL) {
-        proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");
-    }
-    
-    if (proc)
-        proc(bid, format, data, size, freq);
-    
-    return;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-typedef ALvoid	AL_APIENTRY	(*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value);
-ALvoid  alcMacOSXMixerOutputRateProc(const ALdouble value)
-{
-    static	alcMacOSXMixerOutputRateProcPtr	proc = NULL;
-    
-    if (proc == NULL) {
-        proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate");
-    }
-    
-    if (proc)
-        proc(value);
-    
-    return;
-}
-
-#pragma mark ***** OpenALThread *****
-//==================================================================================================
-//	Threading functions
-//==================================================================================================
-class	OpenALThread
-    {
-        // returns the thread's priority as it was last set by the API
-#define OpenALThread_SET_PRIORITY				0
-        // returns the thread's priority as it was last scheduled by the Kernel
-#define OpenALThread_SCHEDULED_PRIORITY		1
-        
-        //	Types
-    public:
-        typedef void*			(*ThreadRoutine)(void* inParameter);
-        
-        //	Constants
-    public:
-        enum
-        {
-            kMinThreadPriority = 1,
-            kMaxThreadPriority = 63,
-            kDefaultThreadPriority = 31
-        };
-        
-        //	Construction/Destruction
-    public:
-        OpenALThread(ThreadRoutine inThreadRoutine, void* inParameter)
-        :	mPThread(0),
-        mSpawningThreadPriority(getScheduledPriority(pthread_self(), OpenALThread_SET_PRIORITY)),
-        mThreadRoutine(inThreadRoutine),
-        mThreadParameter(inParameter),
-        mPriority(kDefaultThreadPriority),
-        mFixedPriority(false),
-        mAutoDelete(true) { }
-        
-        ~OpenALThread() { }
-        
-        //	Properties
-        bool IsRunning() const { return 0 != mPThread; }
-        void SetAutoDelete(bool b) { mAutoDelete = b; }
-        
-        void SetPriority(UInt32 inPriority, bool inFixedPriority)
-        {
-            OSStatus result = noErr;
-            mPriority = inPriority;
-            mFixedPriority = inFixedPriority;
-            if(mPThread != 0)
-            {
-                if (mFixedPriority)
-                {
-                    thread_extended_policy_data_t		theFixedPolicy;
-                    theFixedPolicy.timeshare = false;	// set to true for a non-fixed thread
-                    result  = thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
-                    if (result) {
-                        printf("OpenALThread::SetPriority: failed to set the fixed-priority policy");
-                        return;
-                    }
-                }
-                // We keep a reference to the spawning thread's priority around (initialized in the constructor), 
-                // and set the importance of the child thread relative to the spawning thread's priority.
-                thread_precedence_policy_data_t		thePrecedencePolicy;
-                
-                thePrecedencePolicy.importance = mPriority - mSpawningThreadPriority;
-                result =thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
-                if (result) {
-                    printf("OpenALThread::SetPriority: failed to set the precedence policy");
-                    return;
-                }
-            } 
-        }
-        //	Actions
-        void Start()
-        {
-            if(mPThread != 0)
-            {
-                printf("OpenALThread::Start: can't start because the thread is already running\n");
-                return;
-            }
-            
-            OSStatus			result;
-            pthread_attr_t		theThreadAttributes;
-            
-            result = pthread_attr_init(&theThreadAttributes);
-            AssertNoError("Error initializing thread", end);
-            
-            result = pthread_attr_setdetachstate(&theThreadAttributes, PTHREAD_CREATE_DETACHED);
-            AssertNoError("Error setting thread detach state", end);
-            
-            result = pthread_create(&mPThread, &theThreadAttributes, (ThreadRoutine)OpenALThread::Entry, this);
-            AssertNoError("Error creating thread", end);
-            
-            pthread_attr_destroy(&theThreadAttributes);
-            AssertNoError("Error destroying thread attributes", end);
-        end:
-            return;
-        }
-        
-        //	Implementation
-    protected:
-        static void* Entry(OpenALThread* inOpenALThread)
-        {
-            void* theAnswer = NULL;
-            
-            inOpenALThread->SetPriority(inOpenALThread->mPriority, inOpenALThread->mFixedPriority);
-            
-            if(inOpenALThread->mThreadRoutine != NULL)
-            {
-                theAnswer = inOpenALThread->mThreadRoutine(inOpenALThread->mThreadParameter);
-            }
-            
-            inOpenALThread->mPThread = 0;
-            if (inOpenALThread->mAutoDelete)
-                delete inOpenALThread;
-            return theAnswer;
-        }
-        
-        static UInt32 getScheduledPriority(pthread_t inThread, int inPriorityKind)
-        {
-            thread_basic_info_data_t			threadInfo;
-            policy_info_data_t					thePolicyInfo;
-            unsigned int						count;
-            
-            if (inThread == NULL)
-                return 0;
-            
-            // get basic info
-            count = THREAD_BASIC_INFO_COUNT;
-            thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);
-            
-            switch (threadInfo.policy) {
-                case POLICY_TIMESHARE:
-                    count = POLICY_TIMESHARE_INFO_COUNT;
-                    thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count);
-                    if (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) {
-                        return thePolicyInfo.ts.cur_priority;
-                    }
-                    return thePolicyInfo.ts.base_priority;
-                    break;
-                    
-                case POLICY_FIFO:
-                    count = POLICY_FIFO_INFO_COUNT;
-                    thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count);
-                    if ( (thePolicyInfo.fifo.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
-                        return thePolicyInfo.fifo.depress_priority;
-                    }
-                    return thePolicyInfo.fifo.base_priority;
-                    break;
-                    
-                case POLICY_RR:
-                    count = POLICY_RR_INFO_COUNT;
-                    thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count);
-                    if ( (thePolicyInfo.rr.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {
-                        return thePolicyInfo.rr.depress_priority;
-                    }
-                    return thePolicyInfo.rr.base_priority;
-                    break;
-            }
-            
-            return 0;
-        }
-        
-        pthread_t				mPThread;
-        UInt32					mSpawningThreadPriority;
-        ThreadRoutine			mThreadRoutine;
-        void*					mThreadParameter;
-        SInt32					mPriority;
-        bool					mFixedPriority;
-        bool					mAutoDelete;		// delete self when thread terminates
-    };
-
-//==================================================================================================
-//	Helper functions
-//==================================================================================================
-OSStatus OpenFile(const char *inFilePath, AudioFileID &outAFID)
-{
-    
-    CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);
-    if (theURL == NULL)
-        return kSoundEngineErrFileNotFound;
-    
-#if TARGET_OS_iOS
-    OSStatus result = AudioFileOpenURL(theURL, fsRdPerm, 0, &outAFID);
-#else
-    OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID);
-#endif
-    CFRelease(theURL);
-    AssertNoError("Error opening file", end);
-end:
-    return result;
-}
-
-OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize)
-{
-    UInt32 thePropSize = sizeof(outFormat);				
-    OSStatus result = OpenFile(inFilePath, outAFID);
-    if( result != noErr ) {
-        int a = 0;
-        a++;
-    } else {
-        int a = 0;
-        a++;
-    }
-    AssertNoError("Error opening file", end);
-    
-    result = AudioFileGetProperty(outAFID, kAudioFilePropertyDataFormat, &thePropSize, &outFormat);
-    AssertNoError("Error getting file format", end);
-    
-    thePropSize = sizeof(UInt64);
-    result = AudioFileGetProperty(outAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize);
-    AssertNoError("Error getting file data size", end);
-    
-end:
-    return result;
-}
-
-void CalculateBytesForTime (AudioStreamBasicDescription & inDesc, UInt32 inMaxPacketSize, Float64 inSeconds, UInt32 *outBufferSize, UInt32 *outNumPackets)
-{
-    static const UInt32 maxBufferSize = 0x10000; // limit size to 64K
-    static const UInt32 minBufferSize = 0x4000; // limit size to 16K
-    
-    if (inDesc.mFramesPerPacket) {
-        Float64 numPacketsForTime = inDesc.mSampleRate / inDesc.mFramesPerPacket * inSeconds;
-        *outBufferSize = numPacketsForTime * inMaxPacketSize;
-    } else {
-        // if frames per packet is zero, then the codec has no predictable packet == time
-        // so we can't tailor this (we don't know how many Packets represent a time period
-        // we'll just return a default buffer size
-        *outBufferSize = maxBufferSize > inMaxPacketSize ? maxBufferSize : inMaxPacketSize;
-    }
-    
-    // we're going to limit our size to our default
-    if (*outBufferSize > maxBufferSize && *outBufferSize > inMaxPacketSize)
-        *outBufferSize = maxBufferSize;
-    else {
-        // also make sure we're not too small - we don't want to go the disk for too small chunks
-        if (*outBufferSize < minBufferSize)
-            *outBufferSize = minBufferSize;
-    }
-    *outNumPackets = *outBufferSize / inMaxPacketSize;
-}
-
-static Boolean MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y)
-{
-    UInt32 xFlags = x.mFormatFlags;
-    UInt32 yFlags = y.mFormatFlags;
-    
-    // match wildcards
-    if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0) 
-        return true;
-    
-    if (x.mFormatID == kAudioFormatLinearPCM)
-    {		 		
-        // knock off the all clear flag
-        xFlags = xFlags & ~kAudioFormatFlagsAreAllClear;
-        yFlags = yFlags & ~kAudioFormatFlagsAreAllClear;
-        
-        // if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit.
-        if (xFlags & yFlags & kAudioFormatFlagIsPacked) {
-            xFlags = xFlags & ~kAudioFormatFlagIsAlignedHigh;
-            yFlags = yFlags & ~kAudioFormatFlagIsAlignedHigh;
-        }
-        
-        // if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit.
-        if (xFlags & yFlags & kAudioFormatFlagIsFloat) {
-            xFlags = xFlags & ~kAudioFormatFlagIsSignedInteger;
-            yFlags = yFlags & ~kAudioFormatFlagIsSignedInteger;
-        }
-        
-        //	if the bit depth is 8 bits or less and the format is packed, we don't care about endianness
-        if((x.mBitsPerChannel <= 8) && ((xFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
-        {
-            xFlags = xFlags & ~kAudioFormatFlagIsBigEndian;
-        }
-        if((y.mBitsPerChannel <= 8) && ((yFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked))
-        {
-            yFlags = yFlags & ~kAudioFormatFlagIsBigEndian;
-        }
-        
-        //	if the number of channels is 0 or 1, we don't care about non-interleavedness
-        if (x.mChannelsPerFrame <= 1 && y.mChannelsPerFrame <= 1) {
-            xFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
-            yFlags &= ~kLinearPCMFormatFlagIsNonInterleaved;
-        }
-    }
-    return xFlags == yFlags;
-}
-
-Boolean FormatIsEqual(AudioStreamBasicDescription x, AudioStreamBasicDescription y)
-{
-    //	the semantics for equality are:
-    //		1) Values must match exactly
-    //		2) wildcard's are ignored in the comparison
-    
-#define MATCH(name) ((x.name) == 0 || (y.name) == 0 || (x.name) == (y.name))
-    
-    return 
-    ((x.mSampleRate==0.) || (y.mSampleRate==0.) || (x.mSampleRate==y.mSampleRate)) 
-    && MATCH(mFormatID)
-    && MatchFormatFlags(x, y)  
-    && MATCH(mBytesPerPacket) 
-    && MATCH(mFramesPerPacket) 
-    && MATCH(mBytesPerFrame) 
-    && MATCH(mChannelsPerFrame) 		
-    && MATCH(mBitsPerChannel) ;
-}
-
-#pragma mark ***** BackgroundTrackMgr *****
-//==================================================================================================
-//	BackgroundTrackMgr class
-//==================================================================================================
-class BackgroundTrackMgr
-    {	
-#define CurFileInfo THIS->mBGFileInfo[THIS->mCurrentFileIndex]
-    public:
-        typedef struct BG_FileInfo {
-            const char*						mFilePath;
-            AudioFileID						mAFID;
-            AudioStreamBasicDescription		mFileFormat;
-            UInt64							mFileDataSize;
-            //UInt64							mFileNumPackets; // this is only used if loading file to memory
-            Boolean							mLoadAtOnce;
-            Boolean							mIsPlaying;//-Mat added this
-            Boolean							mFileDataInQueue;
-        } BackgroundMusicFileInfo;
-        
-        BackgroundTrackMgr() 
-        :	mQueue(0),
-        mBufferByteSize(0),
-        mCurrentPacket(0),
-        mNumPacketsToRead(0),
-        mVolume(1.0),
-        mPacketDescs(NULL),
-        mCurrentFileIndex(0),
-        mMakeNewQueueWhenStopped(false),
-        mStopAtEnd(false) { }
-        
-        ~BackgroundTrackMgr() { Teardown(); }
-        
-        void Teardown()
-        {
-            if (mQueue)
-                AudioQueueDispose(mQueue, true);
-            for (UInt32 i=0; i < mBGFileInfo.size(); i++)
-                if (mBGFileInfo[i]->mAFID)
-                    AudioFileClose(mBGFileInfo[i]->mAFID);
-            
-            if (mPacketDescs)
-            {
-                delete mPacketDescs;
-                mPacketDescs = NULL;
-            }
-        }
-        
-        AudioStreamPacketDescription *GetPacketDescsPtr() { return mPacketDescs; }
-        
-        UInt32 GetNumPacketsToRead(BackgroundTrackMgr::BG_FileInfo *inFileInfo) 
-        { 
-            return mNumPacketsToRead; 
-        }
-        
-        static OSStatus AttachNewCookie(AudioQueueRef inQueue, BackgroundTrackMgr::BG_FileInfo *inFileInfo)
-        {
-            OSStatus result = noErr;
-            UInt32 size = sizeof(UInt32);
-            result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
-            if (!result && size) 
-            {
-                char* cookie = new char [size];		
-                result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
-                AssertNoError("Error getting cookie data", end);
-                result = AudioQueueSetProperty(inQueue, kAudioQueueProperty_MagicCookie, cookie, size);
-                delete [] cookie;
-                AssertNoError("Error setting cookie data for queue", end);
-            }
-            return noErr;
-            
-        end:
-            return noErr;
-        }
-        
-        static void QueueStoppedProc(	void *                  inUserData,
-                                     AudioQueueRef           inAQ,
-                                     AudioQueuePropertyID    inID)
-        {
-            UInt32 isRunning;
-            UInt32 propSize = sizeof(isRunning);
-            
-            BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
-            OSStatus result = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &isRunning, &propSize);
-            
-            if ((!isRunning) && (THIS->mMakeNewQueueWhenStopped))
-            {
-                result = AudioQueueDispose(inAQ, true);
-                AssertNoError("Error disposing queue", end);
-                result = THIS->SetupQueue(CurFileInfo);
-                AssertNoError("Error setting up new queue", end);
-                result = THIS->SetupBuffers(CurFileInfo);
-                AssertNoError("Error setting up new queue buffers", end);
-                result = THIS->Start();
-                AssertNoError("Error starting queue", end);
-            }
-        end:
-            return;
-        }
-        
-        static Boolean DisposeBuffer(AudioQueueRef inAQ, std::vector<AudioQueueBufferRef> inDisposeBufferList, AudioQueueBufferRef inBufferToDispose)
-        {
-            for (unsigned int i=0; i < inDisposeBufferList.size(); i++)
-            {
-                if (inBufferToDispose == inDisposeBufferList[i])
-                {
-                    OSStatus result = AudioQueueFreeBuffer(inAQ, inBufferToDispose);
-                    if (result == noErr)
-                        inDisposeBufferList.pop_back();
-                    return true;
-                }
-            }
-            return false;
-        }
-        
-        enum {
-            kQueueState_DoNothing		= 0,
-            kQueueState_ResizeBuffer	= 1,
-            kQueueState_NeedNewCookie	= 2,
-            kQueueState_NeedNewBuffers	= 3,
-            kQueueState_NeedNewQueue	= 4,
-        };
-        
-        static SInt8 GetQueueStateForNextBuffer(BackgroundTrackMgr::BG_FileInfo *inFileInfo, BackgroundTrackMgr::BG_FileInfo *inNextFileInfo)
-        {
-            inFileInfo->mFileDataInQueue = false;
-            
-            // unless the data formats are the same, we need a new queue
-            if (!FormatIsEqual(inFileInfo->mFileFormat, inNextFileInfo->mFileFormat))
-                return kQueueState_NeedNewQueue;
-            
-            // if going from a load-at-once file to streaming or vice versa, we need new buffers
-            if (inFileInfo->mLoadAtOnce != inNextFileInfo->mLoadAtOnce)
-                return kQueueState_NeedNewBuffers;
-            
-            // if the next file is smaller than the current, we just need to resize
-            if (inNextFileInfo->mLoadAtOnce)
-                return (inFileInfo->mFileDataSize >= inNextFileInfo->mFileDataSize) ? kQueueState_ResizeBuffer : kQueueState_NeedNewBuffers;
-            
-            return kQueueState_NeedNewCookie;
-        }
-        
-        static void QueueCallback(	void *					inUserData,
-                                  AudioQueueRef			inAQ,
-                                  AudioQueueBufferRef		inCompleteAQBuffer) 
-        {
-            // dispose of the buffer if no longer in use
-            OSStatus result = noErr;
-            BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData;
-            if (DisposeBuffer(inAQ, THIS->mBuffersToDispose, inCompleteAQBuffer))
-                return;
-            UInt32 nPackets = 0;
-            //-Mat 
-            if (CurFileInfo->mIsPlaying == false)
-            {
-                result = AudioQueueStop(inAQ, false);
-                AssertNoError("Error stopping queue", end);
-                return;
-            }
-            // loop the current buffer if the following:
-            // 1. file was loaded into the buffer previously
-            // 2. only one file in the queue
-            // 3. we have not been told to stop at playlist completion
-            if ((CurFileInfo->mFileDataInQueue) && (THIS->mBGFileInfo.size() == 1) && (!THIS->mStopAtEnd))
-                nPackets = THIS->GetNumPacketsToRead(CurFileInfo);
-            
-            else
-            {
-                UInt32 numBytes;
-                while (nPackets == 0)
-                {
-                    // if loadAtOnce, get all packets in the file, otherwise ~.5 seconds of data
-                    nPackets = THIS->GetNumPacketsToRead(CurFileInfo);					
-                    result = AudioFileReadPackets(CurFileInfo->mAFID, false, &numBytes, THIS->mPacketDescs, THIS->mCurrentPacket, &nPackets, 
-                                                  inCompleteAQBuffer->mAudioData);
-                    AssertNoError("Error reading file data", end);
-                    
-                    inCompleteAQBuffer->mAudioDataByteSize = numBytes;	
-                    
-                    if (nPackets == 0) // no packets were read, this file has ended.
-                    {
-                        if (CurFileInfo->mLoadAtOnce)
-                            CurFileInfo->mFileDataInQueue = true;
-                        
-                        THIS->mCurrentPacket = 0;
-                        UInt32 theNextFileIndex = (THIS->mCurrentFileIndex < THIS->mBGFileInfo.size()-1) ? THIS->mCurrentFileIndex+1 : 0;
-                        
-                        // we have gone through the playlist. if mStopAtEnd, stop the queue here
-                        if (theNextFileIndex == 0 && THIS->mStopAtEnd)
-                        {
-                            result = AudioQueueStop(inAQ, false);
-                            AssertNoError("Error stopping queue", end);
-                            return;
-                        }					
-                        SInt8 theQueueState = GetQueueStateForNextBuffer(CurFileInfo, THIS->mBGFileInfo[theNextFileIndex]);
-                        if (theNextFileIndex != THIS->mCurrentFileIndex)
-                        {
-                            // if were are not looping the same file. Close the old one and open the new
-                            result = AudioFileClose(CurFileInfo->mAFID);
-                            AssertNoError("Error closing file", end);
-                            THIS->mCurrentFileIndex = theNextFileIndex;
-                            
-                            result = LoadFileDataInfo(CurFileInfo->mFilePath, CurFileInfo->mAFID, CurFileInfo->mFileFormat, CurFileInfo->mFileDataSize);
-                            AssertNoError("Error opening file", end);
-                        }
-                        
-                        switch (theQueueState) 
-                        {							
-                                // if we need to resize the buffer, set the buffer's audio data size to the new file's size
-                                // we will also need to get the new file cookie
-                            case kQueueState_ResizeBuffer:
-                                inCompleteAQBuffer->mAudioDataByteSize = CurFileInfo->mFileDataSize;							
-                                // if the data format is the same but we just need a new cookie, attach a new cookie
-                            case kQueueState_NeedNewCookie:
-                                result = AttachNewCookie(inAQ, CurFileInfo);
-                                AssertNoError("Error attaching new file cookie data to queue", end);
-                                break;
-                                
-                                // we can keep the same queue, but not the same buffer(s)
-                            case kQueueState_NeedNewBuffers:
-                                THIS->mBuffersToDispose.push_back(inCompleteAQBuffer);
-                                THIS->SetupBuffers(CurFileInfo);
-                                break;
-                                
-                                // if the data formats are not the same, we need to dispose the current queue and create a new one
-                            case kQueueState_NeedNewQueue:
-                                THIS->mMakeNewQueueWhenStopped = true;
-                                result = AudioQueueStop(inAQ, false);
-                                AssertNoError("Error stopping queue", end);
-                                return;
-                                
-                            default:
-                                break;
-                        }
-                    }
-                }
-            }
-            result = AudioQueueEnqueueBuffer(inAQ, inCompleteAQBuffer, (THIS->mPacketDescs ? nPackets : 0), THIS->mPacketDescs);
-            if(result != noErr) {
-                int a = 0;
-                a++;
-            }
-            AssertNoError("Error enqueuing new buffer", end);
-            if (CurFileInfo->mLoadAtOnce)
-                CurFileInfo->mFileDataInQueue = true;
-            
-            THIS->mCurrentPacket += nPackets;
-            
-        end:
-            return;
-        }
-        
-        OSStatus SetupQueue(BG_FileInfo *inFileInfo)
-        {
-            UInt32 size = 0;
-            OSStatus result = AudioQueueNewOutput(&inFileInfo->mFileFormat, QueueCallback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &mQueue);
-            AssertNoError("Error creating queue", end);
-            
-            // (2) If the file has a cookie, we should get it and set it on the AQ
-            size = sizeof(UInt32);
-            result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL);
-            
-            if (!result && size) {
-                char* cookie = new char [size];		
-                result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie);
-                AssertNoError("Error getting magic cookie", end);
-                result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_MagicCookie, cookie, size);
-                delete [] cookie;
-                AssertNoError("Error setting magic cookie", end);
-            }
-            
-            // channel layout
-            OSStatus err = AudioFileGetPropertyInfo(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, NULL);
-            if (err == noErr && size > 0) {
-                AudioChannelLayout *acl = (AudioChannelLayout *)malloc(size);
-                result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, acl);
-                AssertNoError("Error getting channel layout from file", end);
-                result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_ChannelLayout, acl, size);
-                free(acl);
-                AssertNoError("Error setting channel layout on queue", end);
-            }
-            
-            // add a notification proc for when the queue stops
-            result = AudioQueueAddPropertyListener(mQueue, kAudioQueueProperty_IsRunning, QueueStoppedProc, this);
-            AssertNoError("Error adding isRunning property listener to queue", end);
-            
-            // we need to reset this variable so that if the queue is stopped mid buffer we don't dispose it 
-            mMakeNewQueueWhenStopped = false;
-            
-            // volume
-            result = SetVolume(mVolume);
-            
-        end:
-            return result;
-        }
-        
-        OSStatus SetupBuffers(BG_FileInfo *inFileInfo)
-        {
-            int numBuffersToQueue = kNumberBuffers;
-            UInt32 maxPacketSize;
-            UInt32 size = sizeof(maxPacketSize);
-            // we need to calculate how many packets we read at a time, and how big a buffer we need
-            // we base this on the size of the packets in the file and an approximate duration for each buffer
-            
-            // first check to see what the max size of a packet is - if it is bigger
-            // than our allocation default size, that needs to become larger
-            OSStatus result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize);
-            AssertNoError("Error getting packet upper bound size", end);
-            bool isFormatVBR = (inFileInfo->mFileFormat.mBytesPerPacket == 0 || inFileInfo->mFileFormat.mFramesPerPacket == 0);
-            
-            CalculateBytesForTime(inFileInfo->mFileFormat, maxPacketSize, 0.5, &mBufferByteSize, &mNumPacketsToRead);
-            
-            // if the file is smaller than the capacity of all the buffer queues, always load it at once
-            if ((mBufferByteSize * numBuffersToQueue) > inFileInfo->mFileDataSize)
-                inFileInfo->mLoadAtOnce = true;
-            
-            if (inFileInfo->mLoadAtOnce)
-            {
-                UInt64 theFileNumPackets;
-                size = sizeof(UInt64);
-                result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyAudioDataPacketCount, &size, &theFileNumPackets);
-                AssertNoError("Error getting packet count for file", end);
-                
-                mNumPacketsToRead = (UInt32)theFileNumPackets;
-                mBufferByteSize = inFileInfo->mFileDataSize;
-                numBuffersToQueue = 1;
-            }	
-            else
-            {
-                mNumPacketsToRead = mBufferByteSize / maxPacketSize;
-            }
-            
-            if (isFormatVBR)
-                mPacketDescs = new AudioStreamPacketDescription [mNumPacketsToRead];
-            else
-                mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM)	
-            
-            // allocate the queue's buffers
-            for (int i = 0; i < numBuffersToQueue; ++i) 
-            {
-                result = AudioQueueAllocateBuffer(mQueue, mBufferByteSize, &mBuffers[i]);
-                AssertNoError("Error allocating buffer for queue", end);
-                QueueCallback (this, mQueue, mBuffers[i]);
-                if (inFileInfo->mLoadAtOnce)
-                    inFileInfo->mFileDataInQueue = true;
-            }
-            
-        end:
-            return result;
-        }
-        
-        OSStatus LoadTrack(const char* inFilePath, Boolean inAddToQueue, Boolean inLoadAtOnce)
-        {
-            BG_FileInfo *fileInfo = new BG_FileInfo;
-            fileInfo->mFilePath = inFilePath;
-            OSStatus result = LoadFileDataInfo(fileInfo->mFilePath, fileInfo->mAFID, fileInfo->mFileFormat, fileInfo->mFileDataSize);
-            AssertNoError("Error getting file data info", fail);
-            fileInfo->mLoadAtOnce = inLoadAtOnce;
-            fileInfo->mFileDataInQueue = false;
-            // if not adding to the queue, clear the current file vector
-            if (!inAddToQueue)
-                mBGFileInfo.clear();
-            
-            fileInfo->mIsPlaying = true;
-            mBGFileInfo.push_back(fileInfo);
-            
-            // setup the queue if this is the first (or only) file
-            if (mBGFileInfo.size() == 1)
-            {
-                result = SetupQueue(fileInfo);
-                AssertNoError("Error setting up queue", fail);
-                result = SetupBuffers(fileInfo);
-                AssertNoError("Error setting up queue buffers", fail);					
-            }
-            // if this is just part of the playlist, close the file for now
-            else
-            {
-                result = AudioFileClose(fileInfo->mAFID);
-                AssertNoError("Error closing file", fail);
-            }	
-            return result;
-            
-        fail:
-            if (fileInfo)
-                delete fileInfo;
-            return result;
-        }
-        
-        OSStatus UpdateGain()
-        {
-            return SetVolume(mVolume);
-        }
-        
-        OSStatus SetVolume(Float32 inVolume)
-        {
-            mVolume = inVolume;
-            return AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, mVolume * gMasterVolumeGain);
-        }
-        
-        OSStatus Start()
-        {
-            OSStatus result = AudioQueuePrime(mQueue, 1, NULL);	
-            if (result)
-            {
-                printf("Error priming queue");
-                return result;
-            }
-            //-Mat set mIsPlaying flag
-            mBGFileInfo.back()->mIsPlaying = true;
-            return AudioQueueStart(mQueue, NULL);
-        }
-        
-        OSStatus Stop(Boolean inStopAtEnd)
-        {
-            if (inStopAtEnd)
-            {
-                mStopAtEnd = true;
-                return noErr;
-            }
-            else {
-                mBGFileInfo.back()->mIsPlaying = false;
-                return AudioQueueStop(mQueue, true);
-            }
-        }
-        
-    private:
-        AudioQueueRef						mQueue;
-        AudioQueueBufferRef					mBuffers[kNumberBuffers];
-        UInt32								mBufferByteSize;
-        SInt64								mCurrentPacket;
-        UInt32								mNumPacketsToRead;
-        Float32								mVolume;
-        AudioStreamPacketDescription *		mPacketDescs;
-        std::vector<BG_FileInfo*>			mBGFileInfo;
-        UInt32								mCurrentFileIndex;
-        Boolean								mMakeNewQueueWhenStopped;
-        Boolean								mStopAtEnd;
-        std::vector<AudioQueueBufferRef>	mBuffersToDispose;
-    };
-
-#pragma mark ***** SoundEngineEffect *****
-//==================================================================================================
-//	SoundEngineEffect class
-//==================================================================================================
-class SoundEngineEffect
-    {
-    public:	
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        SoundEngineEffect(const char* inLoopPath, const char* inAttackPath, const char* inDecayPath, Boolean inDoLoop) 
-        :	mSourceID(0),
-        mAttackBufferID(0),
-        mLoopBufferID(0),
-        mDecayBufferID(0),
-        mLoopPath(inLoopPath),
-        mAttackPath(inAttackPath),
-        mDecayPath(inDecayPath),
-        mLoopData(NULL),
-        mAttackData(NULL),
-        mDecayData(NULL),
-        mLoopDataSize(0),
-        mAttackDataSize(0),
-        mDecayDataSize(0),
-        mIsLoopingEffect(inDoLoop),
-        mPlayThread(NULL),
-        mPlayThreadState(kPlayThreadState_Loop) 
-        { 
-            
-            alGenSources(1, &mSourceID); 
-            
-        }
-        
-        ~SoundEngineEffect()
-        {
-            alDeleteSources(1, &mSourceID);
-            
-            if (mLoopData)
-                free(mLoopData);
-            if (mAttackData)
-                free(mAttackData);
-            if (mDecayData)
-                free(mDecayData);
-        }
-        
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        // Accessors
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        UInt32	GetEffectID() { return mSourceID; }
-        UInt32	GetPlayThreadState() { return mPlayThreadState; }
-        Boolean	HasAttackBuffer() { return mAttackBufferID != 0; }
-        
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        // Helper Functions
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        ALenum GetALFormat(AudioStreamBasicDescription inFileFormat)
-        {
-            if (inFileFormat.mFormatID != kAudioFormatLinearPCM)
-                return kSoundEngineErrInvalidFileFormat;
-            
-            if ((inFileFormat.mChannelsPerFrame > 2) || (inFileFormat.mChannelsPerFrame < 1))
-                return kSoundEngineErrInvalidFileFormat;
-            
-            if(inFileFormat.mBitsPerChannel == 8)
-                return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO8 : AL_FORMAT_STEREO8;
-            else if(inFileFormat.mBitsPerChannel == 16)
-                return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
-            
-            return kSoundEngineErrInvalidFileFormat;
-        }
-        
-        OSStatus LoadFileData(const char *inFilePath, void* &outData, UInt32 &outDataSize, ALuint &outBufferID)
-        {
-            AudioFileID theAFID = 0;
-            OSStatus result = noErr;
-            UInt64 theFileSize = 0;
-            AudioStreamBasicDescription theFileFormat;
-            
-            result = LoadFileDataInfo(inFilePath, theAFID, theFileFormat, theFileSize);
-            outDataSize = (UInt32)theFileSize;
-            AssertNoError("Error loading file info", fail)
-            
-            outData = malloc(outDataSize);
-            
-            result = AudioFileReadBytes(theAFID, false, 0, &outDataSize, outData);
-            AssertNoError("Error reading file data", fail)
-            
-            if (!TestAudioFormatNativeEndian(theFileFormat) && (theFileFormat.mBitsPerChannel > 8)) 
-                return kSoundEngineErrInvalidFileFormat;
-            
-            alGenBuffers(1, &outBufferID);
-            AssertNoOALError("Error generating buffer\n", fail);
-            
-            alBufferDataStaticProc(outBufferID, GetALFormat(theFileFormat), outData, outDataSize, theFileFormat.mSampleRate);
-            AssertNoOALError("Error attaching data to buffer\n", fail);
-            
-            AudioFileClose(theAFID);
-            return result;
-            
-        fail:			
-            if (theAFID)
-                AudioFileClose(theAFID);
-            if (outData)
-            {
-                free(outData);
-                outData = NULL;
-            }
-            return result;
-        }
-        
-        OSStatus AttachFilesToSource()
-        {
-            OSStatus result = AL_NO_ERROR;			
-            // first check for the attack file. That will be first in the queue if present
-            if (mAttackPath)
-            {
-                result = LoadFileData(mAttackPath, mAttackData, mAttackDataSize, mAttackBufferID);
-                AssertNoError("Error loading attack file info", end)
-            }
-            
-            result = LoadFileData(mLoopPath, mLoopData, mLoopDataSize, mLoopBufferID);
-            AssertNoError("Error loading looping file info", end)
-            
-            // if one-shot effect, attach the buffer to the source now
-            if (!mIsLoopingEffect)
-            {
-                alSourcei(mSourceID, AL_BUFFER, mLoopBufferID);
-                AssertNoOALError("Error attaching file data to effect", end)
-            }
-            
-            if (mDecayPath)
-            {
-                result = LoadFileData(mDecayPath, mDecayData, mDecayDataSize, mDecayBufferID);
-                AssertNoError("Error loading decay file info", end)
-            }
-        end:
-            return result;
-        }
-        
-        OSStatus ClearSourceBuffers()
-        {
-            OSStatus result = AL_NO_ERROR;
-            ALint numQueuedBuffers = 0;
-            ALuint *bufferIDs = (ALuint*)malloc(numQueuedBuffers * sizeof(ALint));
-            alGetSourcei(mSourceID, AL_BUFFERS_QUEUED, &numQueuedBuffers);
-            AssertNoOALError("Error getting OpenAL queued buffer size", end)
-            
-            alSourceUnqueueBuffers(mSourceID, numQueuedBuffers, bufferIDs);
-            AssertNoOALError("Error unqueueing buffers from source", end)
-            
-        end:
-            free(bufferIDs);
-            return result;
-        }
-        
-        static void* PlaybackProc(void *args)
-        {
-            OSStatus result = AL_NO_ERROR;
-            SoundEngineEffect *THIS = (SoundEngineEffect*)args;
-            
-            alSourcePlay(THIS->GetEffectID());
-            AssertNoOALError("Error starting effect playback", end)
-            
-            // if attack buffer is present, wait until it has completed, then turn looping on
-            if (THIS->HasAttackBuffer())
-            {
-                ALint numBuffersProcessed = 0;						
-                while (numBuffersProcessed < 1)
-                {
-                    alGetSourcei(THIS->GetEffectID(), AL_BUFFERS_PROCESSED, &numBuffersProcessed);
-                    AssertNoOALError("Error getting processed buffer number", end)
-                }
-                
-                ALuint tmpBuffer = 0;
-                alSourceUnqueueBuffers(THIS->GetEffectID(), 1, &tmpBuffer);
-                AssertNoOALError("Error unqueueing buffers from source", end)
-            }
-            // now that we have processed the attack buffer, loop the main one
-            THIS->SetLooping(true);
-            
-        end:	
-            return NULL;
-        }
-        
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        // Effect management
-        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-        OSStatus Start()
-        {
-            OSStatus result = AL_NO_ERROR;				
-            alSourceStop(mSourceID);
-            AssertNoOALError("Error stopping source", end)
-            
-            if (!mIsLoopingEffect)
-            {
-                // if we are just playing one-short effects, start playback here
-                alSourcePlay(mSourceID);
-                return alGetError();
-            }
-            // for loops we need to spawn a new thread					
-            mPlayThread = new OpenALThread(PlaybackProc, (void*)this);
-            // we want this to delete upon thread completion
-            mPlayThreadState = kPlayThreadState_Loop;
-            // clean up remnants from any previous playback of the source
-            result = ClearSourceBuffers();
-            AssertNoError("Error clearing buffers", end)
-            
-            // if the effect has an attack sample, queue this first
-            if (HasAttackBuffer())
-            {
-                alSourceQueueBuffers(mSourceID, 1, &mAttackBufferID);
-                AssertNoOALError("Error queueing buffers for attack", end)
-                // turn on looping after the attack buffer has been processed
-                SetLooping(false);
-            }
-            
-            alSourceQueueBuffers(mSourceID, 1, &mLoopBufferID);
-            AssertNoOALError("Error queueing looping buffer", end)
-            mPlayThread->Start();
-        end:			
-            return result;
-        }
-        
-        OSStatus StartDecay()
-        {
-            // turn off looping, and queue the decay buffer
-            OSStatus result = AL_NO_ERROR;
-            alSourcei(mSourceID, AL_LOOPING, 0);
-            AssertNoOALError("Error turning off looping", end)
-            alSourceQueueBuffers(mSourceID, 1, &mDecayBufferID);
-            AssertNoOALError("Error queueing decay file", end)
-        end:
-            return result;
-        }
-        
-        OSStatus Stop(Boolean inDoDecay)
-        {
-            OSStatus result = AL_NO_ERROR;
-            // for non looped effects and loops with no decay sample
-            if ((mDecayBufferID == 0) || !inDoDecay)
-            {
-                // if no decay to play, just stop the source
-                alSourceStop(mSourceID);
-                AssertNoOALError("Error stopping source", end)
-            }
-            else
-                return StartDecay();
-        end:
-            return result;
-        }
-        
-        OSStatus SetPitch(Float32 inValue)
-        {
-            alSourcef(mSourceID, AL_PITCH, inValue);
-            return alGetError();
-        }
-        
-        OSStatus SetLooping(Boolean inDoLoop)
-        {
-            ALint doLoop = inDoLoop ? 1 : 0;
-            alSourcei(mSourceID, AL_LOOPING, doLoop);
-            return alGetError();
-        }
-        
-        OSStatus SetPosition(Float32 inX, Float32 inY, Float32 inZ)
-        {
-            alSource3f(mSourceID, AL_POSITION, inX, inY, inZ);
-            return alGetError();
-        }
-        
-        OSStatus SetMaxDistance(Float32 inValue)
-        {
-            alSourcef(mSourceID, AL_MAX_DISTANCE, inValue);
-            return alGetError();
-        }
-        
-        OSStatus SetReferenceDistance(Float32 inValue)
-        {
-            alSourcef(mSourceID, AL_REFERENCE_DISTANCE, inValue);
-            return alGetError();
-        }
-        
-        OSStatus SetLevel(Float32 inValue)
-        {
-            alSourcef(mSourceID, AL_GAIN, inValue * gMasterVolumeGain);
-            return alGetError();
-        }
-        
-        enum {
-            kPlayThreadState_Loop	= 0,
-            kPlayThreadState_Decay	= 1,
-            kPlayThreadState_End	= 2
-        };
-        
-    private:
-        ALuint					mSourceID;
-        ALuint					mAttackBufferID;
-        ALuint					mLoopBufferID;
-        ALuint					mDecayBufferID;		
-        UInt32					mNumberBuffers;
-        const char*				mLoopPath;
-        const char*				mAttackPath;
-        const char*				mDecayPath;
-        void*					mLoopData;
-        void*					mAttackData;
-        void*					mDecayData;
-        UInt32					mLoopDataSize;
-        UInt32					mAttackDataSize;
-        UInt32					mDecayDataSize;
-        Boolean					mIsLoopingEffect;
-        OpenALThread*			mPlayThread;
-        UInt32					mPlayThreadState;
-    };
-
-#pragma mark ***** SoundEngineEffectMap *****
-//==================================================================================================
-//	SoundEngineEffectMap class
-//==================================================================================================
-class SoundEngineEffectMap 
-: std::multimap<UInt32, SoundEngineEffect*, std::less<ALuint> > 
-{
-public:
-    // add a new context to the map
-    void Add (const	ALuint	inEffectToken, SoundEngineEffect **inEffect)
-    {
-        iterator	it = upper_bound(inEffectToken);
-        insert(it, value_type (inEffectToken, *inEffect));
-    }
-    
-    SoundEngineEffect* Get(ALuint	inEffectToken) 
-    {
-        iterator	it = find(inEffectToken);
-        if (it != end())
-            return ((*it).second);
-        return (NULL);
-    }
-    
-    void Remove (const	ALuint	inSourceToken) {
-        iterator 	it = find(inSourceToken);
-        if (it != end())
-            erase(it);
-    }
-    
-    SoundEngineEffect* GetEffectByIndex(UInt32	inIndex) {
-        iterator	it = begin();
-        
-        for (UInt32 i = 0; i < inIndex; i++) {
-            if (it != end())
-                ++it;
-            else
-                i = inIndex;
-        }
-        
-        if (it != end())
-            return ((*it).second);		
-        return (NULL);
-    }
-    
-    iterator GetIterator() { return begin(); }
-    
-    UInt32 Size () const { return size(); }
-    bool Empty () const { return empty(); }
-};
-
-#pragma mark ***** OpenALObject *****
-//==================================================================================================
-//	OpenALObject class
-//==================================================================================================
-class OpenALObject
-    {	
-    public:	
-        OpenALObject(Float32 inMixerOutputRate)
-        :	mOutputRate(inMixerOutputRate),
-        mGain(1.0),
-        mContext(NULL),
-        mDevice(NULL),
-        mEffectsMap(NULL) 
-        {
-            mEffectsMap = new SoundEngineEffectMap();
-        }
-        
-        ~OpenALObject() { Teardown(); }
-        
-        OSStatus Initialize()
-        {
-            OSStatus result = noErr;
-            mDevice = alcOpenDevice(NULL);
-            
-            ALenum err = alGetError();			
-            int mRequestSources = 16;
-            static ALuint                 mSource[16];
-            
-            
-            AssertNoOALError("Error opening output device", end)
-            if(mDevice == NULL) { return kSoundEngineErrDeviceNotFound; }
-            
-            // if a mixer output rate was specified, set it here
-            // must be done before the alcCreateContext() call
-            if (mOutputRate)
-                alcMacOSXMixerOutputRateProc(mOutputRate);
-            
-            // Create an OpenAL Context
-            mContext = alcCreateContext(mDevice, NULL);
-            AssertNoOALError("Error creating OpenAL context", end)
-            
-            alcMakeContextCurrent(mContext);
-            AssertNoOALError("Error setting current OpenAL context", end)
-            
-            
-            //we will get a a source as we play it
-            while(true)
-            {
-                alGenSources(1, &mSource[0]);
-                err = alGetError();
-                if (err == AL_NO_ERROR)
-                    break;
-                
-                mRequestSources--;
-                
-                if (mRequestSources == 0)
-                {
-                    return (false);
-                }
-            }
-            
-            
-            
-            
-        end:
-            return result;
-        }
-        
-        void Teardown()
-        {
-            if (mEffectsMap) 
-            {
-                for (UInt32  i = 0; i < mEffectsMap->Size(); i++)
-                {
-                    SoundEngineEffect	*theEffect = mEffectsMap->GetEffectByIndex(0);
-                    if (theEffect)
-                    {
-                        mEffectsMap->Remove(theEffect->GetEffectID());
-                        delete theEffect;
-                    }
-                }
-                delete mEffectsMap;
-            }
-            
-            if (mContext) alcDestroyContext(mContext);
-            
-            if (mDevice) alcCloseDevice(mDevice);
-        }
-        
-        OSStatus SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ)
-        {
-            alListener3f(AL_POSITION, inX, inY, inZ);
-            return alGetError();
-        }
-        
-        OSStatus SetListenerGain(Float32 inValue)
-        {
-            alListenerf(AL_GAIN, inValue);
-            return alGetError();
-        }
-        
-        OSStatus SetMaxDistance(Float32 inValue)
-        {
-            OSStatus result = 0;
-            for (UInt32 i=0; i < mEffectsMap->Size(); i++)
-            {
-                SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
-                if ((result = theEffect->SetMaxDistance(inValue)) != AL_NO_ERROR)
-                    return result;
-            }
-            return result;			
-        }
-        
-        OSStatus SetReferenceDistance(Float32 inValue)
-        {
-            OSStatus result = 0;
-            for (UInt32 i=0; i < mEffectsMap->Size(); i++)
-            {
-                SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
-                if ((result = theEffect->SetReferenceDistance(inValue)) != AL_NO_ERROR)
-                    return result;
-            }
-            return result;	
-        }
-        
-        OSStatus SetEffectsVolume(Float32 inValue)
-        {
-            OSStatus result = 0;
-            for (UInt32 i=0; i < mEffectsMap->Size(); i++)
-            {
-                SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i);
-                if ((result = theEffect->SetLevel(inValue)) != AL_NO_ERROR)
-                    return result;
-            }
-            return result;	
-        }
-        
-        OSStatus UpdateGain()
-        {
-            return SetEffectsVolume(mGain);
-        }
-        
-        OSStatus LoadEffect(const char *inFilePath, UInt32 *outEffectID)
-        {
-            SoundEngineEffect *theEffect = new SoundEngineEffect(inFilePath, NULL, NULL, false);
-            OSStatus result = theEffect->AttachFilesToSource();
-            if (result == noErr)
-            {
-                *outEffectID = theEffect->GetEffectID();
-                mEffectsMap->Add(*outEffectID, &theEffect);
-            }
-            return result;
-        }
-        
-        OSStatus LoadLoopingEffect(const char *inLoopFilePath, const char *inAttackFilePath, const char *inDecayFilePath, UInt32 *outEffectID)
-        {
-            SoundEngineEffect *theEffect = new SoundEngineEffect(inLoopFilePath, inAttackFilePath, inDecayFilePath, true);
-            OSStatus result = theEffect->AttachFilesToSource();
-            if (result == noErr)
-            {
-                *outEffectID = theEffect->GetEffectID();
-                mEffectsMap->Add(*outEffectID, &theEffect);
-            }
-            return result;
-        }
-        
-        OSStatus UnloadEffect(UInt32 inEffectID)
-        {
-            mEffectsMap->Remove(inEffectID);
-            return 0;
-        }
-        
-        OSStatus StartEffect(UInt32 inEffectID)
-        {
-            SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
-            return (theEffect) ? theEffect->Start() : kSoundEngineErrInvalidID;
-        }
-        
-        OSStatus StopEffect(UInt32 inEffectID, Boolean inDoDecay)
-        {
-            SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
-            return (theEffect) ? theEffect->Stop(inDoDecay) : kSoundEngineErrInvalidID;
-        }
-        
-        OSStatus SetEffectPitch(UInt32 inEffectID, Float32 inValue)
-        {
-            SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
-            return (theEffect) ? theEffect->SetPitch(inValue) : kSoundEngineErrInvalidID;			
-        }
-        
-        OSStatus SetEffectVolume(UInt32 inEffectID, Float32 inValue)
-        {
-            SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
-            return (theEffect) ?  theEffect->SetLevel(inValue) : kSoundEngineErrInvalidID;
-        }
-        
-        OSStatus	SetEffectPosition(UInt32 inEffectID, Float32 inX, Float32 inY, Float32 inZ)	
-        {
-            SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID);
-            return (theEffect) ? theEffect->SetPosition(inX, inY, inZ) : kSoundEngineErrInvalidID;
-        }
-        
-    private:
-        Float32									mOutputRate;
-        Float32									mGain;
-        ALCcontext*								mContext;
-        ALCdevice*								mDevice;
-        SoundEngineEffectMap*					mEffectsMap;
-    };
-
-#pragma mark ***** API *****
-//==================================================================================================
-//	Sound Engine
-//==================================================================================================
-
-extern "C"
-OSStatus  SoundEngine_Initialize(Float32 inMixerOutputRate)
-{
-    if (sOpenALObject)
-        delete sOpenALObject;
-    
-    if (sBackgroundTrackMgr)
-        delete sBackgroundTrackMgr;
-    
-    AudioSessionInitialize(nil, nil, nil, nil);
-    
-    UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
-    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
-    
-    AudioSessionSetActive(true);		
-    
-    sOpenALObject = new OpenALObject(inMixerOutputRate);	
-    sBackgroundTrackMgr = new BackgroundTrackMgr();
-    
-    return sOpenALObject->Initialize();
-    
-}
-
-extern "C"
-OSStatus  SoundEngine_Teardown()
-{
-    if (sOpenALObject)
-    {
-        delete sOpenALObject;
-        sOpenALObject = NULL;
-    }
-    
-    if (sBackgroundTrackMgr)
-    {
-        delete sBackgroundTrackMgr;
-        sBackgroundTrackMgr = NULL;	
-    }
-    
-    return 0; 
-}
-
-extern "C"
-OSStatus  SoundEngine_SetMasterVolume(Float32 inValue)
-{
-    OSStatus result = noErr;
-    gMasterVolumeGain = inValue;
-    if (sBackgroundTrackMgr)
-        result = sBackgroundTrackMgr->UpdateGain();
-    
-    if (result) return result;
-    
-    if (sOpenALObject) 
-        return sOpenALObject->UpdateGain();
-    
-    return result;
-}
-
-extern "C"
-OSStatus  SoundEngine_SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ)
-{	
-    return (sOpenALObject) ? sOpenALObject->SetListenerPosition(inX, inY, inZ) : kSoundEngineErrUnitialized;
-}
-
-extern "C"
-OSStatus  SoundEngine_SetListenerGain(Float32 inValue)
-{
-    return (sOpenALObject) ? sOpenALObject->SetListenerGain(inValue) : kSoundEngineErrUnitialized;
-}
-
-extern "C"
-OSStatus  SoundEngine_LoadBackgroundMusicTrack(const char* inPath, Boolean inAddToQueue, Boolean inLoadAtOnce)
-{
-    if (sBackgroundTrackMgr == NULL)
-        sBackgroundTrackMgr = new BackgroundTrackMgr();
-    return sBackgroundTrackMgr->LoadTrack(inPath, inAddToQueue, inLoadAtOnce);
-}
-
-extern "C"
-OSStatus  SoundEngine_UnloadBackgroundMusicTrack()
-{
-    if (sBackgroundTrackMgr)
-    {
-        delete sBackgroundTrackMgr;
-        sBackgroundTrackMgr = NULL;
-    }
-    
-    return 0;
-}
-
-extern "C"
-OSStatus  SoundEngine_StartBackgroundMusic()
-{
-    return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->Start() : kSoundEngineErrUnitialized;
-}
-
-extern "C"
-OSStatus  SoundEngine_StopBackgroundMusic(Boolean stopAtEnd)
-{
-    return (sBackgroundTrackMgr) ?  sBackgroundTrackMgr->Stop(stopAtEnd) : kSoundEngineErrUnitialized;
-}
-
-extern "C"
-OSStatus  SoundEngine_SetBackgroundMusicVolume(Float32 inValue)
-{
-    return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->SetVolume(inValue) : kSoundEngineErrUnitialized;
-}
-
-extern "C"
-bool LoadSoundFile(const char *inFilePath, UInt32 *outEffectID)
-{
-    SoundEngineEffect *theEffect = new SoundEngineEffect(inFilePath, NULL, NULL, false);
-    OSStatus result = theEffect->AttachFilesToSource();
-    if (result == noErr)
-    {
-        //-Mat getEffectID() returns sourceID, but we want the genBuffer ID that was done last (mAttackBufferID), I have no idea
-        //what SourceID is used for, but it's not the sound buffer, anyhow, the buffer after mSourceID is the one we want so +1
-        *outEffectID = theEffect->GetEffectID()+1;
-    }
-    return (result == noErr);
-}
-    
-}//namespace SoundEngine
-*/

+ 0 - 217
engine/source/platformAndroid/SoundEngine.h

@@ -1,217 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2013 GarageGames, LLC
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to
-// deal in the Software without restriction, including without limitation the
-// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-// sell copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-// IN THE SOFTWARE.
-//-----------------------------------------------------------------------------
-
-/*
- ===== IMPORTANT =====
- This is sample code demonstrating API, technology or techniques in development.
- Although this sample code has been reviewed for technical accuracy, it is not
- final. Apple is supplying this information to help you plan for the adoption of
- the technologies and programming interfaces described herein. This information
- is subject to change, and software implemented based on this sample code should
- be tested with final operating system software and final documentation. Newer
- versions of this sample code may be provided with future seeds of the API or
- technology. For information about updates to this and other developer
- documentation, view the New & Updated sidebars in subsequent documentation
- seeds.
- =====================
- File: SoundEngine.h
- Abstract: This C API is a sound engine intended for games and applications that
- want to do more than casual UI sounds playback e.g. background music track,
- multiple sound effects, stereo panning... while ensuring low-latency response at
- the same time.
-
- Version: 1.1
- 
- Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
- ("Apple") in consideration of your agreement to the following terms, and your
- use, installation, modification or redistribution of this Apple software
- constitutes acceptance of these terms.  If you do not agree with these terms,
- please do not use, install, modify or redistribute this Apple software.
- In consideration of your agreement to abide by the following terms, and subject
- to these terms, Apple grants you a personal, non-exclusive license, under
- Apple's copyrights in this original Apple software (the "Apple Software"), to
- use, reproduce, modify and redistribute the Apple Software, with or without
- modifications, in source and/or binary forms; provided that if you redistribute
- the Apple Software in its entirety and without modifications, you must retain
- this notice and the following text and disclaimers in all such redistributions
- of the Apple Software.
- Neither the name, trademarks, service marks or logos of Apple Inc. may be used
- to endorse or promote products derived from the Apple Software without specific
- prior written permission from Apple.  Except as expressly stated in this notice,
- no other rights or licenses, express or implied, are granted by Apple herein,
- including but not limited to any patent rights that may be infringed by your
- derivative works or by other works in which the Apple Software may be
- incorporated.
- 
- The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
-  WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
-  WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-  PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
-  COMBINATION WITH YOUR PRODUCTS.
-  IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
-  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
-  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-  ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
-  DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
-  CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
-  APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-  Copyright (C) 2008 Apple Inc. All Rights Reserved.
-  */
-
-/*============================================================================= =====================
- SoundEngine.h
- =============================================================================== ===================*/
-//TODO: do we need this?
-/*
-#ifndef SOUND_ENGINE_H
-#define SOUND_ENGINE_H
-
-extern"C"
-{
-namespace SoundEngine {
-	
-#include <CoreAudio/CoreAudioTypes.h>
-#include <AudioToolbox/AudioToolbox.h>
-#include <OpenAL/al.h>
-
-//============================================================================= =====================
-//Sound Engine
-//============================================================================= =====================
-	
-
-//	 @enum SoundEngine error codes
-//	 @abstract   These are the error codes returned from the SoundEngine API.
-//	 @constant   kSoundEngineErrUnitialized 	 The SoundEngine has not been initialized. Use SoundEngine_Initialize().
-//	 @constant   kSoundEngineErrInvalidID 	 The specified EffectID was not found. This can occur if the effect has not been loaded, or
-//	 if an unloaded is trying to be accessed.
-//	 @constant   kSoundEngineErrFileNotFound 	 The specified file was not found.
-//	 @constant   kSoundEngineErrInvalidFileFormat 	 The format of the file is invalid. Effect data must be little-endian 8 or 16 bit LPCM.
-//	 @constant   kSoundEngineErrDeviceNotFound 	 The output device was not found.
-
-	
-	enum {
-		kSoundEngineErrUnitialized = 1,
-		kSoundEngineErrInvalidID = 2,
-		kSoundEngineErrFileNotFound = 3,
-		kSoundEngineErrInvalidFileFormat = 4,
-		kSoundEngineErrDeviceNotFound = 5
-	};
-	
-
-//	 @function       SoundEngine_Initialize
-//	 @abstract       Initializes and sets up the sound engine. Calling after a previous initialize will
-//	 reset the state of the SoundEngine, with all previous effects and music tracks
-//	 erased. Note: This is not required, loading an effect or background track will
-//	 initialize as necessary.
-//	 @param          inMixerOutputRate
-//	 & nbsp;          A Float32 that represents the output sample rate of the mixer unit. Setting this to
-//	 0 will use the default rate (the sample rate of the device)
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_Initialize(Float32 inMixerOutputRate);
-	
-//	 @function       SoundEngine_Teardown
-//	 @abstract       Tearsdown the sound engine.
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_Teardown();
-	
-//	 @function       SoundEngine_SetMasterVolume
-//	 @abstract       Sets the overall volume of all sounds coming from the process
-//	 @param          inValue
-//	 & nbsp;          A Float32 that represents the level. The range is between 0.0 and 1.0 (inclusive).
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_SetMasterVolume(Float32 inValue);
-
-//	 @function       SoundEngine_SetListenerPosition
-//	 @abstract       Sets the position of the listener in the 3D space
-//	 @param          inX
-//	 & nbsp;          A Float32 that represents the listener's position along the X axis.
-//	 @param          inY
-//	 & nbsp;          A Float32 that represents the listener's position along the Y axis.
-//	 @param          inZ
-//	 & nbsp;          A Float32 that represents the listener's position along the Z axis.
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ);
-	
-
-//	 @function       SoundEngine_SetListenerGain
-//	 @abstract       Sets the gain of the listener. Must be >= 0.0
-//	 @param          inValue
-//	 & nbsp;          A Float32 that represents the listener's gain
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_SetListenerGain(Float32 inValue);
-	
-//	 @function       SoundEngine_LoadBackgroundMusicTrack
-//	 @abstract       Tells the background music player which file to play
-//	 @param          inPath
-//	 & nbsp;          The absolute path to the file to play.
-//	 @param          inAddToQueue
-//	 & nbsp;          If true, file will be added to the current background music queue. If
-//	 false, queue will be cleared and only loop the specified file.
-//	 @param          inLoadAtOnce
-//	 & nbsp;          If true, file will be loaded completely into memory. If false, data will be
-//	 streamed from the file as needed. For games without large memory pressure and/or
-//	 small background music files, this can save memory access and improve power efficiency
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_LoadBackgroundMusicTrack(const char* inPath, Boolean inAddToQueue, Boolean inLoadAtOnce);
-	
-//	 @function       SoundEngine_UnloadBackgroundMusicTrack
-//	 @abstract       Tells the background music player to release all resources and stop playing.
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_UnloadBackgroundMusicTrack();
-	
-
-//	 @function       SoundEngine_StartBackgroundMusic
-//	 @abstract       Tells the background music player to start playing.
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_StartBackgroundMusic();
-	
-//	 @function       SoundEngine_StopBackgroundMusic
-//	 @abstract       Tells the background music player to stop playing.
-//	 @param          inAddToQueue
-//	 & nbsp;          If true, playback will stop when all tracks have completed. If false, playback
-//	 will stop immediately.
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_StopBackgroundMusic(Boolean inStopAtEnd);
-	
-//	 @function       SoundEngine_SetBackgroundMusicVolume
-//	 @abstract       Sets the volume for the background music player
-//	 @param          inValue
-//	 & nbsp;          A Float32 that represents the level. The range is between 0.0 and 1.0 (inclusive).
-//	 @result         A OSStatus indicating success or failure.
-
-	OSStatus  SoundEngine_SetBackgroundMusicVolume(Float32 inValue);
-	
-	//-Mat for loading caf files, this creates a soundeffect and sets outEffectID to it's alGenBuffer ID
-	bool LoadSoundFile(const char *inFilePath, UInt32 *outEffectID);
-}
-}
-#endif //SOUND_ENGINE_H
-*/

+ 634 - 126
engine/source/platformAndroid/T2DActivity.cpp

@@ -25,9 +25,13 @@
 #include "platformAndroid/AndroidWindow.h"
 #include "platformAndroid/AndroidWindow.h"
 #include "platformAndroid/platformAndroid.h"
 #include "platformAndroid/platformAndroid.h"
 #include "graphics/dgl.h"
 #include "graphics/dgl.h"
+#include "platform/event.h"
+#include "game/gameInterface.h"
 
 
 extern AndroidPlatState platState;
 extern AndroidPlatState platState;
 
 
+T2DActivity activity;
+
 bool keyboardShowing = false;
 bool keyboardShowing = false;
 float keyboardTransition = 1.0f;
 float keyboardTransition = 1.0f;
 bool bSuspended = false;
 bool bSuspended = false;
@@ -36,7 +40,7 @@ double lastSystemTime = 0;
 
 
 #define USE_DEPTH_BUFFER 0
 #define USE_DEPTH_BUFFER 0
 
 
-extern int _AndroidRunTorqueMain();
+extern int _AndroidRunTorqueMain(engine *eng);
 extern bool createMouseMoveEvent(S32 i, S32 x, S32 y, S32 lastX, S32 lastY);
 extern bool createMouseMoveEvent(S32 i, S32 x, S32 y, S32 lastX, S32 lastY);
 extern bool createMouseDownEvent(S32 touchNumber, S32 x, S32 y, U32 numTouches);
 extern bool createMouseDownEvent(S32 touchNumber, S32 x, S32 y, U32 numTouches);
 extern bool createMouseUpEvent(S32 touchNumber, S32 x, S32 y, S32 lastX, S32 lastY, U32 numTouches); //EFM
 extern bool createMouseUpEvent(S32 touchNumber, S32 x, S32 y, S32 lastX, S32 lastY, U32 numTouches); //EFM
@@ -45,18 +49,14 @@ extern void _AndroidGameInnerLoop();
 extern void _AndroidGameResignActive();
 extern void _AndroidGameResignActive();
 extern void _AndroidGameBecomeActive();
 extern void _AndroidGameBecomeActive();
 extern void _AndroidGameWillTerminate();
 extern void _AndroidGameWillTerminate();
-extern S32 _AndroidGameGetOrientation();
 
 
-// Store current orientation for easy access
-extern void _AndroidGameChangeOrientation(S32 newOrientation);
-//TODO: android
-/*
-UIDeviceOrientation currentOrientation;
-*/
+S32 _AndroidGameGetOrientation()
+{
+	return AConfiguration_getOrientation(platState.engine->app->config);
+}
+
 bool _AndroidTorqueFatalError = false;
 bool _AndroidTorqueFatalError = false;
 
 
-//-Mat we should update the accelereometer once per frame
-extern U32  AccelerometerUpdateMS;
 extern void _AndroidGameInnerLoop();
 extern void _AndroidGameInnerLoop();
 
 
 double timeGetTime() {
 double timeGetTime() {
@@ -90,8 +90,7 @@ bool T2DActivity::createFramebuffer() {
 	}
 	}
 	
 	
 	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
 	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
-		//TODO: android
-		//NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
+		adprintf("failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
 		return false;
 		return false;
 	}
 	}
 	
 	
@@ -112,49 +111,249 @@ void T2DActivity::destroyFramebuffer() {
 	}
 	}
 }
 }
 
 
-// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-void T2DActivity::finishGLSetup()
-{
-    //TODO: android
-    //self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
-    
-    //if (!self.context) {
-      //  NSLog(@"Failed to create ES context");
-    //}
-    
-	if( AccelerometerUpdateMS <= 0 ) {
-        //Luma:	This variable needs to be store MS value, not Seconds value
-        AccelerometerUpdateMS = 33; // 33 ms
-	}
-	
-	//[EAGLContext setCurrentContext:self.context];
-	createFramebuffer();
-	
-    platState.multipleTouchesEnabled = true;
-    //[self.view setMultipleTouchEnabled:YES];
-    
-	_AndroidTorqueFatalError = false;
-	if(!_AndroidRunTorqueMain())
-	{
-		_AndroidTorqueFatalError = true;
-		return;
-	}
+void ChangeVolume(bool up) {
+
+    // Attaches the current thread to the JVM.
+    jint lResult;
+    jint lFlags = 0;
+
+    JavaVM* lJavaVM = platState.engine->app->activity->vm;
+    JNIEnv* lJNIEnv = platState.engine->app->activity->env;
+
+    JavaVMAttachArgs lJavaVMAttachArgs;
+    lJavaVMAttachArgs.version = JNI_VERSION_1_6;
+    lJavaVMAttachArgs.name = "NativeThread";
+    lJavaVMAttachArgs.group = NULL;
+
+    lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
+    if (lResult == JNI_ERR) {
+        return;
+    }
+
+    // Retrieves NativeActivity.
+    jobject lNativeActivity = platState.engine->app->activity->clazz;
+    jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
+
+    // Retrieves Context.AUDIO_SERVICE.
+    jclass ClassContext = lJNIEnv->FindClass("android/content/Context");
+    jfieldID FieldAUDIO_SERVICE =lJNIEnv->GetStaticFieldID(ClassContext,"AUDIO_SERVICE", "Ljava/lang/String;");
+    jobject AUDIO_SERVICE = lJNIEnv->GetStaticObjectField(ClassContext, FieldAUDIO_SERVICE);
+
+    // Runs getSystemService(AUDIO_SERVICE)
+    jclass ClassAudioManager = lJNIEnv->FindClass("android/media/AudioManager");
+    jmethodID MethodGetSystemService = lJNIEnv->GetMethodID(ClassNativeActivity, "getSystemService","(Ljava/lang/String;)Ljava/lang/Object;");
+    jobject lAudioManager = lJNIEnv->CallObjectMethod(lNativeActivity, MethodGetSystemService, AUDIO_SERVICE);
+
+    //get AudioManager.STREAM_MUSIC
+    jfieldID FieldSTREAM_MUSIC =lJNIEnv->GetStaticFieldID(ClassAudioManager,"STREAM_MUSIC", "I");
+    jint STREAM_MUSIC = lJNIEnv->GetStaticIntField(ClassAudioManager, FieldSTREAM_MUSIC);
+
+    //get AudioManager.FLAG_SHOW_UI
+    jfieldID FieldFLAG_SHOW_UI =lJNIEnv->GetStaticFieldID(ClassAudioManager,"FLAG_SHOW_UI", "I");
+    jint FLAG_SHOW_UI = lJNIEnv->GetStaticIntField(ClassAudioManager, FieldFLAG_SHOW_UI);
+
+    if (up) {
+    	//get AudioManager.ADJUST_RAISE
+    	jfieldID FieldADJUST_RAISE =lJNIEnv->GetStaticFieldID(ClassAudioManager,"ADJUST_RAISE", "I");
+    	jint ADJUST_RAISE = lJNIEnv->GetStaticIntField(ClassAudioManager, FieldADJUST_RAISE);
+
+    	//audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
+        jmethodID MethodAdjustStreamVolume = lJNIEnv->GetMethodID(ClassAudioManager, "adjustStreamVolume", "(III)V");
+        lJNIEnv->CallVoidMethod(lAudioManager,MethodAdjustStreamVolume, STREAM_MUSIC, ADJUST_RAISE, FLAG_SHOW_UI);
+
+    } else {
+    	//get AudioManager.ADJUST_LOWER
+    	jfieldID FieldADJUST_LOWER =lJNIEnv->GetStaticFieldID(ClassAudioManager,"ADJUST_LOWER", "I");
+    	jint ADJUST_LOWER = lJNIEnv->GetStaticIntField(ClassAudioManager, FieldADJUST_LOWER);
+
+    	//audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
+    	jmethodID MethodAdjustStreamVolume = lJNIEnv->GetMethodID(ClassAudioManager, "adjustStreamVolume", "(III)V");
+    	lJNIEnv->CallVoidMethod(lAudioManager,MethodAdjustStreamVolume, STREAM_MUSIC, ADJUST_LOWER, FLAG_SHOW_UI);
+    }
+
+    // Finished with the JVM.
+    lJavaVM->DetachCurrentThread();
 }
 }
 
 
-void T2DActivity::finishShutdown()
-{
-	//TODO: android
-    // Release any retained subviews of the main view.
-    //if ([EAGLContext currentContext] == self.context) {
-      //  [EAGLContext setCurrentContext:nil];
-    //}
-    
-    //self.context = nil;
+int convertAndroidToWindowsKeyCode(int key) {
+
+	switch(key) {
+	case AKEYCODE_0:
+		return 48;
+	case AKEYCODE_1:
+		return 49;
+	case AKEYCODE_2:
+		return 50;
+	case AKEYCODE_3:
+		return 51;
+	case AKEYCODE_4:
+		return 52;
+	case AKEYCODE_5:
+		return 53;
+	case AKEYCODE_6:
+		return 54;
+	case AKEYCODE_7:
+		return 55;
+	case AKEYCODE_8:
+		return 56;
+	case AKEYCODE_9:
+		return 57;
+	case AKEYCODE_A:
+		return 65;
+	case AKEYCODE_ALT_LEFT:
+		return 0xA4;
+	case AKEYCODE_ALT_RIGHT:
+		return 0xA5;
+	case AKEYCODE_APOSTROPHE:
+		return 39;
+	case AKEYCODE_AT:
+		return 64;
+	case AKEYCODE_B:
+		return 66;
+	case AKEYCODE_BACKSLASH:
+		return 92;
+	case AKEYCODE_C:
+		return 67;
+	//case KEYCODE_CAPS_LOCK:
+	//	return 0x14;
+	case AKEYCODE_COMMA:
+		return 44;
+	case AKEYCODE_D:
+		return 68;
+	case AKEYCODE_DEL:
+		return 8;
+	case AKEYCODE_E:
+		return 69;
+	case AKEYCODE_ENTER:
+		return 13;
+	case AKEYCODE_EQUALS:
+		return 61;
+	//case AKEYCODE_ESCAPE:
+	//	return 0x1B;
+	case AKEYCODE_F:
+		return 70;
+	//case AKEYCODE_F1:
+	//	return 0x70;
+	//case AKEYCODE_F10:
+	//	return 0x79;
+	//case AKEYCODE_F11:
+	//	return 0x7A;
+	//case AKEYCODE_F12:
+	//	return 0x7B;
+	//case AKEYCODE_F2:
+	//	return 0x71;
+	//case AKEYCODE_F3:
+	//	return 0x72;
+	//case AKEYCODE_F4:
+	//	return 0x73;
+	//case AKEYCODE_F5:
+	//	return 0x74;
+	//case AKEYCODE_F6:
+	//	return 0x75;
+	//case AKEYCODE_F7:
+	//	return 0x76;
+	//case AKEYCODE_F8:
+	//	return 0x77;
+	//case AKEYCODE_F9:
+	//	return 0x78;
+	case AKEYCODE_G:
+		return 71;
+	case AKEYCODE_GRAVE:
+		return 96;
+	case AKEYCODE_H:
+		return 72;
+	case AKEYCODE_I:
+		return 73;
+	//case AKEYCODE_INSERT:
+	//	return 0x2D;
+	case AKEYCODE_J:
+		return 74;
+	case AKEYCODE_K:
+		return 75;
+	case AKEYCODE_L:
+		return 76;
+	case AKEYCODE_LEFT_BRACKET:
+		return 91;
+	case AKEYCODE_M:
+		return 77;
+	case AKEYCODE_MINUS:
+		return 45;
+	case AKEYCODE_N:
+		return 78;
+	case AKEYCODE_O:
+		return 79;
+	case AKEYCODE_P:
+		return 80;
+	case AKEYCODE_PAGE_DOWN:
+		return 0x22;
+	case AKEYCODE_PAGE_UP:
+		return 0x21;
+	case AKEYCODE_PERIOD:
+		return 46;
+	case AKEYCODE_PLUS:
+		return 43;
+	case AKEYCODE_POUND:
+		return 35;
+	case AKEYCODE_Q:
+		return 81;
+	case AKEYCODE_R:
+		return 82;
+	case AKEYCODE_RIGHT_BRACKET:
+		return 93;
+	case AKEYCODE_S:
+		return 83;
+	case AKEYCODE_SEMICOLON:
+		return 59;
+	case AKEYCODE_SHIFT_LEFT:
+		return 0xA0;
+	case AKEYCODE_SHIFT_RIGHT:
+		return 0xA1;
+	case AKEYCODE_SLASH:
+		return 47;
+	case AKEYCODE_SPACE:
+		return 32;
+	case AKEYCODE_STAR:
+		return 42;
+	case AKEYCODE_T:
+		return 84;
+	case AKEYCODE_TAB:
+		return 0x09;
+	case AKEYCODE_U:
+		return 85;
+	case AKEYCODE_V:
+		return 86;
+	case AKEYCODE_W:
+		return 87;
+	case AKEYCODE_X:
+		return 88;
+	case AKEYCODE_Y:
+		return 89;
+	case AKEYCODE_Z:
+		return 90;
+	default:
+		return 0;
+	}
+
+	return 0;
+
 }
 }
 
 
-void T2DActivity::update()
-{
-    _AndroidGameInnerLoop();
+
+void androidKeyboardEvent(int keyval, bool make) {
+
+   S32 keyCode = convertAndroidToWindowsKeyCode(keyval);
+
+   InputEvent event;
+   event.deviceInst = 0;
+   event.deviceType = KeyboardDeviceType;
+   event.objType    = SI_KEY;
+   event.objInst    = keyCode;
+   event.action     = make ? SI_MAKE : SI_BREAK;
+   event.modifier   = 0;
+   event.ascii      = keyCode;
+   event.fValue     = make ? 1.0f : 0.0f;
+
+   Game->postEvent(event);
 }
 }
 
 
 Vector<Point2I> rawLastTouches;
 Vector<Point2I> rawLastTouches;
@@ -183,13 +382,12 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
         			rawLastTouches[i].y = point.y;
         			rawLastTouches[i].y = point.y;
         		}
         		}
 
 
-        	    S32 orientation = _AndroidGameGetOrientation();
-        	    //TODO: android
-        	    /* if (UIDeviceOrientationIsPortrait(orientation))
+        	    /*S32 orientation = _AndroidGameGetOrientation();
+        	    if (orientation == ACONFIGURATION_ORIENTATION_PORT)
         	    {
         	    {
         	    	point.y -= _AndroidGetPortraitTouchoffset();
         	    	point.y -= _AndroidGetPortraitTouchoffset();
-        	    }
-        	    */
+        	    }*/
+
         	    createMouseDownEvent(i, point.x, point.y, touchCount);
         	    createMouseDownEvent(i, point.x, point.y, touchCount);
         	}
         	}
 
 
@@ -205,9 +403,8 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
 				point.y = AMotionEvent_getY(event, i);
 				point.y = AMotionEvent_getY(event, i);
 				Point2I prevPoint = rawLastTouches[i];
 				Point2I prevPoint = rawLastTouches[i];
 
 
-				S32 orientation = _AndroidGameGetOrientation();
-				//TODO: android
-				/*if (UIDeviceOrientationIsPortrait(orientation))
+				/*S32 orientation = _AndroidGameGetOrientation();
+				if (orientation == ACONFIGURATION_ORIENTATION_PORT)
 				{
 				{
 					point.y -= _AndroidGetPortraitTouchoffset();
 					point.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
@@ -234,10 +431,8 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
 				point.y = AMotionEvent_getY(event, i);
 				point.y = AMotionEvent_getY(event, i);
 				Point2I prevPoint = rawLastTouches[i];
 				Point2I prevPoint = rawLastTouches[i];
 
 
-				S32 orientation = _AndroidGameGetOrientation();
-				//TODO: android
-				/*
-				if (UIDeviceOrientationIsPortrait(orientation))
+				/*S32 orientation = _AndroidGameGetOrientation();
+				if (orientation == ACONFIGURATION_ORIENTATION_PORT)
 				{
 				{
 					point.y -= _AndroidGetPortraitTouchoffset();
 					point.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
@@ -260,15 +455,13 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
 				point.y = AMotionEvent_getY(event, i);
 				point.y = AMotionEvent_getY(event, i);
 				Point2I prevPoint = rawLastTouches[i];
 				Point2I prevPoint = rawLastTouches[i];
 
 
-				S32 orientation = _AndroidGameGetOrientation();
-				//TODO: android
-				/*
-				if (UIDeviceOrientationIsPortrait(orientation))
+				/*S32 orientation = _AndroidGameGetOrientation();
+				if (orientation == ACONFIGURATION_ORIENTATION_PORT)
 				{
 				{
 					point.y -= _AndroidGetPortraitTouchoffset();
 					point.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
 					prevPoint.y -= _AndroidGetPortraitTouchoffset();
-				}
-				*/
+				}*/
+
 				createMouseUpEvent(i, point.x, point.y, prevPoint.x, prevPoint.y, touchCount);
 				createMouseUpEvent(i, point.x, point.y, prevPoint.x, prevPoint.y, touchCount);
 
 
 				//Luma: Tap support
 				//Luma: Tap support
@@ -294,32 +487,26 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
 			case AKEY_EVENT_ACTION_DOWN:
 			case AKEY_EVENT_ACTION_DOWN:
 
 
 				if (key_val == AKEYCODE_VOLUME_UP) {
 				if (key_val == AKEYCODE_VOLUME_UP) {
-					//TODO: android
-					//ChangeVolume(true);
+					ChangeVolume(true);
 				} else if (key_val == AKEYCODE_VOLUME_DOWN) {
 				} else if (key_val == AKEYCODE_VOLUME_DOWN) {
-					//TODO: android
-					//ChangeVolume(false);
+					ChangeVolume(false);
 				} else if (key_val == AKEYCODE_BACK) {
 				} else if (key_val == AKEYCODE_BACK) {
-					//android back button
+					Con::executef(2, "androidBackButton", Con::getBoolArg(true));
 			    } else {
 			    } else {
-			        //TODO: android
-			    	//convertAndroidToWindowsKeyCode(key_val);
+			    	androidKeyboardEvent(key_val, true);
 			    }
 			    }
 				break;
 				break;
 
 
 			case AKEY_EVENT_ACTION_UP:
 			case AKEY_EVENT_ACTION_UP:
 
 
 				if (key_val == AKEYCODE_VOLUME_UP) {
 				if (key_val == AKEYCODE_VOLUME_UP) {
-					//TODO: android
-					//ChangeVolume(true);
+					ChangeVolume(true);
 				} else if (key_val == AKEYCODE_VOLUME_DOWN) {
 				} else if (key_val == AKEYCODE_VOLUME_DOWN) {
-					//TODO: android
-					//ChangeVolume(false);
+					ChangeVolume(false);
 				} else if (key_val == AKEYCODE_BACK) {
 				} else if (key_val == AKEYCODE_BACK) {
-					//android back button
+					Con::executef(2, "androidBackButton", Con::getBoolArg(false));
 				} else {
 				} else {
-					//TODO: android
-					//convertAndroidToWindowsKeyCode(key_val);
+					androidKeyboardEvent(key_val, false);
 				}
 				}
 				break;
 				break;
 
 
@@ -333,17 +520,17 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
 
 
 int _AndroidGetScreenWidth() {
 int _AndroidGetScreenWidth() {
 
 
-	return engine.width;
+	return platState.engine->width;
 }
 }
 
 
 int _AndroidGetScreenHeight() {
 int _AndroidGetScreenHeight() {
 
 
-	return engine.height;
+	return platState.engine->height;
 }
 }
 
 
 bool _AndroidGetFileDescriptor(const char* fileName, int32_t *mDescriptor, off_t *mStart, off_t* mLength) {
 bool _AndroidGetFileDescriptor(const char* fileName, int32_t *mDescriptor, off_t *mStart, off_t* mLength) {
 
 
-	AAsset* asset = AAssetManager_open(engine.app->activity->assetManager, fileName, AASSET_MODE_UNKNOWN);
+	AAsset* asset = AAssetManager_open(platState.engine->app->activity->assetManager, fileName, AASSET_MODE_UNKNOWN);
 	if (asset != NULL) {
 	if (asset != NULL) {
 		*mDescriptor = AAsset_openFileDescriptor(asset, mStart, mLength);
 		*mDescriptor = AAsset_openFileDescriptor(asset, mStart, mLength);
 		AAsset_close(asset);
 		AAsset_close(asset);
@@ -363,7 +550,7 @@ char* _AndroidLoadFile(const char* fileName, int *size) {
 	uint8_t buf[1024];
 	uint8_t buf[1024];
 	char* buffer = NULL;
 	char* buffer = NULL;
 	*size = 0;
 	*size = 0;
-	asset = AAssetManager_open(engine.app->activity->assetManager, fileName, AASSET_MODE_UNKNOWN);
+	asset = AAssetManager_open(platState.engine->app->activity->assetManager, fileName, AASSET_MODE_UNKNOWN);
 	if(asset != NULL){
 	if(asset != NULL){
 		*size = AAsset_getLength(asset);
 		*size = AAsset_getLength(asset);
 		if (*size <= 0)
 		if (*size <= 0)
@@ -398,8 +585,8 @@ void _AndroidGetDeviceIPAddress(char* address) {
 	 jint lResult;
 	 jint lResult;
 	 jint lFlags = 0;
 	 jint lFlags = 0;
 
 
-	 JavaVM* lJavaVM = engine.app->activity->vm;
-	 JNIEnv* lJNIEnv = engine.app->activity->env;
+	 JavaVM* lJavaVM = platState.engine->app->activity->vm;
+	 JNIEnv* lJNIEnv = platState.engine->app->activity->env;
 
 
 	 JavaVMAttachArgs lJavaVMAttachArgs;
 	 JavaVMAttachArgs lJavaVMAttachArgs;
 	 lJavaVMAttachArgs.version = JNI_VERSION_1_6;
 	 lJavaVMAttachArgs.version = JNI_VERSION_1_6;
@@ -412,7 +599,7 @@ void _AndroidGetDeviceIPAddress(char* address) {
 	 }
 	 }
 
 
 	 // Retrieves NativeActivity.
 	 // Retrieves NativeActivity.
-	 jobject lNativeActivity = engine.app->activity->clazz;
+	 jobject lNativeActivity = platState.engine->app->activity->clazz;
 	 jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
 	 jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
 
 
 	 // Retrieves Context.INPUT_METHOD_SERVICE.
 	 // Retrieves Context.INPUT_METHOD_SERVICE.
@@ -538,8 +725,8 @@ static int engine_init_display(struct engine* engine) {
 
 
     if (SetupCompleted == false)
     if (SetupCompleted == false)
     {
     {
-
-    	//TODO: android
+    	activity.finishGLSetup();
+    	_AndroidRunTorqueMain(engine);
 
 
     }
     }
     else
     else
@@ -551,6 +738,45 @@ static int engine_init_display(struct engine* engine) {
     return 0;
     return 0;
 }
 }
 
 
+void T2DActivity::finishGLSetup()
+{
+	createFramebuffer();
+
+    platState.multipleTouchesEnabled = true;
+
+	_AndroidTorqueFatalError = false;
+}
+
+void T2DActivity::finishShutdown()
+{
+	destroyFramebuffer();
+}
+
+void T2DActivity::enableAccelerometer(bool enable) {
+
+	accelerometerActive = enable;
+
+	if (enable) {
+
+		if (platState.engine->accelerometerSensor != NULL) {
+			ASensorEventQueue_enableSensor(platState.engine->sensorEventQueue,
+					platState.engine->accelerometerSensor);
+			// We'd like to get 30 events per second (in us).
+			ASensorEventQueue_setEventRate(platState.engine->sensorEventQueue,
+					platState.engine->accelerometerSensor, (1000L/30)*1000);
+		}
+
+	} else {
+
+		if (platState.engine->accelerometerSensor != NULL) {
+			ASensorEventQueue_disableSensor(platState.engine->sensorEventQueue,
+					platState.engine->accelerometerSensor);
+		}
+
+	}
+
+}
+
 /**
 /**
  * update callback
  * update callback
  */
  */
@@ -663,6 +889,8 @@ static void engine_term_display(struct engine* engine, bool shutdown) {
 		 _AndroidGameResignActive();
 		 _AndroidGameResignActive();
 	}
 	}
 
 
+	activity.finishShutdown();
+
     if (engine->display != EGL_NO_DISPLAY) {
     if (engine->display != EGL_NO_DISPLAY) {
         eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
         eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
         if (engine->context != EGL_NO_CONTEXT) {
         if (engine->context != EGL_NO_CONTEXT) {
@@ -679,54 +907,334 @@ static void engine_term_display(struct engine* engine, bool shutdown) {
     engine->surface = EGL_NO_SURFACE;
     engine->surface = EGL_NO_SURFACE;
 }
 }
 
 
-//TODO: android rotate
-/*- (void)didRotate:(NSNotification *)notification
+void keepScreenOn() {
+
+    // Attaches the current thread to the JVM.
+    jint lResult;
+    jint lFlags = 0;
+
+    JavaVM* lJavaVM = platState.engine->app->activity->vm;
+    JNIEnv* lJNIEnv = platState.engine->app->activity->env;
+
+    JavaVMAttachArgs lJavaVMAttachArgs;
+    lJavaVMAttachArgs.version = JNI_VERSION_1_6;
+    lJavaVMAttachArgs.name = "NativeThread";
+    lJavaVMAttachArgs.group = NULL;
+
+    lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
+    if (lResult == JNI_ERR) {
+        return;
+    }
+
+    // Retrieves NativeActivity.
+    jobject lNativeActivity = platState.engine->app->activity->clazz;
+    jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
+
+    // Runs getWindow().getDecorView().
+    jmethodID MethodGetWindow = lJNIEnv->GetMethodID(
+        ClassNativeActivity, "getWindow",
+        "()Landroid/view/Window;");
+    jobject lWindow = lJNIEnv->CallObjectMethod(lNativeActivity,
+        MethodGetWindow);
+    jclass ClassWindow = lJNIEnv->FindClass(
+        "android/view/Window");
+    jmethodID MethodGetDecorView = lJNIEnv->GetMethodID(
+        ClassWindow, "getDecorView", "()Landroid/view/View;");
+    jobject lDecorView = lJNIEnv->CallObjectMethod(lWindow,
+        MethodGetDecorView);
+
+    jclass ClassView = lJNIEnv->FindClass("android/view/View");
+    jmethodID MethodSetKeepScreenOn = lJNIEnv->GetMethodID(
+            ClassView, "setKeepScreenOn", "(Z)V");
+    jboolean on = true;
+    lJNIEnv->CallVoidMethod(lDecorView, MethodSetKeepScreenOn, on);
+
+    // Finished with the JVM.
+    lJavaVM->DetachCurrentThread();
+}
+
+void T2DActivity::loadCacheDir() {
+
+    // Attaches the current thread to the JVM.
+    jint lResult;
+    jint lFlags = 0;
+
+    JavaVM* lJavaVM = platState.engine->app->activity->vm;
+    JNIEnv* lJNIEnv = platState.engine->app->activity->env;
+
+    JavaVMAttachArgs lJavaVMAttachArgs;
+    lJavaVMAttachArgs.version = JNI_VERSION_1_6;
+    lJavaVMAttachArgs.name = "NativeThread";
+    lJavaVMAttachArgs.group = NULL;
+
+    lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
+    if (lResult == JNI_ERR) {
+        return;
+    }
+
+    // Retrieves NativeActivity.
+    jobject lNativeActivity = platState.engine->app->activity->clazz;
+    jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
+
+    jmethodID getCacheDir = lJNIEnv->GetMethodID(ClassNativeActivity, "getCacheDir", "()Ljava/io/File;");
+    jobject file = lJNIEnv->CallObjectMethod(platState.engine->app->activity->clazz, getCacheDir);
+    jclass fileClass = lJNIEnv->FindClass("java/io/File");
+    jmethodID getAbsolutePath = lJNIEnv->GetMethodID(fileClass, "getAbsolutePath", "()Ljava/lang/String;");
+    jstring jpath = (jstring)lJNIEnv->CallObjectMethod(file, getAbsolutePath);
+    const char* app_dir = lJNIEnv->GetStringUTFChars(jpath, NULL);
+
+    strcpy(cacheDir, app_dir);
+    cacheDir[strlen(app_dir)] = '\0';
+
+    lJNIEnv->ReleaseStringUTFChars(jpath, app_dir);
+
+    // Finished with the JVM.
+    lJavaVM->DetachCurrentThread();
+
+}
+
+/**
+ * Process the next main command.
+ */
+static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
+    struct engine* engine = (struct engine*)app->userData;
+    switch (cmd) {
+        case APP_CMD_SAVE_STATE:
+            // The system has asked us to save our current state.  Do so.
+            engine->app->savedState = malloc(sizeof(struct saved_state));
+            *((struct saved_state*)engine->app->savedState) = engine->state;
+            engine->app->savedStateSize = sizeof(struct saved_state);
+            break;
+        case APP_CMD_INIT_WINDOW:
+            // The window is being shown, get it ready.
+            if (engine->app->window != NULL) {
+
+                engine_init_display(engine);
+
+                if (bSuspended == true) {
+
+					//TODO: resume
+
+					glViewport(0, 0, engine->width, engine->height);
+
+					bSuspended = false;
+				}
+
+                engine_draw_frame(engine);
+            }
+            break;
+        case APP_CMD_TERM_WINDOW:
+        	if (bSuspended == false) {
+				//TODO: suspend
+
+				bSuspended = true;
+			}
+
+            // The window is being hidden or closed, clean it up.
+            engine_term_display(engine, false);
+            break;
+        case APP_CMD_RESUME:
+            break;
+        case APP_CMD_GAINED_FOCUS:
+        	// When our app gains focus, we start monitoring the accelerometer.
+			if (engine->accelerometerSensor != NULL && activity.isAccelerometerActive()) {
+				ASensorEventQueue_enableSensor(engine->sensorEventQueue,
+						engine->accelerometerSensor);
+				// We'd like to get 30 events per second (in us).
+				ASensorEventQueue_setEventRate(engine->sensorEventQueue,
+						engine->accelerometerSensor, (1000L/30)*1000);
+			}
+
+            engine->animating = 1;
+            engine_draw_frame(engine);
+            break;
+        case APP_CMD_LOST_FOCUS:
+        	// When our app loses focus, we stop monitoring the accelerometer.
+			// This is to avoid consuming battery while not being used.
+			if (engine->accelerometerSensor != NULL) {
+				ASensorEventQueue_disableSensor(engine->sensorEventQueue,
+						engine->accelerometerSensor);
+			}
+
+            // stop animating.
+        	engine->animating = 0;
+            engine_draw_frame(engine);
+            break;
+        case APP_CMD_PAUSE:
+            break;
+    }
+}
+
+struct engine engine;
+
+/**
+ * This is the main entry point of a native application that is using
+ * android_native_app_glue.  It runs in its own thread, with its own
+ * event loop for receiving input events and doing other things.
+ */
+void android_main(struct android_app* state) {
+
+    // Make sure glue isn't stripped.
+    app_dummy();
+
+    memset(&engine, 0, sizeof(engine));
+    state->userData = &engine;
+    state->onAppCmd = engine_handle_cmd;
+    state->onInputEvent = engine_handle_input;
+    engine.app = state;
+
+    // Prepare to monitor accelerometer
+	engine.sensorManager = ASensorManager_getInstance();
+	engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
+			ASENSOR_TYPE_ACCELEROMETER);
+	engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
+			state->looper, LOOPER_ID_USER, NULL, NULL);
+
+
+    if (state->savedState != NULL) {
+        // We are starting with a previous saved state; restore from it.
+        engine.state = *(struct saved_state*)state->savedState;
+    }
+
+    keepScreenOn();
+
+    //This is to help the debugger catch up.  If you dont have this you cant debug this early in the execution
+    //so only uncomment when needed as it adds 10 seconds to startup
+    //sleep(10);
+
+    //store the cache dir
+    activity.loadCacheDir();
+
+    //TODO: anything we need to do with these?
+    platState.argc = 0;
+    //platState.argv
+
+    // loop waiting for stuff to do.
+    while (1) {
+        // Read all pending events.
+        int ident;
+        int events;
+        struct android_poll_source* source;
+
+        // If not animating, we will block forever waiting for events.
+        // If animating, we loop until all events are read, then continue
+        // to draw the next frame of animation.
+        while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
+                (void**)&source)) >= 0) {
+
+            // Process this event.
+            if (source != NULL) {
+                source->process(state, source);
+            }
+
+            // If a sensor has data, process it now.
+			if (ident == LOOPER_ID_USER) {
+				if (engine.accelerometerSensor != NULL && activity.isAccelerometerActive()) {
+					ASensorEvent event;
+					int i = 0;
+					while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
+							&event, 1) > 0) {
+
+						InputEvent inputEvent;
+						U32 accelAxes[6] = { SI_ACCELX, SI_ACCELY, SI_ACCELZ, SI_GRAVX, SI_GRAVY, SI_GRAVZ };
+						double userAcc[6] = { event.acceleration.x, event.acceleration.y, event.acceleration.z,0,0,0};
+
+						inputEvent.deviceInst = 0;
+						inputEvent.fValue = userAcc[i];
+						inputEvent.deviceType = AccelerometerDeviceType;
+						inputEvent.objType = accelAxes[i];
+						inputEvent.objInst = i;
+						inputEvent.action = SI_MOTION;
+						inputEvent.modifier = 0;
+
+						Game->postEvent(inputEvent);
+
+						i++;
+					}
+				}
+			}
+
+            // Check if we are exiting.
+            if (state->destroyRequested != 0) {
+                engine_term_display(&engine, true);
+                return;
+            }
+        }
+
+        engine_update_frame(&engine);
+
+        if (engine.animating) {
+
+            // Drawing is throttled to the screen update rate, so there
+            // is no need to do timing here.
+            engine_draw_frame(&engine);
+        }
+    }
+
+    engine_term_display(&engine, true);
+}
+
+ConsoleFunction(doDeviceVibrate, void, 1, 1, "Makes the device do a quick vibration. Only works on devices with vibration functionality.")
 {
 {
-    //Default to landscape left
-	UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
-	if(currentOrientation != orientation)
-	{
-		//Change the orientation
-		currentOrientation = orientation;
-		//Tell the rest of the engine
-		_AndroidGameChangeOrientation(currentOrientation);
+	// Vibrate for 500 milliseconds
+	long vibrateTimeMS = 500L;
+	// Attaches the current thread to the JVM.
+	jint lResult;
+	jint lFlags = 0;
+
+	JavaVM* lJavaVM = platState.engine->app->activity->vm;
+	JNIEnv* lJNIEnv = platState.engine->app->activity->env;
+
+	JavaVMAttachArgs lJavaVMAttachArgs;
+	lJavaVMAttachArgs.version = JNI_VERSION_1_6;
+	lJavaVMAttachArgs.name = "NativeThread";
+	lJavaVMAttachArgs.group = NULL;
+
+	lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
+	if (lResult == JNI_ERR) {
+		return;
 	}
 	}
-}*/
 
 
-void supportLandscape( bool enable)
-{
-	//TODO: android
-    //platState.viewController->mOrientationLandscapeLeftSupported = enable;
-    //platState.viewController->mOrientationLandscapeRightSupported = enable;
+	// Retrieves NativeActivity.
+	jobject lNativeActivity = platState.engine->app->activity->clazz;
+	jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
+
+	// Retrieves Context.VIBRATOR_SERVICE.
+	jclass ClassContext = lJNIEnv->FindClass("android/content/Context");
+	jfieldID FieldVIBRATOR_SERVICE =lJNIEnv->GetStaticFieldID(ClassContext,"VIBRATOR_SERVICE", "Ljava/lang/String;");
+	jobject VIBRATOR_SERVICE = lJNIEnv->GetStaticObjectField(ClassContext, FieldVIBRATOR_SERVICE);
+
+	// Runs getSystemService(VIBRATOR_SERVICE)
+	jmethodID MethodGetSystemService = lJNIEnv->GetMethodID(ClassNativeActivity, "getSystemService","(Ljava/lang/String;)Ljava/lang/Object;");
+	jobject lVibrator = lJNIEnv->CallObjectMethod(lNativeActivity, MethodGetSystemService, VIBRATOR_SERVICE);
+
+	//Runs v.vibrate(ms)
+	jclass ClassVibrator = lJNIEnv->FindClass("android/os/Vibrator");
+	jmethodID MethodVibrate = lJNIEnv->GetMethodID(ClassVibrator, "vibrate", "(J)V");
+	lJNIEnv->CallVoidMethod(lVibrator, MethodVibrate, vibrateTimeMS);
+
+	// Finished with the JVM.
+	lJavaVM->DetachCurrentThread();
 }
 }
 
 
-ConsoleFunction(supportLandscape, void, 2, 2, "supportLandscape( bool ) "
-                "enable or disable Landscape")
+ConsoleFunction(enableAccelerometer, void, 1, 1, "() Allow accelerometer tracking during device motion updates")
 {
 {
-    bool enable = true;
-    if( argc > 1 )
-        enable = dAtob( argv[1] );
-    
-    supportLandscape(enable);
+	activity.enableAccelerometer(true);
 }
 }
 
 
-void supportPortrait( bool enable )
+ConsoleFunction(disableAccelerometer, void, 1, 1, "() Stop accelerometer tracking")
 {
 {
-	//TODO: android
-    //platState.viewController->mOrientationPortraitSupported = enable;
-    //platState.viewController->mOrientationPortraitUpsideDownSupported = enable;
+	activity.enableAccelerometer(false);
 }
 }
 
 
-ConsoleFunction(supportPortrait, void, 2, 2, "supportPortrait( bool ) "
-                "enable or disable portrait")
+ConsoleFunction(isAccelerometerActive, bool, 1, 1, "() Check to see if Accelerometer is being polled\n"
+                "@return True if accelerometer is on, false otherwise")
 {
 {
-    bool enable = true;
-    if( argc > 1 )
-        enable = dAtob( argv[1] );
-    
-    supportPortrait(enable);
+
+	return activity.isAccelerometerActive();
 }
 }
 
 
+
 void adprintf(const char* fmt,...) {
 void adprintf(const char* fmt,...) {
 
 
 	va_list argptr;
 	va_list argptr;

+ 25 - 11
engine/source/platformAndroid/T2DActivity.h

@@ -28,6 +28,8 @@
 #include <android/log.h>
 #include <android/log.h>
 #include <android_native_app_glue.h>
 #include <android_native_app_glue.h>
 #include <android/asset_manager.h>
 #include <android/asset_manager.h>
+#include <android/sensor.h>
+#include <android/configuration.h>
 #include <sstream>
 #include <sstream>
 #include <list>
 #include <list>
 #include <unistd.h>
 #include <unistd.h>
@@ -50,6 +52,10 @@ struct saved_state {
 struct engine {
 struct engine {
     struct android_app* app;
     struct android_app* app;
 
 
+    ASensorManager* sensorManager;
+    const ASensor* accelerometerSensor;
+    ASensorEventQueue* sensorEventQueue;
+
     int animating;
     int animating;
     EGLDisplay display;
     EGLDisplay display;
     EGLSurface surface;
     EGLSurface surface;
@@ -59,8 +65,6 @@ struct engine {
     struct saved_state state;
     struct saved_state state;
 };
 };
 
 
-static struct engine engine;
-
 class T2DActivity {
 class T2DActivity {
 
 
 private:
 private:
@@ -80,17 +84,27 @@ private:
     
     
     bool isLayedOut;
     bool isLayedOut;
     
     
+    char cacheDir[2048];
+
+    bool accelerometerActive;
+
 public:
 public:
-    //TODO: android
-    //NSURLConnection *connection;
-    //NSMutableData *connectionData;
-    bool mOrientationLandscapeRightSupported;
-    bool mOrientationLandscapeLeftSupported;
-    bool mOrientationPortraitSupported;
-    bool mOrientationPortraitUpsideDownSupported;
 
 
-    void supportLandscape( bool );
-    void supportPortrait( bool );
+    T2DActivity() {
+
+    	accelerometerActive = false;
+    }
+
+    void enableAccelerometer(bool enable);
+    bool isAccelerometerActive() {
+
+    	return accelerometerActive;
+    }
+
+    void loadCacheDir();
+    char *getCacheDir() {
+    	return cacheDir;
+    }
     bool createFramebuffer();
     bool createFramebuffer();
     void destroyFramebuffer();
     void destroyFramebuffer();
     void update();
     void update();

+ 3 - 149
engine/source/platformAndroid/main.cpp

@@ -32,22 +32,11 @@ S32 gLastStart = 0;
 
 
 bool appIsRunning = true;
 bool appIsRunning = true;
 
 
-//TODO: android
-
-int _AndroidRunTorqueMain()
+int _AndroidRunTorqueMain(engine *eng)
 {
 {
-/*
-    UIApplication *app = [UIApplication sharedApplication];
-    platState.viewController = viewController;
+	platState.engine = eng;
+    platState.firstThreadId = ThreadManager::getCurrentThreadId();
     
     
-	platState.appID = appID;
-	platState.firstThreadId = ThreadManager::getCurrentThreadId();
-	platState.Window = Window;
-	platState.application = app;
-	
-	// Hidden by default.
-	platState.application.statusBarHidden = YES;
-	
 	printf("performing mainInit()\n");
 	printf("performing mainInit()\n");
     
     
 	platState.lastTimeTick = Platform::getRealMilliseconds();
 	platState.lastTimeTick = Platform::getRealMilliseconds();
@@ -56,7 +45,6 @@ int _AndroidRunTorqueMain()
 	{
 	{
 		return 0;
 		return 0;
 	}
 	}
-	*/
 }
 }
 
 
 
 
@@ -112,76 +100,6 @@ void _AndroidGameWillTerminate()
 	Game->mainShutdown();
 	Game->mainShutdown();
 }
 }
 
 
-// Store current orientation for easy access
-void _AndroidGameChangeOrientation(S32 newOrientation)
-{    
-	_AndroidGameSetCurrentOrientation(newOrientation);
-    
-    return;
-    /*
-    bool enableAutoOrientation = Con::getBoolVariable("$pref::Android::EnableOrientationRotation");
-    int screenOrientation = Con::getIntVariable("$pref::Android::ScreenOrientation");
-    bool allowOtherOrientation = Con::getBoolVariable("$pref::Android::EnableOtherOrientationRotation");
-
-    // The rotation matching the project orientation must be allowed for any to occur
-    if (enableAutoOrientation)
-    {
-        // Start "collecting animations"
-        [UIView beginAnimations: nil context: nil];
-        
-        //  If the project is designed for landscape or it allows landscape rotation
-        if (screenOrientation == 0 || allowOtherOrientation)
-        {
-            if (newOrientation == UIDeviceOrientationLandscapeLeft)
-            {
-                platState.Window.transform = CGAffineTransformMakeRotation(M_PI*1.5);
-                Con::executef(1, "onAndroidOrientationToLandscapeLeft");
-                //  Show animations
-                [UIView commitAnimations];
-                
-                return;
-            }
-            
-            if (newOrientation == UIDeviceOrientationLandscapeRight)
-            {
-                platState.Window.transform = CGAffineTransformMakeRotation(M_PI_2);
-                Con::executef(1, "onAndroidOrientationToLandscapeRight");
-                //  Show animations
-                [UIView commitAnimations];
-                
-                return;
-            }
-        }
-        
-        // If the project is designed for portrait or it allows portrait rotation
-        if (screenOrientation == 1 ||  allowOtherOrientation)
-        {
-            if (newOrientation == UIDeviceOrientationPortrait)
-            {
-                platState.Window.transform = CGAffineTransformMakeRotation(M_PI*1.5);
-                Con::executef(1, "onAndroidOrientationToPortrait");
-                //  Show animations
-                [UIView commitAnimations];
-                
-                return;
-            }
-            
-            if (newOrientation == UIDeviceOrientationPortraitUpsideDown)
-            {
-                platState.Window.transform = CGAffineTransformMakeRotation(M_PI_2);
-                Con::executef(1, "onAndroidOrientationToPortraitUpsideDown");
-                //  Show animations
-                [UIView commitAnimations];
-                
-                return;
-            }
-        }
-        
-        // Show animations
-        [UIView commitAnimations];
-    }*/
-}
-
 static void _AndroidGetTxtFileArgs(int &argc, char** argv, int maxargc)
 static void _AndroidGetTxtFileArgs(int &argc, char** argv, int maxargc)
 {
 {
     argc = 0;
     argc = 0;
@@ -235,67 +153,3 @@ static void _AndroidGetTxtFileArgs(int &argc, char** argv, int maxargc)
 	text = NULL;
 	text = NULL;
 }
 }
 
 
-int main(int argc, char *argv[])
-{
-    //TODO: android
-	/*
-        int kMaxCmdlineArgs = 32; //Arbitrary
-        
-        printf("Initial Command Line\n");
-        
-        for( int i = 0; i < argc; i++ )
-        {
-            printf("%i : %s", i, argv[i] );
-        }
-        
-        NSString *nsStrVersion = [UIDevice currentDevice ].systemVersion;
-        const char *strVersion = [nsStrVersion UTF8String ];
-        platState.osVersion = dAtof( strVersion);
-        
-        // Find Main.cs .
-        const char* cwd = Platform::getMainDotCsDir();
-        
-        // Change to the directory that contains main.cs
-        Platform::setCurrentDirectory(cwd);
-        
-        // get the actual command line args
-        S32   newArgc = argc;
-        
-        const char* newArgv[kMaxCmdlineArgs];
-        
-        for(int i=0; i < argc && i < kMaxCmdlineArgs; i++)
-            newArgv[i] = argv[i];
-        
-        // get the text file args
-        S32 textArgc;
-        char* textArgv[kMaxCmdlineArgs];
-        
-        _AndroidGetTxtFileArgs(textArgc, textArgv, kMaxCmdlineArgs);
-        
-        // merge them
-        int i=0;
-        
-        while(i < textArgc && newArgc < kMaxCmdlineArgs)
-            newArgv[newArgc++] = textArgv[i++];
-        
-        // store them in platState
-        platState.argc = newArgc;
-        platState.argv = newArgv;
-        
-        printf("\nMerged Command Line\n");
-        
-        for( int i = 0; i < platState.argc; i++ )
-        {
-            printf("%i : %s", i, platState.argv[i] );
-        }
-        
-        printf("\n");
-        
-        // now, we run UIApplication which calls back and starts thread or timer
-        platState.appReturn = UIApplicationMain(argc, argv, nil, NSStringFromClass([T2DAppDelegate class]));
-        
-        printf("exiting...\n");
-        return(platState.appReturn);
-
-    */
-}

+ 1 - 11
engine/source/platformAndroid/platformAndroid.h

@@ -39,14 +39,9 @@ public:
     bool              captureDisplay;
     bool              captureDisplay;
     bool              fadeWindows;
     bool              fadeWindows;
 
 
-    //TODO: android
-    //id				 appID;
-    //UIView			 *Window;
+    struct engine	  *engine;
     char              appWindowTitle[256];
     char              appWindowTitle[256];
     bool              quit;
     bool              quit;
-    //TODO: android
-    void*          *ctx;
-    //T2DViewController *viewController;
     bool              ctxNeedsUpdate;
     bool              ctxNeedsUpdate;
 
 
     bool			portrait;
     bool			portrait;
@@ -87,11 +82,6 @@ public:
 
 
 
 
     StringTableEntry  mainDotCsDir;
     StringTableEntry  mainDotCsDir;
-
-    //TODO: android
-    //NSTimer			 *mainLoopTimer;
-    //NSTimeInterval	 timerInterval;
-    //UIApplication	*application;
     //-Mat
     //-Mat
     bool		multipleTouchesEnabled;
     bool		multipleTouchesEnabled;