Przeglądaj źródła

Add PolycodeUI, Polycode2DPhysics (including Box2D), experimental OnScreenKeyboard.

Joachim Meyer 9 lat temu
rodzic
commit
ae34bca779
72 zmienionych plików z 6362 dodań i 204 usunięć
  1. 4 0
      build/android/.idea/gradle.xml
  2. 2 0
      build/android/.idea/modules.xml
  3. 1 0
      build/android/Polycode2DPhysics/.gitignore
  4. 31 0
      build/android/Polycode2DPhysics/AndroidManifest.xml
  5. 41 0
      build/android/Polycode2DPhysics/build.gradle
  6. 9 0
      build/android/Polycode2DPhysics/jni/Android.mk
  7. 5 0
      build/android/Polycode2DPhysics/jni/Application.mk
  8. 17 0
      build/android/Polycode2DPhysics/proguard-rules.pro
  9. 1 0
      build/android/PolycodeUI/.gitignore
  10. 31 0
      build/android/PolycodeUI/AndroidManifest.xml
  11. 41 0
      build/android/PolycodeUI/build.gradle
  12. 9 0
      build/android/PolycodeUI/jni/Android.mk
  13. 5 0
      build/android/PolycodeUI/jni/Application.mk
  14. 17 0
      build/android/PolycodeUI/proguard-rules.pro
  15. 1 1
      build/android/TemplateApp/AndroidManifest.xml
  16. 36 1
      build/android/TemplateApp/jni/Android.mk
  17. 32 13
      build/android/TemplateApp/jni/PolycodeTemplateApp.cpp
  18. 3 0
      build/android/TemplateApp/jni/PolycodeTemplateApp.h
  19. 1 1
      build/android/settings.gradle
  20. 62 0
      include/Box2D/Box2D.h
  21. 87 0
      include/Box2D/Collision/Shapes/b2CircleShape.h
  22. 131 0
      include/Box2D/Collision/Shapes/b2PolygonShape.h
  23. 95 0
      include/Box2D/Collision/Shapes/b2Shape.h
  24. 229 0
      include/Box2D/Collision/b2BroadPhase.h
  25. 240 0
      include/Box2D/Collision/b2Collision.h
  26. 141 0
      include/Box2D/Collision/b2Distance.h
  27. 286 0
      include/Box2D/Collision/b2DynamicTree.h
  28. 59 0
      include/Box2D/Collision/b2TimeOfImpact.h
  29. 59 0
      include/Box2D/Common/b2BlockAllocator.h
  30. 624 0
      include/Box2D/Common/b2Math.h
  31. 151 0
      include/Box2D/Common/b2Settings.h
  32. 60 0
      include/Box2D/Common/b2StackAllocator.h
  33. 38 0
      include/Box2D/Dynamics/Contacts/b2CircleContact.h
  34. 242 0
      include/Box2D/Dynamics/Contacts/b2Contact.h
  35. 78 0
      include/Box2D/Dynamics/Contacts/b2ContactSolver.h
  36. 38 0
      include/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h
  37. 38 0
      include/Box2D/Dynamics/Contacts/b2PolygonContact.h
  38. 51 0
      include/Box2D/Dynamics/Contacts/b2TOISolver.h
  39. 140 0
      include/Box2D/Dynamics/Joints/b2DistanceJoint.h
  40. 99 0
      include/Box2D/Dynamics/Joints/b2FrictionJoint.h
  41. 111 0
      include/Box2D/Dynamics/Joints/b2GearJoint.h
  42. 226 0
      include/Box2D/Dynamics/Joints/b2Joint.h
  43. 170 0
      include/Box2D/Dynamics/Joints/b2LineJoint.h
  44. 114 0
      include/Box2D/Dynamics/Joints/b2MouseJoint.h
  45. 175 0
      include/Box2D/Dynamics/Joints/b2PrismaticJoint.h
  46. 148 0
      include/Box2D/Dynamics/Joints/b2PulleyJoint.h
  47. 174 0
      include/Box2D/Dynamics/Joints/b2RevoluteJoint.h
  48. 82 0
      include/Box2D/Dynamics/Joints/b2WeldJoint.h
  49. 802 0
      include/Box2D/Dynamics/b2Body.h
  50. 52 0
      include/Box2D/Dynamics/b2ContactManager.h
  51. 326 0
      include/Box2D/Dynamics/b2Fixture.h
  52. 105 0
      include/Box2D/Dynamics/b2Island.h
  53. 35 0
      include/Box2D/Dynamics/b2TimeStep.h
  54. 285 0
      include/Box2D/Dynamics/b2World.h
  55. 217 0
      include/Box2D/Dynamics/b2WorldCallbacks.h
  56. 1 7
      include/polycode/core/PolyAAssetFileProvider.h
  57. 1 0
      include/polycode/core/PolyAndroidCore.h
  58. 6 0
      include/polycode/core/PolyCore.h
  59. 2 0
      include/polycode/core/PolyGlobals.h
  60. 1 21
      include/polycode/core/PolyOpenSLAudioInterface.h
  61. 1 5
      include/polycode/core/PolySoundManager.h
  62. 4 4
      include/polycode/modules/physics2D/PolyPhysicsScreen.h
  63. 2 2
      include/polycode/modules/physics2D/PolyPhysicsScreenEntity.h
  64. 0 1
      include/polycode/view/android/PolycodeView.h
  65. 3 7
      src/core/PolyAAssetFileProvider.cpp
  66. 64 2
      src/core/PolyAndroidCore.cpp
  67. 4 71
      src/core/PolyOpenSLAudioInterface.cpp
  68. 4 4
      src/core/PolySound.cpp
  69. 0 1
      src/core/PolySoundManager.cpp
  70. 4 4
      src/modules/physics2D/PolyPhysicsScreen.cpp
  71. 4 4
      src/modules/physics2D/PolyPhysicsScreenEntity.cpp
  72. 4 55
      src/view/android/PolycodeView.cpp

+ 4 - 0
build/android/.idea/gradle.xml

@@ -9,6 +9,8 @@
         <option name="modules">
           <set>
             <option value="$PROJECT_DIR$" />
+            <option value="$PROJECT_DIR$/Polycode2DPhysics" />
+            <option value="$PROJECT_DIR$/PolycodeUI" />
             <option value="$PROJECT_DIR$/Polycore" />
             <option value="$PROJECT_DIR$/TemplateApp" />
           </set>
@@ -16,6 +18,8 @@
         <option name="myModules">
           <set>
             <option value="$PROJECT_DIR$" />
+            <option value="$PROJECT_DIR$/Polycode2DPhysics" />
+            <option value="$PROJECT_DIR$/PolycodeUI" />
             <option value="$PROJECT_DIR$/Polycore" />
             <option value="$PROJECT_DIR$/TemplateApp" />
           </set>

+ 2 - 0
build/android/.idea/modules.xml

@@ -2,6 +2,8 @@
 <project version="4">
   <component name="ProjectModuleManager">
     <modules>
+      <module fileurl="file://$PROJECT_DIR$/Polycode2DPhysics/Polycode2DPhysics.iml" filepath="$PROJECT_DIR$/Polycode2DPhysics/Polycode2DPhysics.iml" />
+      <module fileurl="file://$PROJECT_DIR$/PolycodeUI/PolycodeUI.iml" filepath="$PROJECT_DIR$/PolycodeUI/PolycodeUI.iml" />
       <module fileurl="file://$PROJECT_DIR$/Polycore/Polycore.iml" filepath="$PROJECT_DIR$/Polycore/Polycore.iml" />
       <module fileurl="file://$PROJECT_DIR$/TemplateApp/TemplateApp.iml" filepath="$PROJECT_DIR$/TemplateApp/TemplateApp.iml" />
       <module fileurl="file://$PROJECT_DIR$/android.iml" filepath="$PROJECT_DIR$/android.iml" />

+ 1 - 0
build/android/Polycode2DPhysics/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/Polycode2DPhysics/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="Polycode2DPhysics"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 41 - 0
build/android/Polycode2DPhysics/build.gradle

@@ -0,0 +1,41 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+
+    defaultConfig {
+    applicationId "org.polycode.polycode2dphysics"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+}
+
+dependencies {
+}

+ 9 - 0
build/android/Polycode2DPhysics/jni/Android.mk

@@ -0,0 +1,9 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/linux/android
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode2DPhysics
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include
+LOCAL_SRC_FILES := $(SRCDIR)/modules/physics2D/PolyPhysicsScreen.cpp $(SRCDIR)/modules/physics2D/PolyPhysicsScreenEntity.cpp
+include $(BUILD_STATIC_LIBRARY)

+ 5 - 0
build/android/Polycode2DPhysics/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/Polycode2DPhysics/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 1 - 0
build/android/PolycodeUI/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/PolycodeUI/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="PolycodeUI"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 41 - 0
build/android/PolycodeUI/build.gradle

@@ -0,0 +1,41 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+
+    defaultConfig {
+    applicationId "org.polycode.polycodeui"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+}
+
+dependencies {
+}

+ 9 - 0
build/android/PolycodeUI/jni/Android.mk

@@ -0,0 +1,9 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/linux/android
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := PolycodeUI
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include
+LOCAL_SRC_FILES := $(SRCDIR)/modules/ui/PolyUIBox.cpp $(SRCDIR)/modules/ui/PolyUIButton.cpp $(SRCDIR)/modules/ui/PolyUICheckBox.cpp $(SRCDIR)/modules/ui/PolyUIColorBox.cpp $(SRCDIR)/modules/ui/PolyUIComboBox.cpp $(SRCDIR)/modules/ui/PolyUIElement.cpp $(SRCDIR)/modules/ui/PolyUIEvent.cpp $(SRCDIR)/modules/ui/PolyUIFileDialog.cpp $(SRCDIR)/modules/ui/PolyUIHScrollBar.cpp $(SRCDIR)/modules/ui/PolyUIHSizer.cpp $(SRCDIR)/modules/ui/PolyUIHSlider.cpp $(SRCDIR)/modules/ui/PolyUIIconSelector.cpp $(SRCDIR)/modules/ui/PolyUIImageButton.cpp $(SRCDIR)/modules/ui/PolyUIMenu.cpp $(SRCDIR)/modules/ui/PolyUIMenuBar.cpp $(SRCDIR)/modules/ui/PolyUIScrollContainer.cpp $(SRCDIR)/modules/ui/PolyUITextInput.cpp $(SRCDIR)/modules/ui/PolyUITree.cpp $(SRCDIR)/modules/ui/PolyUITreeContainer.cpp $(SRCDIR)/modules/ui/PolyUITreeEvent.cpp $(SRCDIR)/modules/ui/PolyUIVScrollBar.cpp $(SRCDIR)/modules/ui/PolyUIVSizer.cpp $(SRCDIR)/modules/ui/PolyUIWindow.cpp
+include $(BUILD_STATIC_LIBRARY)

+ 5 - 0
build/android/PolycodeUI/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/PolycodeUI/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 1 - 1
build/android/TemplateApp/AndroidManifest.xml

@@ -8,7 +8,7 @@
     <application android:label="TemplateApp">
         <activity
             android:name="org.polycode.templateapp.PolycodeActivity"
-            android:configChanges="keyboardHidden"
+            android:configChanges="keyboardHidden|keyboard"
             android:screenOrientation="landscape"
             android:label="TemplateApp">
 

+ 36 - 1
build/android/TemplateApp/jni/Android.mk

@@ -7,6 +7,16 @@ LOCAL_MODULE := Polycore
 LOCAL_SRC_FILES := ../../Polycore/obj/local/$(TARGET_ARCH_ABI)/libPolycore.a
 include $(PREBUILT_STATIC_LIBRARY)
 
+include $(CLEAR_VARS)
+LOCAL_MODULE := PolycodeUI
+LOCAL_SRC_FILES := ../../PolycodeUI/obj/local/$(TARGET_ARCH_ABI)/libPolycodeUI.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode2DPhysics
+LOCAL_SRC_FILES := ../../Polycode2DPhysics/obj/local/$(TARGET_ARCH_ABI)/libPolycode2DPhysics.a
+include $(PREBUILT_STATIC_LIBRARY)
+
 include $(CLEAR_VARS)
 LOCAL_MODULE := freetype
 LOCAL_SRC_FILES := $(LIBDIR)/libfreetype.a
@@ -22,6 +32,31 @@ LOCAL_MODULE := physfs
 LOCAL_SRC_FILES := $(LIBDIR)/libphysfs.a
 include $(PREBUILT_STATIC_LIBRARY)
 
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletDynamics
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletDynamics.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletCollision
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletCollision.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := LinearMath
+LOCAL_SRC_FILES := $(LIBDIR)/libLinearMath.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletSoftBody
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletSoftBody.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := box2d
+LOCAL_SRC_FILES := $(LIBDIR)/libbox2d.a
+include $(PREBUILT_STATIC_LIBRARY)
+
 include $(CLEAR_VARS)
 LOCAL_MODULE := ogg
 LOCAL_SRC_FILES := $(LIBDIR)/libogg.so
@@ -35,7 +70,7 @@ include $(PREBUILT_SHARED_LIBRARY)
 include $(CLEAR_VARS)
 LOCAL_MODULE := TemplateApp
 LOCAL_LDLIBS := -landroid -lEGL -lGLESv2 -lOpenSLES -lz -llog
-LOCAL_STATIC_LIBRARIES := Polycore freetype lua physfs
+LOCAL_STATIC_LIBRARIES := Polycore PolycodeUI Polycode2DPhysics freetype lua physfs box2d
 LOCAL_SHARED_LIBRARIES := ogg vorbis
 LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include -DUSE_EGL -DSTRICT_OPENGLES2
 LOCAL_SRC_FILES := PolycodeTemplate.cpp PolycodeTemplateApp.cpp

+ 32 - 13
build/android/TemplateApp/jni/PolycodeTemplateApp.cpp

@@ -10,11 +10,11 @@ PolycodeTemplateApp::PolycodeTemplateApp(PolycodeView *view) {
     core = new POLYCODE_CORE(view, 800,480,false,false, 0,0,60, -1, true);
 
     core->addFileSource("archive", "default.pak");
-    Logger::log("defaultWD: %s", core->getDefaultWorkingDirectory().c_str());
     core->addFileSource("folder", core->getDefaultWorkingDirectory());
     ResourcePool *globalPool = Services()->getResourceManager()->getGlobalPool();
     globalPool->loadResourcesFromFolder("default", true);
 
+    CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/dark_retina/theme.xml");
 
 	// Write your code here!
     srand(time(NULL));
@@ -40,12 +40,9 @@ PolycodeTemplateApp::PolycodeTemplateApp(PolycodeView *view) {
         scene->addChild(box);
     }*/
 
-    Logger::log("before sound");
-//    bgSound = new Sound("FightBG.wav");
+    bgSound = new Sound("FightBG.wav");
 //    bgSound->Play();
 
-
-
 //    sound1 = new Sound("hit.wav");
     //Logger::log("before Play");
     //sound1->Play(true);
@@ -64,14 +61,26 @@ PolycodeTemplateApp::PolycodeTemplateApp(PolycodeView *view) {
     scene->addChild(fps);
     scene->addChild(test);
 
-    /*game = new Scene(Scene::SCENE_3D);
-    game->useClearColor = true;
-    game->getActiveCamera()->setPosition(0, 0, 10);
+    /*game = new Scene(Scene::SCENE_2D_TOPLEFT);
+    //game->useClearColor = true;
+    //game->getActiveCamera()->setPosition(0, 0, 10);
 
-    box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 2, 2, 2);
+    /*box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 2, 2, 2);
     box->setMaterialByName("UnlitUntextured");
     box->setColor(0.1, 1.0, 1.0, 1.0);
-    game->addChild(box);*/
+    game->addChild(box);
+
+    UILabel *uiLabel = new UILabel("Text");
+    game->addChild(uiLabel);
+
+    btn = new UIButton("Press me!", 80);
+    btn->setPosition(5, 70);
+    game->addChild(btn);
+    btn->addEventListener(this, UIEvent::CLICK_EVENT);
+
+    Services()->getInput()->simulateMouseWithTouch = true;
+
+    game->rootEntity.processInputEvents = true;*/
 
     Services()->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
     Services()->getInput()->addEventListener(this, InputEvent::EVENT_TOUCHES_BEGAN);
@@ -85,15 +94,19 @@ void PolycodeTemplateApp::handleEvent(Event *event) {
     if(event->getEventType()=="InputEvent"){
         InputEvent *inputEvent = (InputEvent*) event;
         if(inputEvent->getEventCode() == InputEvent::EVENT_KEYDOWN){
+        //Logger::log("keyevent %d", inputEvent->getKey());
         switch(inputEvent->getKey()) {
+            case KEY_ESCAPE:
+                core->openOnScreenKeyboard(false);
+                break;
             case KEY_z:
-                sound1->Play(true);
+                //sound1->Play(true);
             break;
             case KEY_x:
-                sound2->Play();
+                //sound2->Play();
             break;
             case KEY_c:
-                sound3->Play();
+                //sound3->Play();
             break;
             }
         } else if (inputEvent->getEventCode() == InputEvent::EVENT_TOUCHES_BEGAN){
@@ -112,6 +125,12 @@ void PolycodeTemplateApp::handleEvent(Event *event) {
         } else if (motionEvent->getEventCode() == Core::EVENT_GYRO_ROTATION){
             test->Translate(motionEvent->amount.x*0.01, motionEvent->amount.y*0.01);
         }
+    } else if(event->getEventType()=="UIEvent"){
+        UIEvent* uiEvent = (UIEvent*)event;
+        if(uiEvent->getDispatcher() == btn){
+        Logger::log("hit");
+            core->openOnScreenKeyboard(true);
+        }
     }
 }
 

+ 3 - 0
build/android/TemplateApp/jni/PolycodeTemplateApp.h

@@ -3,6 +3,8 @@
 //
 
 #include "Polycode.h"
+#include "polycode/modules/ui/PolycodeUI.h"
+#include "polycode/modules/physics2D/Polycode2DPhysics.h"
 
 using namespace Polycode;
 
@@ -33,4 +35,5 @@ private:
 
     Scene* game;
     ScenePrimitive* box;
+    UIButton* btn;
 };

+ 1 - 1
build/android/settings.gradle

@@ -1 +1 @@
-include ':Polycore', ':TemplateApp'
+include ':Polycore', ':TemplateApp', ':PolycodeUI', ':Polycode2DPhysics'

+ 62 - 0
include/Box2D/Box2D.h

@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef BOX2D_H
+#define BOX2D_H
+
+/**
+\mainpage Box2D API Documentation
+
+\section intro_sec Getting Started
+
+For documentation please see http://box2d.org/documentation.html
+
+For discussion please visit http://box2d.org/forum
+*/
+
+// These include files constitute the main Box2D API
+
+#include <Box2D/Common/b2Settings.h>
+
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+#include <Box2D/Collision/b2BroadPhase.h>
+#include <Box2D/Collision/b2Distance.h>
+#include <Box2D/Collision/b2DynamicTree.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+#include <Box2D/Dynamics/b2World.h>
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
+#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
+#include <Box2D/Dynamics/Joints/b2GearJoint.h>
+#include <Box2D/Dynamics/Joints/b2LineJoint.h>
+#include <Box2D/Dynamics/Joints/b2MouseJoint.h>
+#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
+#include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
+#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/Joints/b2WeldJoint.h>
+
+#endif

+ 87 - 0
include/Box2D/Collision/Shapes/b2CircleShape.h

@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CIRCLE_SHAPE_H
+#define B2_CIRCLE_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A circle shape.
+class b2CircleShape : public b2Shape
+{
+public:
+	b2CircleShape();
+
+	/// Implement b2Shape.
+	b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+	/// Implement b2Shape.
+	bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+	/// Implement b2Shape.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeAABB
+	void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeMass
+	void ComputeMass(b2MassData* massData, float32 density) const;
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const { return 1; }
+
+	/// Get a vertex by index. Used by b2Distance.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	/// Position
+	b2Vec2 m_p;
+};
+
+inline b2CircleShape::b2CircleShape()
+{
+	m_type = e_circle;
+	m_radius = 0.0f;
+	m_p.SetZero();
+}
+
+inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const
+{
+	B2_NOT_USED(d);
+	return 0;
+}
+
+inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const
+{
+	B2_NOT_USED(d);
+	return m_p;
+}
+
+inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const
+{
+	B2_NOT_USED(index);
+	b2Assert(index == 0);
+	return m_p;
+}
+
+#endif

+ 131 - 0
include/Box2D/Collision/Shapes/b2PolygonShape.h

@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_SHAPE_H
+#define B2_POLYGON_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A convex polygon. It is assumed that the interior of the polygon is to
+/// the left of each edge.
+class b2PolygonShape : public b2Shape
+{
+public:
+	b2PolygonShape();
+
+	/// Implement b2Shape.
+	b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+	/// Copy vertices. This assumes the vertices define a convex polygon.
+	/// It is assumed that the exterior is the the right of each edge.
+	void Set(const b2Vec2* vertices, int32 vertexCount);
+
+	/// Build vertices to represent an axis-aligned box.
+	/// @param hx the half-width.
+	/// @param hy the half-height.
+	void SetAsBox(float32 hx, float32 hy);
+
+	/// Build vertices to represent an oriented box.
+	/// @param hx the half-width.
+	/// @param hy the half-height.
+	/// @param center the center of the box in local coordinates.
+	/// @param angle the rotation of the box in local coordinates.
+	void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);
+
+	/// Set this as a single edge.
+	void SetAsEdge(const b2Vec2& v1, const b2Vec2& v2);
+
+	/// @see b2Shape::TestPoint
+	bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+	/// Implement b2Shape.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeAABB
+	void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeMass
+	void ComputeMass(b2MassData* massData, float32 density) const;
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const { return m_vertexCount; }
+
+	/// Get a vertex by index.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	b2Vec2 m_centroid;
+	b2Vec2 m_vertices[b2_maxPolygonVertices];
+	b2Vec2 m_normals[b2_maxPolygonVertices];
+	int32 m_vertexCount;
+};
+
+inline b2PolygonShape::b2PolygonShape()
+{
+	m_type = e_polygon;
+	m_radius = b2_polygonRadius;
+	m_vertexCount = 0;
+	m_centroid.SetZero();
+}
+
+inline int32 b2PolygonShape::GetSupport(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_vertexCount; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return bestIndex;
+}
+
+inline const b2Vec2& b2PolygonShape::GetSupportVertex(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_vertexCount; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return m_vertices[bestIndex];
+}
+
+inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const
+{
+	b2Assert(0 <= index && index < m_vertexCount);
+	return m_vertices[index];
+}
+
+#endif

+ 95 - 0
include/Box2D/Collision/Shapes/b2Shape.h

@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_SHAPE_H
+#define B2_SHAPE_H
+
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+
+/// This holds the mass data computed for a shape.
+struct b2MassData
+{
+	/// The mass of the shape, usually in kilograms.
+	float32 mass;
+
+	/// The position of the shape's centroid relative to the shape's origin.
+	b2Vec2 center;
+
+	/// The rotational inertia of the shape about the local origin.
+	float32 I;
+};
+
+/// A shape is used for collision detection. You can create a shape however you like.
+/// Shapes used for simulation in b2World are created automatically when a b2Fixture
+/// is created.
+class b2Shape
+{
+public:
+	
+	enum Type
+	{
+		e_unknown= -1,
+		e_circle = 0,
+		e_polygon = 1,
+		e_typeCount = 2,
+	};
+
+	b2Shape() { m_type = e_unknown; }
+	virtual ~b2Shape() {}
+
+	/// Clone the concrete shape using the provided allocator.
+	virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
+
+	/// Get the type of this shape. You can use this to down cast to the concrete shape.
+	/// @return the shape type.
+	Type GetType() const;
+
+	/// Test a point for containment in this shape. This only works for convex shapes.
+	/// @param xf the shape world transform.
+	/// @param p a point in world coordinates.
+	virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0;
+
+	/// Cast a ray against this shape.
+	/// @param output the ray-cast results.
+	/// @param input the ray-cast input parameters.
+	/// @param transform the transform to be applied to the shape.
+	virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0;
+
+	/// Given a transform, compute the associated axis aligned bounding box for this shape.
+	/// @param aabb returns the axis aligned box.
+	/// @param xf the world transform of the shape.
+	virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0;
+
+	/// Compute the mass properties of this shape using its dimensions and density.
+	/// The inertia tensor is computed about the local origin.
+	/// @param massData returns the mass data for this shape.
+	/// @param density the density in kilograms per meter squared.
+	virtual void ComputeMass(b2MassData* massData, float32 density) const = 0;
+
+	Type m_type;
+	float32 m_radius;
+};
+
+inline b2Shape::Type b2Shape::GetType() const
+{
+	return m_type;
+}
+
+#endif

+ 229 - 0
include/Box2D/Collision/b2BroadPhase.h

@@ -0,0 +1,229 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BROAD_PHASE_H
+#define B2_BROAD_PHASE_H
+
+#include <Box2D/Common/b2Settings.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/b2DynamicTree.h>
+#include <algorithm>
+
+struct b2Pair
+{
+	int32 proxyIdA;
+	int32 proxyIdB;
+	int32 next;
+};
+
+/// The broad-phase is used for computing pairs and performing volume queries and ray casts.
+/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
+/// It is up to the client to consume the new pairs and to track subsequent overlap.
+class b2BroadPhase
+{
+public:
+
+	enum
+	{
+		e_nullProxy = -1,
+	};
+
+	b2BroadPhase();
+	~b2BroadPhase();
+
+	/// Create a proxy with an initial AABB. Pairs are not reported until
+	/// UpdatePairs is called.
+	int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+	/// Destroy a proxy. It is up to the client to remove any pairs.
+	void DestroyProxy(int32 proxyId);
+
+	/// Call MoveProxy as many times as you like, then when you are done
+	/// call UpdatePairs to finalized the proxy pairs (for your time step).
+	void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);
+
+	/// Get the fat AABB for a proxy.
+	const b2AABB& GetFatAABB(int32 proxyId) const;
+
+	/// Get user data from a proxy. Returns NULL if the id is invalid.
+	void* GetUserData(int32 proxyId) const;
+
+	/// Test overlap of fat AABBs.
+	bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
+
+	/// Get the number of proxies.
+	int32 GetProxyCount() const;
+
+	/// Update the pairs. This results in pair callbacks. This can only add pairs.
+	template <typename T>
+	void UpdatePairs(T* callback);
+
+	/// Query an AABB for overlapping proxies. The callback class
+	/// is called for each proxy that overlaps the supplied AABB.
+	template <typename T>
+	void Query(T* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast against the proxies in the tree. This relies on the callback
+	/// to perform a exact ray-cast in the case were the proxy contains a shape.
+	/// The callback also performs the any collision filtering. This has performance
+	/// roughly equal to k * log(n), where k is the number of collisions and n is the
+	/// number of proxies in the tree.
+	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+	/// @param callback a callback class that is called for each proxy that is hit by the ray.
+	template <typename T>
+	void RayCast(T* callback, const b2RayCastInput& input) const;
+
+	/// Compute the height of the embedded tree.
+	int32 ComputeHeight() const;
+
+private:
+
+	friend class b2DynamicTree;
+
+	void BufferMove(int32 proxyId);
+	void UnBufferMove(int32 proxyId);
+
+	bool QueryCallback(int32 proxyId);
+
+	b2DynamicTree m_tree;
+
+	int32 m_proxyCount;
+
+	int32* m_moveBuffer;
+	int32 m_moveCapacity;
+	int32 m_moveCount;
+
+	b2Pair* m_pairBuffer;
+	int32 m_pairCapacity;
+	int32 m_pairCount;
+
+	int32 m_queryProxyId;
+};
+
+/// This is used to sort pairs.
+inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
+{
+	if (pair1.proxyIdA < pair2.proxyIdA)
+	{
+		return true;
+	}
+
+	if (pair1.proxyIdA == pair2.proxyIdA)
+	{
+		return pair1.proxyIdB < pair2.proxyIdB;
+	}
+
+	return false;
+}
+
+inline void* b2BroadPhase::GetUserData(int32 proxyId) const
+{
+	return m_tree.GetUserData(proxyId);
+}
+
+inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
+{
+	const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
+	const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
+	return b2TestOverlap(aabbA, aabbB);
+}
+
+inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
+{
+	return m_tree.GetFatAABB(proxyId);
+}
+
+inline int32 b2BroadPhase::GetProxyCount() const
+{
+	return m_proxyCount;
+}
+
+inline int32 b2BroadPhase::ComputeHeight() const
+{
+	return m_tree.ComputeHeight();
+}
+
+template <typename T>
+void b2BroadPhase::UpdatePairs(T* callback)
+{
+	// Reset pair buffer
+	m_pairCount = 0;
+
+	// Perform tree queries for all moving proxies.
+	for (int32 i = 0; i < m_moveCount; ++i)
+	{
+		m_queryProxyId = m_moveBuffer[i];
+		if (m_queryProxyId == e_nullProxy)
+		{
+			continue;
+		}
+
+		// We have to query the tree with the fat AABB so that
+		// we don't fail to create a pair that may touch later.
+		const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
+
+		// Query tree, create pairs and add them pair buffer.
+		m_tree.Query(this, fatAABB);
+	}
+
+	// Reset move buffer
+	m_moveCount = 0;
+
+	// Sort the pair buffer to expose duplicates.
+	std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);
+
+	// Send the pairs back to the client.
+	int32 i = 0;
+	while (i < m_pairCount)
+	{
+		b2Pair* primaryPair = m_pairBuffer + i;
+		void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
+		void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
+
+		callback->AddPair(userDataA, userDataB);
+		++i;
+
+		// Skip any duplicate pairs.
+		while (i < m_pairCount)
+		{
+			b2Pair* pair = m_pairBuffer + i;
+			if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB)
+			{
+				break;
+			}
+			++i;
+		}
+	}
+
+	// Try to keep the tree balanced.
+	m_tree.Rebalance(4);
+}
+
+template <typename T>
+inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
+{
+	m_tree.Query(callback, aabb);
+}
+
+template <typename T>
+inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
+{
+	m_tree.RayCast(callback, input);
+}
+
+#endif

+ 240 - 0
include/Box2D/Collision/b2Collision.h

@@ -0,0 +1,240 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_COLLISION_H
+#define B2_COLLISION_H
+
+#include <Box2D/Common/b2Math.h>
+#include <climits>
+
+/// @file
+/// Structures and functions used for computing contact points, distance
+/// queries, and TOI queries.
+
+class b2Shape;
+class b2CircleShape;
+class b2PolygonShape;
+
+const uint8 b2_nullFeature = UCHAR_MAX;
+
+/// Contact ids to facilitate warm starting.
+union b2ContactID
+{
+	/// The features that intersect to form the contact point
+	struct Features
+	{
+		uint8 referenceEdge;	///< The edge that defines the outward contact normal.
+		uint8 incidentEdge;		///< The edge most anti-parallel to the reference edge.
+		uint8 incidentVertex;	///< The vertex (0 or 1) on the incident edge that was clipped.
+		uint8 flip;				///< A value of 1 indicates that the reference edge is on shape2.
+	} features;
+	uint32 key;					///< Used to quickly compare contact ids.
+};
+
+/// A manifold point is a contact point belonging to a contact
+/// manifold. It holds details related to the geometry and dynamics
+/// of the contact points.
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleB
+/// -e_faceA: the local center of cirlceB or the clip point of polygonB
+/// -e_faceB: the clip point of polygonA
+/// This structure is stored across time steps, so we keep it small.
+/// Note: the impulses are used for internal caching and may not
+/// provide reliable contact forces, especially for high speed collisions.
+struct b2ManifoldPoint
+{
+	b2Vec2 localPoint;		///< usage depends on manifold type
+	float32 normalImpulse;	///< the non-penetration impulse
+	float32 tangentImpulse;	///< the friction impulse
+	b2ContactID id;			///< uniquely identifies a contact point between two shapes
+};
+
+/// A manifold for two touching convex shapes.
+/// Box2D supports multiple types of contact:
+/// - clip point versus plane with radius
+/// - point versus point with radius (circles)
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleA
+/// -e_faceA: the center of faceA
+/// -e_faceB: the center of faceB
+/// Similarly the local normal usage:
+/// -e_circles: not used
+/// -e_faceA: the normal on polygonA
+/// -e_faceB: the normal on polygonB
+/// We store contacts in this way so that position correction can
+/// account for movement, which is critical for continuous physics.
+/// All contact scenarios must be expressed in one of these types.
+/// This structure is stored across time steps, so we keep it small.
+struct b2Manifold
+{
+	enum Type
+	{
+		e_circles,
+		e_faceA,
+		e_faceB
+	};
+
+	b2ManifoldPoint points[b2_maxManifoldPoints];	///< the points of contact
+	b2Vec2 localNormal;								///< not use for Type::e_points
+	b2Vec2 localPoint;								///< usage depends on manifold type
+	Type type;
+	int32 pointCount;								///< the number of manifold points
+};
+
+/// This is used to compute the current state of a contact manifold.
+struct b2WorldManifold
+{
+	/// Evaluate the manifold with supplied transforms. This assumes
+	/// modest motion from the original state. This does not change the
+	/// point count, impulses, etc. The radii must come from the shapes
+	/// that generated the manifold.
+	void Initialize(const b2Manifold* manifold,
+					const b2Transform& xfA, float32 radiusA,
+					const b2Transform& xfB, float32 radiusB);
+
+	b2Vec2 normal;						///< world vector pointing from A to B
+	b2Vec2 points[b2_maxManifoldPoints];	///< world contact point (point of intersection)
+};
+
+/// This is used for determining the state of contact points.
+enum b2PointState
+{
+	b2_nullState,		///< point does not exist
+	b2_addState,		///< point was added in the update
+	b2_persistState,	///< point persisted across the update
+	b2_removeState		///< point was removed in the update
+};
+
+/// Compute the point states given two manifolds. The states pertain to the transition from manifold1
+/// to manifold2. So state1 is either persist or remove while state2 is either add or persist.
+void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
+					  const b2Manifold* manifold1, const b2Manifold* manifold2);
+
+/// Used for computing contact manifolds.
+struct b2ClipVertex
+{
+	b2Vec2 v;
+	b2ContactID id;
+};
+
+/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+struct b2RayCastInput
+{
+	b2Vec2 p1, p2;
+	float32 maxFraction;
+};
+
+/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
+/// come from b2RayCastInput.
+struct b2RayCastOutput
+{
+	b2Vec2 normal;
+	float32 fraction;
+};
+
+/// An axis aligned bounding box.
+struct b2AABB
+{
+	/// Verify that the bounds are sorted.
+	bool IsValid() const;
+
+	/// Get the center of the AABB.
+	b2Vec2 GetCenter() const
+	{
+		return 0.5f * (lowerBound + upperBound);
+	}
+
+	/// Get the extents of the AABB (half-widths).
+	b2Vec2 GetExtents() const
+	{
+		return 0.5f * (upperBound - lowerBound);
+	}
+
+	/// Combine two AABBs into this one.
+	void Combine(const b2AABB& aabb1, const b2AABB& aabb2)
+	{
+		lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
+		upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
+	}
+
+	/// Does this aabb contain the provided AABB.
+	bool Contains(const b2AABB& aabb) const
+	{
+		bool result = true;
+		result = result && lowerBound.x <= aabb.lowerBound.x;
+		result = result && lowerBound.y <= aabb.lowerBound.y;
+		result = result && aabb.upperBound.x <= upperBound.x;
+		result = result && aabb.upperBound.y <= upperBound.y;
+		return result;
+	}
+
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
+
+	b2Vec2 lowerBound;	///< the lower vertex
+	b2Vec2 upperBound;	///< the upper vertex
+};
+
+/// Compute the collision manifold between two circles.
+void b2CollideCircles(b2Manifold* manifold,
+					  const b2CircleShape* circle1, const b2Transform& xf1,
+					  const b2CircleShape* circle2, const b2Transform& xf2);
+
+/// Compute the collision manifold between a polygon and a circle.
+void b2CollidePolygonAndCircle(b2Manifold* manifold,
+							   const b2PolygonShape* polygon, const b2Transform& xf1,
+							   const b2CircleShape* circle, const b2Transform& xf2);
+
+/// Compute the collision manifold between two polygons.
+void b2CollidePolygons(b2Manifold* manifold,
+					   const b2PolygonShape* polygon1, const b2Transform& xf1,
+					   const b2PolygonShape* polygon2, const b2Transform& xf2);
+
+/// Clipping for contact manifolds.
+int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
+							const b2Vec2& normal, float32 offset);
+
+/// Determine if two generic shapes overlap.
+bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB,
+				   const b2Transform& xfA, const b2Transform& xfB);
+
+// ---------------- Inline Functions ------------------------------------------
+
+inline bool b2AABB::IsValid() const
+{
+	b2Vec2 d = upperBound - lowerBound;
+	bool valid = d.x >= 0.0f && d.y >= 0.0f;
+	valid = valid && lowerBound.IsValid() && upperBound.IsValid();
+	return valid;
+}
+
+inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b)
+{
+	b2Vec2 d1, d2;
+	d1 = b.lowerBound - a.upperBound;
+	d2 = a.lowerBound - b.upperBound;
+
+	if (d1.x > 0.0f || d1.y > 0.0f)
+		return false;
+
+	if (d2.x > 0.0f || d2.y > 0.0f)
+		return false;
+
+	return true;
+}
+
+#endif

+ 141 - 0
include/Box2D/Collision/b2Distance.h

@@ -0,0 +1,141 @@
+
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DISTANCE_H
+#define B2_DISTANCE_H
+
+#include <Box2D/Common/b2Math.h>
+#include <climits>
+
+class b2Shape;
+
+/// A distance proxy is used by the GJK algorithm.
+/// It encapsulates any shape.
+struct b2DistanceProxy
+{
+	b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {}
+
+	/// Initialize the proxy using the given shape. The shape
+	/// must remain in scope while the proxy is in use.
+	void Set(const b2Shape* shape);
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const;
+
+	/// Get a vertex by index. Used by b2Distance.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	const b2Vec2* m_vertices;
+	int32 m_count;
+	float32 m_radius;
+};
+
+/// Used to warm start b2Distance.
+/// Set count to zero on first call.
+struct b2SimplexCache
+{
+	float32 metric;		///< length or area
+	uint16 count;
+	uint8 indexA[3];	///< vertices on shape A
+	uint8 indexB[3];	///< vertices on shape B
+};
+
+/// Input for b2Distance.
+/// You have to option to use the shape radii
+/// in the computation. Even 
+struct b2DistanceInput
+{
+	b2DistanceProxy proxyA;
+	b2DistanceProxy proxyB;
+	b2Transform transformA;
+	b2Transform transformB;
+	bool useRadii;
+};
+
+/// Output for b2Distance.
+struct b2DistanceOutput
+{
+	b2Vec2 pointA;		///< closest point on shapeA
+	b2Vec2 pointB;		///< closest point on shapeB
+	float32 distance;
+	int32 iterations;	///< number of GJK iterations used
+};
+
+/// Compute the closest points between two shapes. Supports any combination of:
+/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output.
+/// On the first call set b2SimplexCache.count to zero.
+void b2Distance(b2DistanceOutput* output,
+				b2SimplexCache* cache, 
+				const b2DistanceInput* input);
+
+
+//////////////////////////////////////////////////////////////////////////
+
+inline int32 b2DistanceProxy::GetVertexCount() const
+{
+	return m_count;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const
+{
+	b2Assert(0 <= index && index < m_count);
+	return m_vertices[index];
+}
+
+inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_count; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return bestIndex;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_count; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return m_vertices[bestIndex];
+}
+
+#endif

+ 286 - 0
include/Box2D/Collision/b2DynamicTree.h

@@ -0,0 +1,286 @@
+/*
+* Copyright (c) 2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DYNAMIC_TREE_H
+#define B2_DYNAMIC_TREE_H
+
+#include <Box2D/Collision/b2Collision.h>
+
+/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
+
+#define b2_nullNode (-1)
+
+/// A node in the dynamic tree. The client does not interact with this directly.
+struct b2DynamicTreeNode
+{
+	bool IsLeaf() const
+	{
+		return child1 == b2_nullNode;
+	}
+
+	/// This is the fattened AABB.
+	b2AABB aabb;
+
+	//int32 userData;
+	void* userData;
+
+	union
+	{
+		int32 parent;
+		int32 next;
+	};
+
+	int32 child1;
+	int32 child2;
+};
+
+/// A dynamic tree arranges data in a binary tree to accelerate
+/// queries such as volume queries and ray casts. Leafs are proxies
+/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
+/// so that the proxy AABB is bigger than the client object. This allows the client
+/// object to move by small amounts without triggering a tree update.
+///
+/// Nodes are pooled and relocatable, so we use node indices rather than pointers.
+class b2DynamicTree
+{
+public:
+
+	/// Constructing the tree initializes the node pool.
+	b2DynamicTree();
+
+	/// Destroy the tree, freeing the node pool.
+	~b2DynamicTree();
+
+	/// Create a proxy. Provide a tight fitting AABB and a userData pointer.
+	int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+	/// Destroy a proxy. This asserts if the id is invalid.
+	void DestroyProxy(int32 proxyId);
+
+	/// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
+	/// then the proxy is removed from the tree and re-inserted. Otherwise
+	/// the function returns immediately.
+	/// @return true if the proxy was re-inserted.
+	bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement);
+
+	/// Perform some iterations to re-balance the tree.
+	void Rebalance(int32 iterations);
+
+	/// Get proxy user data.
+	/// @return the proxy user data or 0 if the id is invalid.
+	void* GetUserData(int32 proxyId) const;
+
+	/// Get the fat AABB for a proxy.
+	const b2AABB& GetFatAABB(int32 proxyId) const;
+
+	/// Compute the height of the tree.
+	int32 ComputeHeight() const;
+
+	/// Query an AABB for overlapping proxies. The callback class
+	/// is called for each proxy that overlaps the supplied AABB.
+	template <typename T>
+	void Query(T* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast against the proxies in the tree. This relies on the callback
+	/// to perform a exact ray-cast in the case were the proxy contains a shape.
+	/// The callback also performs the any collision filtering. This has performance
+	/// roughly equal to k * log(n), where k is the number of collisions and n is the
+	/// number of proxies in the tree.
+	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+	/// @param callback a callback class that is called for each proxy that is hit by the ray.
+	template <typename T>
+	void RayCast(T* callback, const b2RayCastInput& input) const;
+
+private:
+
+	int32 AllocateNode();
+	void FreeNode(int32 node);
+
+	void InsertLeaf(int32 node);
+	void RemoveLeaf(int32 node);
+
+	int32 ComputeHeight(int32 nodeId) const;
+
+	int32 m_root;
+
+	b2DynamicTreeNode* m_nodes;
+	int32 m_nodeCount;
+	int32 m_nodeCapacity;
+
+	int32 m_freeList;
+
+	/// This is used incrementally traverse the tree for re-balancing.
+	uint32 m_path;
+
+	int32 m_insertionCount;
+};
+
+inline void* b2DynamicTree::GetUserData(int32 proxyId) const
+{
+	b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+	return m_nodes[proxyId].userData;
+}
+
+inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const
+{
+	b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+	return m_nodes[proxyId].aabb;
+}
+
+template <typename T>
+inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const
+{
+	const int32 k_stackSize = 128;
+	int32 stack[k_stackSize];
+
+	int32 count = 0;
+	stack[count++] = m_root;
+
+	while (count > 0)
+	{
+		int32 nodeId = stack[--count];
+		if (nodeId == b2_nullNode)
+		{
+			continue;
+		}
+
+		const b2DynamicTreeNode* node = m_nodes + nodeId;
+
+		if (b2TestOverlap(node->aabb, aabb))
+		{
+			if (node->IsLeaf())
+			{
+				bool proceed = callback->QueryCallback(nodeId);
+				if (proceed == false)
+				{
+					return;
+				}
+			}
+			else
+			{
+				if (count < k_stackSize)
+				{
+					stack[count++] = node->child1;
+				}
+
+				if (count < k_stackSize)
+				{
+					stack[count++] = node->child2;
+				}
+			}
+		}
+	}
+}
+
+template <typename T>
+inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const
+{
+	b2Vec2 p1 = input.p1;
+	b2Vec2 p2 = input.p2;
+	b2Vec2 r = p2 - p1;
+	b2Assert(r.LengthSquared() > 0.0f);
+	r.Normalize();
+
+	// v is perpendicular to the segment.
+	b2Vec2 v = b2Cross(1.0f, r);
+	b2Vec2 abs_v = b2Abs(v);
+
+	// Separating axis for segment (Gino, p80).
+	// |dot(v, p1 - c)| > dot(|v|, h)
+
+	float32 maxFraction = input.maxFraction;
+
+	// Build a bounding box for the segment.
+	b2AABB segmentAABB;
+	{
+		b2Vec2 t = p1 + maxFraction * (p2 - p1);
+		segmentAABB.lowerBound = b2Min(p1, t);
+		segmentAABB.upperBound = b2Max(p1, t);
+	}
+
+	const int32 k_stackSize = 128;
+	int32 stack[k_stackSize];
+
+	int32 count = 0;
+	stack[count++] = m_root;
+
+	while (count > 0)
+	{
+		int32 nodeId = stack[--count];
+		if (nodeId == b2_nullNode)
+		{
+			continue;
+		}
+
+		const b2DynamicTreeNode* node = m_nodes + nodeId;
+
+		if (b2TestOverlap(node->aabb, segmentAABB) == false)
+		{
+			continue;
+		}
+
+		// Separating axis for segment (Gino, p80).
+		// |dot(v, p1 - c)| > dot(|v|, h)
+		b2Vec2 c = node->aabb.GetCenter();
+		b2Vec2 h = node->aabb.GetExtents();
+		float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);
+		if (separation > 0.0f)
+		{
+			continue;
+		}
+
+		if (node->IsLeaf())
+		{
+			b2RayCastInput subInput;
+			subInput.p1 = input.p1;
+			subInput.p2 = input.p2;
+			subInput.maxFraction = maxFraction;
+
+			float32 value = callback->RayCastCallback(subInput, nodeId);
+
+			if (value == 0.0f)
+			{
+				// The client has terminated the ray cast.
+				return;
+			}
+
+			if (value > 0.0f)
+			{
+				// Update segment bounding box.
+				maxFraction = value;
+				b2Vec2 t = p1 + maxFraction * (p2 - p1);
+				segmentAABB.lowerBound = b2Min(p1, t);
+				segmentAABB.upperBound = b2Max(p1, t);
+			}
+		}
+		else
+		{
+			if (count < k_stackSize)
+			{
+				stack[count++] = node->child1;
+			}
+
+			if (count < k_stackSize)
+			{
+				stack[count++] = node->child2;
+			}
+		}
+	}
+}
+
+#endif

+ 59 - 0
include/Box2D/Collision/b2TimeOfImpact.h

@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TIME_OF_IMPACT_H
+#define B2_TIME_OF_IMPACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Distance.h>
+#include <climits>
+
+/// Input parameters for b2TimeOfImpact
+struct b2TOIInput
+{
+	b2DistanceProxy proxyA;
+	b2DistanceProxy proxyB;
+	b2Sweep sweepA;
+	b2Sweep sweepB;
+	float32 tMax;		// defines sweep interval [0, tMax]
+};
+
+// Output parameters for b2TimeOfImpact.
+struct b2TOIOutput
+{
+	enum State
+	{
+		e_unknown,
+		e_failed,
+		e_overlapped,
+		e_touching,
+		e_separated
+	};
+
+	State state;
+	float32 t;
+};
+
+/// Compute the upper bound on time before two shapes penetrate. Time is represented as
+/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
+/// non-tunneling collision. If you change the time interval, you should call this function
+/// again.
+/// Note: use b2Distance to compute the contact point and normal at the time of impact.
+void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input);
+
+#endif

+ 59 - 0
include/Box2D/Common/b2BlockAllocator.h

@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BLOCK_ALLOCATOR_H
+#define B2_BLOCK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_chunkSize = 4096;
+const int32 b2_maxBlockSize = 640;
+const int32 b2_blockSizes = 14;
+const int32 b2_chunkArrayIncrement = 128;
+
+struct b2Block;
+struct b2Chunk;
+
+// This is a small object allocator used for allocating small
+// objects that persist for more than one time step.
+// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp
+class b2BlockAllocator
+{
+public:
+	b2BlockAllocator();
+	~b2BlockAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p, int32 size);
+
+	void Clear();
+
+private:
+
+	b2Chunk* m_chunks;
+	int32 m_chunkCount;
+	int32 m_chunkSpace;
+
+	b2Block* m_freeLists[b2_blockSizes];
+
+	static int32 s_blockSizes[b2_blockSizes];
+	static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
+	static bool s_blockSizeLookupInitialized;
+};
+
+#endif

+ 624 - 0
include/Box2D/Common/b2Math.h

@@ -0,0 +1,624 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_MATH_H
+#define B2_MATH_H
+
+#include <Box2D/Common/b2Settings.h>
+
+#include <cmath>
+#include <cfloat>
+#include <cstddef>
+#include <limits>
+
+/// This function is used to ensure that a floating point number is
+/// not a NaN or infinity.
+inline bool b2IsValid(float32 x)
+{
+	if (x != x)
+	{
+		// NaN.
+		return false;
+	}
+
+	float32 infinity = std::numeric_limits<float32>::infinity();
+	return -infinity < x && x < infinity;
+}
+
+/// This is a approximate yet fast inverse square-root.
+inline float32 b2InvSqrt(float32 x)
+{
+	union
+	{
+		float32 x;
+		int32 i;
+	} convert;
+
+	convert.x = x;
+	float32 xhalf = 0.5f * x;
+	convert.i = 0x5f3759df - (convert.i >> 1);
+	x = convert.x;
+	x = x * (1.5f - xhalf * x * x);
+	return x;
+}
+
+#define	b2Sqrt(x)	sqrtf(x)
+#define	b2Atan2(y, x)	atan2f(y, x)
+
+inline float32 b2Abs(float32 a)
+{
+	return a > 0.0f ? a : -a;
+}
+
+/// A 2D column vector.
+struct b2Vec2
+{
+	/// Default constructor does nothing (for performance).
+	b2Vec2() {}
+
+	/// Construct using coordinates.
+	b2Vec2(float32 x, float32 y) : x(x), y(y) {}
+
+	/// Set this vector to all zeros.
+	void SetZero() { x = 0.0f; y = 0.0f; }
+
+	/// Set this vector to some specified coordinates.
+	void Set(float32 x_, float32 y_) { x = x_; y = y_; }
+
+	/// Negate this vector.
+	b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
+	
+	/// Read from and indexed element.
+	float32 operator () (int32 i) const
+	{
+		return (&x)[i];
+	}
+
+	/// Write to an indexed element.
+	float32& operator () (int32 i)
+	{
+		return (&x)[i];
+	}
+
+	/// Add a vector to this vector.
+	void operator += (const b2Vec2& v)
+	{
+		x += v.x; y += v.y;
+	}
+	
+	/// Subtract a vector from this vector.
+	void operator -= (const b2Vec2& v)
+	{
+		x -= v.x; y -= v.y;
+	}
+
+	/// Multiply this vector by a scalar.
+	void operator *= (float32 a)
+	{
+		x *= a; y *= a;
+	}
+
+	/// Get the length of this vector (the norm).
+	float32 Length() const
+	{
+		return b2Sqrt(x * x + y * y);
+	}
+
+	/// Get the length squared. For performance, use this instead of
+	/// b2Vec2::Length (if possible).
+	float32 LengthSquared() const
+	{
+		return x * x + y * y;
+	}
+
+	/// Convert this vector into a unit vector. Returns the length.
+	float32 Normalize()
+	{
+		float32 length = Length();
+		if (length < b2_epsilon)
+		{
+			return 0.0f;
+		}
+		float32 invLength = 1.0f / length;
+		x *= invLength;
+		y *= invLength;
+
+		return length;
+	}
+
+	/// Does this vector contain finite coordinates?
+	bool IsValid() const
+	{
+		return b2IsValid(x) && b2IsValid(y);
+	}
+
+	float32 x, y;
+};
+
+/// A 2D column vector with 3 elements.
+struct b2Vec3
+{
+	/// Default constructor does nothing (for performance).
+	b2Vec3() {}
+
+	/// Construct using coordinates.
+	b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
+
+	/// Set this vector to all zeros.
+	void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }
+
+	/// Set this vector to some specified coordinates.
+	void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; }
+
+	/// Negate this vector.
+	b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; }
+
+	/// Add a vector to this vector.
+	void operator += (const b2Vec3& v)
+	{
+		x += v.x; y += v.y; z += v.z;
+	}
+
+	/// Subtract a vector from this vector.
+	void operator -= (const b2Vec3& v)
+	{
+		x -= v.x; y -= v.y; z -= v.z;
+	}
+
+	/// Multiply this vector by a scalar.
+	void operator *= (float32 s)
+	{
+		x *= s; y *= s; z *= s;
+	}
+
+	float32 x, y, z;
+};
+
+/// A 2-by-2 matrix. Stored in column-major order.
+struct b2Mat22
+{
+	/// The default constructor does nothing (for performance).
+	b2Mat22() {}
+
+	/// Construct this matrix using columns.
+	b2Mat22(const b2Vec2& c1, const b2Vec2& c2)
+	{
+		col1 = c1;
+		col2 = c2;
+	}
+
+	/// Construct this matrix using scalars.
+	b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22)
+	{
+		col1.x = a11; col1.y = a21;
+		col2.x = a12; col2.y = a22;
+	}
+
+	/// Construct this matrix using an angle. This matrix becomes
+	/// an orthonormal rotation matrix.
+	explicit b2Mat22(float32 angle)
+	{
+		// TODO_ERIN compute sin+cos together.
+		float32 c = cosf(angle), s = sinf(angle);
+		col1.x = c; col2.x = -s;
+		col1.y = s; col2.y = c;
+	}
+
+	/// Initialize this matrix using columns.
+	void Set(const b2Vec2& c1, const b2Vec2& c2)
+	{
+		col1 = c1;
+		col2 = c2;
+	}
+
+	/// Initialize this matrix using an angle. This matrix becomes
+	/// an orthonormal rotation matrix.
+	void Set(float32 angle)
+	{
+		float32 c = cosf(angle), s = sinf(angle);
+		col1.x = c; col2.x = -s;
+		col1.y = s; col2.y = c;
+	}
+
+	/// Set this to the identity matrix.
+	void SetIdentity()
+	{
+		col1.x = 1.0f; col2.x = 0.0f;
+		col1.y = 0.0f; col2.y = 1.0f;
+	}
+
+	/// Set this matrix to all zeros.
+	void SetZero()
+	{
+		col1.x = 0.0f; col2.x = 0.0f;
+		col1.y = 0.0f; col2.y = 0.0f;
+	}
+
+	/// Extract the angle from this matrix (assumed to be
+	/// a rotation matrix).
+	float32 GetAngle() const
+	{
+		return b2Atan2(col1.y, col1.x);
+	}
+
+	b2Mat22 GetInverse() const
+	{
+		float32 a = col1.x, b = col2.x, c = col1.y, d = col2.y;
+		b2Mat22 B;
+		float32 det = a * d - b * c;
+		if (det != 0.0f)
+		{
+			det = 1.0f / det;
+		}
+		B.col1.x =  det * d;	B.col2.x = -det * b;
+		B.col1.y = -det * c;	B.col2.y =  det * a;
+		return B;
+	}
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases.
+	b2Vec2 Solve(const b2Vec2& b) const
+	{
+		float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y;
+		float32 det = a11 * a22 - a12 * a21;
+		if (det != 0.0f)
+		{
+			det = 1.0f / det;
+		}
+		b2Vec2 x;
+		x.x = det * (a22 * b.x - a12 * b.y);
+		x.y = det * (a11 * b.y - a21 * b.x);
+		return x;
+	}
+
+	b2Vec2 col1, col2;
+};
+
+/// A 3-by-3 matrix. Stored in column-major order.
+struct b2Mat33
+{
+	/// The default constructor does nothing (for performance).
+	b2Mat33() {}
+
+	/// Construct this matrix using columns.
+	b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3)
+	{
+		col1 = c1;
+		col2 = c2;
+		col3 = c3;
+	}
+
+	/// Set this matrix to all zeros.
+	void SetZero()
+	{
+		col1.SetZero();
+		col2.SetZero();
+		col3.SetZero();
+	}
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases.
+	b2Vec3 Solve33(const b2Vec3& b) const;
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases. Solve only the upper
+	/// 2-by-2 matrix equation.
+	b2Vec2 Solve22(const b2Vec2& b) const;
+
+	b2Vec3 col1, col2, col3;
+};
+
+/// A transform contains translation and rotation. It is used to represent
+/// the position and orientation of rigid frames.
+struct b2Transform
+{
+	/// The default constructor does nothing (for performance).
+	b2Transform() {}
+
+	/// Initialize using a position vector and a rotation matrix.
+	b2Transform(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {}
+
+	/// Set this to the identity transform.
+	void SetIdentity()
+	{
+		position.SetZero();
+		R.SetIdentity();
+	}
+
+	/// Set this based on the position and angle.
+	void Set(const b2Vec2& p, float32 angle)
+	{
+		position = p;
+		R.Set(angle);
+	}
+
+	/// Calculate the angle that the rotation matrix represents.
+	float32 GetAngle() const
+	{
+		return b2Atan2(R.col1.y, R.col1.x);
+	}
+
+	b2Vec2 position;
+	b2Mat22 R;
+};
+
+/// This describes the motion of a body/shape for TOI computation.
+/// Shapes are defined with respect to the body origin, which may
+/// no coincide with the center of mass. However, to support dynamics
+/// we must interpolate the center of mass position.
+struct b2Sweep
+{
+	/// Get the interpolated transform at a specific time.
+	/// @param alpha is a factor in [0,1], where 0 indicates t0.
+	void GetTransform(b2Transform* xf, float32 alpha) const;
+
+	/// Advance the sweep forward, yielding a new initial state.
+	/// @param t the new initial time.
+	void Advance(float32 t);
+
+	/// Normalize the angles.
+	void Normalize();
+
+	b2Vec2 localCenter;	///< local center of mass position
+	b2Vec2 c0, c;		///< center world positions
+	float32 a0, a;		///< world angles
+};
+
+
+extern const b2Vec2 b2Vec2_zero;
+extern const b2Mat22 b2Mat22_identity;
+extern const b2Transform b2Transform_identity;
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.x + a.y * b.y;
+}
+
+/// Perform the cross product on two vectors. In 2D this produces a scalar.
+inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.y - a.y * b.x;
+}
+
+/// Perform the cross product on a vector and a scalar. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(const b2Vec2& a, float32 s)
+{
+	return b2Vec2(s * a.y, -s * a.x);
+}
+
+/// Perform the cross product on a scalar and a vector. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(float32 s, const b2Vec2& a)
+{
+	return b2Vec2(-s * a.y, s * a.x);
+}
+
+/// Multiply a matrix times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another.
+inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v)
+{
+	return b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y);
+}
+
+/// Multiply a matrix transpose times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another (inverse transform).
+inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v)
+{
+	return b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2));
+}
+
+/// Add two vectors component-wise.
+inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x + b.x, a.y + b.y);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x - b.x, a.y - b.y);
+}
+
+inline b2Vec2 operator * (float32 s, const b2Vec2& a)
+{
+	return b2Vec2(s * a.x, s * a.y);
+}
+
+inline bool operator == (const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x == b.x && a.y == b.y;
+}
+
+inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - b;
+	return c.Length();
+}
+
+inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - b;
+	return b2Dot(c, c);
+}
+
+inline b2Vec3 operator * (float32 s, const b2Vec3& a)
+{
+	return b2Vec3(s * a.x, s * a.y, s * a.z);
+}
+
+/// Add two vectors component-wise.
+inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
+}
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b)
+{
+	return a.x * b.x + a.y * b.y + a.z * b.z;
+}
+
+/// Perform the cross product on two vectors.
+inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
+}
+
+inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B)
+{
+	return b2Mat22(A.col1 + B.col1, A.col2 + B.col2);
+}
+
+// A * B
+inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B)
+{
+	return b2Mat22(b2Mul(A, B.col1), b2Mul(A, B.col2));
+}
+
+// A^T * B
+inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B)
+{
+	b2Vec2 c1(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1));
+	b2Vec2 c2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2));
+	return b2Mat22(c1, c2);
+}
+
+/// Multiply a matrix times a vector.
+inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v)
+{
+	return v.x * A.col1 + v.y * A.col2 + v.z * A.col3;
+}
+
+inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v)
+{
+	float32 x = T.position.x + T.R.col1.x * v.x + T.R.col2.x * v.y;
+	float32 y = T.position.y + T.R.col1.y * v.x + T.R.col2.y * v.y;
+
+	return b2Vec2(x, y);
+}
+
+inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v)
+{
+	return b2MulT(T.R, v - T.position);
+}
+
+inline b2Vec2 b2Abs(const b2Vec2& a)
+{
+	return b2Vec2(b2Abs(a.x), b2Abs(a.y));
+}
+
+inline b2Mat22 b2Abs(const b2Mat22& A)
+{
+	return b2Mat22(b2Abs(A.col1), b2Abs(A.col2));
+}
+
+template <typename T>
+inline T b2Min(T a, T b)
+{
+	return a < b ? a : b;
+}
+
+inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Max(T a, T b)
+{
+	return a > b ? a : b;
+}
+
+inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Clamp(T a, T low, T high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+template<typename T> inline void b2Swap(T& a, T& b)
+{
+	T tmp = a;
+	a = b;
+	b = tmp;
+}
+
+/// "Next Largest Power of 2
+/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
+/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
+/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
+/// largest power of 2. For a 32-bit value:"
+inline uint32 b2NextPowerOfTwo(uint32 x)
+{
+	x |= (x >> 1);
+	x |= (x >> 2);
+	x |= (x >> 4);
+	x |= (x >> 8);
+	x |= (x >> 16);
+	return x + 1;
+}
+
+inline bool b2IsPowerOfTwo(uint32 x)
+{
+	bool result = x > 0 && (x & (x - 1)) == 0;
+	return result;
+}
+
+inline void b2Sweep::GetTransform(b2Transform* xf, float32 alpha) const
+{
+	xf->position = (1.0f - alpha) * c0 + alpha * c;
+	float32 angle = (1.0f - alpha) * a0 + alpha * a;
+	xf->R.Set(angle);
+
+	// Shift to origin
+	xf->position -= b2Mul(xf->R, localCenter);
+}
+
+inline void b2Sweep::Advance(float32 t)
+{
+	c0 = (1.0f - t) * c0 + t * c;
+	a0 = (1.0f - t) * a0 + t * a;
+}
+
+/// Normalize an angle in radians to be between -pi and pi
+inline void b2Sweep::Normalize()
+{
+	float32 twoPi = 2.0f * b2_pi;
+	float32 d =  twoPi * floorf(a0 / twoPi);
+	a0 -= d;
+	a -= d;
+}
+
+#endif

+ 151 - 0
include/Box2D/Common/b2Settings.h

@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_SETTINGS_H
+#define B2_SETTINGS_H
+
+#include <cassert>
+#include <cmath>
+
+#define B2_NOT_USED(x) ((void)(x))
+#define b2Assert(A) assert(A)
+
+typedef signed char	int8;
+typedef signed short int16;
+typedef signed int int32;
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint32;
+typedef float float32;
+
+#define	b2_maxFloat		FLT_MAX
+#define	b2_epsilon		FLT_EPSILON
+#define b2_pi			3.14159265359f
+
+/// @file
+/// Global tuning constants based on meters-kilograms-seconds (MKS) units.
+///
+
+// Collision
+
+/// The maximum number of contact points between two convex shapes.
+#define b2_maxManifoldPoints	2
+
+/// The maximum number of vertices on a convex polygon.
+#define b2_maxPolygonVertices	8
+
+/// This is used to fatten AABBs in the dynamic tree. This allows proxies
+/// to move by a small amount without triggering a tree adjustment.
+/// This is in meters.
+#define b2_aabbExtension		0.1f
+
+/// This is used to fatten AABBs in the dynamic tree. This is used to predict
+/// the future position based on the current displacement.
+/// This is a dimensionless multiplier.
+#define b2_aabbMultiplier		2.0f
+
+/// A small length used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_linearSlop			0.005f
+
+/// A small angle used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_angularSlop			(2.0f / 180.0f * b2_pi)
+
+/// The radius of the polygon/edge shape skin. This should not be modified. Making
+/// this smaller means polygons will have an insufficient buffer for continuous collision.
+/// Making it larger may create artifacts for vertex collision.
+#define b2_polygonRadius		(2.0f * b2_linearSlop)
+
+
+// Dynamics
+
+/// Maximum number of contacts to be handled to solve a TOI impact.
+#define b2_maxTOIContacts			32
+
+/// A velocity threshold for elastic collisions. Any collision with a relative linear
+/// velocity below this threshold will be treated as inelastic.
+#define b2_velocityThreshold		1.0f
+
+/// The maximum linear position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxLinearCorrection		0.2f
+
+/// The maximum angular position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxAngularCorrection		(8.0f / 180.0f * b2_pi)
+
+/// The maximum linear velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxTranslation			2.0f
+#define b2_maxTranslationSquared	(b2_maxTranslation * b2_maxTranslation)
+
+/// The maximum angular velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxRotation				(0.5f * b2_pi)
+#define b2_maxRotationSquared		(b2_maxRotation * b2_maxRotation)
+
+/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so
+/// that overlap is removed in one time step. However using values close to 1 often lead
+/// to overshoot.
+#define b2_contactBaumgarte			0.2f
+
+// Sleep
+
+/// The time that a body must be still before it will go to sleep.
+#define b2_timeToSleep				0.5f
+
+/// A body cannot sleep if its linear velocity is above this tolerance.
+#define b2_linearSleepTolerance		0.01f
+
+/// A body cannot sleep if its angular velocity is above this tolerance.
+#define b2_angularSleepTolerance	(2.0f / 180.0f * b2_pi)
+
+// Memory Allocation
+
+/// Implement this function to use your own memory allocator.
+void* b2Alloc(int32 size);
+
+/// If you implement b2Alloc, you should also implement this function.
+void b2Free(void* mem);
+
+/// Version numbering scheme.
+/// See http://en.wikipedia.org/wiki/Software_versioning
+struct b2Version
+{
+	int32 major;		///< significant changes
+	int32 minor;		///< incremental changes
+	int32 revision;		///< bug fixes
+};
+
+/// Current version.
+extern b2Version b2_version;
+
+/// Friction mixing law. Feel free to customize this.
+inline float32 b2MixFriction(float32 friction1, float32 friction2)
+{
+	return sqrtf(friction1 * friction2);
+}
+
+/// Restitution mixing law. Feel free to customize this.
+inline float32 b2MixRestitution(float32 restitution1, float32 restitution2)
+{
+	return restitution1 > restitution2 ? restitution1 : restitution2;
+}
+
+#endif

+ 60 - 0
include/Box2D/Common/b2StackAllocator.h

@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_STACK_ALLOCATOR_H
+#define B2_STACK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_stackSize = 100 * 1024;	// 100k
+const int32 b2_maxStackEntries = 32;
+
+struct b2StackEntry
+{
+	char* data;
+	int32 size;
+	bool usedMalloc;
+};
+
+// This is a stack allocator used for fast per step allocations.
+// You must nest allocate/free pairs. The code will assert
+// if you try to interleave multiple allocate/free pairs.
+class b2StackAllocator
+{
+public:
+	b2StackAllocator();
+	~b2StackAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p);
+
+	int32 GetMaxAllocation() const;
+
+private:
+
+	char m_data[b2_stackSize];
+	int32 m_index;
+
+	int32 m_allocation;
+	int32 m_maxAllocation;
+
+	b2StackEntry m_entries[b2_maxStackEntries];
+	int32 m_entryCount;
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2CircleContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CIRCLE_CONTACT_H
+#define B2_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2CircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2CircleContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 242 - 0
include/Box2D/Dynamics/Contacts/b2Contact.h

@@ -0,0 +1,242 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_H
+#define B2_CONTACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+class b2Body;
+class b2Contact;
+class b2Fixture;
+class b2World;
+class b2BlockAllocator;
+class b2StackAllocator;
+class b2ContactListener;
+
+typedef b2Contact* b2ContactCreateFcn(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator);
+
+struct b2ContactRegister
+{
+	b2ContactCreateFcn* createFcn;
+	b2ContactDestroyFcn* destroyFcn;
+	bool primary;
+};
+
+/// A contact edge is used to connect bodies and contacts together
+/// in a contact graph where each body is a node and each contact
+/// is an edge. A contact edge belongs to a doubly linked list
+/// maintained in each attached body. Each contact has two contact
+/// nodes, one for each attached body.
+struct b2ContactEdge
+{
+	b2Body* other;			///< provides quick access to the other body attached.
+	b2Contact* contact;		///< the contact
+	b2ContactEdge* prev;	///< the previous contact edge in the body's contact list
+	b2ContactEdge* next;	///< the next contact edge in the body's contact list
+};
+
+/// The class manages contact between two shapes. A contact exists for each overlapping
+/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
+/// that has no contact points.
+class b2Contact
+{
+public:
+
+	/// Get the contact manifold. Do not modify the manifold unless you understand the
+	/// internals of Box2D.
+	b2Manifold* GetManifold();
+	const b2Manifold* GetManifold() const;
+
+	/// Get the world manifold.
+	void GetWorldManifold(b2WorldManifold* worldManifold) const;
+
+	/// Is this contact touching?
+	bool IsTouching() const;
+
+	/// Enable/disable this contact. This can be used inside the pre-solve
+	/// contact listener. The contact is only disabled for the current
+	/// time step (or sub-step in continuous collisions).
+	void SetEnabled(bool flag);
+
+	/// Has this contact been disabled?
+	bool IsEnabled() const;
+
+	/// Get the next contact in the world's contact list.
+	b2Contact* GetNext();
+	const b2Contact* GetNext() const;
+
+	/// Get the first fixture in this contact.
+	b2Fixture* GetFixtureA();
+	const b2Fixture* GetFixtureA() const;
+
+	/// Get the second fixture in this contact.
+	b2Fixture* GetFixtureB();
+	const b2Fixture* GetFixtureB() const;
+
+	/// Evaluate this contact with your own manifold and transforms.
+	virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0;
+
+protected:
+	friend class b2ContactManager;
+	friend class b2World;
+	friend class b2ContactSolver;
+	friend class b2Body;
+	friend class b2Fixture;
+
+	// Flags stored in m_flags
+	enum
+	{
+		// Used when crawling contact graph when forming islands.
+		e_islandFlag		= 0x0001,
+
+        // Set when the shapes are touching.
+		e_touchingFlag		= 0x0002,
+
+		// This contact can be disabled (by user)
+		e_enabledFlag		= 0x0004,
+
+		// This contact needs filtering because a fixture filter was changed.
+		e_filterFlag		= 0x0008,
+
+		// This bullet contact had a TOI event
+		e_bulletHitFlag		= 0x0010,
+
+	};
+
+	/// Flag this contact for filtering. Filtering will occur the next time step.
+	void FlagForFiltering();
+
+	static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn,
+						b2Shape::Type typeA, b2Shape::Type typeB);
+	static void InitializeRegisters();
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {}
+	b2Contact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	virtual ~b2Contact() {}
+
+	void Update(b2ContactListener* listener);
+
+	static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
+	static bool s_initialized;
+
+	uint32 m_flags;
+
+	// World pool and list pointers.
+	b2Contact* m_prev;
+	b2Contact* m_next;
+
+	// Nodes for connecting bodies.
+	b2ContactEdge m_nodeA;
+	b2ContactEdge m_nodeB;
+
+	b2Fixture* m_fixtureA;
+	b2Fixture* m_fixtureB;
+
+	b2Manifold m_manifold;
+
+	int32 m_toiCount;
+//	float32 m_toi;
+};
+
+inline b2Manifold* b2Contact::GetManifold()
+{
+	return &m_manifold;
+}
+
+inline const b2Manifold* b2Contact::GetManifold() const
+{
+	return &m_manifold;
+}
+
+inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const
+{
+	const b2Body* bodyA = m_fixtureA->GetBody();
+	const b2Body* bodyB = m_fixtureB->GetBody();
+	const b2Shape* shapeA = m_fixtureA->GetShape();
+	const b2Shape* shapeB = m_fixtureB->GetShape();
+
+	worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius);
+}
+
+inline void b2Contact::SetEnabled(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_enabledFlag;
+	}
+	else
+	{
+		m_flags &= ~e_enabledFlag;
+	}
+}
+
+inline bool b2Contact::IsEnabled() const
+{
+	return (m_flags & e_enabledFlag) == e_enabledFlag;
+}
+
+inline bool b2Contact::IsTouching() const
+{
+	return (m_flags & e_touchingFlag) == e_touchingFlag;
+}
+
+inline b2Contact* b2Contact::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Contact* b2Contact::GetNext() const
+{
+	return m_next;
+}
+
+inline b2Fixture* b2Contact::GetFixtureA()
+{
+	return m_fixtureA;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureA() const
+{
+	return m_fixtureA;
+}
+
+inline b2Fixture* b2Contact::GetFixtureB()
+{
+	return m_fixtureB;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureB() const
+{
+	return m_fixtureB;
+}
+
+inline void b2Contact::FlagForFiltering()
+{
+	m_flags |= e_filterFlag;
+}
+
+#endif

+ 78 - 0
include/Box2D/Dynamics/Contacts/b2ContactSolver.h

@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_SOLVER_H
+#define B2_CONTACT_SOLVER_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Dynamics/b2Island.h>
+
+class b2Contact;
+class b2Body;
+class b2StackAllocator;
+
+struct b2ContactConstraintPoint
+{
+	b2Vec2 localPoint;
+	b2Vec2 rA;
+	b2Vec2 rB;
+	float32 normalImpulse;
+	float32 tangentImpulse;
+	float32 normalMass;
+	float32 tangentMass;
+	float32 velocityBias;
+};
+
+struct b2ContactConstraint
+{
+	b2ContactConstraintPoint points[b2_maxManifoldPoints];
+	b2Vec2 localNormal;
+	b2Vec2 localPoint;
+	b2Vec2 normal;
+	b2Mat22 normalMass;
+	b2Mat22 K;
+	b2Body* bodyA;
+	b2Body* bodyB;
+	b2Manifold::Type type;
+	float32 radius;
+	float32 friction;
+	int32 pointCount;
+	b2Manifold* manifold;
+};
+
+class b2ContactSolver
+{
+public:
+	b2ContactSolver(b2Contact** contacts, int32 contactCount,
+					b2StackAllocator* allocator, float32 impulseRatio);
+
+	~b2ContactSolver();
+
+	void WarmStart();
+	void SolveVelocityConstraints();
+	void StoreImpulses();
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2StackAllocator* m_allocator;
+	b2ContactConstraint* m_constraints;
+	int m_constraintCount;
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H
+#define B2_POLYGON_AND_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonAndCircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2PolygonAndCircleContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2PolygonContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_CONTACT_H
+#define B2_POLYGON_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2PolygonContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 51 - 0
include/Box2D/Dynamics/Contacts/b2TOISolver.h

@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TOI_SOLVER_H
+#define B2_TOI_SOLVER_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Contact;
+class b2Body;
+struct b2TOIConstraint;
+class b2StackAllocator;
+
+/// This is a pure position solver for a single movable body in contact with
+/// multiple non-moving bodies.
+class b2TOISolver
+{
+public:
+	b2TOISolver(b2StackAllocator* allocator);
+	~b2TOISolver();
+
+	void Initialize(b2Contact** contacts, int32 contactCount, b2Body* toiBody);
+	void Clear();
+
+	// Perform one solver iteration. Returns true if converged.
+	bool Solve(float32 baumgarte);
+
+private:
+
+	b2TOIConstraint* m_constraints;
+	int32 m_count;
+	b2Body* m_toiBody;
+	b2StackAllocator* m_allocator;
+};
+
+#endif

+ 140 - 0
include/Box2D/Dynamics/Joints/b2DistanceJoint.h

@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DISTANCE_JOINT_H
+#define B2_DISTANCE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Distance joint definition. This requires defining an
+/// anchor point on both bodies and the non-zero length of the
+/// distance joint. The definition uses local anchor points
+/// so that the initial configuration can violate the constraint
+/// slightly. This helps when saving and loading a game.
+/// @warning Do not use a zero or short length.
+struct b2DistanceJointDef : public b2JointDef
+{
+	b2DistanceJointDef()
+	{
+		type = e_distanceJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		length = 1.0f;
+		frequencyHz = 0.0f;
+		dampingRatio = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, and length using the world
+	/// anchors.
+	void Initialize(b2Body* bodyA, b2Body* bodyB,
+					const b2Vec2& anchorA, const b2Vec2& anchorB);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The natural length between the anchor points.
+	float32 length;
+
+	/// The mass-spring-damper frequency in Hertz.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// A distance joint constrains two points on two bodies
+/// to remain at a fixed distance from each other. You can view
+/// this as a massless, rigid rod.
+class b2DistanceJoint : public b2Joint
+{
+public:
+
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set/get the natural length.
+	/// Manipulating the length can lead to non-physical behavior when the frequency is zero.
+	void SetLength(float32 length);
+	float32 GetLength() const;
+
+	// Set/get frequency in Hz.
+	void SetFrequency(float32 hz);
+	float32 GetFrequency() const;
+
+	// Set/get damping ratio.
+	void SetDampingRatio(float32 ratio);
+	float32 GetDampingRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2DistanceJoint(const b2DistanceJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_u;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_gamma;
+	float32 m_bias;
+	float32 m_impulse;
+	float32 m_mass;
+	float32 m_length;
+};
+
+inline void b2DistanceJoint::SetLength(float32 length)
+{
+	m_length = length;
+}
+
+inline float32 b2DistanceJoint::GetLength() const
+{
+	return m_length;
+}
+
+inline void b2DistanceJoint::SetFrequency(float32 hz)
+{
+	m_frequencyHz = hz;
+}
+
+inline float32 b2DistanceJoint::GetFrequency() const
+{
+	return m_frequencyHz;
+}
+
+inline void b2DistanceJoint::SetDampingRatio(float32 ratio)
+{
+	m_dampingRatio = ratio;
+}
+
+inline float32 b2DistanceJoint::GetDampingRatio() const
+{
+	return m_dampingRatio;
+}
+
+#endif

+ 99 - 0
include/Box2D/Dynamics/Joints/b2FrictionJoint.h

@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_FRICTION_JOINT_H
+#define B2_FRICTION_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Friction joint definition.
+struct b2FrictionJointDef : public b2JointDef
+{
+	b2FrictionJointDef()
+	{
+		type = e_frictionJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		maxForce = 0.0f;
+		maxTorque = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
+
+	/// The local anchor point relative to bodyA's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to bodyB's origin.
+	b2Vec2 localAnchorB;
+
+	/// The maximum friction force in N.
+	float32 maxForce;
+
+	/// The maximum friction torque in N-m.
+	float32 maxTorque;
+};
+
+/// Friction joint. This is used for top-down friction.
+/// It provides 2D translational friction and angular friction.
+class b2FrictionJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set the maximum friction force in N.
+	void SetMaxForce(float32 force);
+
+	/// Get the maximum friction force in N.
+	float32 GetMaxForce() const;
+
+	/// Set the maximum friction torque in N*m.
+	void SetMaxTorque(float32 torque);
+
+	/// Get the maximum friction torque in N*m.
+	float32 GetMaxTorque() const;
+
+protected:
+
+	friend class b2Joint;
+
+	b2FrictionJoint(const b2FrictionJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchorA;
+	b2Vec2 m_localAnchorB;
+
+	b2Mat22 m_linearMass;
+	float32 m_angularMass;
+
+	b2Vec2 m_linearImpulse;
+	float32 m_angularImpulse;
+
+	float32 m_maxForce;
+	float32 m_maxTorque;
+};
+
+#endif

+ 111 - 0
include/Box2D/Dynamics/Joints/b2GearJoint.h

@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_GEAR_JOINT_H
+#define B2_GEAR_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+class b2RevoluteJoint;
+class b2PrismaticJoint;
+
+/// Gear joint definition. This definition requires two existing
+/// revolute or prismatic joints (any combination will work).
+/// The provided joints must attach a dynamic body to a static body.
+struct b2GearJointDef : public b2JointDef
+{
+	b2GearJointDef()
+	{
+		type = e_gearJoint;
+		joint1 = NULL;
+		joint2 = NULL;
+		ratio = 1.0f;
+	}
+
+	/// The first revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint1;
+
+	/// The second revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint2;
+
+	/// The gear ratio.
+	/// @see b2GearJoint for explanation.
+	float32 ratio;
+};
+
+/// A gear joint is used to connect two joints together. Either joint
+/// can be a revolute or prismatic joint. You specify a gear ratio
+/// to bind the motions together:
+/// coordinate1 + ratio * coordinate2 = constant
+/// The ratio can be negative or positive. If one joint is a revolute joint
+/// and the other joint is a prismatic joint, then the ratio will have units
+/// of length or units of 1/length.
+/// @warning The revolute and prismatic joints must be attached to
+/// fixed bodies (which must be body1 on those joints).
+class b2GearJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set/Get the gear ratio.
+	void SetRatio(float32 ratio);
+	float32 GetRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2GearJoint(const b2GearJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Body* m_ground1;
+	b2Body* m_ground2;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute1;
+	b2PrismaticJoint* m_prismatic1;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute2;
+	b2PrismaticJoint* m_prismatic2;
+
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Jacobian m_J;
+
+	float32 m_constant;
+	float32 m_ratio;
+
+	// Effective mass
+	float32 m_mass;
+
+	// Impulse for accumulation/warm starting.
+	float32 m_impulse;
+};
+
+#endif

+ 226 - 0
include/Box2D/Dynamics/Joints/b2Joint.h

@@ -0,0 +1,226 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_JOINT_H
+#define B2_JOINT_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Body;
+class b2Joint;
+struct b2TimeStep;
+class b2BlockAllocator;
+
+enum b2JointType
+{
+	e_unknownJoint,
+	e_revoluteJoint,
+	e_prismaticJoint,
+	e_distanceJoint,
+	e_pulleyJoint,
+	e_mouseJoint,
+	e_gearJoint,
+	e_lineJoint,
+    e_weldJoint,
+	e_frictionJoint,
+};
+
+enum b2LimitState
+{
+	e_inactiveLimit,
+	e_atLowerLimit,
+	e_atUpperLimit,
+	e_equalLimits
+};
+
+struct b2Jacobian
+{
+	b2Vec2 linearA;
+	float32 angularA;
+	b2Vec2 linearB;
+	float32 angularB;
+
+	void SetZero();
+	void Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2);
+	float32 Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2);
+};
+
+/// A joint edge is used to connect bodies and joints together
+/// in a joint graph where each body is a node and each joint
+/// is an edge. A joint edge belongs to a doubly linked list
+/// maintained in each attached body. Each joint has two joint
+/// nodes, one for each attached body.
+struct b2JointEdge
+{
+	b2Body* other;			///< provides quick access to the other body attached.
+	b2Joint* joint;			///< the joint
+	b2JointEdge* prev;		///< the previous joint edge in the body's joint list
+	b2JointEdge* next;		///< the next joint edge in the body's joint list
+};
+
+/// Joint definitions are used to construct joints.
+struct b2JointDef
+{
+	b2JointDef()
+	{
+		type = e_unknownJoint;
+		userData = NULL;
+		bodyA = NULL;
+		bodyB = NULL;
+		collideConnected = false;
+	}
+
+	/// The joint type is set automatically for concrete joint types.
+	b2JointType type;
+
+	/// Use this to attach application specific data to your joints.
+	void* userData;
+
+	/// The first attached body.
+	b2Body* bodyA;
+
+	/// The second attached body.
+	b2Body* bodyB;
+
+	/// Set this flag to true if the attached bodies should collide.
+	bool collideConnected;
+};
+
+/// The base joint class. Joints are used to constraint two bodies together in
+/// various fashions. Some joints also feature limits and motors.
+class b2Joint
+{
+public:
+
+	/// Get the type of the concrete joint.
+	b2JointType GetType() const;
+
+	/// Get the first body attached to this joint.
+	b2Body* GetBodyA();
+
+	/// Get the second body attached to this joint.
+	b2Body* GetBodyB();
+
+	/// Get the anchor point on bodyA in world coordinates.
+	virtual b2Vec2 GetAnchorA() const = 0;
+
+	/// Get the anchor point on bodyB in world coordinates.
+	virtual b2Vec2 GetAnchorB() const = 0;
+
+	/// Get the reaction force on body2 at the joint anchor in Newtons.
+	virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0;
+
+	/// Get the reaction torque on body2 in N*m.
+	virtual float32 GetReactionTorque(float32 inv_dt) const = 0;
+
+	/// Get the next joint the world joint list.
+	b2Joint* GetNext();
+
+	/// Get the user data pointer.
+	void* GetUserData() const;
+
+	/// Set the user data pointer.
+	void SetUserData(void* data);
+
+	/// Short-cut function to determine if either body is inactive.
+	bool IsActive() const;
+
+protected:
+	friend class b2World;
+	friend class b2Body;
+	friend class b2Island;
+
+	static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator);
+	static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
+
+	b2Joint(const b2JointDef* def);
+	virtual ~b2Joint() {}
+
+	virtual void InitVelocityConstraints(const b2TimeStep& step) = 0;
+	virtual void SolveVelocityConstraints(const b2TimeStep& step) = 0;
+
+	// This returns true if the position errors are within tolerance.
+	virtual bool SolvePositionConstraints(float32 baumgarte) = 0;
+
+	b2JointType m_type;
+	b2Joint* m_prev;
+	b2Joint* m_next;
+	b2JointEdge m_edgeA;
+	b2JointEdge m_edgeB;
+	b2Body* m_bodyA;
+	b2Body* m_bodyB;
+
+	bool m_islandFlag;
+	bool m_collideConnected;
+
+	void* m_userData;
+
+	// Cache here per time step to reduce cache misses.
+	b2Vec2 m_localCenterA, m_localCenterB;
+	float32 m_invMassA, m_invIA;
+	float32 m_invMassB, m_invIB;
+};
+
+inline void b2Jacobian::SetZero()
+{
+	linearA.SetZero(); angularA = 0.0f;
+	linearB.SetZero(); angularB = 0.0f;
+}
+
+inline void b2Jacobian::Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2)
+{
+	linearA = x1; angularA = a1;
+	linearB = x2; angularB = a2;
+}
+
+inline float32 b2Jacobian::Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2)
+{
+	return b2Dot(linearA, x1) + angularA * a1 + b2Dot(linearB, x2) + angularB * a2;
+}
+
+inline b2JointType b2Joint::GetType() const
+{
+	return m_type;
+}
+
+inline b2Body* b2Joint::GetBodyA()
+{
+	return m_bodyA;
+}
+
+inline b2Body* b2Joint::GetBodyB()
+{
+	return m_bodyB;
+}
+
+inline b2Joint* b2Joint::GetNext()
+{
+	return m_next;
+}
+
+inline void* b2Joint::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Joint::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+#endif

+ 170 - 0
include/Box2D/Dynamics/Joints/b2LineJoint.h

@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_LINE_JOINT_H
+#define B2_LINE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Line joint definition. This requires defining a line of
+/// motion using an axis and an anchor point. The definition uses local
+/// anchor points and a local axis so that the initial configuration
+/// can violate the constraint slightly. The joint translation is zero
+/// when the local anchor points coincide in world space. Using local
+/// anchors and a local axis helps when saving and loading a game.
+struct b2LineJointDef : public b2JointDef
+{
+	b2LineJointDef()
+	{
+		type = e_lineJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		localAxisA.Set(1.0f, 0.0f);
+		enableLimit = false;
+		lowerTranslation = 0.0f;
+		upperTranslation = 0.0f;
+		enableMotor = false;
+		maxMotorForce = 0.0f;
+		motorSpeed = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxisA;
+
+	/// Enable/disable the joint limit.
+	bool enableLimit;
+
+	/// The lower translation limit, usually in meters.
+	float32 lowerTranslation;
+
+	/// The upper translation limit, usually in meters.
+	float32 upperTranslation;
+
+	/// Enable/disable the joint motor.
+	bool enableMotor;
+
+	/// The maximum motor torque, usually in N-m.
+	float32 maxMotorForce;
+
+	/// The desired motor speed in radians per second.
+	float32 motorSpeed;
+};
+
+/// A line joint. This joint provides two degrees of freedom: translation
+/// along an axis fixed in body1 and rotation in the plane. You can use a
+/// joint limit to restrict the range of motion and a joint motor to drive
+/// the motion or to model joint friction.
+class b2LineJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint translation, usually in meters.
+	float32 GetJointTranslation() const;
+
+	/// Get the current joint translation speed, usually in meters per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit, usually in meters.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit, usually in meters.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits, usually in meters.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed, usually in meters per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed, usually in meters per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set/Get the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+	float32 GetMaxMotorForce() const;
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+protected:
+
+	friend class b2Joint;
+	b2LineJoint(const b2LineJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_localXAxis1;
+	b2Vec2 m_localYAxis1;
+
+	b2Vec2 m_axis, m_perp;
+	float32 m_s1, m_s2;
+	float32 m_a1, m_a2;
+
+	b2Mat22 m_K;
+	b2Vec2 m_impulse;
+
+	float32 m_motorMass;			// effective mass for motor/limit translational constraint.
+	float32 m_motorImpulse;
+
+	float32 m_lowerTranslation;
+	float32 m_upperTranslation;
+	float32 m_maxMotorForce;
+	float32 m_motorSpeed;
+
+	bool m_enableLimit;
+	bool m_enableMotor;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2LineJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 114 - 0
include/Box2D/Dynamics/Joints/b2MouseJoint.h

@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_MOUSE_JOINT_H
+#define B2_MOUSE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Mouse joint definition. This requires a world target point,
+/// tuning parameters, and the time step.
+struct b2MouseJointDef : public b2JointDef
+{
+	b2MouseJointDef()
+	{
+		type = e_mouseJoint;
+		target.Set(0.0f, 0.0f);
+		maxForce = 0.0f;
+		frequencyHz = 5.0f;
+		dampingRatio = 0.7f;
+	}
+
+	/// The initial world target point. This is assumed
+	/// to coincide with the body anchor initially.
+	b2Vec2 target;
+
+	/// The maximum constraint force that can be exerted
+	/// to move the candidate body. Usually you will express
+	/// as some multiple of the weight (multiplier * mass * gravity).
+	float32 maxForce;
+
+	/// The response speed.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// A mouse joint is used to make a point on a body track a
+/// specified world point. This a soft constraint with a maximum
+/// force. This allows the constraint to stretch and without
+/// applying huge forces.
+/// NOTE: this joint is not documented in the manual because it was
+/// developed to be used in the testbed. If you want to learn how to
+/// use the mouse joint, look at the testbed.
+class b2MouseJoint : public b2Joint
+{
+public:
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchorA() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchorB() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+
+	/// Implements b2Joint.
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Use this to update the target point.
+	void SetTarget(const b2Vec2& target);
+	const b2Vec2& GetTarget() const;
+
+	/// Set/get the maximum force in Newtons.
+	void SetMaxForce(float32 force);
+	float32 GetMaxForce() const;
+
+	/// Set/get the frequency in Hertz.
+	void SetFrequency(float32 hz);
+	float32 GetFrequency() const;
+
+	/// Set/get the damping ratio (dimensionless).
+	void SetDampingRatio(float32 ratio);
+	float32 GetDampingRatio() const;
+
+protected:
+	friend class b2Joint;
+
+	b2MouseJoint(const b2MouseJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte) { B2_NOT_USED(baumgarte); return true; }
+
+	b2Vec2 m_localAnchor;
+	b2Vec2 m_target;
+	b2Vec2 m_impulse;
+
+	b2Mat22 m_mass;		// effective mass for point-to-point constraint.
+	b2Vec2 m_C;				// position error
+	float32 m_maxForce;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_beta;
+	float32 m_gamma;
+};
+
+#endif

+ 175 - 0
include/Box2D/Dynamics/Joints/b2PrismaticJoint.h

@@ -0,0 +1,175 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_PRISMATIC_JOINT_H
+#define B2_PRISMATIC_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Prismatic joint definition. This requires defining a line of
+/// motion using an axis and an anchor point. The definition uses local
+/// anchor points and a local axis so that the initial configuration
+/// can violate the constraint slightly. The joint translation is zero
+/// when the local anchor points coincide in world space. Using local
+/// anchors and a local axis helps when saving and loading a game.
+/// @warning at least one body should by dynamic with a non-fixed rotation.
+struct b2PrismaticJointDef : public b2JointDef
+{
+	b2PrismaticJointDef()
+	{
+		type = e_prismaticJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		localAxis1.Set(1.0f, 0.0f);
+		referenceAngle = 0.0f;
+		enableLimit = false;
+		lowerTranslation = 0.0f;
+		upperTranslation = 0.0f;
+		enableMotor = false;
+		maxMotorForce = 0.0f;
+		motorSpeed = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxis1;
+
+	/// The constrained angle between the bodies: body2_angle - body1_angle.
+	float32 referenceAngle;
+
+	/// Enable/disable the joint limit.
+	bool enableLimit;
+
+	/// The lower translation limit, usually in meters.
+	float32 lowerTranslation;
+
+	/// The upper translation limit, usually in meters.
+	float32 upperTranslation;
+
+	/// Enable/disable the joint motor.
+	bool enableMotor;
+
+	/// The maximum motor torque, usually in N-m.
+	float32 maxMotorForce;
+
+	/// The desired motor speed in radians per second.
+	float32 motorSpeed;
+};
+
+/// A prismatic joint. This joint provides one degree of freedom: translation
+/// along an axis fixed in body1. Relative rotation is prevented. You can
+/// use a joint limit to restrict the range of motion and a joint motor to
+/// drive the motion or to model joint friction.
+class b2PrismaticJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint translation, usually in meters.
+	float32 GetJointTranslation() const;
+
+	/// Get the current joint translation speed, usually in meters per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit, usually in meters.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit, usually in meters.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits, usually in meters.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed, usually in meters per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed, usually in meters per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+protected:
+	friend class b2Joint;
+	friend class b2GearJoint;
+	b2PrismaticJoint(const b2PrismaticJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_localXAxis1;
+	b2Vec2 m_localYAxis1;
+	float32 m_refAngle;
+
+	b2Vec2 m_axis, m_perp;
+	float32 m_s1, m_s2;
+	float32 m_a1, m_a2;
+
+	b2Mat33 m_K;
+	b2Vec3 m_impulse;
+
+	float32 m_motorMass;			// effective mass for motor/limit translational constraint.
+	float32 m_motorImpulse;
+
+	float32 m_lowerTranslation;
+	float32 m_upperTranslation;
+	float32 m_maxMotorForce;
+	float32 m_motorSpeed;
+	
+	bool m_enableLimit;
+	bool m_enableMotor;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2PrismaticJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 148 - 0
include/Box2D/Dynamics/Joints/b2PulleyJoint.h

@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_PULLEY_JOINT_H
+#define B2_PULLEY_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+const float32 b2_minPulleyLength = 2.0f;
+
+/// Pulley joint definition. This requires two ground anchors,
+/// two dynamic body anchor points, max lengths for each side,
+/// and a pulley ratio.
+struct b2PulleyJointDef : public b2JointDef
+{
+	b2PulleyJointDef()
+	{
+		type = e_pulleyJoint;
+		groundAnchorA.Set(-1.0f, 1.0f);
+		groundAnchorB.Set(1.0f, 1.0f);
+		localAnchorA.Set(-1.0f, 0.0f);
+		localAnchorB.Set(1.0f, 0.0f);
+		lengthA = 0.0f;
+		maxLengthA = 0.0f;
+		lengthB = 0.0f;
+		maxLengthB = 0.0f;
+		ratio = 1.0f;
+		collideConnected = true;
+	}
+
+	/// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
+	void Initialize(b2Body* bodyA, b2Body* bodyB,
+					const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB,
+					const b2Vec2& anchorA, const b2Vec2& anchorB,
+					float32 ratio);
+
+	/// The first ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchorA;
+
+	/// The second ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchorB;
+
+	/// The local anchor point relative to bodyA's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to bodyB's origin.
+	b2Vec2 localAnchorB;
+
+	/// The a reference length for the segment attached to bodyA.
+	float32 lengthA;
+
+	/// The maximum length of the segment attached to bodyA.
+	float32 maxLengthA;
+
+	/// The a reference length for the segment attached to bodyB.
+	float32 lengthB;
+
+	/// The maximum length of the segment attached to bodyB.
+	float32 maxLengthB;
+
+	/// The pulley ratio, used to simulate a block-and-tackle.
+	float32 ratio;
+};
+
+/// The pulley joint is connected to two bodies and two fixed ground points.
+/// The pulley supports a ratio such that:
+/// length1 + ratio * length2 <= constant
+/// Yes, the force transmitted is scaled by the ratio.
+/// The pulley also enforces a maximum length limit on both sides. This is
+/// useful to prevent one side of the pulley hitting the top.
+class b2PulleyJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the first ground anchor.
+	b2Vec2 GetGroundAnchorA() const;
+
+	/// Get the second ground anchor.
+	b2Vec2 GetGroundAnchorB() const;
+
+	/// Get the current length of the segment attached to body1.
+	float32 GetLength1() const;
+
+	/// Get the current length of the segment attached to body2.
+	float32 GetLength2() const;
+
+	/// Get the pulley ratio.
+	float32 GetRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2PulleyJoint(const b2PulleyJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Vec2 m_u1;
+	b2Vec2 m_u2;
+	
+	float32 m_constant;
+	float32 m_ratio;
+	
+	float32 m_maxLength1;
+	float32 m_maxLength2;
+
+	// Effective masses
+	float32 m_pulleyMass;
+	float32 m_limitMass1;
+	float32 m_limitMass2;
+
+	// Impulses for accumulation/warm starting.
+	float32 m_impulse;
+	float32 m_limitImpulse1;
+	float32 m_limitImpulse2;
+
+	b2LimitState m_state;
+	b2LimitState m_limitState1;
+	b2LimitState m_limitState2;
+};
+
+#endif

+ 174 - 0
include/Box2D/Dynamics/Joints/b2RevoluteJoint.h

@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_REVOLUTE_JOINT_H
+#define B2_REVOLUTE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Revolute joint definition. This requires defining an
+/// anchor point where the bodies are joined. The definition
+/// uses local anchor points so that the initial configuration
+/// can violate the constraint slightly. You also need to
+/// specify the initial relative angle for joint limits. This
+/// helps when saving and loading a game.
+/// The local anchor points are measured from the body's origin
+/// rather than the center of mass because:
+/// 1. you might not know where the center of mass will be.
+/// 2. if you add/remove shapes from a body and recompute the mass,
+///    the joints will be broken.
+struct b2RevoluteJointDef : public b2JointDef
+{
+	b2RevoluteJointDef()
+	{
+		type = e_revoluteJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		referenceAngle = 0.0f;
+		lowerAngle = 0.0f;
+		upperAngle = 0.0f;
+		maxMotorTorque = 0.0f;
+		motorSpeed = 0.0f;
+		enableLimit = false;
+		enableMotor = false;
+	}
+
+	/// Initialize the bodies, anchors, and reference angle using a world
+	/// anchor point.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The body2 angle minus body1 angle in the reference state (radians).
+	float32 referenceAngle;
+
+	/// A flag to enable joint limits.
+	bool enableLimit;
+
+	/// The lower angle for the joint limit (radians).
+	float32 lowerAngle;
+
+	/// The upper angle for the joint limit (radians).
+	float32 upperAngle;
+
+	/// A flag to enable the joint motor.
+	bool enableMotor;
+
+	/// The desired motor speed. Usually in radians per second.
+	float32 motorSpeed;
+
+	/// The maximum motor torque used to achieve the desired motor speed.
+	/// Usually in N-m.
+	float32 maxMotorTorque;
+};
+
+/// A revolute joint constrains two bodies to share a common point while they
+/// are free to rotate about the point. The relative rotation about the shared
+/// point is the joint angle. You can limit the relative rotation with
+/// a joint limit that specifies a lower and upper angle. You can use a motor
+/// to drive the relative rotation about the shared point. A maximum motor torque
+/// is provided so that infinite forces are not generated.
+class b2RevoluteJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint angle in radians.
+	float32 GetJointAngle() const;
+
+	/// Get the current joint angle speed in radians per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit in radians.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit in radians.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits in radians.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed in radians per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed in radians per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set the maximum motor torque, usually in N-m.
+	void SetMaxMotorTorque(float32 torque);
+
+	/// Get the current motor torque, usually in N-m.
+	float32 GetMotorTorque() const;
+
+protected:
+	
+	friend class b2Joint;
+	friend class b2GearJoint;
+
+	b2RevoluteJoint(const b2RevoluteJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;	// relative
+	b2Vec2 m_localAnchor2;
+	b2Vec3 m_impulse;
+	float32 m_motorImpulse;
+
+	b2Mat33 m_mass;			// effective mass for point-to-point constraint.
+	float32 m_motorMass;	// effective mass for motor/limit angular constraint.
+	
+	bool m_enableMotor;
+	float32 m_maxMotorTorque;
+	float32 m_motorSpeed;
+
+	bool m_enableLimit;
+	float32 m_referenceAngle;
+	float32 m_lowerAngle;
+	float32 m_upperAngle;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2RevoluteJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 82 - 0
include/Box2D/Dynamics/Joints/b2WeldJoint.h

@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WELD_JOINT_H
+#define B2_WELD_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Weld joint definition. You need to specify local anchor points
+/// where they are attached and the relative body angle. The position
+/// of the anchor points is important for computing the reaction torque.
+struct b2WeldJointDef : public b2JointDef
+{
+	b2WeldJointDef()
+	{
+		type = e_weldJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		referenceAngle = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, and reference angle using a world
+	/// anchor point.
+	void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The body2 angle minus body1 angle in the reference state (radians).
+	float32 referenceAngle;
+};
+
+/// A weld joint essentially glues two bodies together. A weld joint may
+/// distort somewhat because the island constraint solver is approximate.
+class b2WeldJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+protected:
+
+	friend class b2Joint;
+
+	b2WeldJoint(const b2WeldJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchorA;
+	b2Vec2 m_localAnchorB;
+	float32 m_referenceAngle;
+
+	b2Vec3 m_impulse;
+
+	b2Mat33 m_mass;
+};
+
+#endif

+ 802 - 0
include/Box2D/Dynamics/b2Body.h

@@ -0,0 +1,802 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BODY_H
+#define B2_BODY_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <memory>
+
+class b2Fixture;
+class b2Joint;
+class b2Contact;
+class b2Controller;
+class b2World;
+struct b2FixtureDef;
+struct b2JointEdge;
+struct b2ContactEdge;
+
+/// The body type.
+/// static: zero mass, zero velocity, may be manually moved
+/// kinematic: zero mass, non-zero velocity set by user, moved by solver
+/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver
+enum b2BodyType
+{
+	b2_staticBody = 0,
+	b2_kinematicBody,
+	b2_dynamicBody,
+};
+
+/// A body definition holds all the data needed to construct a rigid body.
+/// You can safely re-use body definitions. Shapes are added to a body after construction.
+struct b2BodyDef
+{
+	/// This constructor sets the body definition default values.
+	b2BodyDef()
+	{
+		userData = NULL;
+		position.Set(0.0f, 0.0f);
+		angle = 0.0f;
+		linearVelocity.Set(0.0f, 0.0f);
+		angularVelocity = 0.0f;
+		linearDamping = 0.0f;
+		angularDamping = 0.0f;
+		allowSleep = true;
+		awake = true;
+		fixedRotation = false;
+		bullet = false;
+		type = b2_staticBody;
+		active = true;
+		inertiaScale = 1.0f;
+	}
+
+	/// The body type: static, kinematic, or dynamic.
+	/// Note: if a dynamic body would have zero mass, the mass is set to one.
+	b2BodyType type;
+
+	/// The world position of the body. Avoid creating bodies at the origin
+	/// since this can lead to many overlapping shapes.
+	b2Vec2 position;
+
+	/// The world angle of the body in radians.
+	float32 angle;
+
+	/// The linear velocity of the body's origin in world co-ordinates.
+	b2Vec2 linearVelocity;
+
+	/// The angular velocity of the body.
+	float32 angularVelocity;
+
+	/// Linear damping is use to reduce the linear velocity. The damping parameter
+	/// can be larger than 1.0f but the damping effect becomes sensitive to the
+	/// time step when the damping parameter is large.
+	float32 linearDamping;
+
+	/// Angular damping is use to reduce the angular velocity. The damping parameter
+	/// can be larger than 1.0f but the damping effect becomes sensitive to the
+	/// time step when the damping parameter is large.
+	float32 angularDamping;
+
+	/// Set this flag to false if this body should never fall asleep. Note that
+	/// this increases CPU usage.
+	bool allowSleep;
+
+	/// Is this body initially awake or sleeping?
+	bool awake;
+
+	/// Should this body be prevented from rotating? Useful for characters.
+	bool fixedRotation;
+
+	/// Is this a fast moving body that should be prevented from tunneling through
+	/// other moving bodies? Note that all bodies are prevented from tunneling through
+	/// kinematic and static bodies. This setting is only considered on dynamic bodies.
+	/// @warning You should use this flag sparingly since it increases processing time.
+	bool bullet;
+
+	/// Does this body start out active?
+	bool active;
+
+	/// Use this to store application specific body data.
+	void* userData;
+
+	/// Experimental: scales the inertia tensor.
+	float32 inertiaScale;
+};
+
+/// A rigid body. These are created via b2World::CreateBody.
+class b2Body
+{
+public:
+	/// Creates a fixture and attach it to this body. Use this function if you need
+	/// to set some fixture parameters, like friction. Otherwise you can create the
+	/// fixture directly from a shape.
+	/// If the density is non-zero, this function automatically updates the mass of the body.
+	/// Contacts are not created until the next time step.
+	/// @param def the fixture definition.
+	/// @warning This function is locked during callbacks.
+	b2Fixture* CreateFixture(const b2FixtureDef* def);
+
+	/// Creates a fixture from a shape and attach it to this body.
+	/// This is a convenience function. Use b2FixtureDef if you need to set parameters
+	/// like friction, restitution, user data, or filtering.
+	/// If the density is non-zero, this function automatically updates the mass of the body.
+	/// @param shape the shape to be cloned.
+	/// @param density the shape density (set to zero for static bodies).
+	/// @warning This function is locked during callbacks.
+	b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
+
+	/// Destroy a fixture. This removes the fixture from the broad-phase and
+	/// destroys all contacts associated with this fixture. This will
+	/// automatically adjust the mass of the body if the body is dynamic and the
+	/// fixture has positive density.
+	/// All fixtures attached to a body are implicitly destroyed when the body is destroyed.
+	/// @param fixture the fixture to be removed.
+	/// @warning This function is locked during callbacks.
+	void DestroyFixture(b2Fixture* fixture);
+
+	/// Set the position of the body's origin and rotation.
+	/// This breaks any contacts and wakes the other bodies.
+	/// Manipulating a body's transform may cause non-physical behavior.
+	/// @param position the world position of the body's local origin.
+	/// @param angle the world rotation in radians.
+	void SetTransform(const b2Vec2& position, float32 angle);
+
+	/// Get the body transform for the body's origin.
+	/// @return the world transform of the body's origin.
+	const b2Transform& GetTransform() const;
+
+	/// Get the world body origin position.
+	/// @return the world position of the body's origin.
+	const b2Vec2& GetPosition() const;
+
+	/// Get the angle in radians.
+	/// @return the current world rotation angle in radians.
+	float32 GetAngle() const;
+
+	/// Get the world position of the center of mass.
+	const b2Vec2& GetWorldCenter() const;
+
+	/// Get the local position of the center of mass.
+	const b2Vec2& GetLocalCenter() const;
+
+	/// Set the linear velocity of the center of mass.
+	/// @param v the new linear velocity of the center of mass.
+	void SetLinearVelocity(const b2Vec2& v);
+
+	/// Get the linear velocity of the center of mass.
+	/// @return the linear velocity of the center of mass.
+	b2Vec2 GetLinearVelocity() const;
+
+	/// Set the angular velocity.
+	/// @param omega the new angular velocity in radians/second.
+	void SetAngularVelocity(float32 omega);
+
+	/// Get the angular velocity.
+	/// @return the angular velocity in radians/second.
+	float32 GetAngularVelocity() const;
+
+	/// Apply a force at a world point. If the force is not
+	/// applied at the center of mass, it will generate a torque and
+	/// affect the angular velocity. This wakes up the body.
+	/// @param force the world force vector, usually in Newtons (N).
+	/// @param point the world position of the point of application.
+	void ApplyForce(const b2Vec2& force, const b2Vec2& point);
+
+	/// Apply a torque. This affects the angular velocity
+	/// without affecting the linear velocity of the center of mass.
+	/// This wakes up the body.
+	/// @param torque about the z-axis (out of the screen), usually in N-m.
+	void ApplyTorque(float32 torque);
+
+	/// Apply an impulse at a point. This immediately modifies the velocity.
+	/// It also modifies the angular velocity if the point of application
+	/// is not at the center of mass. This wakes up the body.
+	/// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
+	/// @param point the world position of the point of application.
+	void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point);
+
+	/// Apply an angular impulse.
+	/// @param impulse the angular impulse in units of kg*m*m/s
+	void ApplyAngularImpulse(float32 impulse);
+
+	/// Get the total mass of the body.
+	/// @return the mass, usually in kilograms (kg).
+	float32 GetMass() const;
+
+	/// Get the rotational inertia of the body about the local origin.
+	/// @return the rotational inertia, usually in kg-m^2.
+	float32 GetInertia() const;
+
+	/// Get the mass data of the body.
+	/// @return a struct containing the mass, inertia and center of the body.
+	void GetMassData(b2MassData* data) const;
+
+	/// Set the mass properties to override the mass properties of the fixtures.
+	/// Note that this changes the center of mass position.
+	/// Note that creating or destroying fixtures can also alter the mass.
+	/// This function has no effect if the body isn't dynamic.
+	/// @param massData the mass properties.
+	void SetMassData(const b2MassData* data);
+
+	/// This resets the mass properties to the sum of the mass properties of the fixtures.
+	/// This normally does not need to be called unless you called SetMassData to override
+	/// the mass and you later want to reset the mass.
+	void ResetMassData();
+
+	/// Get the world coordinates of a point given the local coordinates.
+	/// @param localPoint a point on the body measured relative the the body's origin.
+	/// @return the same point expressed in world coordinates.
+	b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
+
+	/// Get the world coordinates of a vector given the local coordinates.
+	/// @param localVector a vector fixed in the body.
+	/// @return the same vector expressed in world coordinates.
+	b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
+
+	/// Gets a local point relative to the body's origin given a world point.
+	/// @param a point in world coordinates.
+	/// @return the corresponding local point relative to the body's origin.
+	b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
+
+	/// Gets a local vector given a world vector.
+	/// @param a vector in world coordinates.
+	/// @return the corresponding local vector.
+	b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
+
+	/// Get the world linear velocity of a world point attached to this body.
+	/// @param a point in world coordinates.
+	/// @return the world velocity of a point.
+	b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
+
+	/// Get the world velocity of a local point.
+	/// @param a point in local coordinates.
+	/// @return the world velocity of a point.
+	b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
+
+	/// Get the linear damping of the body.
+	float32 GetLinearDamping() const;
+
+	/// Set the linear damping of the body.
+	void SetLinearDamping(float32 linearDamping);
+
+	/// Get the angular damping of the body.
+	float32 GetAngularDamping() const;
+
+	/// Set the angular damping of the body.
+	void SetAngularDamping(float32 angularDamping);
+
+	/// Set the type of this body. This may alter the mass and velocity.
+	void SetType(b2BodyType type);
+
+	/// Get the type of this body.
+	b2BodyType GetType() const;
+
+	/// Should this body be treated like a bullet for continuous collision detection?
+	void SetBullet(bool flag);
+
+	/// Is this body treated like a bullet for continuous collision detection?
+	bool IsBullet() const;
+
+	/// You can disable sleeping on this body. If you disable sleeping, the
+	/// body will be woken.
+	void SetSleepingAllowed(bool flag);
+
+	/// Is this body allowed to sleep
+	bool IsSleepingAllowed() const;
+
+	/// Set the sleep state of the body. A sleeping body has very
+	/// low CPU cost.
+	/// @param flag set to true to put body to sleep, false to wake it.
+	void SetAwake(bool flag);
+
+	/// Get the sleeping state of this body.
+	/// @return true if the body is sleeping.
+	bool IsAwake() const;
+
+	/// Set the active state of the body. An inactive body is not
+	/// simulated and cannot be collided with or woken up.
+	/// If you pass a flag of true, all fixtures will be added to the
+	/// broad-phase.
+	/// If you pass a flag of false, all fixtures will be removed from
+	/// the broad-phase and all contacts will be destroyed.
+	/// Fixtures and joints are otherwise unaffected. You may continue
+	/// to create/destroy fixtures and joints on inactive bodies.
+	/// Fixtures on an inactive body are implicitly inactive and will
+	/// not participate in collisions, ray-casts, or queries.
+	/// Joints connected to an inactive body are implicitly inactive.
+	/// An inactive body is still owned by a b2World object and remains
+	/// in the body list.
+	void SetActive(bool flag);
+
+	/// Get the active state of the body.
+	bool IsActive() const;
+
+	/// Set this body to have fixed rotation. This causes the mass
+	/// to be reset.
+	void SetFixedRotation(bool flag);
+
+	/// Does this body have fixed rotation?
+	bool IsFixedRotation() const;
+
+	/// Get the list of all fixtures attached to this body.
+	b2Fixture* GetFixtureList();
+	const b2Fixture* GetFixtureList() const;
+
+	/// Get the list of all joints attached to this body.
+	b2JointEdge* GetJointList();
+	const b2JointEdge* GetJointList() const;
+
+	/// Get the list of all contacts attached to this body.
+	/// @warning this list changes during the time step and you may
+	/// miss some collisions if you don't use b2ContactListener.
+	b2ContactEdge* GetContactList();
+	const b2ContactEdge* GetContactList() const;
+
+	/// Get the next body in the world's body list.
+	b2Body* GetNext();
+	const b2Body* GetNext() const;
+
+	/// Get the user data pointer that was provided in the body definition.
+	void* GetUserData() const;
+
+	/// Set the user data. Use this to store your application specific data.
+	void SetUserData(void* data);
+
+	/// Get the parent world of this body.
+	b2World* GetWorld();
+	const b2World* GetWorld() const;
+
+private:
+
+	friend class b2World;
+	friend class b2Island;
+	friend class b2ContactManager;
+	friend class b2ContactSolver;
+	friend class b2TOISolver;
+	
+	friend class b2DistanceJoint;
+	friend class b2GearJoint;
+	friend class b2LineJoint;
+	friend class b2MouseJoint;
+	friend class b2PrismaticJoint;
+	friend class b2PulleyJoint;
+	friend class b2RevoluteJoint;
+	friend class b2WeldJoint;
+	friend class b2FrictionJoint;
+
+	// m_flags
+	enum
+	{
+		e_islandFlag		= 0x0001,
+		e_awakeFlag			= 0x0002,
+		e_autoSleepFlag		= 0x0004,
+		e_bulletFlag		= 0x0008,
+		e_fixedRotationFlag	= 0x0010,
+		e_activeFlag		= 0x0020,
+		e_toiFlag			= 0x0040,
+	};
+
+	b2Body(const b2BodyDef* bd, b2World* world);
+	~b2Body();
+
+	void SynchronizeFixtures();
+	void SynchronizeTransform();
+
+	// This is used to prevent connected bodies from colliding.
+	// It may lie, depending on the collideConnected flag.
+	bool ShouldCollide(const b2Body* other) const;
+
+	void Advance(float32 t);
+
+	b2BodyType m_type;
+
+	uint16 m_flags;
+
+	int32 m_islandIndex;
+
+	b2Transform m_xf;		// the body origin transform
+	b2Sweep m_sweep;		// the swept motion for CCD
+
+	b2Vec2 m_linearVelocity;
+	float32 m_angularVelocity;
+
+	b2Vec2 m_force;
+	float32 m_torque;
+
+	b2World* m_world;
+	b2Body* m_prev;
+	b2Body* m_next;
+
+	b2Fixture* m_fixtureList;
+	int32 m_fixtureCount;
+
+	b2JointEdge* m_jointList;
+	b2ContactEdge* m_contactList;
+
+	float32 m_mass, m_invMass;
+
+	// Rotational inertia about the center of mass.
+	float32 m_I, m_invI;
+
+	float32 m_linearDamping;
+	float32 m_angularDamping;
+
+	float32 m_sleepTime;
+
+	void* m_userData;
+};
+
+inline b2BodyType b2Body::GetType() const
+{
+	return m_type;
+}
+
+inline const b2Transform& b2Body::GetTransform() const
+{
+	return m_xf;
+}
+
+inline const b2Vec2& b2Body::GetPosition() const
+{
+	return m_xf.position;
+}
+
+inline float32 b2Body::GetAngle() const
+{
+	return m_sweep.a;
+}
+
+inline const b2Vec2& b2Body::GetWorldCenter() const
+{
+	return m_sweep.c;
+}
+
+inline const b2Vec2& b2Body::GetLocalCenter() const
+{
+	return m_sweep.localCenter;
+}
+
+inline void b2Body::SetLinearVelocity(const b2Vec2& v)
+{
+	if (m_type == b2_staticBody)
+	{
+		return;
+	}
+
+	if (b2Dot(v,v) > 0.0f)
+	{
+		SetAwake(true);
+	}
+
+	m_linearVelocity = v;
+}
+
+inline b2Vec2 b2Body::GetLinearVelocity() const
+{
+	return m_linearVelocity;
+}
+
+inline void b2Body::SetAngularVelocity(float32 w)
+{
+	if (m_type == b2_staticBody)
+	{
+		return;
+	}
+
+	if (w * w > 0.0f)
+	{
+		SetAwake(true);
+	}
+
+	m_angularVelocity = w;
+}
+
+inline float32 b2Body::GetAngularVelocity() const
+{
+	return m_angularVelocity;
+}
+
+inline float32 b2Body::GetMass() const
+{
+	return m_mass;
+}
+
+inline float32 b2Body::GetInertia() const
+{
+	return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+}
+
+inline void b2Body::GetMassData(b2MassData* data) const
+{
+	data->mass = m_mass;
+	data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+	data->center = m_sweep.localCenter;
+}
+
+inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const
+{
+	return b2Mul(m_xf, localPoint);
+}
+
+inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const
+{
+	return b2Mul(m_xf.R, localVector);
+}
+
+inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const
+{
+	return b2MulT(m_xf, worldPoint);
+}
+
+inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const
+{
+	return b2MulT(m_xf.R, worldVector);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const
+{
+	return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const
+{
+	return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
+}
+
+inline float32 b2Body::GetLinearDamping() const
+{
+	return m_linearDamping;
+}
+
+inline void b2Body::SetLinearDamping(float32 linearDamping)
+{
+	m_linearDamping = linearDamping;
+}
+
+inline float32 b2Body::GetAngularDamping() const
+{
+	return m_angularDamping;
+}
+
+inline void b2Body::SetAngularDamping(float32 angularDamping)
+{
+	m_angularDamping = angularDamping;
+}
+
+inline void b2Body::SetBullet(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_bulletFlag;
+	}
+	else
+	{
+		m_flags &= ~e_bulletFlag;
+	}
+}
+
+inline bool b2Body::IsBullet() const
+{
+	return (m_flags & e_bulletFlag) == e_bulletFlag;
+}
+
+inline void b2Body::SetAwake(bool flag)
+{
+	if (flag)
+	{
+		if ((m_flags & e_awakeFlag) == 0)
+		{
+			m_flags |= e_awakeFlag;
+			m_sleepTime = 0.0f;
+		}
+	}
+	else
+	{
+		m_flags &= ~e_awakeFlag;
+		m_sleepTime = 0.0f;
+		m_linearVelocity.SetZero();
+		m_angularVelocity = 0.0f;
+		m_force.SetZero();
+		m_torque = 0.0f;
+	}
+}
+
+inline bool b2Body::IsAwake() const
+{
+	return (m_flags & e_awakeFlag) == e_awakeFlag;
+}
+
+inline bool b2Body::IsActive() const
+{
+	return (m_flags & e_activeFlag) == e_activeFlag;
+}
+
+inline void b2Body::SetFixedRotation(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_fixedRotationFlag;
+	}
+	else
+	{
+		m_flags &= ~e_fixedRotationFlag;
+	}
+
+	ResetMassData();
+}
+
+inline bool b2Body::IsFixedRotation() const
+{
+	return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
+}
+
+inline void b2Body::SetSleepingAllowed(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_autoSleepFlag;
+	}
+	else
+	{
+		m_flags &= ~e_autoSleepFlag;
+		SetAwake(true);
+	}
+}
+
+inline bool b2Body::IsSleepingAllowed() const
+{
+	return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
+}
+
+inline b2Fixture* b2Body::GetFixtureList()
+{
+	return m_fixtureList;
+}
+
+inline const b2Fixture* b2Body::GetFixtureList() const
+{
+	return m_fixtureList;
+}
+
+inline b2JointEdge* b2Body::GetJointList()
+{
+	return m_jointList;
+}
+
+inline const b2JointEdge* b2Body::GetJointList() const
+{
+	return m_jointList;
+}
+
+inline b2ContactEdge* b2Body::GetContactList()
+{
+	return m_contactList;
+}
+
+inline const b2ContactEdge* b2Body::GetContactList() const
+{
+	return m_contactList;
+}
+
+inline b2Body* b2Body::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Body* b2Body::GetNext() const
+{
+	return m_next;
+}
+
+inline void b2Body::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+inline void* b2Body::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+
+	m_force += force;
+	m_torque += b2Cross(point - m_sweep.c, force);
+}
+
+inline void b2Body::ApplyTorque(float32 torque)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+
+	m_torque += torque;
+}
+
+inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+	m_linearVelocity += m_invMass * impulse;
+	m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
+}
+
+inline void b2Body::ApplyAngularImpulse(float32 impulse)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+	m_angularVelocity += m_invI * impulse;
+}
+
+inline void b2Body::SynchronizeTransform()
+{
+	m_xf.R.Set(m_sweep.a);
+	m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter);
+}
+
+inline void b2Body::Advance(float32 t)
+{
+	// Advance to the new safe time.
+	m_sweep.Advance(t);
+	m_sweep.c = m_sweep.c0;
+	m_sweep.a = m_sweep.a0;
+	SynchronizeTransform();
+}
+
+inline b2World* b2Body::GetWorld()
+{
+	return m_world;
+}
+
+inline const b2World* b2Body::GetWorld() const
+{
+	return m_world;
+}
+
+#endif

+ 52 - 0
include/Box2D/Dynamics/b2ContactManager.h

@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_MANAGER_H
+#define B2_CONTACT_MANAGER_H
+
+#include <Box2D/Collision/b2BroadPhase.h>
+
+class b2Contact;
+class b2ContactFilter;
+class b2ContactListener;
+class b2BlockAllocator;
+
+// Delegate of b2World.
+class b2ContactManager
+{
+public:
+	b2ContactManager();
+
+	// Broad-phase callback.
+	void AddPair(void* proxyUserDataA, void* proxyUserDataB);
+
+	void FindNewContacts();
+
+	void Destroy(b2Contact* c);
+
+	void Collide();
+            
+	b2BroadPhase m_broadPhase;
+	b2Contact* m_contactList;
+	int32 m_contactCount;
+	b2ContactFilter* m_contactFilter;
+	b2ContactListener* m_contactListener;
+	b2BlockAllocator* m_allocator;
+};
+
+#endif

+ 326 - 0
include/Box2D/Dynamics/b2Fixture.h

@@ -0,0 +1,326 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_FIXTURE_H
+#define B2_FIXTURE_H
+
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+class b2BlockAllocator;
+class b2Body;
+class b2BroadPhase;
+
+/// This holds contact filtering data.
+struct b2Filter
+{
+	/// The collision category bits. Normally you would just set one bit.
+	uint16 categoryBits;
+
+	/// The collision mask bits. This states the categories that this
+	/// shape would accept for collision.
+	uint16 maskBits;
+
+	/// Collision groups allow a certain group of objects to never collide (negative)
+	/// or always collide (positive). Zero means no collision group. Non-zero group
+	/// filtering always wins against the mask bits.
+	int16 groupIndex;
+};
+
+/// A fixture definition is used to create a fixture. This class defines an
+/// abstract fixture definition. You can reuse fixture definitions safely.
+struct b2FixtureDef
+{
+	/// The constructor sets the default fixture definition values.
+	b2FixtureDef()
+	{
+		shape = NULL;
+		userData = NULL;
+		friction = 0.2f;
+		restitution = 0.0f;
+		density = 0.0f;
+		filter.categoryBits = 0x0001;
+		filter.maskBits = 0xFFFF;
+		filter.groupIndex = 0;
+		isSensor = false;
+	}
+
+	virtual ~b2FixtureDef() {}
+
+	/// The shape, this must be set. The shape will be cloned, so you
+	/// can create the shape on the stack.
+	const b2Shape* shape;
+
+	/// Use this to store application specific fixture data.
+	void* userData;
+
+	/// The friction coefficient, usually in the range [0,1].
+	float32 friction;
+
+	/// The restitution (elasticity) usually in the range [0,1].
+	float32 restitution;
+
+	/// The density, usually in kg/m^2.
+	float32 density;
+
+	/// A sensor shape collects contact information but never generates a collision
+	/// response.
+	bool isSensor;
+
+	/// Contact filtering data.
+	b2Filter filter;
+};
+
+
+/// A fixture is used to attach a shape to a body for collision detection. A fixture
+/// inherits its transform from its parent. Fixtures hold additional non-geometric data
+/// such as friction, collision filters, etc.
+/// Fixtures are created via b2Body::CreateFixture.
+/// @warning you cannot reuse fixtures.
+class b2Fixture
+{
+public:
+	/// Get the type of the child shape. You can use this to down cast to the concrete shape.
+	/// @return the shape type.
+	b2Shape::Type GetType() const;
+
+	/// Get the child shape. You can modify the child shape, however you should not change the
+	/// number of vertices because this will crash some collision caching mechanisms.
+	/// Manipulating the shape may lead to non-physical behavior.
+	b2Shape* GetShape();
+	const b2Shape* GetShape() const;
+
+	/// Set if this fixture is a sensor.
+	void SetSensor(bool sensor);
+
+	/// Is this fixture a sensor (non-solid)?
+	/// @return the true if the shape is a sensor.
+	bool IsSensor() const;
+
+	/// Set the contact filtering data. This will not update contacts until the next time
+	/// step when either parent body is active and awake.
+	void SetFilterData(const b2Filter& filter);
+
+	/// Get the contact filtering data.
+	const b2Filter& GetFilterData() const;
+
+	/// Get the parent body of this fixture. This is NULL if the fixture is not attached.
+	/// @return the parent body.
+	b2Body* GetBody();
+	const b2Body* GetBody() const;
+
+	/// Get the next fixture in the parent body's fixture list.
+	/// @return the next shape.
+	b2Fixture* GetNext();
+	const b2Fixture* GetNext() const;
+
+	/// Get the user data that was assigned in the fixture definition. Use this to
+	/// store your application specific data.
+	void* GetUserData() const;
+
+	/// Set the user data. Use this to store your application specific data.
+	void SetUserData(void* data);
+
+	/// Test a point for containment in this fixture.
+	/// @param xf the shape world transform.
+	/// @param p a point in world coordinates.
+	bool TestPoint(const b2Vec2& p) const;
+
+	/// Cast a ray against this shape.
+	/// @param output the ray-cast results.
+	/// @param input the ray-cast input parameters.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
+
+	/// Get the mass data for this fixture. The mass data is based on the density and
+	/// the shape. The rotational inertia is about the shape's origin. This operation
+	/// may be expensive.
+	void GetMassData(b2MassData* massData) const;
+
+	/// Set the density of this fixture. This will _not_ automatically adjust the mass
+	/// of the body. You must call b2Body::ResetMassData to update the body's mass.
+	void SetDensity(float32 density);
+
+	/// Get the density of this fixture.
+	float32 GetDensity() const;
+
+	/// Get the coefficient of friction.
+	float32 GetFriction() const;
+
+	/// Set the coefficient of friction.
+	void SetFriction(float32 friction);
+
+	/// Get the coefficient of restitution.
+	float32 GetRestitution() const;
+
+	/// Set the coefficient of restitution.
+	void SetRestitution(float32 restitution);
+
+	/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
+	/// If you need a more accurate AABB, compute it using the shape and
+	/// the body transform.
+	const b2AABB& GetAABB() const;
+
+protected:
+
+	friend class b2Body;
+	friend class b2World;
+	friend class b2Contact;
+	friend class b2ContactManager;
+
+	b2Fixture();
+	~b2Fixture();
+
+	// We need separation create/destroy functions from the constructor/destructor because
+	// the destructor cannot access the allocator (no destructor arguments allowed by C++).
+	void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def);
+	void Destroy(b2BlockAllocator* allocator);
+
+	// These support body activation/deactivation.
+	void CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf);
+	void DestroyProxy(b2BroadPhase* broadPhase);
+
+	void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2);
+
+	b2AABB m_aabb;
+
+	float32 m_density;
+
+	b2Fixture* m_next;
+	b2Body* m_body;
+
+	b2Shape* m_shape;
+
+	float32 m_friction;
+	float32 m_restitution;
+
+	int32 m_proxyId;
+	b2Filter m_filter;
+
+	bool m_isSensor;
+
+	void* m_userData;
+};
+
+inline b2Shape::Type b2Fixture::GetType() const
+{
+	return m_shape->GetType();
+}
+
+inline b2Shape* b2Fixture::GetShape()
+{
+	return m_shape;
+}
+
+inline const b2Shape* b2Fixture::GetShape() const
+{
+	return m_shape;
+}
+
+inline bool b2Fixture::IsSensor() const
+{
+	return m_isSensor;
+}
+
+inline const b2Filter& b2Fixture::GetFilterData() const
+{
+	return m_filter;
+}
+
+inline void* b2Fixture::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Fixture::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+inline b2Body* b2Fixture::GetBody()
+{
+	return m_body;
+}
+
+inline const b2Body* b2Fixture::GetBody() const
+{
+	return m_body;
+}
+
+inline b2Fixture* b2Fixture::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Fixture* b2Fixture::GetNext() const
+{
+	return m_next;
+}
+
+inline void b2Fixture::SetDensity(float32 density)
+{
+	b2Assert(b2IsValid(density) && density >= 0.0f);
+	m_density = density;
+}
+
+inline float32 b2Fixture::GetDensity() const
+{
+	return m_density;
+}
+
+inline float32 b2Fixture::GetFriction() const
+{
+	return m_friction;
+}
+
+inline void b2Fixture::SetFriction(float32 friction)
+{
+	m_friction = friction;
+}
+
+inline float32 b2Fixture::GetRestitution() const
+{
+	return m_restitution;
+}
+
+inline void b2Fixture::SetRestitution(float32 restitution)
+{
+	m_restitution = restitution;
+}
+
+inline bool b2Fixture::TestPoint(const b2Vec2& p) const
+{
+	return m_shape->TestPoint(m_body->GetTransform(), p);
+}
+
+inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const
+{
+	return m_shape->RayCast(output, input, m_body->GetTransform());
+}
+
+inline void b2Fixture::GetMassData(b2MassData* massData) const
+{
+	m_shape->ComputeMass(massData, m_density);
+}
+
+inline const b2AABB& b2Fixture::GetAABB() const
+{
+	return m_aabb;
+}
+
+#endif

+ 105 - 0
include/Box2D/Dynamics/b2Island.h

@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_ISLAND_H
+#define B2_ISLAND_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+class b2Contact;
+class b2Joint;
+class b2StackAllocator;
+class b2ContactListener;
+struct b2ContactConstraint;
+
+/// This is an internal structure.
+struct b2Position
+{
+	b2Vec2 x;
+	float32 a;
+};
+
+/// This is an internal structure.
+struct b2Velocity
+{
+	b2Vec2 v;
+	float32 w;
+};
+
+/// This is an internal class.
+class b2Island
+{
+public:
+	b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
+			b2StackAllocator* allocator, b2ContactListener* listener);
+	~b2Island();
+
+	void Clear()
+	{
+		m_bodyCount = 0;
+		m_contactCount = 0;
+		m_jointCount = 0;
+	}
+
+	void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
+
+	void Add(b2Body* body)
+	{
+		b2Assert(m_bodyCount < m_bodyCapacity);
+		body->m_islandIndex = m_bodyCount;
+		m_bodies[m_bodyCount++] = body;
+	}
+
+	void Add(b2Contact* contact)
+	{
+		b2Assert(m_contactCount < m_contactCapacity);
+		m_contacts[m_contactCount++] = contact;
+	}
+
+	void Add(b2Joint* joint)
+	{
+		b2Assert(m_jointCount < m_jointCapacity);
+		m_joints[m_jointCount++] = joint;
+	}
+
+	void Report(const b2ContactConstraint* constraints);
+
+	b2StackAllocator* m_allocator;
+	b2ContactListener* m_listener;
+
+	b2Body** m_bodies;
+	b2Contact** m_contacts;
+	b2Joint** m_joints;
+
+	b2Position* m_positions;
+	b2Velocity* m_velocities;
+
+	int32 m_bodyCount;
+	int32 m_jointCount;
+	int32 m_contactCount;
+
+	int32 m_bodyCapacity;
+	int32 m_contactCapacity;
+	int32 m_jointCapacity;
+
+	int32 m_positionIterationCount;
+};
+
+#endif

+ 35 - 0
include/Box2D/Dynamics/b2TimeStep.h

@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TIME_STEP_H
+#define B2_TIME_STEP_H
+
+#include <Box2D/Common/b2Settings.h>
+
+/// This is an internal structure.
+struct b2TimeStep
+{
+	float32 dt;			// time step
+	float32 inv_dt;		// inverse time step (0 if dt == 0).
+	float32 dtRatio;	// dt * inv_dt0
+	int32 velocityIterations;
+	int32 positionIterations;
+	bool warmStarting;
+};
+
+#endif

+ 285 - 0
include/Box2D/Dynamics/b2World.h

@@ -0,0 +1,285 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WORLD_H
+#define B2_WORLD_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2StackAllocator.h>
+#include <Box2D/Dynamics/b2ContactManager.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+
+struct b2AABB;
+struct b2BodyDef;
+struct b2JointDef;
+struct b2TimeStep;
+class b2Body;
+class b2Fixture;
+class b2Joint;
+
+/// The world class manages all physics entities, dynamic simulation,
+/// and asynchronous queries. The world also contains efficient memory
+/// management facilities.
+class b2World
+{
+public:
+	/// Construct a world object.
+	/// @param gravity the world gravity vector.
+	/// @param doSleep improve performance by not simulating inactive bodies.
+	b2World(const b2Vec2& gravity, bool doSleep);
+
+	/// Destruct the world. All physics entities are destroyed and all heap memory is released.
+	~b2World();
+
+	/// Register a destruction listener. The listener is owned by you and must
+	/// remain in scope.
+	void SetDestructionListener(b2DestructionListener* listener);
+
+	/// Register a contact filter to provide specific control over collision.
+	/// Otherwise the default filter is used (b2_defaultFilter). The listener is
+	/// owned by you and must remain in scope. 
+	void SetContactFilter(b2ContactFilter* filter);
+
+	/// Register a contact event listener. The listener is owned by you and must
+	/// remain in scope.
+	void SetContactListener(b2ContactListener* listener);
+
+	/// Register a routine for debug drawing. The debug draw functions are called
+	/// inside with b2World::DrawDebugData method. The debug draw object is owned
+	/// by you and must remain in scope.
+	void SetDebugDraw(b2DebugDraw* debugDraw);
+
+	/// Create a rigid body given a definition. No reference to the definition
+	/// is retained.
+	/// @warning This function is locked during callbacks.
+	b2Body* CreateBody(const b2BodyDef* def);
+
+	/// Destroy a rigid body given a definition. No reference to the definition
+	/// is retained. This function is locked during callbacks.
+	/// @warning This automatically deletes all associated shapes and joints.
+	/// @warning This function is locked during callbacks.
+	void DestroyBody(b2Body* body);
+
+	/// Create a joint to constrain bodies together. No reference to the definition
+	/// is retained. This may cause the connected bodies to cease colliding.
+	/// @warning This function is locked during callbacks.
+	b2Joint* CreateJoint(const b2JointDef* def);
+
+	/// Destroy a joint. This may cause the connected bodies to begin colliding.
+	/// @warning This function is locked during callbacks.
+	void DestroyJoint(b2Joint* joint);
+
+	/// Take a time step. This performs collision detection, integration,
+	/// and constraint solution.
+	/// @param timeStep the amount of time to simulate, this should not vary.
+	/// @param velocityIterations for the velocity constraint solver.
+	/// @param positionIterations for the position constraint solver.
+	void Step(	float32 timeStep,
+				int32 velocityIterations,
+				int32 positionIterations);
+
+	/// Call this after you are done with time steps to clear the forces. You normally
+	/// call this after each call to Step, unless you are performing sub-steps. By default,
+	/// forces will be automatically cleared, so you don't need to call this function.
+	/// @see SetAutoClearForces
+	void ClearForces();
+
+	/// Call this to draw shapes and other debug draw data.
+	void DrawDebugData();
+
+	/// Query the world for all fixtures that potentially overlap the
+	/// provided AABB.
+	/// @param callback a user implemented callback class.
+	/// @param aabb the query box.
+	void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast the world for all fixtures in the path of the ray. Your callback
+	/// controls whether you get the closest point, any point, or n-points.
+	/// The ray-cast ignores shapes that contain the starting point.
+	/// @param callback a user implemented callback class.
+	/// @param point1 the ray starting point
+	/// @param point2 the ray ending point
+	void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
+
+	/// Get the world body list. With the returned body, use b2Body::GetNext to get
+	/// the next body in the world list. A NULL body indicates the end of the list.
+	/// @return the head of the world body list.
+	b2Body* GetBodyList();
+
+	/// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
+	/// the next joint in the world list. A NULL joint indicates the end of the list.
+	/// @return the head of the world joint list.
+	b2Joint* GetJointList();
+
+	/// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
+	/// the next contact in the world list. A NULL contact indicates the end of the list.
+	/// @return the head of the world contact list.
+	/// @warning contacts are 
+	b2Contact* GetContactList();
+
+	/// Enable/disable warm starting. For testing.
+	void SetWarmStarting(bool flag) { m_warmStarting = flag; }
+
+	/// Enable/disable continuous physics. For testing.
+	void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
+
+	/// Get the number of broad-phase proxies.
+	int32 GetProxyCount() const;
+
+	/// Get the number of bodies.
+	int32 GetBodyCount() const;
+
+	/// Get the number of joints.
+	int32 GetJointCount() const;
+
+	/// Get the number of contacts (each may have 0 or more contact points).
+	int32 GetContactCount() const;
+
+	/// Change the global gravity vector.
+	void SetGravity(const b2Vec2& gravity);
+	
+	/// Get the global gravity vector.
+	b2Vec2 GetGravity() const;
+
+	/// Is the world locked (in the middle of a time step).
+	bool IsLocked() const;
+
+	/// Set flag to control automatic clearing of forces after each time step.
+	void SetAutoClearForces(bool flag);
+
+	/// Get the flag that controls automatic clearing of forces after each time step.
+	bool GetAutoClearForces() const;
+
+private:
+
+	// m_flags
+	enum
+	{
+		e_newFixture	= 0x0001,
+		e_locked		= 0x0002,
+		e_clearForces	= 0x0004,
+	};
+
+	friend class b2Body;
+	friend class b2ContactManager;
+	friend class b2Controller;
+
+	void Solve(const b2TimeStep& step);
+	void SolveTOI();
+	void SolveTOI(b2Body* body);
+
+	void DrawJoint(b2Joint* joint);
+	void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
+
+	b2BlockAllocator m_blockAllocator;
+	b2StackAllocator m_stackAllocator;
+
+	int32 m_flags;
+
+	b2ContactManager m_contactManager;
+
+	b2Body* m_bodyList;
+	b2Joint* m_jointList;
+
+	int32 m_bodyCount;
+	int32 m_jointCount;
+
+	b2Vec2 m_gravity;
+	bool m_allowSleep;
+
+	b2Body* m_groundBody;
+
+	b2DestructionListener* m_destructionListener;
+	b2DebugDraw* m_debugDraw;
+
+	// This is used to compute the time step ratio to
+	// support a variable time step.
+	float32 m_inv_dt0;
+
+	// This is for debugging the solver.
+	bool m_warmStarting;
+
+	// This is for debugging the solver.
+	bool m_continuousPhysics;
+};
+
+inline b2Body* b2World::GetBodyList()
+{
+	return m_bodyList;
+}
+
+inline b2Joint* b2World::GetJointList()
+{
+	return m_jointList;
+}
+
+inline b2Contact* b2World::GetContactList()
+{
+	return m_contactManager.m_contactList;
+}
+
+inline int32 b2World::GetBodyCount() const
+{
+	return m_bodyCount;
+}
+
+inline int32 b2World::GetJointCount() const
+{
+	return m_jointCount;
+}
+
+inline int32 b2World::GetContactCount() const
+{
+	return m_contactManager.m_contactCount;
+}
+
+inline void b2World::SetGravity(const b2Vec2& gravity)
+{
+	m_gravity = gravity;
+}
+
+inline b2Vec2 b2World::GetGravity() const
+{
+	return m_gravity;
+}
+
+inline bool b2World::IsLocked() const
+{
+	return (m_flags & e_locked) == e_locked;
+}
+
+inline void b2World::SetAutoClearForces(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_clearForces;
+	}
+	else
+	{
+		m_flags &= ~e_clearForces;
+	}
+}
+
+/// Get the flag that controls automatic clearing of forces after each time step.
+inline bool b2World::GetAutoClearForces() const
+{
+	return (m_flags & e_clearForces) == e_clearForces;
+}
+
+#endif

+ 217 - 0
include/Box2D/Dynamics/b2WorldCallbacks.h

@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WORLD_CALLBACKS_H
+#define B2_WORLD_CALLBACKS_H
+
+#include <Box2D/Common/b2Settings.h>
+
+struct b2Vec2;
+struct b2Transform;
+class b2Fixture;
+class b2Body;
+class b2Joint;
+class b2Contact;
+struct b2ContactPoint;
+struct b2ContactResult;
+struct b2Manifold;
+
+/// Joints and fixtures are destroyed when their associated
+/// body is destroyed. Implement this listener so that you
+/// may nullify references to these joints and shapes.
+class b2DestructionListener
+{
+public:
+	virtual ~b2DestructionListener() {}
+
+	/// Called when any joint is about to be destroyed due
+	/// to the destruction of one of its attached bodies.
+	virtual void SayGoodbye(b2Joint* joint) = 0;
+
+	/// Called when any fixture is about to be destroyed due
+	/// to the destruction of its parent body.
+	virtual void SayGoodbye(b2Fixture* fixture) = 0;
+};
+
+/// Implement this class to provide collision filtering. In other words, you can implement
+/// this class if you want finer control over contact creation.
+class b2ContactFilter
+{
+public:
+	virtual ~b2ContactFilter() {}
+
+	/// Return true if contact calculations should be performed between these two shapes.
+	/// @warning for performance reasons this is only called when the AABBs begin to overlap.
+	virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
+};
+
+/// Contact impulses for reporting. Impulses are used instead of forces because
+/// sub-step forces may approach infinity for rigid body collisions. These
+/// match up one-to-one with the contact points in b2Manifold.
+struct b2ContactImpulse
+{
+	float32 normalImpulses[b2_maxManifoldPoints];
+	float32 tangentImpulses[b2_maxManifoldPoints];
+};
+
+/// Implement this class to get contact information. You can use these results for
+/// things like sounds and game logic. You can also get contact results by
+/// traversing the contact lists after the time step. However, you might miss
+/// some contacts because continuous physics leads to sub-stepping.
+/// Additionally you may receive multiple callbacks for the same contact in a
+/// single time step.
+/// You should strive to make your callbacks efficient because there may be
+/// many callbacks per time step.
+/// @warning You cannot create/destroy Box2D entities inside these callbacks.
+class b2ContactListener
+{
+public:
+	virtual ~b2ContactListener() {}
+
+	/// Called when two fixtures begin to touch.
+	virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+	/// Called when two fixtures cease to touch.
+	virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+	/// This is called after a contact is updated. This allows you to inspect a
+	/// contact before it goes to the solver. If you are careful, you can modify the
+	/// contact manifold (e.g. disable contact).
+	/// A copy of the old manifold is provided so that you can detect changes.
+	/// Note: this is called only for awake bodies.
+	/// Note: this is called even when the number of contact points is zero.
+	/// Note: this is not called for sensors.
+	/// Note: if you set the number of contact points to zero, you will not
+	/// get an EndContact callback. However, you may get a BeginContact callback
+	/// the next step.
+	virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
+	{
+		B2_NOT_USED(contact);
+		B2_NOT_USED(oldManifold);
+	}
+
+	/// This lets you inspect a contact after the solver is finished. This is useful
+	/// for inspecting impulses.
+	/// Note: the contact manifold does not include time of impact impulses, which can be
+	/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
+	/// in a separate data structure.
+	/// Note: this is only called for contacts that are touching, solid, and awake.
+	virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
+	{
+		B2_NOT_USED(contact);
+		B2_NOT_USED(impulse);
+	}
+};
+
+/// Callback class for AABB queries.
+/// See b2World::Query
+class b2QueryCallback
+{
+public:
+	virtual ~b2QueryCallback() {}
+
+	/// Called for each fixture found in the query AABB.
+	/// @return false to terminate the query.
+	virtual bool ReportFixture(b2Fixture* fixture) = 0;
+};
+
+/// Callback class for ray casts.
+/// See b2World::RayCast
+class b2RayCastCallback
+{
+public:
+	virtual ~b2RayCastCallback() {}
+
+	/// Called for each fixture found in the query. You control how the ray cast
+	/// proceeds by returning a float:
+	/// return -1: ignore this fixture and continue
+	/// return 0: terminate the ray cast
+	/// return fraction: clip the ray to this point
+	/// return 1: don't clip the ray and continue
+	/// @param fixture the fixture hit by the ray
+	/// @param point the point of initial intersection
+	/// @param normal the normal vector at the point of intersection
+	/// @return -1 to filter, 0 to terminate, fraction to clip the ray for
+	/// closest hit, 1 to continue
+	virtual float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
+									const b2Vec2& normal, float32 fraction) = 0;
+};
+
+/// Color for debug drawing. Each value has the range [0,1].
+struct b2Color
+{
+	b2Color() {}
+	b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {}
+	void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; }
+	float32 r, g, b;
+};
+
+/// Implement and register this class with a b2World to provide debug drawing of physics
+/// entities in your game.
+class b2DebugDraw
+{
+public:
+	b2DebugDraw();
+
+	virtual ~b2DebugDraw() {}
+
+	enum
+	{
+		e_shapeBit				= 0x0001, ///< draw shapes
+		e_jointBit				= 0x0002, ///< draw joint connections
+		e_aabbBit				= 0x0004, ///< draw axis aligned bounding boxes
+		e_pairBit				= 0x0008, ///< draw broad-phase pairs
+		e_centerOfMassBit		= 0x0010, ///< draw center of mass frame
+	};
+
+	/// Set the drawing flags.
+	void SetFlags(uint32 flags);
+
+	/// Get the drawing flags.
+	uint32 GetFlags() const;
+	
+	/// Append flags to the current flags.
+	void AppendFlags(uint32 flags);
+
+	/// Clear flags from the current flags.
+	void ClearFlags(uint32 flags);
+
+	/// Draw a closed polygon provided in CCW order.
+	virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+	/// Draw a solid closed polygon provided in CCW order.
+	virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+	/// Draw a circle.
+	virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0;
+	
+	/// Draw a solid circle.
+	virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0;
+	
+	/// Draw a line segment.
+	virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0;
+
+	/// Draw a transform. Choose your own length scale.
+	/// @param xf a transform.
+	virtual void DrawTransform(const b2Transform& xf) = 0;
+
+protected:
+	uint32 m_drawFlags;
+};
+
+#endif

+ 1 - 7
include/polycode/core/PolyAAssetFileProvider.h

@@ -37,12 +37,6 @@ namespace Polycode {
 		
 		AAsset *file;
 	};
-    
-	class _PolyExport AAssetDirClass : public PolyBase {
-	public:
-		AAssetDir* system;
-		String name;
-	};
 	
 	class _PolyExport AAssetFileProvider : public CoreFileProvider {
 		public:
@@ -56,7 +50,7 @@ namespace Polycode {
 			void addSource(const String &source);
 			void removeSource(const String &source);
 		
-			std::vector<AAssetDirClass> sourceFolders;
+			std::vector<String> sourceFolders;
 			
 			AAssetManager* manager;
 	};

+ 1 - 0
include/polycode/core/PolyAndroidCore.h

@@ -86,6 +86,7 @@ namespace Polycode {
 		bool systemUpdate();
 		
 		void setCursor(int cursorType);
+		void openOnScreenKeyboard(bool open);
 		
 		void createThread(Threaded *target);
 		CoreMutex *createMutex();

+ 6 - 0
include/polycode/core/PolyCore.h

@@ -153,6 +153,12 @@ namespace Polycode {
 		*/
 		virtual void warpCursor(int x, int y) {}
 		
+		/**
+		 * Opens / closes the on-screen keyboard on a mobile device.
+		 * @param open True to open false to close
+		 */
+		virtual void openOnScreenKeyboard(bool open){};
+		
 		/**
 		* Launches a Threaded class into its own thread. See the documentation for Threaded for information on how to crated threaded classes.
 		* @param target Target threaded class.

+ 2 - 0
include/polycode/core/PolyGlobals.h

@@ -80,11 +80,13 @@ typedef unsigned int PolyRendererIndexType;
 	#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
 		#define PLATFORM PLATFORM_IOS
 		#define STRICT_OPENGLES2 1
+		#define POLYCODE_NUMBER_IS_SINGLE 1
 	#else
 		#define PLATFORM PLATFORM_MAC
 	#endif
 #elif defined(__ANDROID__)
 	#define PLATFORM PLATFORM_ANDROID
+	#define POLYCODE_NUMBER_IS_SINGLE 1
 #else
 	#include <cstddef>
 	#define PLATFORM PLATFORM_UNIX

+ 1 - 21
include/polycode/core/PolyOpenSLAudioInterface.h

@@ -24,30 +24,12 @@
 
 #include "polycode/core/PolyGlobals.h"
 #include "polycode/core/PolySoundManager.h"
-#include "polycode/core/PolyThreaded.h"
 
 #include <SLES/OpenSLES_Android.h>
 
 namespace Polycode {
 	
-	class OpenSLAudioInterface;
-	
-// 	class OpenSLStream : public Threaded {
-// 	public:
-// 		OpenSLStream();
-// 		
-// 		void runThread();
-// 		void updateThread(int16_t *buf);
-// 		void setInterface(OpenSLAudioInterface *itf);
-// 		
-// 		static void queueCallback(SLAndroidSimpleBufferQueueItf caller, void *pContext);
-// 	private:
-// 		OpenSLAudioInterface* itf;
-// 		int currentBufferCount;
-// 		CoreMutex* queueMutex;
-// 	};
-
-    class OpenSLAudioInterface : public AudioInterface {
+	class OpenSLAudioInterface : public AudioInterface {
 	public:
 		OpenSLAudioInterface();
 		~OpenSLAudioInterface();
@@ -61,8 +43,6 @@ namespace Polycode {
 		
 		SLAndroidSimpleBufferQueueItf mPlayerQueue;
 	private:
-// 		OpenSLStream* stream;
-
 		int16_t* buffer;
 		
 		SLObjectItf mEngineObj;

+ 1 - 5
include/polycode/core/PolySoundManager.h

@@ -26,14 +26,10 @@
 #include "polycode/core/PolyQuaternion.h"
 #include "polycode/core/PolySound.h"
 
-#define POLY_FRAMES_PER_BUFFER 512
+#define POLY_FRAMES_PER_BUFFER 2048
 #define POLY_AUDIO_FREQ 44100
 #define POLY_CIRCULAR_BUFFER_SIZE 32
-#if PLATFORM == PLATFORM_ANDROID
-#define POLY_NUM_CHANNELS 1
-#else
 #define POLY_NUM_CHANNELS 2
-#endif
 #define POLY_MIX_BUFFER_SIZE (POLY_FRAMES_PER_BUFFER*POLY_CIRCULAR_BUFFER_SIZE)
 
 namespace Polycode {

+ 4 - 4
include/polycode/modules/physics2D/PolyPhysicsScreen.h

@@ -21,10 +21,10 @@ THE SOFTWARE.
 */
 
 #pragma once
-#include "PolyGlobals.h"
-#include "PolyEvent.h"
-#include "PolyScene.h"
-#include "PolyVector2.h"
+#include "polycode/core/PolyGlobals.h"
+#include "polycode/core/PolyEvent.h"
+#include "polycode/core/PolyScene.h"
+#include "polycode/core/PolyVector2.h"
 #include "Box2D/Box2D.h"
 #include <vector>
 

+ 2 - 2
include/polycode/modules/physics2D/PolyPhysicsScreenEntity.h

@@ -21,8 +21,8 @@ THE SOFTWARE.
 */
 
 #pragma once
-#include "PolyGlobals.h"
-#include "PolyVector2.h"
+#include "polycode/core/PolyGlobals.h"
+#include "polycode/core/PolyVector2.h"
 #include "Box2D/Box2D.h"
 
 namespace Polycode {

+ 0 - 1
include/polycode/view/android/PolycodeView.h

@@ -114,5 +114,4 @@ void* startApp(void* data);
 
 int JNIGetUnicodeChar(ANativeActivity* native_activity, int eventType, int keyCode, int metaState);
 void JNIAutoHideNavBar(ANativeActivity* native_activity);
-void GetAudioInfo(ANativeActivity* native_activity);
 void JNIWakeLock(ANativeActivity* native_activity, bool acquire);

+ 3 - 7
src/core/PolyAAssetFileProvider.cpp

@@ -32,16 +32,12 @@ AAssetFileProvider::AAssetFileProvider(AAssetManager* manager) : CoreFileProvide
 }
 
 void AAssetFileProvider::addSource(const String &source) {
-	AAssetDirClass dir;
-	dir.name = source;
-	dir.system = AAssetManager_openDir(manager, source.c_str());
-	sourceFolders.push_back(dir);
+	sourceFolders.push_back(source);
 }
 
 void AAssetFileProvider::removeSource(const String &source) {
 	for(int i=0; i < sourceFolders.size(); i++) {
-		if(sourceFolders[i].name == source) {
-			AAssetDir_close(sourceFolders[i].system);
+		if(sourceFolders[i] == source) {
 			sourceFolders.erase(sourceFolders.begin()+i);
 			return;
 		}
@@ -52,7 +48,7 @@ Polycode::CoreFile *AAssetFileProvider::openFile(const String &fileName, const S
 	Logger::log("openFile %s", fileName.c_str());
 	AAsset *file = NULL;
 	for(int i=0; i < sourceFolders.size(); i++) {
-		file = AAssetManager_open(manager, (sourceFolders[i].name+"/"+fileName).c_str(), AASSET_MODE_BUFFER);
+		file = AAssetManager_open(manager, (sourceFolders[i]+"/"+fileName).c_str(), AASSET_MODE_BUFFER);
 		if(file) {
 			break;
 		}

+ 64 - 2
src/core/PolyAndroidCore.cpp

@@ -93,7 +93,7 @@ AndroidCore::AndroidCore(PolycodeView *view, int xRes, int yRes, bool fullScreen
 	this->view = view;
 	core = this;
 	
-// 	services->getSoundManager()->setAudioInterface(new OpenSLAudioInterface());
+	services->getSoundManager()->setAudioInterface(new OpenSLAudioInterface());
 	extractResources();
 }
 
@@ -191,6 +191,68 @@ void AndroidCore::setCursor(int cursorType) {
 
 }
 
+//adapted from https://groups.google.com/d/msg/android-ndk/Tk3g00wLKhk/TJQucoaE_asJ
+void AndroidCore::openOnScreenKeyboard(bool open){
+	// Attaches the current thread to the JVM. 
+	jint lResult; 
+	jint lFlags = 0; 
+
+	JavaVM* javaVM = view->native_activity->vm;
+	JNIEnv* jniEnv;
+	bool attached = false;
+
+	if(javaVM->GetEnv((void**)&jniEnv, JNI_VERSION_1_6) ==JNI_EDETACHED){
+		JavaVMAttachArgs attachArgs;
+		attachArgs.version = JNI_VERSION_1_6;
+		attachArgs.name = "NativeThread";
+		attachArgs.group = NULL;
+		
+		jint result = javaVM->AttachCurrentThread(&jniEnv, &attachArgs);
+		if(result == JNI_ERR){
+			return;
+		}
+		attached = true;
+	} 
+
+	// Retrieves Context.INPUT_METHOD_SERVICE. 
+	jclass ClassContext = jniEnv->FindClass("android/content/Context"); 
+	jfieldID FieldINPUT_METHOD_SERVICE = jniEnv->GetStaticFieldID(ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;"); 
+	jobject INPUT_METHOD_SERVICE = jniEnv->GetStaticObjectField(ClassContext, FieldINPUT_METHOD_SERVICE); 
+
+	jclass ClassNativeActivity = jniEnv->FindClass("android/app/NativeActivity");
+	jobject lNativeActivity = view->native_activity->clazz;
+	
+	// Runs getSystemService(Context.INPUT_METHOD_SERVICE). 
+	jclass ClassInputMethodManager = jniEnv->FindClass("android/view/inputmethod/InputMethodManager");
+	jmethodID MethodGetSystemService = jniEnv->GetMethodID(ClassNativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); 
+	jobject lInputMethodManager = jniEnv->CallObjectMethod(lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE); 
+
+	// Runs getWindow().getDecorView().
+	jmethodID MethodGetWindow = jniEnv->GetMethodID(ClassNativeActivity, "getWindow", "()Landroid/view/Window;"); 
+	jobject lWindow = jniEnv->CallObjectMethod(lNativeActivity, MethodGetWindow); 
+	jclass ClassWindow = jniEnv->FindClass("android/view/Window");
+	jmethodID MethodGetDecorView = jniEnv->GetMethodID(ClassWindow, "getDecorView", "()Landroid/view/View;");
+	jobject lDecorView = jniEnv->CallObjectMethod(lWindow, MethodGetDecorView);
+
+		// Runs lWindow.getViewToken() 
+	jclass ClassView = jniEnv->FindClass("android/view/View"); 
+	jmethodID MethodGetWindowToken = jniEnv->GetMethodID(ClassView, "getWindowToken", "()Landroid/os/IBinder;"); 
+	jobject lBinder = jniEnv->CallObjectMethod(lDecorView, MethodGetWindowToken); 
+
+	if (open) {
+		// Runs lInputMethodManager.showSoftInput(...). 
+		jmethodID MethodShowSoftInput = jniEnv->GetMethodID(ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z"); 
+		jboolean lResult = jniEnv->CallBooleanMethod(lInputMethodManager, MethodShowSoftInput, lDecorView, lFlags);
+	} else { 
+		// lInputMethodManager.hideSoftInput(...). 
+		jmethodID MethodHideSoftInput = jniEnv->GetMethodID(ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); 
+		jboolean lRes = jniEnv->CallBooleanMethod(lInputMethodManager, MethodHideSoftInput, lBinder, lFlags); 
+	} 
+
+	// Finished with the JVM. 
+	javaVM->DetachCurrentThread(); 
+}
+
 void launchThread(Threaded *target) {
 	target->runThread();
 	target->scheduledForRemoval = true;
@@ -493,7 +555,7 @@ void AndroidCore::initKeyMap() {
 	for (int i=0; i<1024; ++i )
 		keyMap[i] = KEY_UNKNOWN;
 
-	keyMap[AKEYCODE_BACK] = KEY_BACKSPACE;
+	keyMap[AKEYCODE_BACK] = KEY_ESCAPE;
 	keyMap[AKEYCODE_TAB] = KEY_TAB;
 	keyMap[AKEYCODE_CLEAR] = KEY_CLEAR;
 	keyMap[AKEYCODE_ENTER] = KEY_RETURN;

+ 4 - 71
src/core/PolyOpenSLAudioInterface.cpp

@@ -27,10 +27,7 @@
 
 using namespace Polycode;
 
-OpenSLAudioInterface::OpenSLAudioInterface(){
-	Logger::log("OpenSL Interface");
-// 	stream = new OpenSLStream();
-}
+OpenSLAudioInterface::OpenSLAudioInterface(){}
 
 OpenSLAudioInterface::~OpenSLAudioInterface(){
 	terminateOpenSL();
@@ -39,11 +36,6 @@ OpenSLAudioInterface::~OpenSLAudioInterface(){
 void OpenSLAudioInterface::setMixer(AudioMixer* newMixer){
 	mixer = newMixer;
 	initOpenSL();
-// 	Logger::log("finished init");
-// 	stream->setInterface(this);
-// 	Logger::log("stream set");
-// // 	Services()->getCore()->createThread(stream);
-// 	Logger::log("stream running");
 }
 
 void OpenSLAudioInterface::initOpenSL(){
@@ -56,18 +48,15 @@ void OpenSLAudioInterface::initOpenSL(){
 	const SLboolean lOutputMixReqs[]={};
  
 	lRes = slCreateEngine(&mEngineObj, 0, NULL, 1, lEngineMixIIDs, lEngineMixReqs);
-	Logger::log("engine: %d", lRes);
 	lRes = (*mEngineObj)->Realize(mEngineObj,SL_BOOLEAN_FALSE);
-	Logger::log("engine real: %d", lRes);
 	lRes = (*mEngineObj)->GetInterface(mEngineObj, SL_IID_ENGINE, &mEngine);
-	Logger::log("engine int: %d", lRes);
 	
 	lRes=(*mEngine)->CreateOutputMix(mEngine, &mOutputMixObj,lOutputMixIIDCount,lOutputMixIIDs, lOutputMixReqs);
 	lRes=(*mOutputMixObj)->Realize(mOutputMixObj, SL_BOOLEAN_FALSE);
 	
 	SLDataLocator_AndroidSimpleBufferQueue lDataLocatorIn;
 	lDataLocatorIn.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
-	lDataLocatorIn.numBuffers = POLY_CIRCULAR_BUFFER_SIZE;
+	lDataLocatorIn.numBuffers = 1;
 	
 	SLDataFormat_PCM lDataFormat;
 	lDataFormat.formatType = SL_DATAFORMAT_PCM;
@@ -98,25 +87,17 @@ void OpenSLAudioInterface::initOpenSL(){
 	const SLInterfaceID lSoundPlayerIIDs[] = { SL_IID_PLAY, SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
 	const SLboolean lSoundPlayerReqs[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
 	
-	Logger::log("before player");
 	lRes = (*mEngine)->CreateAudioPlayer(mEngine, &mPlayerObj, &lDataSource, &lDataSink, lSoundPlayerIIDCount, lSoundPlayerIIDs, lSoundPlayerReqs);
-	Logger::log("player: %d", lRes);
 	lRes = (*mPlayerObj)->Realize(mPlayerObj, SL_BOOLEAN_FALSE);
-	Logger::log("player real: %d", lRes);
 	
 	lRes = (*mPlayerObj)->GetInterface(mPlayerObj, SL_IID_PLAY, &mPlayer);
-	Logger::log("player getI: %d", lRes);
 	lRes = (*mPlayerObj)->GetInterface(mPlayerObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &mPlayerQueue);
-	Logger::log("player getBuffer: %d", lRes);
 	
 	lRes = (*mPlayerQueue)->RegisterCallback(mPlayerQueue, OpenSLAudioInterface::queueCallback, this);
-	Logger::log("queue call: %d", lRes);
 	
 // 	lRes = (*mPlayerObj)->GetInterface(mPlayerObj, SL_IID_VOLUME, &mVolume);
-// 	Logger::log("player itf: %d", lRes);
 	
 	lRes = (*mPlayer)->SetPlayState(mPlayer, SL_PLAYSTATE_PLAYING);
-	Logger::log("play: %d", lRes);
 	
 	buffer = (int16_t*)malloc(sizeof(int16_t)*POLY_FRAMES_PER_BUFFER*POLY_NUM_CHANNELS);
 	int16_t *out = buffer;
@@ -143,54 +124,6 @@ void OpenSLAudioInterface::queueCallback(SLAndroidSimpleBufferQueueItf caller, v
 	if(audioInterface->buffer && audioInterface->getMixer()) {
 		int16_t *out = (int16_t*)audioInterface->buffer;
 		audioInterface->getMixer()->mixIntoBuffer(out, POLY_FRAMES_PER_BUFFER);
-		(*(audioInterface->mPlayerQueue))->Enqueue(audioInterface->mPlayerQueue, out, POLY_FRAMES_PER_BUFFER);
+		(*(audioInterface->mPlayerQueue))->Enqueue(audioInterface->mPlayerQueue, out, sizeof(int16_t)*POLY_FRAMES_PER_BUFFER*POLY_NUM_CHANNELS);
 	}
-}
-
-// void OpenSLStream::queueCallback(SLAndroidSimpleBufferQueueItf caller, void* pContext){
-// 	OpenSLStream *stream = (OpenSLStream*) pContext;
-// 	stream->queueMutex->lock();
-// 	Logger::log("callback %d", stream->currentBufferCount);
-// 	stream->currentBufferCount--;
-// 	stream->queueMutex->unlock();
-// }
-
-// OpenSLStream::OpenSLStream() : Threaded(){}
-
-// void OpenSLStream::setInterface(OpenSLAudioInterface* itf){
-// 	this->itf = itf;
-// 	queueMutex = Services()->getCore()->createMutex();
-// }
-
-// void OpenSLStream::runThread(){
-// 	int16_t *buffer;
-// 	Logger::log("in run");
-// 	buffer = (int16_t*)malloc(POLY_MIX_BUFFER_SIZE*POLY_NUM_CHANNELS*sizeof(int16_t));
-// 	Logger::log("allocated");
-// 	currentBufferCount = 0;
-// 	while(threadRunning){
-// // 		Logger::log("while");
-// 		updateThread(buffer);
-// // 		usleep(20000000);
-// 	}
-// }
-// 
-// void OpenSLStream::updateThread(int16_t *buf){
-// 	Logger::log("in update");
-// 	if(itf->getMixer()){
-// 		int16_t* out;
-// // 		Logger::log("in mixer");
-// 		
-// 		while(currentBufferCount < POLY_CIRCULAR_BUFFER_SIZE){
-// 			queueMutex->lock();
-// // 			Logger::log("mix %d", currentBufferCount);
-// 			out = buf + sizeof(int16_t)*POLY_FRAMES_PER_BUFFER*POLY_NUM_CHANNELS*currentBufferCount++;
-// 			itf->getMixer()->mixIntoBuffer(out, POLY_FRAMES_PER_BUFFER);
-// 			(*(itf->mPlayerQueue))->Enqueue(itf->mPlayerQueue, out, POLY_FRAMES_PER_BUFFER);
-// 			queueMutex->unlock();
-// // 			queueMutex->lock();
-// 		}
-// // 		queueMutex->unlock();
-// // 		Logger::log("unlocked");
-// 	}
-// }
+}

+ 4 - 4
src/core/PolySound.cpp

@@ -95,11 +95,11 @@ long custom_tellfunc(void *datasource) {
 Sound::Sound(const String& fileName) :	referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), numSamples(-1), streamingSound(false), playing(false), playbackOffset(0), streamingSource(NULL), frequencyAdjust(1.0) {
 	soundLoaded = false;
 	setIsPositional(false);
-	Logger::log("sound before load");
 	loadFile(fileName);
-	if(soundLoaded) {
-		Services()->getSoundManager()->registerSound(this);
-	}
+
+    if(soundLoaded) {
+        Services()->getSoundManager()->registerSound(this);
+    }
 }
 
 Sound::Sound(int size, const char *data, int channels, unsigned int freq, SoundFormat format) : referenceDistance(1), maxDistance(MAX_FLOAT), pitch(1), volume(1), numSamples(-1), streamingSound(false), playing(false) , playbackOffset(0), streamingSource(NULL), frequencyAdjust(1.0) {

+ 0 - 1
src/core/PolySoundManager.cpp

@@ -161,7 +161,6 @@ AudioMixer::~AudioMixer() {
 
 void AudioMixer::mixIntoBuffer(int16_t *buffer, unsigned int numSamples) {
 	mixerMutex->lock();
-
 	if (sounds.size() == 0) {
 		memset(buffer, 0, sizeof(int16_t) * numSamples * POLY_NUM_CHANNELS);
 		mixerMutex->unlock();

+ 4 - 4
src/modules/physics2D/PolyPhysicsScreen.cpp

@@ -21,10 +21,10 @@ THE SOFTWARE.
 */
 
 
-#include "PolyPhysicsScreen.h"
-#include "PolyPhysicsScreenEntity.h"
-#include "PolyCoreServices.h"
-#include "PolyCore.h"
+#include "polycode/modules/physics2D/PolyPhysicsScreen.h"
+#include "polycode/modules/physics2D/PolyPhysicsScreenEntity.h"
+#include "polycode/core/PolyCoreServices.h"
+#include "polycode/core/PolyCore.h"
 
 using namespace Polycode;
 

+ 4 - 4
src/modules/physics2D/PolyPhysicsScreenEntity.cpp

@@ -22,10 +22,10 @@ THE SOFTWARE.
 
 #define PI 3.14159265
 
-#include "PolyPhysicsScreenEntity.h"
-#include "PolyLogger.h"
-#include "PolyMesh.h"
-#include "PolyEntity.h"
+#include "polycode/modules/physics2D/PolyPhysicsScreenEntity.h"
+#include "polycode/core/PolyLogger.h"
+#include "polycode/core/PolyMesh.h"
+#include "polycode/core/PolyEntity.h"
 
 using namespace Polycode;
 

+ 4 - 55
src/view/android/PolycodeView.cpp

@@ -55,6 +55,7 @@ PolycodeView::PolycodeView(ANativeActivity* native, String title){
 	native_activity->callbacks->onInputQueueCreated		= onInputQueueCreated;
 	native_activity->callbacks->onInputQueueDestroyed	= onInputQueueDestroyed;
 	native_activity->callbacks->onSaveInstanceState		= onSaveInstanceState;
+	native_activity->callbacks->onConfigurationChanged	= onConfiguartionChanged;
 	
 	native_config = AConfiguration_new();
 	AConfiguration_fromAssetManager(native_config, native_activity->assetManager);
@@ -88,7 +89,6 @@ PolycodeView::PolycodeView(ANativeActivity* native, String title){
 	
 	firstWindowCreate = true;
 	
-	GetAudioInfo(native);
 }
 
 PolycodeView::~PolycodeView(){}
@@ -139,6 +139,7 @@ void onDestroy(ANativeActivity* activity){
 		if(result == JNI_ERR){
 			if(core)
 				core->Shutdown();
+			return;
 		}
 		attached = true;
 	}
@@ -241,7 +242,7 @@ void onLowMemory(ANativeActivity* activity){
 }
 
 static int inputLoop(int fd, int events, void* data){
-	Logger::log("inputLoop");
+// 	Logger::log("inputLoop");
 	AInputQueue* native_input = ((PolycodeView*)data)->native_input;
 	AndroidEvent event;
 	AInputEvent* aev;
@@ -267,7 +268,7 @@ static int inputLoop(int fd, int events, void* data){
 					event.eventCode = InputEvent::EVENT_KEYUP;
 					event.unicodeChar = JNIGetUnicodeChar(((PolycodeView*)data)->native_activity, AKEY_EVENT_ACTION_UP, kC, AKeyEvent_getMetaState(aev));
 				}
-
+				core->handleSystemEvent(event);
 			} else if(type == AINPUT_EVENT_TYPE_MOTION){
 				event.eventTime = AMotionEvent_getEventTime(aev);
 				int evSource = AInputEvent_getSource(aev);
@@ -557,58 +558,6 @@ void JNIWakeLock(ANativeActivity* native_activity, bool acquire){
 		}
 	}
 	
-	if(attached)
-		javaVM->DetachCurrentThread();
-}
-
-void GetAudioInfo(ANativeActivity* native_activity){
-	JavaVM* javaVM = native_activity->vm;
-	JNIEnv* jniEnv;
-	bool attached = false;
-	
-	if(javaVM->GetEnv((void**)&jniEnv, JNI_VERSION_1_6) ==JNI_EDETACHED){
-		JavaVMAttachArgs attachArgs;
-		attachArgs.version = JNI_VERSION_1_6;
-		attachArgs.name = "NativeThread";
-		attachArgs.group = NULL;
-		
-		jint result = javaVM->AttachCurrentThread(&jniEnv, &attachArgs);
-		if(result == JNI_ERR){
-			return;
-		}
-		attached = true;
-	}
-
-	jclass classNativeActivity = jniEnv->FindClass("android/app/NativeActivity");
-	jclass classAudioManager = jniEnv->FindClass("android/os/AudioManager");
-	
-	jmethodID getSystemServiceID = jniEnv->GetMethodID(classNativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
-	jstring AUDIO_SERVICE = jniEnv->NewStringUTF("audio");
-	jobject AudioManager = jniEnv->CallObjectMethod(native_activity->clazz, getSystemServiceID, AUDIO_SERVICE);
-	
-	jmethodID getProperty = jniEnv->GetMethodID(classAudioManager, "getProperty", "(Ljava/lang/String;)Landroid/os/AudioManager;");
-	
-	jobject fpBID = jniEnv->GetStaticObjectField(classAudioManager, "PROPERTY_OUTPUT_FRAMES_PER_BUFFER", "Ljava/lang/String;");
-	jobject srID = jniEnv->GetStaticObjectField(classAudioManager, "PROPERTY_OUTPUT_SAMPLE_RATE", "Ljava/lang/String;");
-	
-	jobject fpBO = jniEnv->CallObjectMethod(AudioManager, getProperty, fpBID);
-	jobject srO = jniEnv->CallObjectMethod(AudioManager, getProperty, fpBID);
-	
-	const char *nativeString = (*jniEnv)->GetStringUTFChars(jniEnv, fpBO, 0);
-	int fpB = atoi(nativeString);
-	(*jniEnv)->ReleaseStringUTFChars(jniEnv, fpBO, nativeString);
-	
-	nativeString = (*jniEnv)->GetStringUTFChars(jniEnv, srO, 0);
-	int sr = atoi(nativeString);
-	(*jniEnv)->ReleaseStringUTFChars(jniEnv, srO, nativeString);
-	
-	Logger::log("fpB: %d, sr: %d", fpB, sr);
-	
-// 	jniEnv->DeleteLocalRef(jWakeLockTag);
-// 	jniEnv->DeleteLocalRef(POWER_SERVICE);
-	
-// 	((PolycodeView*)native_activity->instance)->WakeLock = jniEnv->NewGlobalRef(WakeLock);
-
 	if(attached)
 		javaVM->DetachCurrentThread();
 }