瀏覽代碼

project setup and partial platform first pass

Tim Newell 12 年之前
父節點
當前提交
6a3647c3f7
共有 98 個文件被更改,包括 24690 次插入0 次删除
  1. 9 0
      engine/compilers/android/.classpath
  2. 51 0
      engine/compilers/android/.cproject
  3. 10 0
      engine/compilers/android/.externalToolBuilders/NDK Builder.launch
  4. 100 0
      engine/compilers/android/.project
  5. 66 0
      engine/compilers/android/.settings/org.eclipse.cdt.codan.core.prefs
  6. 11 0
      engine/compilers/android/.settings/org.eclipse.jdt.core.prefs
  7. 36 0
      engine/compilers/android/AndroidManifest.xml
  8. 36 0
      engine/compilers/android/bin/AndroidManifest.xml
  9. 92 0
      engine/compilers/android/build.xml
  10. 6 0
      engine/compilers/android/gen/com/garagegames/torque2d/BuildConfig.java
  11. 50 0
      engine/compilers/android/gen/com/garagegames/torque2d/R.java
  12. 二進制
      engine/compilers/android/ic_launcher-web.png
  13. 483 0
      engine/compilers/android/jni/Android.mk
  14. 4 0
      engine/compilers/android/jni/Application.mk
  15. 134 0
      engine/compilers/android/jni/include/libjpeg/cderror.h
  16. 187 0
      engine/compilers/android/jni/include/libjpeg/cdjpeg.h
  17. 54 0
      engine/compilers/android/jni/include/libjpeg/jconfig.h
  18. 393 0
      engine/compilers/android/jni/include/libjpeg/jdct.h
  19. 304 0
      engine/compilers/android/jni/include/libjpeg/jerror.h
  20. 91 0
      engine/compilers/android/jni/include/libjpeg/jinclude.h
  21. 198 0
      engine/compilers/android/jni/include/libjpeg/jmemsys.h
  22. 390 0
      engine/compilers/android/jni/include/libjpeg/jmorecfg.h
  23. 426 0
      engine/compilers/android/jni/include/libjpeg/jpegint.h
  24. 1173 0
      engine/compilers/android/jni/include/libjpeg/jpeglib.h
  25. 14 0
      engine/compilers/android/jni/include/libjpeg/jversion.h
  26. 213 0
      engine/compilers/android/jni/include/libjpeg/transupp.h
  27. 110 0
      engine/compilers/android/jni/include/libpng/config.h
  28. 2674 0
      engine/compilers/android/jni/include/libpng/png.h
  29. 598 0
      engine/compilers/android/jni/include/libpng/pngconf.h
  30. 157 0
      engine/compilers/android/jni/include/libpng/pngdebug.h
  31. 269 0
      engine/compilers/android/jni/include/libpng/pnginfo.h
  32. 180 0
      engine/compilers/android/jni/include/libpng/pnglibconf.h
  33. 1675 0
      engine/compilers/android/jni/include/libpng/pngpriv.h
  34. 358 0
      engine/compilers/android/jni/include/libpng/pngstruct.h
  35. 3 0
      engine/compilers/android/lint.xml
  36. 14 0
      engine/compilers/android/project.properties
  37. 二進制
      engine/compilers/android/res/drawable-hdpi/ic_launcher.png
  38. 二進制
      engine/compilers/android/res/drawable-ldpi/ic_launcher.png
  39. 二進制
      engine/compilers/android/res/drawable-mdpi/ic_launcher.png
  40. 二進制
      engine/compilers/android/res/drawable-xhdpi/ic_launcher.png
  41. 3 0
      engine/compilers/android/res/menu/activity_main.xml
  42. 11 0
      engine/compilers/android/res/values-v11/styles.xml
  43. 12 0
      engine/compilers/android/res/values-v14/styles.xml
  44. 5 0
      engine/compilers/android/res/values/strings.xml
  45. 20 0
      engine/compilers/android/res/values/styles.xml
  46. 50 0
      engine/source/platformAndroid/AndroidAlerts.cpp
  47. 37 0
      engine/source/platformAndroid/AndroidAlerts.h
  48. 66 0
      engine/source/platformAndroid/AndroidAudio.cpp
  49. 61 0
      engine/source/platformAndroid/AndroidCPUInfo.cpp
  50. 173 0
      engine/source/platformAndroid/AndroidConsole.cpp
  51. 65 0
      engine/source/platformAndroid/AndroidConsole.h
  52. 60 0
      engine/source/platformAndroid/AndroidDialogs.cpp
  53. 110 0
      engine/source/platformAndroid/AndroidEvents.cpp
  54. 76 0
      engine/source/platformAndroid/AndroidEvents.h
  55. 964 0
      engine/source/platformAndroid/AndroidFileio.cpp
  56. 231 0
      engine/source/platformAndroid/AndroidFont.cpp
  57. 59 0
      engine/source/platformAndroid/AndroidFont.h
  58. 245 0
      engine/source/platformAndroid/AndroidGL.cpp
  59. 662 0
      engine/source/platformAndroid/AndroidGL2ES.cpp
  60. 1442 0
      engine/source/platformAndroid/AndroidGL2ES.h
  61. 1263 0
      engine/source/platformAndroid/AndroidInput.cpp
  62. 92 0
      engine/source/platformAndroid/AndroidMath.cpp
  63. 67 0
      engine/source/platformAndroid/AndroidMemory.cpp
  64. 500 0
      engine/source/platformAndroid/AndroidMotionManager.cpp
  65. 70 0
      engine/source/platformAndroid/AndroidMotionManager.h
  66. 98 0
      engine/source/platformAndroid/AndroidMutex.cpp
  67. 79 0
      engine/source/platformAndroid/AndroidNPatch.h
  68. 884 0
      engine/source/platformAndroid/AndroidNet.cpp
  69. 289 0
      engine/source/platformAndroid/AndroidOGLVideo.cpp
  70. 60 0
      engine/source/platformAndroid/AndroidOGLVideo.h
  71. 237 0
      engine/source/platformAndroid/AndroidOutlineGL.cpp
  72. 51 0
      engine/source/platformAndroid/AndroidOutlineGL.h
  73. 217 0
      engine/source/platformAndroid/AndroidPlatform.cpp
  74. 81 0
      engine/source/platformAndroid/AndroidProcessControl.cpp
  75. 257 0
      engine/source/platformAndroid/AndroidProfiler.cpp
  76. 83 0
      engine/source/platformAndroid/AndroidProfiler.h
  77. 113 0
      engine/source/platformAndroid/AndroidSemaphore.cpp
  78. 67 0
      engine/source/platformAndroid/AndroidStreamSource.cc
  79. 40 0
      engine/source/platformAndroid/AndroidStreamSource.h
  80. 425 0
      engine/source/platformAndroid/AndroidStrings.cpp
  81. 181 0
      engine/source/platformAndroid/AndroidThread.cpp
  82. 143 0
      engine/source/platformAndroid/AndroidTime.cpp
  83. 252 0
      engine/source/platformAndroid/AndroidUtil.cpp
  84. 39 0
      engine/source/platformAndroid/AndroidUtil.h
  85. 418 0
      engine/source/platformAndroid/AndroidWindow.cpp
  86. 21 0
      engine/source/platformAndroid/AndroidWindow.h
  87. 1603 0
      engine/source/platformAndroid/SoundEngine.cpp
  88. 221 0
      engine/source/platformAndroid/SoundEngine.h
  89. 108 0
      engine/source/platformAndroid/T2DAppDelegate.cpp
  90. 32 0
      engine/source/platformAndroid/T2DAppDelegate.h
  91. 205 0
      engine/source/platformAndroid/T2DView.cpp
  92. 38 0
      engine/source/platformAndroid/T2DView.h
  93. 259 0
      engine/source/platformAndroid/T2DViewController.cpp
  94. 59 0
      engine/source/platformAndroid/T2DViewController.h
  95. 301 0
      engine/source/platformAndroid/main.cpp
  96. 512 0
      engine/source/platformAndroid/menus/popupMenu.cpp
  97. 141 0
      engine/source/platformAndroid/platformAndroid.h
  98. 263 0
      engine/source/platformAndroid/platformGL.h

+ 9 - 0
engine/compilers/android/.classpath

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>

+ 51 - 0
engine/compilers/android/.cproject

@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+	<storageModule moduleId="org.eclipse.cdt.core.settings">
+		<cconfiguration id="com.android.toolchain.gcc.1442582075">
+			<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="com.android.toolchain.gcc.1442582075" moduleId="org.eclipse.cdt.core.settings" name="Default">
+				<externalSettings/>
+				<extensions>
+					<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+					<extension id="org.eclipse.cdt.core.VCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+					<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+				</extensions>
+			</storageModule>
+			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+				<configuration artifactName="${ProjName}" buildProperties="" description="" id="com.android.toolchain.gcc.1442582075" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
+					<folderInfo id="com.android.toolchain.gcc.1442582075.1056020003" name="/" resourcePath="">
+						<toolChain id="com.android.toolchain.gcc.1400756764" name="com.android.toolchain.gcc" superClass="com.android.toolchain.gcc">
+							<targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="com.android.targetPlatform.1302199400" isAbstract="false" superClass="com.android.targetPlatform"/>
+							<builder arguments="NDEBUG=1" command="ndk-build" id="com.android.builder.1818800065" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Android Builder" superClass="com.android.builder"/>
+							<tool id="com.android.gcc.compiler.1014866906" name="Android GCC Compiler" superClass="com.android.gcc.compiler">
+								<option id="com.android.gcc.option.includePath.100688008" superClass="com.android.gcc.option.includePath" valueType="includePath">
+									<listOptionValue builtIn="false" value="/Users/timmgt/androidDev/android-ndk-r8e/sources/cxx-stl/stlport/stlport"/>
+									<listOptionValue builtIn="false" value="/Users/timmgt/androidDev/android-ndk-r8e/platforms/android-14/arch-arm/usr/include"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/Torque2D/jni/include/libpng}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/Torque2D/jni/include/libjpeg}&quot;"/>
+								</option>
+								<inputType id="com.android.gcc.inputType.2067917403" superClass="com.android.gcc.inputType"/>
+							</tool>
+						</toolChain>
+					</folderInfo>
+				</configuration>
+			</storageModule>
+			<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+		</cconfiguration>
+	</storageModule>
+	<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+		<project id="Torque2D.null.1900297553" name="Torque2D"/>
+	</storageModule>
+	<storageModule moduleId="refreshScope" versionNumber="1"/>
+	<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+	<storageModule moduleId="scannerConfiguration">
+		<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+		<scannerConfigBuildInfo instanceId="com.android.toolchain.gcc.1442582075;com.android.toolchain.gcc.1442582075.1056020003;com.android.gcc.compiler.1014866906;com.android.gcc.inputType.2067917403">
+			<autodiscovery enabled="false" problemReportingEnabled="true" selectedProfileId="com.android.AndroidPerProjectProfile"/>
+		</scannerConfigBuildInfo>
+	</storageModule>
+</cproject>

+ 10 - 0
engine/compilers/android/.externalToolBuilders/NDK Builder.launch

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
+<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/Torque2D/libs&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
+<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
+<stringAttribute key="org.eclipse.ui.externaltools.ATTR_BUILD_SCOPE" value="${working_set:&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#10;&lt;resources&gt;&#10;&lt;item path=&quot;/Torque2D/jni&quot; type=&quot;2&quot;/&gt;&#10;&lt;/resources&gt;}"/>
+<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="/Users/timmgt/androidDev/android-ndk-r8d/ndk-build"/>
+<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
+<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
+<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Torque2D}"/>
+</launchConfiguration>

+ 100 - 0
engine/compilers/android/.project

@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>Torque2D</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+			<triggers>clean,full,incremental,</triggers>
+			<arguments>
+				<dictionary>
+					<key>?name?</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.append_environment</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildArguments</key>
+					<value>NDEBUG=1</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildCommand</key>
+					<value>ndk-build</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
+					<value>clean</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.contents</key>
+					<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
+					<value>false</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableFullBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.stopOnError</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
+					<value>false</value>
+				</dictionary>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+			<triggers>full,incremental,</triggers>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+		<nature>org.eclipse.cdt.core.cnature</nature>
+		<nature>org.eclipse.cdt.core.ccnature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+	</natures>
+	<linkedResources>
+		<link>
+			<name>jni/source</name>
+			<type>2</type>
+			<locationURI>WORKSPACE_LOC/engine/source</locationURI>
+		</link>
+	</linkedResources>
+</projectDescription>

+ 66 - 0
engine/compilers/android/.settings/org.eclipse.cdt.codan.core.prefs

@@ -0,0 +1,66 @@
+eclipse.preferences.version=1
+inEditor=false
+org.eclipse.cdt.codan.checkers.errnoreturn=Warning
+org.eclipse.cdt.codan.checkers.errnoreturn.params={implicit\=>false}
+org.eclipse.cdt.codan.checkers.errreturnvalue=Error
+org.eclipse.cdt.codan.checkers.errreturnvalue.params={}
+org.eclipse.cdt.codan.checkers.noreturn=Error
+org.eclipse.cdt.codan.checkers.noreturn.params={implicit\=>false}
+org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=Error
+org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=Error
+org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={}
+org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error
+org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={}
+org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false}
+org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning
+org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={unknown\=>false,exceptions\=>()}
+org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=Error
+org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=Error
+org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=Error
+org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.InvalidArguments=Error
+org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=Error
+org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=Error
+org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=Error
+org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=Error
+org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=Info
+org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={pattern\=>"^[a-z]",macro\=>true,exceptions\=>()}
+org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={}
+org.eclipse.cdt.codan.internal.checkers.OverloadProblem=Error
+org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=Error
+org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=Error
+org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={}
+org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning
+org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={}
+org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={macro\=>true,exceptions\=>()}
+org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={paramNot\=>false}
+org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={else\=>false,afterelse\=>false}
+org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=Error
+org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}
+org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={macro\=>true}
+org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={macro\=>true}
+org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={macro\=>true,exceptions\=>("@(\#)","$Id")}
+org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Warning
+org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}}

+ 11 - 0
engine/compilers/android/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,11 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6

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

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest package="com.garagegames.torque2d"
+    android:versionCode="1"
+    android:versionName="3.0" xmlns:android="http://schemas.android.com/apk/res/android">
+    
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+
+    <uses-sdk
+        android:minSdkVersion="9"
+        android:targetSdkVersion="15" />   
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
+        android:hardwareAccelerated="true">
+        <activity
+            android:name="android.app.NativeActivity"
+            android:label="@string/app_name"
+            android:screenOrientation="sensorLandscape" >
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="torque2d" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>

+ 36 - 0
engine/compilers/android/bin/AndroidManifest.xml

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest package="com.garagegames.torque2d"
+    android:versionCode="1"
+    android:versionName="3.0" xmlns:android="http://schemas.android.com/apk/res/android">
+    
+    <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+
+    <uses-sdk
+        android:minSdkVersion="9"
+        android:targetSdkVersion="15" />   
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
+        android:hardwareAccelerated="true">
+        <activity
+            android:name="android.app.NativeActivity"
+            android:label="@string/app_name"
+            android:screenOrientation="sensorLandscape" >
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="torque2d" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>

+ 92 - 0
engine/compilers/android/build.xml

@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project name="Torque2D" default="help">
+
+    <!-- The local.properties file is created and updated by the 'android' tool.
+         It contains the path to the SDK. It should *NOT* be checked into
+         Version Control Systems. -->
+    <property file="local.properties" />
+
+    <!-- The ant.properties file can be created by you. It is only edited by the
+         'android' tool to add properties to it.
+         This is the place to change some Ant specific build properties.
+         Here are some properties you may want to change/update:
+
+         source.dir
+             The name of the source directory. Default is 'src'.
+         out.dir
+             The name of the output directory. Default is 'bin'.
+
+         For other overridable properties, look at the beginning of the rules
+         files in the SDK, at tools/ant/build.xml
+
+         Properties related to the SDK location or the project target should
+         be updated using the 'android' tool with the 'update' action.
+
+         This file is an integral part of the build system for your
+         application and should be checked into Version Control Systems.
+
+         -->
+    <property file="ant.properties" />
+
+    <!-- if sdk.dir was not set from one of the property file, then
+         get it from the ANDROID_HOME env var.
+         This must be done before we load project.properties since
+         the proguard config can use sdk.dir -->
+    <property environment="env" />
+    <condition property="sdk.dir" value="${env.ANDROID_HOME}">
+        <isset property="env.ANDROID_HOME" />
+    </condition>
+
+    <!-- The project.properties file is created and updated by the 'android'
+         tool, as well as ADT.
+
+         This contains project specific properties such as project target, and library
+         dependencies. Lower level build properties are stored in ant.properties
+         (or in .classpath for Eclipse projects).
+
+         This file is an integral part of the build system for your
+         application and should be checked into Version Control Systems. -->
+    <loadproperties srcFile="project.properties" />
+
+    <!-- quick check on sdk.dir -->
+    <fail
+            message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
+            unless="sdk.dir"
+    />
+
+    <!--
+        Import per project custom build rules if present at the root of the project.
+        This is the place to put custom intermediary targets such as:
+            -pre-build
+            -pre-compile
+            -post-compile (This is typically used for code obfuscation.
+                           Compiled code location: ${out.classes.absolute.dir}
+                           If this is not done in place, override ${out.dex.input.absolute.dir})
+            -post-package
+            -post-build
+            -pre-clean
+    -->
+    <import file="custom_rules.xml" optional="true" />
+
+    <!-- Import the actual build file.
+
+         To customize existing targets, there are two options:
+         - Customize only one target:
+             - copy/paste the target into this file, *before* the
+               <import> task.
+             - customize it to your needs.
+         - Customize the whole content of build.xml
+             - copy/paste the content of the rules files (minus the top node)
+               into this file, replacing the <import> task.
+             - customize to your needs.
+
+         ***********************
+         ****** IMPORTANT ******
+         ***********************
+         In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
+         in order to avoid having your file be overridden by tools such as "android update project"
+    -->
+    <!-- version-tag: 1 -->
+    <import file="${sdk.dir}/tools/ant/build.xml" />
+
+</project>

+ 6 - 0
engine/compilers/android/gen/com/garagegames/torque2d/BuildConfig.java

@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.garagegames.torque2d;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}

+ 50 - 0
engine/compilers/android/gen/com/garagegames/torque2d/R.java

@@ -0,0 +1,50 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.garagegames.torque2d;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_launcher=0x7f020000;
+    }
+    public static final class menu {
+        public static final int activity_main=0x7f050000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f030000;
+    }
+    public static final class style {
+        /** 
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    
+
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        
+
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    
+ API 11 theme customizations can go here. 
+
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    
+ API 14 theme customizations can go here. 
+         */
+        public static final int AppBaseTheme=0x7f040000;
+        /**  Application theme. 
+ All customizations that are NOT specific to a particular API-level can go here. 
+         */
+        public static final int AppTheme=0x7f040001;
+    }
+}

二進制
engine/compilers/android/ic_launcher-web.png


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

@@ -0,0 +1,483 @@
+# Copyright (C) 2010 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+MY_LOCAL_PATH := $(call my-dir)
+LOCAL_PATH := $(MY_LOCAL_PATH)
+# LibPNG
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := libpng
+LOCAL_SRC_FILES := lib/libpng.a
+
+include $(PREBUILT_STATIC_LIBRARY)
+
+LOCAL_PATH := $(MY_LOCAL_PATH)
+# LibJPEG
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := libjpeg
+LOCAL_SRC_FILES := lib/libjpeg.a
+
+include $(PREBUILT_STATIC_LIBRARY)
+
+LOCAL_PATH := $(MY_LOCAL_PATH)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := torque2d
+LOCAL_C_INCLUDES := $(LOCAL_PATH) \
+    				$(LOCAL_PATH)/../../../source/torqueConfig.h \
+    				$(LOCAL_PATH)/../../../source/2d \
+    				$(LOCAL_PATH)/../../../source/2d/assets \
+    				$(LOCAL_PATH)/../../../source/2d/controllers \
+    				$(LOCAL_PATH)/../../../source/2d/core \
+    				$(LOCAL_PATH)/../../../source/2d/experimental/composites \
+    				$(LOCAL_PATH)/../../../source/2d/gui \
+    				$(LOCAL_PATH)/../../../source/2d/sceneobject \
+    				$(LOCAL_PATH)/../../../source/2d/scene \
+    				$(LOCAL_PATH)/../../../source/algorithm \
+    				$(LOCAL_PATH)/../../../source/assets \
+    				$(LOCAL_PATH)/../../../source/audio \
+    				$(LOCAL_PATH)/../../../source/box2d \
+    				$(LOCAL_PATH)/../../../source/box2d/Collision \
+					$(LOCAL_PATH)/../../../source/box2d/Collision/Shapes \
+					$(LOCAL_PATH)/../../../source/box2d/Common \
+					$(LOCAL_PATH)/../../../source/box2d/Dynamics \
+					$(LOCAL_PATH)/../../../source/box2d/Dynamics/Contacts \
+					$(LOCAL_PATH)/../../../source/box2d/Dynamics/Joints \
+					$(LOCAL_PATH)/../../../source/box2d/Rope \
+    				$(LOCAL_PATH)/../../../source/collection \
+    				$(LOCAL_PATH)/../../../source/component \
+    				$(LOCAL_PATH)/../../../source/component/behaviors \
+    				$(LOCAL_PATH)/../../../source/console \
+    				$(LOCAL_PATH)/../../../source/debug \
+    				$(LOCAL_PATH)/../../../source/debug/remote \
+    				$(LOCAL_PATH)/../../../source/delegates \
+    				$(LOCAL_PATH)/../../../source/game \
+    				$(LOCAL_PATH)/../../../source/graphics \
+    				$(LOCAL_PATH)/../../../source/gui \
+    				$(LOCAL_PATH)/../../../source/gui/buttons \
+    				$(LOCAL_PATH)/../../../source/gui/containers \
+    				$(LOCAL_PATH)/../../../source/gui/editor \
+    				$(LOCAL_PATH)/../../../source/gui/language \
+    				$(LOCAL_PATH)/../../../source/input \
+    				$(LOCAL_PATH)/../../../source/io \
+    				$(LOCAL_PATH)/../../../source/io/resource \
+    				$(LOCAL_PATH)/../../../source/io/zip \
+    				$(LOCAL_PATH)/../../../source/math \
+    				$(LOCAL_PATH)/../../../source/memory \
+    				$(LOCAL_PATH)/../../../source/messaging \
+    				$(LOCAL_PATH)/../../../source/module \
+    				$(LOCAL_PATH)/../../../source/network \
+    				$(LOCAL_PATH)/../../../source/persistence \
+    				$(LOCAL_PATH)/../../../source/persistence/taml \
+    				$(LOCAL_PATH)/../../../source/persistence/taml/binary \
+    				$(LOCAL_PATH)/../../../source/persistence/taml/json \
+    				$(LOCAL_PATH)/../../../source/persistence/taml/xml \
+    				$(LOCAL_PATH)/../../../source/platform \
+    				$(LOCAL_PATH)/../../../source/platform/nativeDialogs \
+    				$(LOCAL_PATH)/../../../source/platformAndroid \
+    				$(LOCAL_PATH)/../../../source/sim \
+    				$(LOCAL_PATH)/../../../source/string \
+    				$(LOCAL_PATH)/../../../source/testing \
+    				$(LOCAL_PATH)/../../../source/testing/tests
+	    			
+	    			
+LOCAL_SRC_FILES :=  ../../../source/2d/assets/AnimationAsset.cc \
+					../../../source/2d/assets/ImageAsset.cc \
+					../../../source/2d/assets/ParticleAsset.cc \
+					../../../source/2d/assets/ParticleAssetEmitter.cc \
+					../../../source/2d/assets/ParticleAssetField.cc \
+					../../../source/2d/assets/ParticleAssetFieldCollection.cc \
+					../../../source/2d/controllers/AmbientForceController.cc \
+					../../../source/2d/controllers/BuoyancyController.cc \
+					../../../source/2d/controllers/core/GroupedSceneController.cc \
+					../../../source/2d/controllers/core/PickingSceneController.cc \
+					../../../source/2d/controllers/PointForceController.cc \
+					../../../source/2d/core/BatchRender.cc \
+					../../../source/2d/core/CoreMath.cc \
+					../../../source/2d/core/ImageFrameProvider.cc \
+					../../../source/2d/core/ImageFrameProviderCore.cc \
+					../../../source/2d/core/ParticleSystem.cc \
+					../../../source/2d/core/RenderProxy.cc \
+					../../../source/2d/core/SpriteBase.cc \
+					../../../source/2d/core/SpriteBatch.cc \
+					../../../source/2d/core/SpriteBatchItem.cc \
+					../../../source/2d/core/SpriteBatchQuery.cc \
+					../../../source/2d/core/Utility.cc \
+					../../../source/2d/core/Vector2.cc \
+					../../../source/2d/experimental/composites/WaveComposite.cc \
+					../../../source/2d/gui/guiImageButtonCtrl.cc \
+					../../../source/2d/gui/guiSceneObjectCtrl.cc \
+					../../../source/2d/gui/guiSpriteCtrl.cc \
+					../../../source/2d/gui/SceneWindow.cc \
+					../../../source/2d/sceneobject/CompositeSprite.cc \
+					../../../source/2d/sceneobject/ImageFont.cc \
+					../../../source/2d/sceneobject/ParticlePlayer.cc \
+					../../../source/2d/sceneobject/SceneObject.cc \
+					../../../source/2d/sceneobject/SceneObjectList.cc \
+					../../../source/2d/sceneobject/SceneObjectSet.cc \
+					../../../source/2d/sceneobject/Scroller.cc \
+					../../../source/2d/sceneobject/ShapeVector.cc \
+					../../../source/2d/sceneobject/Sprite.cc \
+					../../../source/2d/sceneobject/Trigger.cc \
+					../../../source/2d/scene/ContactFilter.cc \
+					../../../source/2d/scene/DebugDraw.cc \
+					../../../source/2d/scene/Scene.cc \
+					../../../source/2d/scene/SceneRenderFactories.cpp \
+					../../../source/2d/scene/SceneRenderQueue.cpp \
+					../../../source/2d/scene/WorldQuery.cc \
+					../../../source/algorithm/crc.cc \
+					../../../source/algorithm/hashFunction.cc \
+					../../../source/assets/assetBase.cc \
+					../../../source/assets/assetFieldTypes.cc \
+					../../../source/assets/assetManager.cc \
+					../../../source/assets/assetQuery.cc \
+					../../../source/assets/assetTagsManifest.cc \
+					../../../source/assets/declaredAssets.cc \
+					../../../source/assets/referencedAssets.cc \
+					../../../source/audio/AudioAsset.cc \
+					../../../source/box2d/Collision/b2BroadPhase.cpp \
+					../../../source/box2d/Collision/b2CollideCircle.cpp \
+					../../../source/box2d/Collision/b2CollideEdge.cpp \
+					../../../source/box2d/Collision/b2CollidePolygon.cpp \
+					../../../source/box2d/Collision/b2Collision.cpp \
+					../../../source/box2d/Collision/b2Distance.cpp \
+					../../../source/box2d/Collision/b2DynamicTree.cpp \
+					../../../source/box2d/Collision/b2TimeOfImpact.cpp \
+					../../../source/box2d/Collision/Shapes/b2ChainShape.cpp \
+					../../../source/box2d/Collision/Shapes/b2CircleShape.cpp \
+					../../../source/box2d/Collision/Shapes/b2EdgeShape.cpp \
+					../../../source/box2d/Collision/Shapes/b2PolygonShape.cpp \
+					../../../source/box2d/Common/b2BlockAllocator.cpp \
+					../../../source/box2d/Common/b2Draw.cpp \
+					../../../source/box2d/Common/b2Math.cpp \
+					../../../source/box2d/Common/b2Settings.cpp \
+					../../../source/box2d/Common/b2StackAllocator.cpp \
+					../../../source/box2d/Common/b2Timer.cpp \
+					../../../source/box2d/Dynamics/b2Body.cpp \
+					../../../source/box2d/Dynamics/b2ContactManager.cpp \
+					../../../source/box2d/Dynamics/b2Fixture.cpp \
+					../../../source/box2d/Dynamics/b2Island.cpp \
+					../../../source/box2d/Dynamics/b2World.cpp \
+					../../../source/box2d/Dynamics/b2WorldCallbacks.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2CircleContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2Contact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2ContactSolver.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp \
+					../../../source/box2d/Dynamics/Contacts/b2PolygonContact.cpp \
+					../../../source/box2d/Dynamics/Joints/b2DistanceJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2FrictionJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2GearJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2Joint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2MotorJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2MouseJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2PrismaticJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2PulleyJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2RevoluteJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2RopeJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2WeldJoint.cpp \
+					../../../source/box2d/Dynamics/Joints/b2WheelJoint.cpp \
+					../../../source/box2d/Rope/b2Rope.cpp \
+					../../../source/collection/bitTables.cc \
+					../../../source/collection/hashTable.cc \
+					../../../source/collection/nameTags.cpp \
+					../../../source/collection/undo.cc \
+					../../../source/collection/vector.cc \
+					../../../source/console/consoleBaseType.cc \
+					../../../source/console/consoleDictionary.cc \
+					../../../source/console/consoleExprEvalState.cc \
+					../../../source/console/consoleNamespace.cc \
+					../../../source/console/ConsoleTypeValidators.cc \
+					../../../source/debug/profiler.cc \
+					../../../source/debug/remote/RemoteDebugger1.cc \
+					../../../source/debug/remote/RemoteDebuggerBase.cc \
+					../../../source/debug/remote/RemoteDebuggerBridge.cc \
+					../../../source/debug/telnetDebugger.cc \
+					../../../source/delegates/delegateSignal.cpp \
+					../../../source/game/defaultGame.cc \
+					../../../source/game/gameInterface.cc \
+					../../../source/graphics/bitmapBmp.cc \
+					../../../source/graphics/bitmapJpeg.cc \
+					../../../source/graphics/bitmapPng.cc \
+					../../../source/graphics/color.cc \
+					../../../source/graphics/dgl.cc \
+					../../../source/graphics/dglMatrix.cc \
+					../../../source/graphics/DynamicTexture.cc \
+					../../../source/graphics/gBitmap.cc \
+					../../../source/graphics/gFont.cc \
+					../../../source/graphics/gPalette.cc \
+					../../../source/graphics/PNGImage.cpp \
+					../../../source/graphics/splineUtil.cc \
+					../../../source/graphics/TextureDictionary.cc \
+					../../../source/graphics/TextureHandle.cc \
+					../../../source/graphics/TextureManager.cc \
+					../../../source/gui/containers/guiGridCtrl.cc \
+					../../../source/gui/guiArrayCtrl.cc \
+					../../../source/gui/guiBackgroundCtrl.cc \
+					../../../source/gui/guiBitmapBorderCtrl.cc \
+					../../../source/gui/guiBitmapCtrl.cc \
+					../../../source/gui/guiBubbleTextCtrl.cc \
+					../../../source/gui/guiCanvas.cc \
+					../../../source/gui/guiColorPicker.cc \
+					../../../source/gui/guiConsole.cc \
+					../../../source/gui/guiConsoleEditCtrl.cc \
+					../../../source/gui/guiConsoleTextCtrl.cc \
+					../../../source/gui/guiControl.cc \
+					../../../source/gui/guiDefaultControlRender.cc \
+					../../../source/gui/guiFadeinBitmapCtrl.cc \
+					../../../source/gui/guiInputCtrl.cc \
+					../../../source/gui/guiListBoxCtrl.cc \
+					../../../source/gui/guiMessageVectorCtrl.cc \
+					../../../source/gui/guiMLTextCtrl.cc \
+					../../../source/gui/guiMLTextEditCtrl.cc \
+					../../../source/gui/guiMouseEventCtrl.cc \
+					../../../source/gui/guiPopUpCtrl.cc \
+					../../../source/gui/guiPopUpCtrlEx.cc \
+					../../../source/gui/guiProgressCtrl.cc \
+					../../../source/gui/guiScriptNotifyControl.cc \
+					../../../source/gui/guiSliderCtrl.cc \
+					../../../source/gui/guiTabPageCtrl.cc \
+					../../../source/gui/guiTextCtrl.cc \
+					../../../source/gui/guiTextEditCtrl.cc \
+					../../../source/gui/guiTextEditSliderCtrl.cc \
+					../../../source/gui/guiTextListCtrl.cc \
+					../../../source/gui/guiTickCtrl.cc \
+					../../../source/gui/guiTreeViewCtrl.cc \
+					../../../source/gui/guiTypes.cc \
+					../../../source/gui/language/lang.cc \
+					../../../source/gui/messageVector.cc \
+					../../../source/input/actionMap.cc \
+					../../../source/io/bitStream.cc \
+					../../../source/io/bufferStream.cc \
+					../../../source/io/fileObject.cc \
+					../../../source/io/fileStream.cc \
+					../../../source/io/fileStreamObject.cc \
+					../../../source/io/fileSystemFunctions.cpp \
+					../../../source/io/filterStream.cc \
+					../../../source/io/memStream.cc \
+					../../../source/io/nStream.cc \
+					../../../source/io/resizeStream.cc \
+					../../../source/io/resource/resourceDictionary.cc \
+					../../../source/io/resource/resourceManager.cc \
+					../../../source/io/streamObject.cc \
+					../../../source/io/zip/centralDir.cc \
+					../../../source/io/zip/compressor.cc \
+					../../../source/io/zip/deflate.cc \
+					../../../source/io/zip/extraField.cc \
+					../../../source/io/zip/fileHeader.cc \
+					../../../source/io/zip/stored.cc \
+					../../../source/io/zip/zipArchive.cc \
+					../../../source/io/zip/zipCryptStream.cc \
+					../../../source/io/zip/zipObject.cc \
+					../../../source/io/zip/zipSubStream.cc \
+					../../../source/io/zip/zipTempStream.cc \
+					../../../source/math/rectClipper.cpp \
+					../../../source/memory/dataChunker.cc \
+					../../../source/memory/frameAllocator.cc \
+					../../../source/messaging/dispatcher.cc \
+					../../../source/messaging/eventManager.cc \
+					../../../source/messaging/message.cc \
+					../../../source/messaging/messageForwarder.cc \
+					../../../source/messaging/scriptMsgListener.cc \
+					../../../source/module/moduleDefinition.cc \
+					../../../source/module/moduleManager.cc \
+					../../../source/module/moduleMergeDefinition.cc \
+					../../../source/network/connectionProtocol.cc \
+					../../../source/network/connectionStringTable.cc \
+					../../../source/network/httpObject.cc \
+					../../../source/network/netConnection.cc \
+					../../../source/network/netDownload.cc \
+					../../../source/network/netEvent.cc \
+					../../../source/network/netGhost.cc \
+					../../../source/network/netInterface.cc \
+					../../../source/network/netObject.cc \
+					../../../source/network/netStringTable.cc \
+					../../../source/network/netTest.cc \
+					../../../source/network/networkProcessList.cc \
+					../../../source/network/RemoteCommandEvent.cc \
+					../../../source/network/serverQuery.cc \
+					../../../source/network/tcpObject.cc \
+					../../../source/network/telnetConsole.cc \
+					../../../source/persistence/taml/binary/tamlBinaryReader.cc \
+					../../../source/persistence/taml/binary/tamlBinaryWriter.cc \
+					../../../source/persistence/taml/json/tamlJSONParser.cc \
+					../../../source/persistence/taml/json/tamlJSONReader.cc \
+					../../../source/persistence/taml/json/tamlJSONWriter.cc \
+					../../../source/persistence/taml/taml.cc \
+					../../../source/persistence/taml/tamlCustom.cc \
+					../../../source/persistence/taml/tamlWriteNode.cc \
+					../../../source/persistence/taml/xml/tamlXmlParser.cc \
+					../../../source/persistence/taml/xml/tamlXmlReader.cc \
+					../../../source/persistence/taml/xml/tamlXmlWriter.cc \
+					../../../source/persistence/tinyXML/tinystr.cpp \
+					../../../source/persistence/tinyXML/tinyxml.cpp \
+					../../../source/persistence/tinyXML/tinyxmlerror.cpp \
+					../../../source/persistence/tinyXML/tinyxmlparser.cpp \
+					../../../source/audio/audio.cc \
+					../../../source/audio/audioBuffer.cc \
+					../../../source/audio/audioDataBlock.cc \
+					../../../source/audio/audioFunctions.cc \
+					../../../source/audio/audioStreamSourceFactory.cc \
+					../../../source/audio/wavStreamSource.cc \
+					../../../source/component/dynamicConsoleMethodComponent.cpp \
+					../../../source/component/simComponent.cpp \
+					../../../source/component/behaviors/behaviorComponent.cpp \
+					../../../source/component/behaviors/behaviorInstance.cpp \
+					../../../source/component/behaviors/behaviorTemplate.cpp \
+					../../../source/console/astAlloc.cc \
+					../../../source/console/astNodes.cc \
+					../../../source/console/cmdgram.cc \
+					../../../source/console/CMDscan.cc \
+					../../../source/console/codeBlock.cc \
+					../../../source/console/compiledEval.cc \
+					../../../source/console/compiler.cc \
+					../../../source/console/console.cc \
+					../../../source/console/consoleDoc.cc \
+					../../../source/console/consoleFunctions.cc \
+					../../../source/console/consoleLogger.cc \
+					../../../source/console/consoleObject.cc \
+					../../../source/console/consoleParser.cc \
+					../../../source/console/consoleTypes.cc \
+					../../../source/game/gameConnection.cc \
+					../../../source/game/version.cc \
+					../../../source/math/mathTypes.cc \
+					../../../source/math/mathUtils.cc \
+					../../../source/math/mBox.cc \
+					../../../source/math/mConsoleFunctions.cc \
+					../../../source/math/mMath_C.cc \
+					../../../source/math/mMathAltivec.cc \
+					../../../source/math/mMathAMD.cc \
+					../../../source/math/mMathFn.cc \
+					../../../source/math/mMathSSE.cc \
+					../../../source/math/mMatrix.cc \
+					../../../source/math/mPlaneTransformer.cc \
+					../../../source/math/mQuadPatch.cc \
+					../../../source/math/mQuat.cc \
+					../../../source/math/mRandom.cc \
+					../../../source/math/mSolver.cc \
+					../../../source/math/mSplinePatch.cc \
+					../../../source/persistence/SimXMLDocument.cpp \
+					../../../source/platform/CursorManager.cc \
+					../../../source/platform/nativeDialogs/fileDialog.cc \
+					../../../source/platform/platform.cc \
+					../../../source/platform/platformAssert.cc \
+					../../../source/platform/platformCPU.cc \
+					../../../source/platform/platformFileIO.cc \
+					../../../source/platform/platformFont.cc \
+					../../../source/platform/platformMemory.cc \
+					../../../source/platform/platformNetwork.cc \
+					../../../source/platform/platformString.cc \
+					../../../source/platform/platformVideo.cc \
+					../../../source/platform/menus/popupMenu.cc \
+					../../../source/platform/nativeDialogs/msgBox.cpp \
+					../../../source/platform/Tickable.cc \
+					../../../source/platformAndroid/AndroidAlerts.cpp \
+					../../../source/platformAndroid/AndroidAudio.cpp \
+					../../../source/platformAndroid/AndroidConsole.cpp \
+					../../../source/platformAndroid/AndroidCPUInfo.cpp \
+					../../../source/platformAndroid/AndroidDialogs.cpp \
+					../../../source/platformAndroid/AndroidEvents.cpp \
+					../../../source/platformAndroid/AndroidFileio.cpp \
+					../../../source/platformAndroid/AndroidFont.cpp \
+					../../../source/platformAndroid/AndroidGL.cpp \
+					../../../source/platformAndroid/AndroidGL2ES.cpp \
+					../../../source/platformAndroid/AndroidInput.cpp \
+					../../../source/platformAndroid/AndroidMath.cpp \
+					../../../source/platformAndroid/AndroidMemory.cpp \
+					../../../source/platformAndroid/AndroidMotionManager.cpp \
+					../../../source/platformAndroid/AndroidMutex.cpp \
+					../../../source/platformAndroid/AndroidNet.cpp \
+					../../../source/platformAndroid/AndroidOGLVideo.cpp \
+					../../../source/platformAndroid/AndroidOutlineGL.cpp \
+					../../../source/platformAndroid/AndroidPlatform.cpp \
+					../../../source/platformAndroid/AndroidProcessControl.cpp \
+					../../../source/platformAndroid/AndroidProfiler.cpp \
+					../../../source/platformAndroid/AndroidSemaphore.cpp \
+					../../../source/platformAndroid/AndroidStreamSource.cc \
+					../../../source/platformAndroid/AndroidStrings.cpp \
+					../../../source/platformAndroid/AndroidThread.cpp \
+					../../../source/platformAndroid/AndroidTime.cpp \
+					../../../source/platformAndroid/AndroidUtil.cpp \
+					
+					../../../source/sim/scriptGroup.cc \
+					../../../source/sim/scriptObject.cc \
+					../../../source/sim/simBase.cc \
+					../../../source/sim/simConsoleEvent.cc \
+					../../../source/sim/simConsoleThreadExecEvent.cc \
+					../../../source/sim/simDatablock.cc \
+					../../../source/sim/simDictionary.cc \
+					../../../source/sim/simFieldDictionary.cc \
+					../../../source/sim/simManager.cc \
+					../../../source/sim/simObject.cc \
+					../../../source/sim/SimObjectList.cc \
+					../../../source/sim/simSerialize.cpp \
+					../../../source/sim/simSet.cc \
+					../../../source/string/findMatch.cc \
+					../../../source/string/stringBuffer.cc \
+					../../../source/string/stringStack.cc \
+					../../../source/string/stringTable.cc \
+					../../../source/string/stringUnit.cpp \
+					../../../source/string/unicode.cc \
+					../../../source/gui/buttons/guiBitmapButtonCtrl.cc \
+					../../../source/gui/buttons/guiBorderButton.cc \
+					../../../source/gui/buttons/guiButtonBaseCtrl.cc \
+					../../../source/gui/buttons/guiButtonCtrl.cc \
+					../../../source/gui/buttons/guiCheckBoxCtrl.cc \
+					../../../source/gui/buttons/guiIconButtonCtrl.cc \
+					../../../source/gui/buttons/guiRadioCtrl.cc \
+					../../../source/gui/buttons/guiToolboxButtonCtrl.cc \
+					../../../source/gui/containers/guiAutoScrollCtrl.cc \
+					../../../source/gui/containers/guiCtrlArrayCtrl.cc \
+					../../../source/gui/containers/guiDragAndDropCtrl.cc \
+					../../../source/gui/containers/guiDynamicCtrlArrayCtrl.cc \
+					../../../source/gui/containers/guiFormCtrl.cc \
+					../../../source/gui/containers/guiFrameCtrl.cc \
+					../../../source/gui/containers/guiPaneCtrl.cc \
+					../../../source/gui/containers/guiRolloutCtrl.cc \
+					../../../source/gui/containers/guiScrollCtrl.cc \
+					../../../source/gui/containers/guiStackCtrl.cc \
+					../../../source/gui/containers/guiTabBookCtrl.cc \
+					../../../source/gui/containers/guiWindowCtrl.cc \
+					../../../source/gui/editor/guiControlListPopup.cc \
+					../../../source/gui/editor/guiDebugger.cc \
+					../../../source/gui/editor/guiEditCtrl.cc \
+					../../../source/gui/editor/guiFilterCtrl.cc \
+					../../../source/gui/editor/guiGraphCtrl.cc \
+					../../../source/gui/editor/guiImageList.cc \
+					../../../source/gui/editor/guiInspector.cc \
+					../../../source/gui/editor/guiInspectorTypes.cc \
+					../../../source/gui/editor/guiMenuBar.cc \
+					../../../source/gui/editor/guiSeparatorCtrl.cc \
+					../../../source/testing/tests/platformFileIoTests.cc \
+					../../../source/testing/tests/platformMemoryTests.cc \
+					../../../source/testing/tests/platformStringTests.cc \
+					../../../source/testing/unitTesting.cc
+ 
+			   
+LOCAL_CFLAGS := -DENABLE_CONSOLE_MSGS -D__ANDROID__ -O0 -fsigned-char
+				   
+LOCAL_LDLIBS    := -llog -landroid -lEGL -lGLESv2 -lz -lOpenSLES
+LOCAL_STATIC_LIBRARIES := android_native_app_glue libpng libjpeg
+
+LOCAL_ARM_MODE := arm
+
+include $(BUILD_SHARED_LIBRARY)
+
+$(call import-module,android/native_app_glue)
+

+ 4 - 0
engine/compilers/android/jni/Application.mk

@@ -0,0 +1,4 @@
+APP_PLATFORM := android-10
+APP_STL := stlport_static
+APP_OPTIM := debug
+APP_ABI   := armeabi-v7a

+ 134 - 0
engine/compilers/android/jni/include/libjpeg/cderror.h

@@ -0,0 +1,134 @@
+/*
+ * cderror.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * Modified 2009 by Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the cjpeg/djpeg
+ * applications.  These strings are not needed as part of the JPEG library
+ * proper.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE.  To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef CDERROR_H
+#define CDERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* CDERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string)	code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_FIRSTADDONCODE=1000, NULL) /* Must be first entry! */
+
+#ifdef BMP_SUPPORTED
+JMESSAGE(JERR_BMP_BADCMAP, "Unsupported BMP colormap format")
+JMESSAGE(JERR_BMP_BADDEPTH, "Only 8- and 24-bit BMP files are supported")
+JMESSAGE(JERR_BMP_BADHEADER, "Invalid BMP file: bad header length")
+JMESSAGE(JERR_BMP_BADPLANES, "Invalid BMP file: biPlanes not equal to 1")
+JMESSAGE(JERR_BMP_COLORSPACE, "BMP output must be grayscale or RGB")
+JMESSAGE(JERR_BMP_COMPRESSED, "Sorry, compressed BMPs not yet supported")
+JMESSAGE(JERR_BMP_EMPTY, "Empty BMP image")
+JMESSAGE(JERR_BMP_NOT, "Not a BMP file - does not start with BM")
+JMESSAGE(JTRC_BMP, "%ux%u 24-bit BMP image")
+JMESSAGE(JTRC_BMP_MAPPED, "%ux%u 8-bit colormapped BMP image")
+JMESSAGE(JTRC_BMP_OS2, "%ux%u 24-bit OS2 BMP image")
+JMESSAGE(JTRC_BMP_OS2_MAPPED, "%ux%u 8-bit colormapped OS2 BMP image")
+#endif /* BMP_SUPPORTED */
+
+#ifdef GIF_SUPPORTED
+JMESSAGE(JERR_GIF_BUG, "GIF output got confused")
+JMESSAGE(JERR_GIF_CODESIZE, "Bogus GIF codesize %d")
+JMESSAGE(JERR_GIF_COLORSPACE, "GIF output must be grayscale or RGB")
+JMESSAGE(JERR_GIF_IMAGENOTFOUND, "Too few images in GIF file")
+JMESSAGE(JERR_GIF_NOT, "Not a GIF file")
+JMESSAGE(JTRC_GIF, "%ux%ux%d GIF image")
+JMESSAGE(JTRC_GIF_BADVERSION,
+	 "Warning: unexpected GIF version number '%c%c%c'")
+JMESSAGE(JTRC_GIF_EXTENSION, "Ignoring GIF extension block of type 0x%02x")
+JMESSAGE(JTRC_GIF_NONSQUARE, "Caution: nonsquare pixels in input")
+JMESSAGE(JWRN_GIF_BADDATA, "Corrupt data in GIF file")
+JMESSAGE(JWRN_GIF_CHAR, "Bogus char 0x%02x in GIF file, ignoring")
+JMESSAGE(JWRN_GIF_ENDCODE, "Premature end of GIF image")
+JMESSAGE(JWRN_GIF_NOMOREDATA, "Ran out of GIF bits")
+#endif /* GIF_SUPPORTED */
+
+#ifdef PPM_SUPPORTED
+JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
+JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
+JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
+JMESSAGE(JTRC_PGM, "%ux%u PGM image")
+JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
+JMESSAGE(JTRC_PPM, "%ux%u PPM image")
+JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
+#endif /* PPM_SUPPORTED */
+
+#ifdef RLE_SUPPORTED
+JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
+JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
+JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
+JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
+JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
+JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
+JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
+JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
+JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
+JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
+JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_GRAY, "%ux%u grayscale RLE file")
+JMESSAGE(JTRC_RLE_MAPGRAY, "%ux%u grayscale RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_MAPPED, "%ux%u colormapped RLE file with map of length %d")
+#endif /* RLE_SUPPORTED */
+
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_TGA_BADCMAP, "Unsupported Targa colormap format")
+JMESSAGE(JERR_TGA_BADPARMS, "Invalid or unsupported Targa file")
+JMESSAGE(JERR_TGA_COLORSPACE, "Targa output must be grayscale or RGB")
+JMESSAGE(JTRC_TGA, "%ux%u RGB Targa image")
+JMESSAGE(JTRC_TGA_GRAY, "%ux%u grayscale Targa image")
+JMESSAGE(JTRC_TGA_MAPPED, "%ux%u colormapped Targa image")
+#else
+JMESSAGE(JERR_TGA_NOTCOMP, "Targa support was not compiled")
+#endif /* TARGA_SUPPORTED */
+
+JMESSAGE(JERR_BAD_CMAP_FILE,
+	 "Color map file is invalid or of unsupported format")
+JMESSAGE(JERR_TOO_MANY_COLORS,
+	 "Output file format cannot handle %d colormap entries")
+JMESSAGE(JERR_UNGETC_FAILED, "ungetc failed")
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_UNKNOWN_FORMAT,
+	 "Unrecognized input file format --- perhaps you need -targa")
+#else
+JMESSAGE(JERR_UNKNOWN_FORMAT, "Unrecognized input file format")
+#endif
+JMESSAGE(JERR_UNSUPPORTED_FORMAT, "Unsupported output file format")
+
+#ifdef JMAKE_ENUM_LIST
+
+  JMSG_LASTADDONCODE
+} ADDON_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE

+ 187 - 0
engine/compilers/android/jni/include/libjpeg/cdjpeg.h

@@ -0,0 +1,187 @@
+/*
+ * cdjpeg.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains common declarations for the sample applications
+ * cjpeg and djpeg.  It is NOT used by the core JPEG library.
+ */
+
+#define JPEG_CJPEG_DJPEG	/* define proper options in jconfig.h */
+#define JPEG_INTERNAL_OPTIONS	/* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"		/* get library error codes too */
+#include "cderror.h"		/* get application-specific error codes */
+
+
+/*
+ * Object interface for cjpeg's source file decoding modules
+ */
+
+typedef struct cjpeg_source_struct * cjpeg_source_ptr;
+
+struct cjpeg_source_struct {
+  JMETHOD(void, start_input, (j_compress_ptr cinfo,
+			      cjpeg_source_ptr sinfo));
+  JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
+				       cjpeg_source_ptr sinfo));
+  JMETHOD(void, finish_input, (j_compress_ptr cinfo,
+			       cjpeg_source_ptr sinfo));
+
+  FILE *input_file;
+
+  JSAMPARRAY buffer;
+  JDIMENSION buffer_height;
+};
+
+
+/*
+ * Object interface for djpeg's output file encoding modules
+ */
+
+typedef struct djpeg_dest_struct * djpeg_dest_ptr;
+
+struct djpeg_dest_struct {
+  /* start_output is called after jpeg_start_decompress finishes.
+   * The color map will be ready at this time, if one is needed.
+   */
+  JMETHOD(void, start_output, (j_decompress_ptr cinfo,
+			       djpeg_dest_ptr dinfo));
+  /* Emit the specified number of pixel rows from the buffer. */
+  JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
+				 djpeg_dest_ptr dinfo,
+				 JDIMENSION rows_supplied));
+  /* Finish up at the end of the image. */
+  JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
+				djpeg_dest_ptr dinfo));
+
+  /* Target file spec; filled in by djpeg.c after object is created. */
+  FILE * output_file;
+
+  /* Output pixel-row buffer.  Created by module init or start_output.
+   * Width is cinfo->output_width * cinfo->output_components;
+   * height is buffer_height.
+   */
+  JSAMPARRAY buffer;
+  JDIMENSION buffer_height;
+};
+
+
+/*
+ * cjpeg/djpeg may need to perform extra passes to convert to or from
+ * the source/destination file format.  The JPEG library does not know
+ * about these passes, but we'd like them to be counted by the progress
+ * monitor.  We use an expanded progress monitor object to hold the
+ * additional pass count.
+ */
+
+struct cdjpeg_progress_mgr {
+  struct jpeg_progress_mgr pub;	/* fields known to JPEG library */
+  int completed_extra_passes;	/* extra passes completed */
+  int total_extra_passes;	/* total extra */
+  /* last printed percentage stored here to avoid multiple printouts */
+  int percent_done;
+};
+
+typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_read_bmp		jIRdBMP
+#define jinit_write_bmp		jIWrBMP
+#define jinit_read_gif		jIRdGIF
+#define jinit_write_gif		jIWrGIF
+#define jinit_read_ppm		jIRdPPM
+#define jinit_write_ppm		jIWrPPM
+#define jinit_read_rle		jIRdRLE
+#define jinit_write_rle		jIWrRLE
+#define jinit_read_targa	jIRdTarga
+#define jinit_write_targa	jIWrTarga
+#define read_quant_tables	RdQTables
+#define read_scan_script	RdScnScript
+#define set_quality_ratings     SetQRates
+#define set_quant_slots		SetQSlots
+#define set_sample_factors	SetSFacts
+#define read_color_map		RdCMap
+#define enable_signal_catcher	EnSigCatcher
+#define start_progress_monitor	StProgMon
+#define end_progress_monitor	EnProgMon
+#define read_stdin		RdStdin
+#define write_stdout		WrStdout
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Module selection routines for I/O modules. */
+
+EXTERN(cjpeg_source_ptr) jinit_read_bmp JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_bmp JPP((j_decompress_ptr cinfo,
+					    boolean is_os2));
+EXTERN(cjpeg_source_ptr) jinit_read_gif JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_gif JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_ppm JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_ppm JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_rle JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_rle JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_targa JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_targa JPP((j_decompress_ptr cinfo));
+
+/* cjpeg support routines (in rdswitch.c) */
+
+EXTERN(boolean) read_quant_tables JPP((j_compress_ptr cinfo, char * filename,
+				       boolean force_baseline));
+EXTERN(boolean) read_scan_script JPP((j_compress_ptr cinfo, char * filename));
+EXTERN(boolean) set_quality_ratings JPP((j_compress_ptr cinfo, char *arg,
+					 boolean force_baseline));
+EXTERN(boolean) set_quant_slots JPP((j_compress_ptr cinfo, char *arg));
+EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
+
+/* djpeg support routines (in rdcolmap.c) */
+
+EXTERN(void) read_color_map JPP((j_decompress_ptr cinfo, FILE * infile));
+
+/* common support routines (in cdjpeg.c) */
+
+EXTERN(void) enable_signal_catcher JPP((j_common_ptr cinfo));
+EXTERN(void) start_progress_monitor JPP((j_common_ptr cinfo,
+					 cd_progress_ptr progress));
+EXTERN(void) end_progress_monitor JPP((j_common_ptr cinfo));
+EXTERN(boolean) keymatch JPP((char * arg, const char * keyword, int minchars));
+EXTERN(FILE *) read_stdin JPP((void));
+EXTERN(FILE *) write_stdout JPP((void));
+
+/* miscellaneous useful macros */
+
+#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
+#define READ_BINARY	"r"
+#define WRITE_BINARY	"w"
+#else
+#ifdef VMS			/* VMS is very nonstandard */
+#define READ_BINARY	"rb", "ctx=stm"
+#define WRITE_BINARY	"wb", "ctx=stm"
+#else				/* standard ANSI-compliant case */
+#define READ_BINARY	"rb"
+#define WRITE_BINARY	"wb"
+#endif
+#endif
+
+#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
+#define EXIT_FAILURE  1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS  1		/* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS  0
+#endif
+#endif
+#ifndef EXIT_WARNING
+#ifdef VMS
+#define EXIT_WARNING  1		/* VMS is very nonstandard */
+#else
+#define EXIT_WARNING  2
+#endif
+#endif

+ 54 - 0
engine/compilers/android/jni/include/libjpeg/jconfig.h

@@ -0,0 +1,54 @@
+/* jconfig.h.  Generated from jconfig.cfg by configure.  */
+/* jconfig.cfg --- source file edited by configure script */
+/* see jconfig.txt for explanations */
+
+#define HAVE_PROTOTYPES 1
+#define HAVE_UNSIGNED_CHAR 1
+#define HAVE_UNSIGNED_SHORT 1
+/* #undef void */
+/* #undef const */
+/* #undef CHAR_IS_UNSIGNED */
+#define HAVE_STDDEF_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_LOCALE_H 1
+/* #undef NEED_BSD_STRINGS */
+/* #undef NEED_SYS_TYPES_H */
+/* #undef NEED_FAR_POINTERS */
+/* #undef NEED_SHORT_EXTERNAL_NAMES */
+/* Define this if you get warnings about undefined structures. */
+/* #undef INCOMPLETE_TYPES_BROKEN */
+
+/* Define "boolean" as unsigned char, not int, on Windows systems. */
+#ifdef _WIN32
+#ifndef __RPCNDR_H__		/* don't conflict if rpcndr.h already read */
+typedef unsigned char boolean;
+#endif
+#define HAVE_BOOLEAN		/* prevent jmorecfg.h from redefining it */
+#endif
+
+#ifdef JPEG_INTERNALS
+
+/* #undef RIGHT_SHIFT_IS_UNSIGNED */
+#define INLINE __inline__
+/* These are for configuring the JPEG memory manager. */
+/* #undef DEFAULT_MAX_MEM */
+/* #undef NO_MKTEMP */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED		/* BMP image file format */
+#define GIF_SUPPORTED		/* GIF image file format */
+#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */
+/* #undef RLE_SUPPORTED */
+#define TARGA_SUPPORTED		/* Targa image file format */
+
+/* #undef TWO_FILE_COMMANDLINE */
+/* #undef NEED_SIGNAL_CATCHER */
+/* #undef DONT_USE_B_MODE */
+
+/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
+/* #undef PROGRESS_REPORT */
+
+#endif /* JPEG_CJPEG_DJPEG */

+ 393 - 0
engine/compilers/android/jni/include/libjpeg/jdct.h

@@ -0,0 +1,393 @@
+/*
+ * jdct.h
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the forward and
+ * inverse DCT modules.  These declarations are private to the DCT managers
+ * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
+ * The individual DCT algorithms are kept in separate files to ease 
+ * machine-dependent tuning (e.g., assembly coding).
+ */
+
+
+/*
+ * A forward DCT routine is given a pointer to an input sample array and
+ * a pointer to a work area of type DCTELEM[]; the DCT is to be performed
+ * in-place in that buffer.  Type DCTELEM is int for 8-bit samples, INT32
+ * for 12-bit samples.  (NOTE: Floating-point DCT implementations use an
+ * array of type FAST_FLOAT, instead.)
+ * The input data is to be fetched from the sample array starting at a
+ * specified column.  (Any row offset needed will be applied to the array
+ * pointer before it is passed to the FDCT code.)
+ * Note that the number of samples fetched by the FDCT routine is
+ * DCT_h_scaled_size * DCT_v_scaled_size.
+ * The DCT outputs are returned scaled up by a factor of 8; they therefore
+ * have a range of +-8K for 8-bit data, +-128K for 12-bit data.  This
+ * convention improves accuracy in integer implementations and saves some
+ * work in floating-point ones.
+ * Quantization of the output coefficients is done by jcdctmgr.c.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM;		/* 16 or 32 bits is fine */
+#else
+typedef INT32 DCTELEM;		/* must have 32 bits */
+#endif
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data,
+					       JSAMPARRAY sample_data,
+					       JDIMENSION start_col));
+typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data,
+					     JSAMPARRAY sample_data,
+					     JDIMENSION start_col));
+
+
+/*
+ * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
+ * to an output sample array.  The routine must dequantize the input data as
+ * well as perform the IDCT; for dequantization, it uses the multiplier table
+ * pointed to by compptr->dct_table.  The output data is to be placed into the
+ * sample array starting at a specified column.  (Any row offset needed will
+ * be applied to the array pointer before it is passed to the IDCT code.)
+ * Note that the number of samples emitted by the IDCT routine is
+ * DCT_h_scaled_size * DCT_v_scaled_size.
+ */
+
+/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
+
+/*
+ * Each IDCT routine has its own ideas about the best dct_table element type.
+ */
+
+typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
+#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
+#define IFAST_SCALE_BITS  2	/* fractional bits in scale factors */
+#else
+typedef INT32 IFAST_MULT_TYPE;	/* need 32 bits for scaled quantizers */
+#define IFAST_SCALE_BITS  13	/* fractional bits in scale factors */
+#endif
+typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
+
+
+/*
+ * Each IDCT routine is responsible for range-limiting its results and
+ * converting them to unsigned form (0..MAXJSAMPLE).  The raw outputs could
+ * be quite far out of range if the input data is corrupt, so a bulletproof
+ * range-limiting step is required.  We use a mask-and-table-lookup method
+ * to do the combined operations quickly.  See the comments with
+ * prepare_range_limit_table (in jdmaster.c) for more info.
+ */
+
+#define IDCT_range_limit(cinfo)  ((cinfo)->sample_range_limit + CENTERJSAMPLE)
+
+#define RANGE_MASK  (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_fdct_islow		jFDislow
+#define jpeg_fdct_ifast		jFDifast
+#define jpeg_fdct_float		jFDfloat
+#define jpeg_fdct_7x7		jFD7x7
+#define jpeg_fdct_6x6		jFD6x6
+#define jpeg_fdct_5x5		jFD5x5
+#define jpeg_fdct_4x4		jFD4x4
+#define jpeg_fdct_3x3		jFD3x3
+#define jpeg_fdct_2x2		jFD2x2
+#define jpeg_fdct_1x1		jFD1x1
+#define jpeg_fdct_9x9		jFD9x9
+#define jpeg_fdct_10x10		jFD10x10
+#define jpeg_fdct_11x11		jFD11x11
+#define jpeg_fdct_12x12		jFD12x12
+#define jpeg_fdct_13x13		jFD13x13
+#define jpeg_fdct_14x14		jFD14x14
+#define jpeg_fdct_15x15		jFD15x15
+#define jpeg_fdct_16x16		jFD16x16
+#define jpeg_fdct_16x8		jFD16x8
+#define jpeg_fdct_14x7		jFD14x7
+#define jpeg_fdct_12x6		jFD12x6
+#define jpeg_fdct_10x5		jFD10x5
+#define jpeg_fdct_8x4		jFD8x4
+#define jpeg_fdct_6x3		jFD6x3
+#define jpeg_fdct_4x2		jFD4x2
+#define jpeg_fdct_2x1		jFD2x1
+#define jpeg_fdct_8x16		jFD8x16
+#define jpeg_fdct_7x14		jFD7x14
+#define jpeg_fdct_6x12		jFD6x12
+#define jpeg_fdct_5x10		jFD5x10
+#define jpeg_fdct_4x8		jFD4x8
+#define jpeg_fdct_3x6		jFD3x6
+#define jpeg_fdct_2x4		jFD2x4
+#define jpeg_fdct_1x2		jFD1x2
+#define jpeg_idct_islow		jRDislow
+#define jpeg_idct_ifast		jRDifast
+#define jpeg_idct_float		jRDfloat
+#define jpeg_idct_7x7		jRD7x7
+#define jpeg_idct_6x6		jRD6x6
+#define jpeg_idct_5x5		jRD5x5
+#define jpeg_idct_4x4		jRD4x4
+#define jpeg_idct_3x3		jRD3x3
+#define jpeg_idct_2x2		jRD2x2
+#define jpeg_idct_1x1		jRD1x1
+#define jpeg_idct_9x9		jRD9x9
+#define jpeg_idct_10x10		jRD10x10
+#define jpeg_idct_11x11		jRD11x11
+#define jpeg_idct_12x12		jRD12x12
+#define jpeg_idct_13x13		jRD13x13
+#define jpeg_idct_14x14		jRD14x14
+#define jpeg_idct_15x15		jRD15x15
+#define jpeg_idct_16x16		jRD16x16
+#define jpeg_idct_16x8		jRD16x8
+#define jpeg_idct_14x7		jRD14x7
+#define jpeg_idct_12x6		jRD12x6
+#define jpeg_idct_10x5		jRD10x5
+#define jpeg_idct_8x4		jRD8x4
+#define jpeg_idct_6x3		jRD6x3
+#define jpeg_idct_4x2		jRD4x2
+#define jpeg_idct_2x1		jRD2x1
+#define jpeg_idct_8x16		jRD8x16
+#define jpeg_idct_7x14		jRD7x14
+#define jpeg_idct_6x12		jRD6x12
+#define jpeg_idct_5x10		jRD5x10
+#define jpeg_idct_4x8		jRD4x8
+#define jpeg_idct_3x6		jRD3x8
+#define jpeg_idct_2x4		jRD2x4
+#define jpeg_idct_1x2		jRD1x2
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Extern declarations for the forward and inverse DCT routines. */
+
+EXTERN(void) jpeg_fdct_islow
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_ifast
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_float
+    JPP((FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_7x7
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_6x6
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_5x5
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_4x4
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_3x3
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_2x2
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_1x1
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_9x9
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_10x10
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_11x11
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_12x12
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_13x13
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_14x14
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_15x15
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_16x16
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_16x8
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_14x7
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_12x6
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_10x5
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_8x4
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_6x3
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_4x2
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_2x1
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_8x16
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_7x14
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_6x12
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_5x10
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_4x8
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_3x6
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_2x4
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+EXTERN(void) jpeg_fdct_1x2
+    JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
+
+EXTERN(void) jpeg_idct_islow
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_ifast
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_float
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_7x7
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_6x6
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_5x5
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_4x4
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_3x3
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_2x2
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_1x1
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_9x9
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_10x10
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_11x11
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_12x12
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_13x13
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_14x14
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_15x15
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_16x16
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_16x8
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_14x7
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_12x6
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_10x5
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_8x4
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_6x3
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_4x2
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_2x1
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_8x16
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_7x14
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_6x12
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_5x10
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_4x8
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_3x6
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_2x4
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_1x2
+    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+
+
+/*
+ * Macros for handling fixed-point arithmetic; these are used by many
+ * but not all of the DCT/IDCT modules.
+ *
+ * All values are expected to be of type INT32.
+ * Fractional constants are scaled left by CONST_BITS bits.
+ * CONST_BITS is defined within each module using these macros,
+ * and may differ from one module to the next.
+ */
+
+#define ONE	((INT32) 1)
+#define CONST_SCALE (ONE << CONST_BITS)
+
+/* Convert a positive real constant to an integer scaled by CONST_SCALE.
+ * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
+ * thus causing a lot of useless floating-point operations at run time.
+ */
+
+#define FIX(x)	((INT32) ((x) * CONST_SCALE + 0.5))
+
+/* Descale and correctly round an INT32 value that's scaled by N bits.
+ * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
+ * the fudge factor is correct for either sign of X.
+ */
+
+#define DESCALE(x,n)  RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * This macro is used only when the two inputs will actually be no more than
+ * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
+ * full 32x32 multiply.  This provides a useful speedup on many machines.
+ * Unfortunately there is no way to specify a 16x16->32 multiply portably
+ * in C, but some C compilers will do the right thing if you provide the
+ * correct combination of casts.
+ */
+
+#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
+#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT16) (const)))
+#endif
+#ifdef SHORTxLCONST_32		/* known to work with Microsoft C 6.0 */
+#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT32) (const)))
+#endif
+
+#ifndef MULTIPLY16C16		/* default definition */
+#define MULTIPLY16C16(var,const)  ((var) * (const))
+#endif
+
+/* Same except both inputs are variables. */
+
+#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
+#define MULTIPLY16V16(var1,var2)  (((INT16) (var1)) * ((INT16) (var2)))
+#endif
+
+#ifndef MULTIPLY16V16		/* default definition */
+#define MULTIPLY16V16(var1,var2)  ((var1) * (var2))
+#endif

+ 304 - 0
engine/compilers/android/jni/include/libjpeg/jerror.h

@@ -0,0 +1,304 @@
+/*
+ * jerror.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * Modified 1997-2012 by Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the JPEG library.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ * A set of error-reporting macros are defined too.  Some applications using
+ * the JPEG library may wish to include this file to get the error codes
+ * and/or the macros.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE.  To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef JERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* JERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string)	code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
+
+/* For maintenance convenience, list is alphabetical by message code name */
+JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
+JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
+JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request")
+JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
+JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported")
+JMESSAGE(JERR_BAD_DROP_SAMPLING,
+	 "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c")
+JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
+JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+JMESSAGE(JERR_BAD_LIB_VERSION,
+	 "Wrong JPEG library version: library is %d, caller expects %d")
+JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+JMESSAGE(JERR_BAD_PROGRESSION,
+	 "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_PROG_SCRIPT,
+	 "Invalid progressive parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+JMESSAGE(JERR_BAD_STRUCT_SIZE,
+	 "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
+JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
+JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
+JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
+JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
+JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
+JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
+JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
+JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
+JMESSAGE(JERR_FILE_READ, "Input file read error")
+JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
+JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
+JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
+JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
+JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
+JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
+JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
+JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
+	 "Cannot transcode due to multiple use of quantization table %d")
+JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
+JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
+JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
+JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
+JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined")
+JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
+JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+JMESSAGE(JERR_QUANT_COMPONENTS,
+	 "Cannot quantize more than %d color components")
+JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
+JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
+JMESSAGE(JERR_SOF_BEFORE, "Invalid JPEG file structure: %s before SOF")
+JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
+JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
+JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
+JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
+JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
+JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
+JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
+JMESSAGE(JERR_TFILE_WRITE,
+	 "Write failed on temporary file --- out of disk space?")
+JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
+JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
+JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
+JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
+JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
+JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
+JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
+JMESSAGE(JMSG_VERSION, JVERSION)
+JMESSAGE(JTRC_16BIT_TABLES,
+	 "Caution: quantization tables are too coarse for baseline JPEG")
+JMESSAGE(JTRC_ADOBE,
+	 "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
+JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
+JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
+JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
+JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
+JMESSAGE(JTRC_DQT, "Define Quantization Table %d  precision %d")
+JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
+JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
+JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
+JMESSAGE(JTRC_EOI, "End Of Image")
+JMESSAGE(JTRC_HUFFBITS, "        %3d %3d %3d %3d %3d %3d %3d %3d")
+JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d  %d")
+JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
+	 "Warning: thumbnail image size does not match data length %u")
+JMESSAGE(JTRC_JFIF_EXTENSION,
+	 "JFIF extension marker: type 0x%02x, length %u")
+JMESSAGE(JTRC_JFIF_THUMBNAIL, "    with %d x %d thumbnail image")
+JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
+JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
+JMESSAGE(JTRC_QUANTVALS, "        %4u %4u %4u %4u %4u %4u %4u %4u")
+JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
+JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
+JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
+JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
+JMESSAGE(JTRC_RST, "RST%d")
+JMESSAGE(JTRC_SMOOTH_NOTIMPL,
+	 "Smoothing not supported with nonstandard sampling ratios")
+JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
+JMESSAGE(JTRC_SOF_COMPONENT, "    Component %d: %dhx%dv q=%d")
+JMESSAGE(JTRC_SOI, "Start of Image")
+JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
+JMESSAGE(JTRC_SOS_COMPONENT, "    Component %d: dc=%d ac=%d")
+JMESSAGE(JTRC_SOS_PARAMS, "  Ss=%d, Se=%d, Ah=%d, Al=%d")
+JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
+JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
+JMESSAGE(JTRC_THUMB_JPEG,
+	 "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_PALETTE,
+	 "JFIF extension marker: palette thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_RGB,
+	 "JFIF extension marker: RGB thumbnail image, length %u")
+JMESSAGE(JTRC_UNKNOWN_IDS,
+	 "Unrecognized component IDs %d %d %d, assuming YCbCr")
+JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
+JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code")
+JMESSAGE(JWRN_BOGUS_PROGRESSION,
+	 "Inconsistent progression sequence for component %d coefficient %d")
+JMESSAGE(JWRN_EXTRANEOUS_DATA,
+	 "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
+JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
+JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
+JMESSAGE(JWRN_MUST_RESYNC,
+	 "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
+
+#ifdef JMAKE_ENUM_LIST
+
+  JMSG_LASTMSGCODE
+} J_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
+
+
+#ifndef JERROR_H
+#define JERROR_H
+
+/* Macros to simplify using the error and trace message stuff */
+/* The first parameter is either type of cinfo pointer */
+
+/* Fatal errors (print message and exit) */
+#define ERREXIT(cinfo,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT1(cinfo,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT2(cinfo,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT3(cinfo,code,p1,p2,p3)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (cinfo)->err->msg_parm.i[2] = (p3), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT4(cinfo,code,p1,p2,p3,p4)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (cinfo)->err->msg_parm.i[2] = (p3), \
+   (cinfo)->err->msg_parm.i[3] = (p4), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (cinfo)->err->msg_parm.i[2] = (p3), \
+   (cinfo)->err->msg_parm.i[3] = (p4), \
+   (cinfo)->err->msg_parm.i[4] = (p5), \
+   (cinfo)->err->msg_parm.i[5] = (p6), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str)  \
+  ((cinfo)->err->msg_code = (code), \
+   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+
+#define MAKESTMT(stuff)		do { stuff } while (0)
+
+/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
+#define WARNMS(cinfo,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS1(cinfo,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS2(cinfo,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+
+/* Informational/debugging messages */
+#define TRACEMS(cinfo,lvl,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS1(cinfo,lvl,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS2(cinfo,lvl,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS3(cinfo,lvl,code,p1,p2,p3)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   _mp[4] = (p5); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMSS(cinfo,lvl,code,str)  \
+  ((cinfo)->err->msg_code = (code), \
+   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+
+#endif /* JERROR_H */

+ 91 - 0
engine/compilers/android/jni/include/libjpeg/jinclude.h

@@ -0,0 +1,91 @@
+/*
+ * jinclude.h
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file exists to provide a single place to fix any problems with
+ * including the wrong system include files.  (Common problems are taken
+ * care of by the standard jconfig symbols, but on really weird systems
+ * you may have to edit this file.)
+ *
+ * NOTE: this file is NOT intended to be included by applications using the
+ * JPEG library.  Most applications need only include jpeglib.h.
+ */
+
+
+/* Include auto-config file to find out which system include files we need. */
+
+#include "jconfig.h"		/* auto configuration options */
+#define JCONFIG_INCLUDED	/* so that jpeglib.h doesn't do it again */
+
+/*
+ * We need the NULL macro and size_t typedef.
+ * On an ANSI-conforming system it is sufficient to include <stddef.h>.
+ * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
+ * pull in <sys/types.h> as well.
+ * Note that the core JPEG library does not require <stdio.h>;
+ * only the default error handler and data source/destination modules do.
+ * But we must pull it in because of the references to FILE in jpeglib.h.
+ * You can remove those references if you want to compile without <stdio.h>.
+ */
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <stdio.h>
+
+/*
+ * We need memory copying and zeroing functions, plus strncpy().
+ * ANSI and System V implementations declare these in <string.h>.
+ * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
+ * Some systems may declare memset and memcpy in <memory.h>.
+ *
+ * NOTE: we assume the size parameters to these functions are of type size_t.
+ * Change the casts in these macros if not!
+ */
+
+#ifdef NEED_BSD_STRINGS
+
+#include <strings.h>
+#define MEMZERO(target,size)	bzero((void *)(target), (size_t)(size))
+#define MEMCOPY(dest,src,size)	bcopy((const void *)(src), (void *)(dest), (size_t)(size))
+
+#else /* not BSD, assume ANSI/SysV string lib */
+
+#include <string.h>
+#define MEMZERO(target,size)	memset((void *)(target), 0, (size_t)(size))
+#define MEMCOPY(dest,src,size)	memcpy((void *)(dest), (const void *)(src), (size_t)(size))
+
+#endif
+
+/*
+ * In ANSI C, and indeed any rational implementation, size_t is also the
+ * type returned by sizeof().  However, it seems there are some irrational
+ * implementations out there, in which sizeof() returns an int even though
+ * size_t is defined as long or unsigned long.  To ensure consistent results
+ * we always use this SIZEOF() macro in place of using sizeof() directly.
+ */
+
+#define SIZEOF(object)	((size_t) sizeof(object))
+
+/*
+ * The modules that use fread() and fwrite() always invoke them through
+ * these macros.  On some systems you may need to twiddle the argument casts.
+ * CAUTION: argument order is different from underlying functions!
+ */
+
+#define JFREAD(file,buf,sizeofbuf)  \
+  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+#define JFWRITE(file,buf,sizeofbuf)  \
+  ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))

+ 198 - 0
engine/compilers/android/jni/include/libjpeg/jmemsys.h

@@ -0,0 +1,198 @@
+/*
+ * jmemsys.h
+ *
+ * Copyright (C) 1992-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file defines the interface between the system-independent
+ * and system-dependent portions of the JPEG memory manager.  No other
+ * modules need include it.  (The system-independent portion is jmemmgr.c;
+ * there are several different versions of the system-dependent portion.)
+ *
+ * This file works as-is for the system-dependent memory managers supplied
+ * in the IJG distribution.  You may need to modify it if you write a
+ * custom memory manager.  If system-dependent changes are needed in
+ * this file, the best method is to #ifdef them based on a configuration
+ * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR
+ * and USE_MAC_MEMMGR.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_get_small		jGetSmall
+#define jpeg_free_small		jFreeSmall
+#define jpeg_get_large		jGetLarge
+#define jpeg_free_large		jFreeLarge
+#define jpeg_mem_available	jMemAvail
+#define jpeg_open_backing_store	jOpenBackStore
+#define jpeg_mem_init		jMemInit
+#define jpeg_mem_term		jMemTerm
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * These two functions are used to allocate and release small chunks of
+ * memory.  (Typically the total amount requested through jpeg_get_small is
+ * no more than 20K or so; this will be requested in chunks of a few K each.)
+ * Behavior should be the same as for the standard library functions malloc
+ * and free; in particular, jpeg_get_small must return NULL on failure.
+ * On most systems, these ARE malloc and free.  jpeg_free_small is passed the
+ * size of the object being freed, just in case it's needed.
+ * On an 80x86 machine using small-data memory model, these manage near heap.
+ */
+
+EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
+EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
+				  size_t sizeofobject));
+
+/*
+ * These two functions are used to allocate and release large chunks of
+ * memory (up to the total free space designated by jpeg_mem_available).
+ * The interface is the same as above, except that on an 80x86 machine,
+ * far pointers are used.  On most other machines these are identical to
+ * the jpeg_get/free_small routines; but we keep them separate anyway,
+ * in case a different allocation strategy is desirable for large chunks.
+ */
+
+EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
+				       size_t sizeofobject));
+EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
+				  size_t sizeofobject));
+
+/*
+ * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
+ * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
+ * matter, but that case should never come into play).  This macro is needed
+ * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
+ * On those machines, we expect that jconfig.h will provide a proper value.
+ * On machines with 32-bit flat address spaces, any large constant may be used.
+ *
+ * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
+ * size_t and will be a multiple of sizeof(align_type).
+ */
+
+#ifndef MAX_ALLOC_CHUNK		/* may be overridden in jconfig.h */
+#define MAX_ALLOC_CHUNK  1000000000L
+#endif
+
+/*
+ * This routine computes the total space still available for allocation by
+ * jpeg_get_large.  If more space than this is needed, backing store will be
+ * used.  NOTE: any memory already allocated must not be counted.
+ *
+ * There is a minimum space requirement, corresponding to the minimum
+ * feasible buffer sizes; jmemmgr.c will request that much space even if
+ * jpeg_mem_available returns zero.  The maximum space needed, enough to hold
+ * all working storage in memory, is also passed in case it is useful.
+ * Finally, the total space already allocated is passed.  If no better
+ * method is available, cinfo->mem->max_memory_to_use - already_allocated
+ * is often a suitable calculation.
+ *
+ * It is OK for jpeg_mem_available to underestimate the space available
+ * (that'll just lead to more backing-store access than is really necessary).
+ * However, an overestimate will lead to failure.  Hence it's wise to subtract
+ * a slop factor from the true available space.  5% should be enough.
+ *
+ * On machines with lots of virtual memory, any large constant may be returned.
+ * Conversely, zero may be returned to always use the minimum amount of memory.
+ */
+
+EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
+				     long min_bytes_needed,
+				     long max_bytes_needed,
+				     long already_allocated));
+
+
+/*
+ * This structure holds whatever state is needed to access a single
+ * backing-store object.  The read/write/close method pointers are called
+ * by jmemmgr.c to manipulate the backing-store object; all other fields
+ * are private to the system-dependent backing store routines.
+ */
+
+#define TEMP_NAME_LENGTH   64	/* max length of a temporary file's name */
+
+
+#ifdef USE_MSDOS_MEMMGR		/* DOS-specific junk */
+
+typedef unsigned short XMSH;	/* type of extended-memory handles */
+typedef unsigned short EMSH;	/* type of expanded-memory handles */
+
+typedef union {
+  short file_handle;		/* DOS file handle if it's a temp file */
+  XMSH xms_handle;		/* handle if it's a chunk of XMS */
+  EMSH ems_handle;		/* handle if it's a chunk of EMS */
+} handle_union;
+
+#endif /* USE_MSDOS_MEMMGR */
+
+#ifdef USE_MAC_MEMMGR		/* Mac-specific junk */
+#include <Files.h>
+#endif /* USE_MAC_MEMMGR */
+
+
+typedef struct backing_store_struct * backing_store_ptr;
+
+typedef struct backing_store_struct {
+  /* Methods for reading/writing/closing this backing-store object */
+  JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
+				     backing_store_ptr info,
+				     void FAR * buffer_address,
+				     long file_offset, long byte_count));
+  JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
+				      backing_store_ptr info,
+				      void FAR * buffer_address,
+				      long file_offset, long byte_count));
+  JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
+				      backing_store_ptr info));
+
+  /* Private fields for system-dependent backing-store management */
+#ifdef USE_MSDOS_MEMMGR
+  /* For the MS-DOS manager (jmemdos.c), we need: */
+  handle_union handle;		/* reference to backing-store storage object */
+  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+#ifdef USE_MAC_MEMMGR
+  /* For the Mac manager (jmemmac.c), we need: */
+  short temp_file;		/* file reference number to temp file */
+  FSSpec tempSpec;		/* the FSSpec for the temp file */
+  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+  /* For a typical implementation with temp files, we need: */
+  FILE * temp_file;		/* stdio reference to temp file */
+  char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
+#endif
+#endif
+} backing_store_info;
+
+
+/*
+ * Initial opening of a backing-store object.  This must fill in the
+ * read/write/close pointers in the object.  The read/write routines
+ * may take an error exit if the specified maximum file size is exceeded.
+ * (If jpeg_mem_available always returns a large value, this routine can
+ * just take an error exit.)
+ */
+
+EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
+					  backing_store_ptr info,
+					  long total_bytes_needed));
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.  jpeg_mem_init will be called before anything is
+ * allocated (and, therefore, nothing in cinfo is of use except the error
+ * manager pointer).  It should return a suitable default value for
+ * max_memory_to_use; this may subsequently be overridden by the surrounding
+ * application.  (Note that max_memory_to_use is only important if
+ * jpeg_mem_available chooses to consult it ... no one else will.)
+ * jpeg_mem_term may assume that all requested memory has been freed and that
+ * all opened backing-store objects have been closed.
+ */
+
+EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
+EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));

+ 390 - 0
engine/compilers/android/jni/include/libjpeg/jmorecfg.h

@@ -0,0 +1,390 @@
+/*
+ * jmorecfg.h
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modified 1997-2012 by Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains additional configuration options that customize the
+ * JPEG software for special applications or support machine-dependent
+ * optimizations.  Most users will not need to touch this file.
+ */
+
+
+/*
+ * Define BITS_IN_JSAMPLE as either
+ *   8   for 8-bit sample values (the usual setting)
+ *   12  for 12-bit sample values
+ * Only 8 and 12 are legal data precisions for lossy JPEG according to the
+ * JPEG standard, and the IJG code does not support anything else!
+ * We do not support run-time selection of data precision, sorry.
+ */
+
+#define BITS_IN_JSAMPLE  8	/* use 8 or 12 */
+
+
+/*
+ * Maximum number of components (color channels) allowed in JPEG image.
+ * To meet the letter of the JPEG spec, set this to 255.  However, darn
+ * few applications need more than 4 channels (maybe 5 for CMYK + alpha
+ * mask).  We recommend 10 as a reasonable compromise; use 4 if you are
+ * really short on memory.  (Each allowed component costs a hundred or so
+ * bytes of storage, whether actually used in an image or not.)
+ */
+
+#define MAX_COMPONENTS  10	/* maximum number of image components */
+
+
+/*
+ * Basic data types.
+ * You may need to change these if you have a machine with unusual data
+ * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
+ * or "long" not 32 bits.  We don't care whether "int" is 16 or 32 bits,
+ * but it had better be at least 16.
+ */
+
+/* Representation of a single sample (pixel element value).
+ * We frequently allocate large arrays of these, so it's important to keep
+ * them small.  But if you have memory to burn and access to char or short
+ * arrays is very slow on your hardware, you might want to change these.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+#define GETJSAMPLE(value)  ((int) (value))
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value)  ((int) (value))
+#else
+#define GETJSAMPLE(value)  ((int) (value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#define MAXJSAMPLE	255
+#define CENTERJSAMPLE	128
+
+#endif /* BITS_IN_JSAMPLE == 8 */
+
+
+#if BITS_IN_JSAMPLE == 12
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+typedef short JSAMPLE;
+#define GETJSAMPLE(value)  ((int) (value))
+
+#define MAXJSAMPLE	4095
+#define CENTERJSAMPLE	2048
+
+#endif /* BITS_IN_JSAMPLE == 12 */
+
+
+/* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+ * if you have memory to burn and "short" is really slow.
+ */
+
+typedef short JCOEF;
+
+
+/* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage.  Note that when using the stdio data source/destination
+ * managers, this is also the data type passed to fread/fwrite.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JOCTET;
+#define GETJOCTET(value)  (value)
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JOCTET;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJOCTET(value)  (value)
+#else
+#define GETJOCTET(value)  ((value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+/* These typedefs are used for various table entries and so forth.
+ * They must be at least as wide as specified; but making them too big
+ * won't cost a huge amount of memory, so we don't provide special
+ * extraction code like we did for JSAMPLE.  (In other words, these
+ * typedefs live at a different point on the speed/space tradeoff curve.)
+ */
+
+/* UINT8 must hold at least the values 0..255. */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char UINT8;
+#else /* not HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char UINT8;
+#else /* not CHAR_IS_UNSIGNED */
+typedef short UINT8;
+#endif /* CHAR_IS_UNSIGNED */
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/* UINT16 must hold at least the values 0..65535. */
+
+#ifdef HAVE_UNSIGNED_SHORT
+typedef unsigned short UINT16;
+#else /* not HAVE_UNSIGNED_SHORT */
+typedef unsigned int UINT16;
+#endif /* HAVE_UNSIGNED_SHORT */
+
+/* INT16 must hold at least the values -32768..32767. */
+
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT16 */
+typedef short INT16;
+#endif
+
+/* INT32 must hold at least signed 32-bit values. */
+
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT32 */
+#ifndef _BASETSD_H_		/* Microsoft defines it in basetsd.h */
+#ifndef _BASETSD_H		/* MinGW is slightly different */
+#ifndef QGLOBAL_H		/* Qt defines it in qglobal.h */
+typedef long INT32;
+#endif
+#endif
+#endif
+#endif
+
+/* Datatype used for image dimensions.  The JPEG standard only supports
+ * images up to 64K*64K due to 16-bit fields in SOF markers.  Therefore
+ * "unsigned int" is sufficient on all machines.  However, if you need to
+ * handle larger images and you don't mind deviating from the spec, you
+ * can change this datatype.
+ */
+
+typedef unsigned int JDIMENSION;
+
+#define JPEG_MAX_DIMENSION  65500L  /* a tad under 64K to prevent overflows */
+
+
+/* These macros are used in all function definitions and extern declarations.
+ * You could modify them if you need to change function linkage conventions;
+ * in particular, you'll need to do that to make the library a Windows DLL.
+ * Another application is to make all functions global for use with debuggers
+ * or code profilers that require it.
+ */
+
+/* a function called through method pointers: */
+#define METHODDEF(type)		static type
+/* a function used only in its module: */
+#define LOCAL(type)		static type
+/* a function referenced thru EXTERNs: */
+#define GLOBAL(type)		type
+/* a reference to a GLOBAL function: */
+#define EXTERN(type)		extern type
+
+
+/* This macro is used to declare a "method", that is, a function pointer.
+ * We want to supply prototype parameters if the compiler can cope.
+ * Note that the arglist parameter must be parenthesized!
+ * Again, you can customize this if you need special linkage keywords.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
+#else
+#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
+#endif
+
+
+/* The noreturn type identifier is used to declare functions
+ * which cannot return.
+ * Compilers can thus create more optimized code and perform
+ * better checks for warnings and errors.
+ * Static analyzer tools can make improved inferences about
+ * execution paths and are prevented from giving false alerts.
+ *
+ * Unfortunately, the proposed specifications of corresponding
+ * extensions in the Dec 2011 ISO C standard revision (C11),
+ * GCC, MSVC, etc. are not viable.
+ * Thus we introduce a user defined type to declare noreturn
+ * functions at least for clarity.  A proper compiler would
+ * have a suitable noreturn type to match in place of void.
+ */
+
+#ifndef HAVE_NORETURN_T
+typedef void noreturn_t;
+#endif
+
+
+/* Here is the pseudo-keyword for declaring pointers that must be "far"
+ * on 80x86 machines.  Most of the specialized coding for 80x86 is handled
+ * by just saying "FAR *" where such a pointer is needed.  In a few places
+ * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
+ */
+
+#ifndef FAR
+#ifdef NEED_FAR_POINTERS
+#define FAR  far
+#else
+#define FAR
+#endif
+#endif
+
+
+/*
+ * On a few systems, type boolean and/or its values FALSE, TRUE may appear
+ * in standard header files.  Or you may have conflicts with application-
+ * specific header files that you want to include together with these files.
+ * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
+ */
+
+#ifdef HAVE_BOOLEAN
+#ifndef FALSE			/* in case these macros already exist */
+#define FALSE	0		/* values of boolean */
+#endif
+#ifndef TRUE
+#define TRUE	1
+#endif
+#else
+#define boolean int
+#endif
+
+
+/*
+ * The remaining options affect code selection within the JPEG library,
+ * but they don't need to be visible to most applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+#define JPEG_INTERNAL_OPTIONS
+#endif
+
+#ifdef JPEG_INTERNAL_OPTIONS
+
+
+/*
+ * These defines indicate whether to include various optional functions.
+ * Undefining some of these symbols will produce a smaller but less capable
+ * library.  Note that you can leave certain source files out of the
+ * compilation/linking process if you've #undef'd the corresponding symbols.
+ * (You may HAVE to do that if your compiler doesn't like null source files.)
+ */
+
+/* Capability options common to encoder and decoder: */
+
+#define DCT_ISLOW_SUPPORTED	/* slow but accurate integer algorithm */
+#define DCT_IFAST_SUPPORTED	/* faster, less accurate integer method */
+#define DCT_FLOAT_SUPPORTED	/* floating-point: accurate, fast on fast HW */
+
+/* Encoder capability options: */
+
+#define C_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
+#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define C_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
+#define DCT_SCALING_SUPPORTED	    /* Input rescaling via DCT? (Requires DCT_ISLOW)*/
+#define ENTROPY_OPT_SUPPORTED	    /* Optimization of entropy coding parms? */
+/* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED.  The standard Huffman tables are only good for 8-bit
+ * precision, so jchuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision.  If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+ * The exact same statements apply for progressive JPEG: the default tables
+ * don't work for progressive mode.  (This may get fixed, however.)
+ */
+#define INPUT_SMOOTHING_SUPPORTED   /* Input image smoothing option? */
+
+/* Decoder capability options: */
+
+#define D_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
+#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define D_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
+#define IDCT_SCALING_SUPPORTED	    /* Output rescaling via IDCT? */
+#define SAVE_MARKERS_SUPPORTED	    /* jpeg_save_markers() needed? */
+#define BLOCK_SMOOTHING_SUPPORTED   /* Block smoothing? (Progressive only) */
+#undef  UPSAMPLE_SCALING_SUPPORTED  /* Output rescaling at upsample stage? */
+#define UPSAMPLE_MERGING_SUPPORTED  /* Fast path for sloppy upsampling? */
+#define QUANT_1PASS_SUPPORTED	    /* 1-pass color quantization? */
+#define QUANT_2PASS_SUPPORTED	    /* 2-pass color quantization? */
+
+/* more capability options later, no doubt */
+
+
+/*
+ * Ordering of RGB data in scanlines passed to or from the application.
+ * If your application wants to deal with data in the order B,G,R, just
+ * change these macros.  You can also deal with formats such as R,G,B,X
+ * (one extra byte per pixel) by changing RGB_PIXELSIZE.  Note that changing
+ * the offsets will also change the order in which colormap data is organized.
+ * RESTRICTIONS:
+ * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
+ * 2. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
+ *    is not 3 (they don't understand about dummy color components!).  So you
+ *    can't use color quantization if you change that value.
+ */
+
+#define RGB_RED		0	/* Offset of Red in an RGB scanline element */
+#define RGB_GREEN	1	/* Offset of Green */
+#define RGB_BLUE	2	/* Offset of Blue */
+#define RGB_PIXELSIZE	3	/* JSAMPLEs per RGB scanline element */
+
+
+/* Definitions for speed-related optimizations. */
+
+
+/* If your compiler supports inline functions, define INLINE
+ * as the inline keyword; otherwise define it as empty.
+ */
+
+#ifndef INLINE
+#ifdef __GNUC__			/* for instance, GNU C knows about inline */
+#define INLINE __inline__
+#endif
+#ifndef INLINE
+#define INLINE			/* default is to define it as empty */
+#endif
+#endif
+
+
+/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
+ * two 16-bit shorts is faster than multiplying two ints.  Define MULTIPLIER
+ * as short on such a machine.  MULTIPLIER must be at least 16 bits wide.
+ */
+
+#ifndef MULTIPLIER
+#define MULTIPLIER  int		/* type for fastest integer multiply */
+#endif
+
+
+/* FAST_FLOAT should be either float or double, whichever is done faster
+ * by your compiler.  (Note that this type is only used in the floating point
+ * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
+ * Typically, float is faster in ANSI C compilers, while double is faster in
+ * pre-ANSI compilers (because they insist on converting to double anyway).
+ * The code below therefore chooses float if we have ANSI-style prototypes.
+ */
+
+#ifndef FAST_FLOAT
+#ifdef HAVE_PROTOTYPES
+#define FAST_FLOAT  float
+#else
+#define FAST_FLOAT  double
+#endif
+#endif
+
+#endif /* JPEG_INTERNAL_OPTIONS */

+ 426 - 0
engine/compilers/android/jni/include/libjpeg/jpegint.h

@@ -0,0 +1,426 @@
+/*
+ * jpegint.h
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modified 1997-2011 by Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides common declarations for the various JPEG modules.
+ * These declarations are considered internal to the JPEG library; most
+ * applications using the library shouldn't need to include this file.
+ */
+
+
+/* Declarations for both compression & decompression */
+
+typedef enum {			/* Operating modes for buffer controllers */
+	JBUF_PASS_THRU,		/* Plain stripwise operation */
+	/* Remaining modes require a full-image buffer to have been created */
+	JBUF_SAVE_SOURCE,	/* Run source subobject only, save output */
+	JBUF_CRANK_DEST,	/* Run dest subobject only, using saved data */
+	JBUF_SAVE_AND_PASS	/* Run both subobjects, save output */
+} J_BUF_MODE;
+
+/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
+#define CSTATE_START	100	/* after create_compress */
+#define CSTATE_SCANNING	101	/* start_compress done, write_scanlines OK */
+#define CSTATE_RAW_OK	102	/* start_compress done, write_raw_data OK */
+#define CSTATE_WRCOEFS	103	/* jpeg_write_coefficients done */
+#define DSTATE_START	200	/* after create_decompress */
+#define DSTATE_INHEADER	201	/* reading header markers, no SOS yet */
+#define DSTATE_READY	202	/* found SOS, ready for start_decompress */
+#define DSTATE_PRELOAD	203	/* reading multiscan file in start_decompress*/
+#define DSTATE_PRESCAN	204	/* performing dummy pass for 2-pass quant */
+#define DSTATE_SCANNING	205	/* start_decompress done, read_scanlines OK */
+#define DSTATE_RAW_OK	206	/* start_decompress done, read_raw_data OK */
+#define DSTATE_BUFIMAGE	207	/* expecting jpeg_start_output */
+#define DSTATE_BUFPOST	208	/* looking for SOS/EOI in jpeg_finish_output */
+#define DSTATE_RDCOEFS	209	/* reading file in jpeg_read_coefficients */
+#define DSTATE_STOPPING	210	/* looking for EOI in jpeg_finish_decompress */
+
+
+/* Declarations for compression modules */
+
+/* Master control module */
+struct jpeg_comp_master {
+  JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
+  JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
+  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+
+  /* State variables made visible to other modules */
+  boolean call_pass_startup;	/* True if pass_startup must be called */
+  boolean is_last_pass;		/* True during last pass */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_c_main_controller {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+  JMETHOD(void, process_data, (j_compress_ptr cinfo,
+			       JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+			       JDIMENSION in_rows_avail));
+};
+
+/* Compression preprocessing (downsampling input buffer control) */
+struct jpeg_c_prep_controller {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+  JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+				   JSAMPARRAY input_buf,
+				   JDIMENSION *in_row_ctr,
+				   JDIMENSION in_rows_avail,
+				   JSAMPIMAGE output_buf,
+				   JDIMENSION *out_row_group_ctr,
+				   JDIMENSION out_row_groups_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_c_coef_controller {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+  JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+				   JSAMPIMAGE input_buf));
+};
+
+/* Colorspace conversion */
+struct jpeg_color_converter {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+  JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+				JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+				JDIMENSION output_row, int num_rows));
+};
+
+/* Downsampling */
+struct jpeg_downsampler {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+  JMETHOD(void, downsample, (j_compress_ptr cinfo,
+			     JSAMPIMAGE input_buf, JDIMENSION in_row_index,
+			     JSAMPIMAGE output_buf,
+			     JDIMENSION out_row_group_index));
+
+  boolean need_context_rows;	/* TRUE if need rows above & below */
+};
+
+/* Forward DCT (also controls coefficient quantization) */
+typedef JMETHOD(void, forward_DCT_ptr,
+		(j_compress_ptr cinfo, jpeg_component_info * compptr,
+		 JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+		 JDIMENSION start_row, JDIMENSION start_col,
+		 JDIMENSION num_blocks));
+
+struct jpeg_forward_dct {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+  /* It is useful to allow each component to have a separate FDCT method. */
+  forward_DCT_ptr forward_DCT[MAX_COMPONENTS];
+};
+
+/* Entropy encoding */
+struct jpeg_entropy_encoder {
+  JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
+  JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
+  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+};
+
+/* Marker writing */
+struct jpeg_marker_writer {
+  JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
+  JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
+  JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
+  JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
+  JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
+  /* These routines are exported to allow insertion of extra markers */
+  /* Probably only COM and APPn markers should be written this way */
+  JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
+				      unsigned int datalen));
+  JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
+};
+
+
+/* Declarations for decompression modules */
+
+/* Master control module */
+struct jpeg_decomp_master {
+  JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
+  JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
+
+  /* State variables made visible to other modules */
+  boolean is_dummy_pass;	/* True during 1st pass for 2-pass quant */
+};
+
+/* Input control module */
+struct jpeg_input_controller {
+  JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
+  JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
+  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+  JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
+
+  /* State variables made visible to other modules */
+  boolean has_multiple_scans;	/* True if file has multiple scans */
+  boolean eoi_reached;		/* True when EOI has been consumed */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_d_main_controller {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+  JMETHOD(void, process_data, (j_decompress_ptr cinfo,
+			       JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+			       JDIMENSION out_rows_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_d_coef_controller {
+  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+  JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+  JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+  JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+				 JSAMPIMAGE output_buf));
+  /* Pointer to array of coefficient virtual arrays, or NULL if none */
+  jvirt_barray_ptr *coef_arrays;
+};
+
+/* Decompression postprocessing (color quantization buffer control) */
+struct jpeg_d_post_controller {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+  JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
+				    JSAMPIMAGE input_buf,
+				    JDIMENSION *in_row_group_ctr,
+				    JDIMENSION in_row_groups_avail,
+				    JSAMPARRAY output_buf,
+				    JDIMENSION *out_row_ctr,
+				    JDIMENSION out_rows_avail));
+};
+
+/* Marker reading & parsing */
+struct jpeg_marker_reader {
+  JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
+  /* Read markers until SOS or EOI.
+   * Returns same codes as are defined for jpeg_consume_input:
+   * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+   */
+  JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
+  /* Read a restart marker --- exported for use by entropy decoder only */
+  jpeg_marker_parser_method read_restart_marker;
+
+  /* State of marker reader --- nominally internal, but applications
+   * supplying COM or APPn handlers might like to know the state.
+   */
+  boolean saw_SOI;		/* found SOI? */
+  boolean saw_SOF;		/* found SOF? */
+  int next_restart_num;		/* next restart number expected (0-7) */
+  unsigned int discarded_bytes;	/* # of bytes skipped looking for a marker */
+};
+
+/* Entropy decoding */
+struct jpeg_entropy_decoder {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+  JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
+				JBLOCKROW *MCU_data));
+};
+
+/* Inverse DCT (also performs dequantization) */
+typedef JMETHOD(void, inverse_DCT_method_ptr,
+		(j_decompress_ptr cinfo, jpeg_component_info * compptr,
+		 JCOEFPTR coef_block,
+		 JSAMPARRAY output_buf, JDIMENSION output_col));
+
+struct jpeg_inverse_dct {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+  /* It is useful to allow each component to have a separate IDCT method. */
+  inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
+};
+
+/* Upsampling (note that upsampler must also call color converter) */
+struct jpeg_upsampler {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+  JMETHOD(void, upsample, (j_decompress_ptr cinfo,
+			   JSAMPIMAGE input_buf,
+			   JDIMENSION *in_row_group_ctr,
+			   JDIMENSION in_row_groups_avail,
+			   JSAMPARRAY output_buf,
+			   JDIMENSION *out_row_ctr,
+			   JDIMENSION out_rows_avail));
+
+  boolean need_context_rows;	/* TRUE if need rows above & below */
+};
+
+/* Colorspace conversion */
+struct jpeg_color_deconverter {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+  JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
+				JSAMPIMAGE input_buf, JDIMENSION input_row,
+				JSAMPARRAY output_buf, int num_rows));
+};
+
+/* Color quantization or color precision reduction */
+struct jpeg_color_quantizer {
+  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
+  JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
+				 JSAMPARRAY input_buf, JSAMPARRAY output_buf,
+				 int num_rows));
+  JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
+  JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
+};
+
+
+/* Miscellaneous useful macros */
+
+#undef MAX
+#define MAX(a,b)	((a) > (b) ? (a) : (b))
+#undef MIN
+#define MIN(a,b)	((a) < (b) ? (a) : (b))
+
+
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity.  This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit.  But some
+ * C compilers implement >> with an unsigned shift.  For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts.  SHIFT_TEMPS must be
+ * included in the variables of any routine using RIGHT_SHIFT.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define SHIFT_TEMPS	INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft)  \
+	((shift_temp = (x)) < 0 ? \
+	 (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
+	 (shift_temp >> (shft)))
+#else
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_compress_master	jICompress
+#define jinit_c_master_control	jICMaster
+#define jinit_c_main_controller	jICMainC
+#define jinit_c_prep_controller	jICPrepC
+#define jinit_c_coef_controller	jICCoefC
+#define jinit_color_converter	jICColor
+#define jinit_downsampler	jIDownsampler
+#define jinit_forward_dct	jIFDCT
+#define jinit_huff_encoder	jIHEncoder
+#define jinit_arith_encoder	jIAEncoder
+#define jinit_marker_writer	jIMWriter
+#define jinit_master_decompress	jIDMaster
+#define jinit_d_main_controller	jIDMainC
+#define jinit_d_coef_controller	jIDCoefC
+#define jinit_d_post_controller	jIDPostC
+#define jinit_input_controller	jIInCtlr
+#define jinit_marker_reader	jIMReader
+#define jinit_huff_decoder	jIHDecoder
+#define jinit_arith_decoder	jIADecoder
+#define jinit_inverse_dct	jIIDCT
+#define jinit_upsampler		jIUpsampler
+#define jinit_color_deconverter	jIDColor
+#define jinit_1pass_quantizer	jI1Quant
+#define jinit_2pass_quantizer	jI2Quant
+#define jinit_merged_upsampler	jIMUpsampler
+#define jinit_memory_mgr	jIMemMgr
+#define jdiv_round_up		jDivRound
+#define jround_up		jRound
+#define jzero_far		jZeroFar
+#define jcopy_sample_rows	jCopySamples
+#define jcopy_block_row		jCopyBlocks
+#define jpeg_zigzag_order	jZIGTable
+#define jpeg_natural_order	jZAGTable
+#define jpeg_natural_order7	jZAG7Table
+#define jpeg_natural_order6	jZAG6Table
+#define jpeg_natural_order5	jZAG5Table
+#define jpeg_natural_order4	jZAG4Table
+#define jpeg_natural_order3	jZAG3Table
+#define jpeg_natural_order2	jZAG2Table
+#define jpeg_aritab		jAriTab
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
+ * and coefficient-block arrays.  This won't work on 80x86 because the arrays
+ * are FAR and we're assuming a small-pointer memory model.  However, some
+ * DOS compilers provide far-pointer versions of memcpy() and memset() even
+ * in the small-model libraries.  These will be used if USE_FMEM is defined.
+ * Otherwise, the routines in jutils.c do it the hard way.
+ */
+
+#ifndef NEED_FAR_POINTERS	/* normal case, same as regular macro */
+#define FMEMZERO(target,size)	MEMZERO(target,size)
+#else				/* 80x86 case */
+#ifdef USE_FMEM
+#define FMEMZERO(target,size)	_fmemset((void FAR *)(target), 0, (size_t)(size))
+#else
+EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
+#define FMEMZERO(target,size)	jzero_far(target, size)
+#endif
+#endif
+
+
+/* Compression module initialization routines */
+EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
+					 boolean transcode_only));
+EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_arith_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+					  boolean need_full_buffer));
+EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_arith_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
+/* Memory manager initialization */
+EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
+
+/* Utility routines in jutils.c */
+EXTERN(long) jdiv_round_up JPP((long a, long b));
+EXTERN(long) jround_up JPP((long a, long b));
+EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
+				    JSAMPARRAY output_array, int dest_row,
+				    int num_rows, JDIMENSION num_cols));
+EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
+				  JDIMENSION num_blocks));
+/* Constant tables in jutils.c */
+#if 0				/* This table is not actually needed in v6a */
+extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
+#endif
+extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
+extern const int jpeg_natural_order7[]; /* zz to natural order for 7x7 block */
+extern const int jpeg_natural_order6[]; /* zz to natural order for 6x6 block */
+extern const int jpeg_natural_order5[]; /* zz to natural order for 5x5 block */
+extern const int jpeg_natural_order4[]; /* zz to natural order for 4x4 block */
+extern const int jpeg_natural_order3[]; /* zz to natural order for 3x3 block */
+extern const int jpeg_natural_order2[]; /* zz to natural order for 2x2 block */
+
+/* Arithmetic coding probability estimation tables in jaricom.c */
+extern const INT32 jpeg_aritab[];
+
+/* Suppress undefined-structure complaints if necessary. */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef AM_MEMORY_MANAGER	/* only jmemmgr.c defines these */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+#endif
+#endif /* INCOMPLETE_TYPES_BROKEN */

+ 1173 - 0
engine/compilers/android/jni/include/libjpeg/jpeglib.h

@@ -0,0 +1,1173 @@
+/*
+ * jpeglib.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modified 2002-2012 by Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the application interface for the JPEG library.
+ * Most applications using the library need only include this file,
+ * and perhaps jerror.h if they want to know the exact error codes.
+ */
+
+#ifndef JPEGLIB_H
+#define JPEGLIB_H
+
+/*
+ * First we include the configuration files that record how this
+ * installation of the JPEG library is set up.  jconfig.h can be
+ * generated automatically for many systems.  jmorecfg.h contains
+ * manual configuration options that most people need not worry about.
+ */
+
+#ifndef JCONFIG_INCLUDED	/* in case jinclude.h already did */
+#include "jconfig.h"		/* widely used configuration options */
+#endif
+#include "jmorecfg.h"		/* seldom changed options */
+
+
+#ifdef __cplusplus
+#ifndef DONT_USE_EXTERN_C
+extern "C" {
+#endif
+#endif
+
+/* Version IDs for the JPEG library.
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 90".
+ */
+
+#define JPEG_LIB_VERSION        90	/* Compatibility version 9.0 */
+#define JPEG_LIB_VERSION_MAJOR  9
+#define JPEG_LIB_VERSION_MINOR  0
+
+
+/* Various constants determining the sizes of things.
+ * All of these are specified by the JPEG standard, so don't change them
+ * if you want to be compatible.
+ */
+
+#define DCTSIZE		    8	/* The basic DCT block is 8x8 coefficients */
+#define DCTSIZE2	    64	/* DCTSIZE squared; # of elements in a block */
+#define NUM_QUANT_TBLS      4	/* Quantization tables are numbered 0..3 */
+#define NUM_HUFF_TBLS       4	/* Huffman tables are numbered 0..3 */
+#define NUM_ARITH_TBLS      16	/* Arith-coding tables are numbered 0..15 */
+#define MAX_COMPS_IN_SCAN   4	/* JPEG limit on # of components in one scan */
+#define MAX_SAMP_FACTOR     4	/* JPEG limit on sampling factors */
+/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+ * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
+ * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
+ * to handle it.  We even let you do this from the jconfig.h file.  However,
+ * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+#define C_MAX_BLOCKS_IN_MCU   10 /* compressor's limit on blocks per MCU */
+#ifndef D_MAX_BLOCKS_IN_MCU
+#define D_MAX_BLOCKS_IN_MCU   10 /* decompressor's limit on blocks per MCU */
+#endif
+
+
+/* Data structures for images (arrays of samples and of DCT coefficients).
+ * On 80x86 machines, the image arrays are too big for near pointers,
+ * but the pointer arrays can fit in near memory.
+ */
+
+typedef JSAMPLE FAR *JSAMPROW;	/* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY;	/* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE;	/* a 3-D sample array: top index is color */
+
+typedef JCOEF JBLOCK[DCTSIZE2];	/* one block of coefficients */
+typedef JBLOCK FAR *JBLOCKROW;	/* pointer to one row of coefficient blocks */
+typedef JBLOCKROW *JBLOCKARRAY;		/* a 2-D array of coefficient blocks */
+typedef JBLOCKARRAY *JBLOCKIMAGE;	/* a 3-D array of coefficient blocks */
+
+typedef JCOEF FAR *JCOEFPTR;	/* useful in a couple of places */
+
+
+/* Types for JPEG compression parameters and working tables. */
+
+
+/* DCT coefficient quantization tables. */
+
+typedef struct {
+  /* This array gives the coefficient quantizers in natural array order
+   * (not the zigzag order in which they are stored in a JPEG DQT marker).
+   * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
+   */
+  UINT16 quantval[DCTSIZE2];	/* quantization step for each coefficient */
+  /* This field is used only during compression.  It's initialized FALSE when
+   * the table is created, and set TRUE when it's been output to the file.
+   * You could suppress output of a table by setting this to TRUE.
+   * (See jpeg_suppress_tables for an example.)
+   */
+  boolean sent_table;		/* TRUE when table has been output */
+} JQUANT_TBL;
+
+
+/* Huffman coding tables. */
+
+typedef struct {
+  /* These two fields directly represent the contents of a JPEG DHT marker */
+  UINT8 bits[17];		/* bits[k] = # of symbols with codes of */
+				/* length k bits; bits[0] is unused */
+  UINT8 huffval[256];		/* The symbols, in order of incr code length */
+  /* This field is used only during compression.  It's initialized FALSE when
+   * the table is created, and set TRUE when it's been output to the file.
+   * You could suppress output of a table by setting this to TRUE.
+   * (See jpeg_suppress_tables for an example.)
+   */
+  boolean sent_table;		/* TRUE when table has been output */
+} JHUFF_TBL;
+
+
+/* Basic info about one component (color channel). */
+
+typedef struct {
+  /* These values are fixed over the whole image. */
+  /* For compression, they must be supplied by parameter setup; */
+  /* for decompression, they are read from the SOF marker. */
+  int component_id;		/* identifier for this component (0..255) */
+  int component_index;		/* its index in SOF or cinfo->comp_info[] */
+  int h_samp_factor;		/* horizontal sampling factor (1..4) */
+  int v_samp_factor;		/* vertical sampling factor (1..4) */
+  int quant_tbl_no;		/* quantization table selector (0..3) */
+  /* These values may vary between scans. */
+  /* For compression, they must be supplied by parameter setup; */
+  /* for decompression, they are read from the SOS marker. */
+  /* The decompressor output side may not use these variables. */
+  int dc_tbl_no;		/* DC entropy table selector (0..3) */
+  int ac_tbl_no;		/* AC entropy table selector (0..3) */
+  
+  /* Remaining fields should be treated as private by applications. */
+  
+  /* These values are computed during compression or decompression startup: */
+  /* Component's size in DCT blocks.
+   * Any dummy blocks added to complete an MCU are not counted; therefore
+   * these values do not depend on whether a scan is interleaved or not.
+   */
+  JDIMENSION width_in_blocks;
+  JDIMENSION height_in_blocks;
+  /* Size of a DCT block in samples,
+   * reflecting any scaling we choose to apply during the DCT step.
+   * Values from 1 to 16 are supported.
+   * Note that different components may receive different DCT scalings.
+   */
+  int DCT_h_scaled_size;
+  int DCT_v_scaled_size;
+  /* The downsampled dimensions are the component's actual, unpadded number
+   * of samples at the main buffer (preprocessing/compression interface);
+   * DCT scaling is included, so
+   * downsampled_width = ceil(image_width * Hi/Hmax * DCT_h_scaled_size/DCTSIZE)
+   * and similarly for height.
+   */
+  JDIMENSION downsampled_width;	 /* actual width in samples */
+  JDIMENSION downsampled_height; /* actual height in samples */
+  /* This flag is used only for decompression.  In cases where some of the
+   * components will be ignored (eg grayscale output from YCbCr image),
+   * we can skip most computations for the unused components.
+   */
+  boolean component_needed;	/* do we need the value of this component? */
+
+  /* These values are computed before starting a scan of the component. */
+  /* The decompressor output side may not use these variables. */
+  int MCU_width;		/* number of blocks per MCU, horizontally */
+  int MCU_height;		/* number of blocks per MCU, vertically */
+  int MCU_blocks;		/* MCU_width * MCU_height */
+  int MCU_sample_width;	/* MCU width in samples: MCU_width * DCT_h_scaled_size */
+  int last_col_width;		/* # of non-dummy blocks across in last MCU */
+  int last_row_height;		/* # of non-dummy blocks down in last MCU */
+
+  /* Saved quantization table for component; NULL if none yet saved.
+   * See jdinput.c comments about the need for this information.
+   * This field is currently used only for decompression.
+   */
+  JQUANT_TBL * quant_table;
+
+  /* Private per-component storage for DCT or IDCT subsystem. */
+  void * dct_table;
+} jpeg_component_info;
+
+
+/* The script for encoding a multiple-scan file is an array of these: */
+
+typedef struct {
+  int comps_in_scan;		/* number of components encoded in this scan */
+  int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+  int Ss, Se;			/* progressive JPEG spectral selection parms */
+  int Ah, Al;			/* progressive JPEG successive approx. parms */
+} jpeg_scan_info;
+
+/* The decompressor can save APPn and COM markers in a list of these: */
+
+typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
+
+struct jpeg_marker_struct {
+  jpeg_saved_marker_ptr next;	/* next in list, or NULL */
+  UINT8 marker;			/* marker code: JPEG_COM, or JPEG_APP0+n */
+  unsigned int original_length;	/* # bytes of data in the file */
+  unsigned int data_length;	/* # bytes of data saved at data[] */
+  JOCTET FAR * data;		/* the data contained in the marker */
+  /* the marker length word is not counted in data_length or original_length */
+};
+
+/* Known color spaces. */
+
+typedef enum {
+	JCS_UNKNOWN,		/* error/unspecified */
+	JCS_GRAYSCALE,		/* monochrome */
+	JCS_RGB,		/* red/green/blue */
+	JCS_YCbCr,		/* Y/Cb/Cr (also known as YUV) */
+	JCS_CMYK,		/* C/M/Y/K */
+	JCS_YCCK		/* Y/Cb/Cr/K */
+} J_COLOR_SPACE;
+
+/* Supported color transforms. */
+
+typedef enum {
+	JCT_NONE           = 0,
+	JCT_SUBTRACT_GREEN = 1
+} J_COLOR_TRANSFORM;
+
+/* DCT/IDCT algorithm options. */
+
+typedef enum {
+	JDCT_ISLOW,		/* slow but accurate integer algorithm */
+	JDCT_IFAST,		/* faster, less accurate integer method */
+	JDCT_FLOAT		/* floating-point: accurate, fast on fast HW */
+} J_DCT_METHOD;
+
+#ifndef JDCT_DEFAULT		/* may be overridden in jconfig.h */
+#define JDCT_DEFAULT  JDCT_ISLOW
+#endif
+#ifndef JDCT_FASTEST		/* may be overridden in jconfig.h */
+#define JDCT_FASTEST  JDCT_IFAST
+#endif
+
+/* Dithering options for decompression. */
+
+typedef enum {
+	JDITHER_NONE,		/* no dithering */
+	JDITHER_ORDERED,	/* simple ordered dither */
+	JDITHER_FS		/* Floyd-Steinberg error diffusion dither */
+} J_DITHER_MODE;
+
+
+/* Common fields between JPEG compression and decompression master structs. */
+
+#define jpeg_common_fields \
+  struct jpeg_error_mgr * err;	/* Error handler module */\
+  struct jpeg_memory_mgr * mem;	/* Memory manager module */\
+  struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
+  void * client_data;		/* Available for use by application */\
+  boolean is_decompressor;	/* So common code can tell which is which */\
+  int global_state		/* For checking call sequence validity */
+
+/* Routines that are to be used by both halves of the library are declared
+ * to receive a pointer to this structure.  There are no actual instances of
+ * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
+ */
+struct jpeg_common_struct {
+  jpeg_common_fields;		/* Fields common to both master struct types */
+  /* Additional fields follow in an actual jpeg_compress_struct or
+   * jpeg_decompress_struct.  All three structs must agree on these
+   * initial fields!  (This would be a lot cleaner in C++.)
+   */
+};
+
+typedef struct jpeg_common_struct * j_common_ptr;
+typedef struct jpeg_compress_struct * j_compress_ptr;
+typedef struct jpeg_decompress_struct * j_decompress_ptr;
+
+
+/* Master record for a compression instance */
+
+struct jpeg_compress_struct {
+  jpeg_common_fields;		/* Fields shared with jpeg_decompress_struct */
+
+  /* Destination for compressed data */
+  struct jpeg_destination_mgr * dest;
+
+  /* Description of source image --- these fields must be filled in by
+   * outer application before starting compression.  in_color_space must
+   * be correct before you can even call jpeg_set_defaults().
+   */
+
+  JDIMENSION image_width;	/* input image width */
+  JDIMENSION image_height;	/* input image height */
+  int input_components;		/* # of color components in input image */
+  J_COLOR_SPACE in_color_space;	/* colorspace of input image */
+
+  double input_gamma;		/* image gamma of input image */
+
+  /* Compression parameters --- these fields must be set before calling
+   * jpeg_start_compress().  We recommend calling jpeg_set_defaults() to
+   * initialize everything to reasonable defaults, then changing anything
+   * the application specifically wants to change.  That way you won't get
+   * burnt when new parameters are added.  Also note that there are several
+   * helper routines to simplify changing parameters.
+   */
+
+  unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+  JDIMENSION jpeg_width;	/* scaled JPEG image width */
+  JDIMENSION jpeg_height;	/* scaled JPEG image height */
+  /* Dimensions of actual JPEG image that will be written to file,
+   * derived from input dimensions by scaling factors above.
+   * These fields are computed by jpeg_start_compress().
+   * You can also use jpeg_calc_jpeg_dimensions() to determine these values
+   * in advance of calling jpeg_start_compress().
+   */
+
+  int data_precision;		/* bits of precision in image data */
+
+  int num_components;		/* # of color components in JPEG image */
+  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+  jpeg_component_info * comp_info;
+  /* comp_info[i] describes component that appears i'th in SOF */
+
+  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+  int q_scale_factor[NUM_QUANT_TBLS];
+  /* ptrs to coefficient quantization tables, or NULL if not defined,
+   * and corresponding scale factors (percentage, initialized 100).
+   */
+
+  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  /* ptrs to Huffman coding tables, or NULL if not defined */
+
+  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+  int num_scans;		/* # of entries in scan_info array */
+  const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
+  /* The default value of scan_info is NULL, which causes a single-scan
+   * sequential JPEG file to be emitted.  To create a multi-scan file,
+   * set num_scans and scan_info to point to an array of scan definitions.
+   */
+
+  boolean raw_data_in;		/* TRUE=caller supplies downsampled data */
+  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
+  boolean optimize_coding;	/* TRUE=optimize entropy encoding parms */
+  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
+  boolean do_fancy_downsampling; /* TRUE=apply fancy downsampling */
+  int smoothing_factor;		/* 1..100, or 0 for no input smoothing */
+  J_DCT_METHOD dct_method;	/* DCT algorithm selector */
+
+  /* The restart interval can be specified in absolute MCUs by setting
+   * restart_interval, or in MCU rows by setting restart_in_rows
+   * (in which case the correct restart_interval will be figured
+   * for each scan).
+   */
+  unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
+  int restart_in_rows;		/* if > 0, MCU rows per restart interval */
+
+  /* Parameters controlling emission of special markers. */
+
+  boolean write_JFIF_header;	/* should a JFIF marker be written? */
+  UINT8 JFIF_major_version;	/* What to write for the JFIF version number */
+  UINT8 JFIF_minor_version;
+  /* These three values are not used by the JPEG code, merely copied */
+  /* into the JFIF APP0 marker.  density_unit can be 0 for unknown, */
+  /* 1 for dots/inch, or 2 for dots/cm.  Note that the pixel aspect */
+  /* ratio is defined by X_density/Y_density even when density_unit=0. */
+  UINT8 density_unit;		/* JFIF code for pixel size units */
+  UINT16 X_density;		/* Horizontal pixel density */
+  UINT16 Y_density;		/* Vertical pixel density */
+  boolean write_Adobe_marker;	/* should an Adobe marker be written? */
+
+  J_COLOR_TRANSFORM color_transform;
+  /* Color transform identifier, writes LSE marker if nonzero */
+
+  /* State variable: index of next scanline to be written to
+   * jpeg_write_scanlines().  Application may use this to control its
+   * processing loop, e.g., "while (next_scanline < image_height)".
+   */
+
+  JDIMENSION next_scanline;	/* 0 .. image_height-1  */
+
+  /* Remaining fields are known throughout compressor, but generally
+   * should not be touched by a surrounding application.
+   */
+
+  /*
+   * These fields are computed during compression startup
+   */
+  boolean progressive_mode;	/* TRUE if scan script uses progressive mode */
+  int max_h_samp_factor;	/* largest h_samp_factor */
+  int max_v_samp_factor;	/* largest v_samp_factor */
+
+  int min_DCT_h_scaled_size;	/* smallest DCT_h_scaled_size of any component */
+  int min_DCT_v_scaled_size;	/* smallest DCT_v_scaled_size of any component */
+
+  JDIMENSION total_iMCU_rows;	/* # of iMCU rows to be input to coef ctlr */
+  /* The coefficient controller receives data in units of MCU rows as defined
+   * for fully interleaved scans (whether the JPEG file is interleaved or not).
+   * There are v_samp_factor * DCTSIZE sample rows of each component in an
+   * "iMCU" (interleaved MCU) row.
+   */
+  
+  /*
+   * These fields are valid during any one scan.
+   * They describe the components and MCUs actually appearing in the scan.
+   */
+  int comps_in_scan;		/* # of JPEG components in this scan */
+  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+  /* *cur_comp_info[i] describes component that appears i'th in SOS */
+  
+  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
+  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
+  
+  int blocks_in_MCU;		/* # of DCT blocks per MCU */
+  int MCU_membership[C_MAX_BLOCKS_IN_MCU];
+  /* MCU_membership[i] is index in cur_comp_info of component owning */
+  /* i'th block in an MCU */
+
+  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
+
+  int block_size;		/* the basic DCT block size: 1..16 */
+  const int * natural_order;	/* natural-order position array */
+  int lim_Se;			/* min( Se, DCTSIZE2-1 ) */
+
+  /*
+   * Links to compression subobjects (methods and private variables of modules)
+   */
+  struct jpeg_comp_master * master;
+  struct jpeg_c_main_controller * main;
+  struct jpeg_c_prep_controller * prep;
+  struct jpeg_c_coef_controller * coef;
+  struct jpeg_marker_writer * marker;
+  struct jpeg_color_converter * cconvert;
+  struct jpeg_downsampler * downsample;
+  struct jpeg_forward_dct * fdct;
+  struct jpeg_entropy_encoder * entropy;
+  jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
+  int script_space_size;
+};
+
+
+/* Master record for a decompression instance */
+
+struct jpeg_decompress_struct {
+  jpeg_common_fields;		/* Fields shared with jpeg_compress_struct */
+
+  /* Source of compressed data */
+  struct jpeg_source_mgr * src;
+
+  /* Basic description of image --- filled in by jpeg_read_header(). */
+  /* Application may inspect these values to decide how to process image. */
+
+  JDIMENSION image_width;	/* nominal image width (from SOF marker) */
+  JDIMENSION image_height;	/* nominal image height */
+  int num_components;		/* # of color components in JPEG image */
+  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+  /* Decompression processing parameters --- these fields must be set before
+   * calling jpeg_start_decompress().  Note that jpeg_read_header() initializes
+   * them to default values.
+   */
+
+  J_COLOR_SPACE out_color_space; /* colorspace for output */
+
+  unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+  double output_gamma;		/* image gamma wanted in output */
+
+  boolean buffered_image;	/* TRUE=multiple output passes */
+  boolean raw_data_out;		/* TRUE=downsampled data wanted */
+
+  J_DCT_METHOD dct_method;	/* IDCT algorithm selector */
+  boolean do_fancy_upsampling;	/* TRUE=apply fancy upsampling */
+  boolean do_block_smoothing;	/* TRUE=apply interblock smoothing */
+
+  boolean quantize_colors;	/* TRUE=colormapped output wanted */
+  /* the following are ignored if not quantize_colors: */
+  J_DITHER_MODE dither_mode;	/* type of color dithering to use */
+  boolean two_pass_quantize;	/* TRUE=use two-pass color quantization */
+  int desired_number_of_colors;	/* max # colors to use in created colormap */
+  /* these are significant only in buffered-image mode: */
+  boolean enable_1pass_quant;	/* enable future use of 1-pass quantizer */
+  boolean enable_external_quant;/* enable future use of external colormap */
+  boolean enable_2pass_quant;	/* enable future use of 2-pass quantizer */
+
+  /* Description of actual output image that will be returned to application.
+   * These fields are computed by jpeg_start_decompress().
+   * You can also use jpeg_calc_output_dimensions() to determine these values
+   * in advance of calling jpeg_start_decompress().
+   */
+
+  JDIMENSION output_width;	/* scaled image width */
+  JDIMENSION output_height;	/* scaled image height */
+  int out_color_components;	/* # of color components in out_color_space */
+  int output_components;	/* # of color components returned */
+  /* output_components is 1 (a colormap index) when quantizing colors;
+   * otherwise it equals out_color_components.
+   */
+  int rec_outbuf_height;	/* min recommended height of scanline buffer */
+  /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
+   * high, space and time will be wasted due to unnecessary data copying.
+   * Usually rec_outbuf_height will be 1 or 2, at most 4.
+   */
+
+  /* When quantizing colors, the output colormap is described by these fields.
+   * The application can supply a colormap by setting colormap non-NULL before
+   * calling jpeg_start_decompress; otherwise a colormap is created during
+   * jpeg_start_decompress or jpeg_start_output.
+   * The map has out_color_components rows and actual_number_of_colors columns.
+   */
+  int actual_number_of_colors;	/* number of entries in use */
+  JSAMPARRAY colormap;		/* The color map as a 2-D pixel array */
+
+  /* State variables: these variables indicate the progress of decompression.
+   * The application may examine these but must not modify them.
+   */
+
+  /* Row index of next scanline to be read from jpeg_read_scanlines().
+   * Application may use this to control its processing loop, e.g.,
+   * "while (output_scanline < output_height)".
+   */
+  JDIMENSION output_scanline;	/* 0 .. output_height-1  */
+
+  /* Current input scan number and number of iMCU rows completed in scan.
+   * These indicate the progress of the decompressor input side.
+   */
+  int input_scan_number;	/* Number of SOS markers seen so far */
+  JDIMENSION input_iMCU_row;	/* Number of iMCU rows completed */
+
+  /* The "output scan number" is the notional scan being displayed by the
+   * output side.  The decompressor will not allow output scan/row number
+   * to get ahead of input scan/row, but it can fall arbitrarily far behind.
+   */
+  int output_scan_number;	/* Nominal scan number being displayed */
+  JDIMENSION output_iMCU_row;	/* Number of iMCU rows read */
+
+  /* Current progression status.  coef_bits[c][i] indicates the precision
+   * with which component c's DCT coefficient i (in zigzag order) is known.
+   * It is -1 when no data has yet been received, otherwise it is the point
+   * transform (shift) value for the most recent scan of the coefficient
+   * (thus, 0 at completion of the progression).
+   * This pointer is NULL when reading a non-progressive file.
+   */
+  int (*coef_bits)[DCTSIZE2];	/* -1 or current Al value for each coef */
+
+  /* Internal JPEG parameters --- the application usually need not look at
+   * these fields.  Note that the decompressor output side may not use
+   * any parameters that can change between scans.
+   */
+
+  /* Quantization and Huffman tables are carried forward across input
+   * datastreams when processing abbreviated JPEG datastreams.
+   */
+
+  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+  /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  /* ptrs to Huffman coding tables, or NULL if not defined */
+
+  /* These parameters are never carried across datastreams, since they
+   * are given in SOF/SOS markers or defined to be reset by SOI.
+   */
+
+  int data_precision;		/* bits of precision in image data */
+
+  jpeg_component_info * comp_info;
+  /* comp_info[i] describes component that appears i'th in SOF */
+
+  boolean is_baseline;		/* TRUE if Baseline SOF0 encountered */
+  boolean progressive_mode;	/* TRUE if SOFn specifies progressive mode */
+  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
+
+  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+  unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
+
+  /* These fields record data obtained from optional markers recognized by
+   * the JPEG library.
+   */
+  boolean saw_JFIF_marker;	/* TRUE iff a JFIF APP0 marker was found */
+  /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
+  UINT8 JFIF_major_version;	/* JFIF version number */
+  UINT8 JFIF_minor_version;
+  UINT8 density_unit;		/* JFIF code for pixel size units */
+  UINT16 X_density;		/* Horizontal pixel density */
+  UINT16 Y_density;		/* Vertical pixel density */
+  boolean saw_Adobe_marker;	/* TRUE iff an Adobe APP14 marker was found */
+  UINT8 Adobe_transform;	/* Color transform code from Adobe marker */
+
+  J_COLOR_TRANSFORM color_transform;
+  /* Color transform identifier derived from LSE marker, otherwise zero */
+
+  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
+
+  /* Aside from the specific data retained from APPn markers known to the
+   * library, the uninterpreted contents of any or all APPn and COM markers
+   * can be saved in a list for examination by the application.
+   */
+  jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
+
+  /* Remaining fields are known throughout decompressor, but generally
+   * should not be touched by a surrounding application.
+   */
+
+  /*
+   * These fields are computed during decompression startup
+   */
+  int max_h_samp_factor;	/* largest h_samp_factor */
+  int max_v_samp_factor;	/* largest v_samp_factor */
+
+  int min_DCT_h_scaled_size;	/* smallest DCT_h_scaled_size of any component */
+  int min_DCT_v_scaled_size;	/* smallest DCT_v_scaled_size of any component */
+
+  JDIMENSION total_iMCU_rows;	/* # of iMCU rows in image */
+  /* The coefficient controller's input and output progress is measured in
+   * units of "iMCU" (interleaved MCU) rows.  These are the same as MCU rows
+   * in fully interleaved JPEG scans, but are used whether the scan is
+   * interleaved or not.  We define an iMCU row as v_samp_factor DCT block
+   * rows of each component.  Therefore, the IDCT output contains
+   * v_samp_factor*DCT_v_scaled_size sample rows of a component per iMCU row.
+   */
+
+  JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+
+  /*
+   * These fields are valid during any one scan.
+   * They describe the components and MCUs actually appearing in the scan.
+   * Note that the decompressor output side must not use these fields.
+   */
+  int comps_in_scan;		/* # of JPEG components in this scan */
+  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+  /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
+  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
+
+  int blocks_in_MCU;		/* # of DCT blocks per MCU */
+  int MCU_membership[D_MAX_BLOCKS_IN_MCU];
+  /* MCU_membership[i] is index in cur_comp_info of component owning */
+  /* i'th block in an MCU */
+
+  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
+
+  /* These fields are derived from Se of first SOS marker.
+   */
+  int block_size;		/* the basic DCT block size: 1..16 */
+  const int * natural_order; /* natural-order position array for entropy decode */
+  int lim_Se;			/* min( Se, DCTSIZE2-1 ) for entropy decode */
+
+  /* This field is shared between entropy decoder and marker parser.
+   * It is either zero or the code of a JPEG marker that has been
+   * read from the data source, but has not yet been processed.
+   */
+  int unread_marker;
+
+  /*
+   * Links to decompression subobjects (methods, private variables of modules)
+   */
+  struct jpeg_decomp_master * master;
+  struct jpeg_d_main_controller * main;
+  struct jpeg_d_coef_controller * coef;
+  struct jpeg_d_post_controller * post;
+  struct jpeg_input_controller * inputctl;
+  struct jpeg_marker_reader * marker;
+  struct jpeg_entropy_decoder * entropy;
+  struct jpeg_inverse_dct * idct;
+  struct jpeg_upsampler * upsample;
+  struct jpeg_color_deconverter * cconvert;
+  struct jpeg_color_quantizer * cquantize;
+};
+
+
+/* "Object" declarations for JPEG modules that may be supplied or called
+ * directly by the surrounding application.
+ * As with all objects in the JPEG library, these structs only define the
+ * publicly visible methods and state variables of a module.  Additional
+ * private fields may exist after the public ones.
+ */
+
+
+/* Error handler object */
+
+struct jpeg_error_mgr {
+  /* Error exit handler: does not return to caller */
+  JMETHOD(noreturn_t, error_exit, (j_common_ptr cinfo));
+  /* Conditionally emit a trace or warning message */
+  JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
+  /* Routine that actually outputs a trace or error message */
+  JMETHOD(void, output_message, (j_common_ptr cinfo));
+  /* Format a message string for the most recent JPEG error or message */
+  JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
+#define JMSG_LENGTH_MAX  200	/* recommended size of format_message buffer */
+  /* Reset error state variables at start of a new image */
+  JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
+  
+  /* The message ID code and any parameters are saved here.
+   * A message can have one string parameter or up to 8 int parameters.
+   */
+  int msg_code;
+#define JMSG_STR_PARM_MAX  80
+  union {
+    int i[8];
+    char s[JMSG_STR_PARM_MAX];
+  } msg_parm;
+  
+  /* Standard state variables for error facility */
+  
+  int trace_level;		/* max msg_level that will be displayed */
+  
+  /* For recoverable corrupt-data errors, we emit a warning message,
+   * but keep going unless emit_message chooses to abort.  emit_message
+   * should count warnings in num_warnings.  The surrounding application
+   * can check for bad data by seeing if num_warnings is nonzero at the
+   * end of processing.
+   */
+  long num_warnings;		/* number of corrupt-data warnings */
+
+  /* These fields point to the table(s) of error message strings.
+   * An application can change the table pointer to switch to a different
+   * message list (typically, to change the language in which errors are
+   * reported).  Some applications may wish to add additional error codes
+   * that will be handled by the JPEG library error mechanism; the second
+   * table pointer is used for this purpose.
+   *
+   * First table includes all errors generated by JPEG library itself.
+   * Error code 0 is reserved for a "no such error string" message.
+   */
+  const char * const * jpeg_message_table; /* Library errors */
+  int last_jpeg_message;    /* Table contains strings 0..last_jpeg_message */
+  /* Second table can be added by application (see cjpeg/djpeg for example).
+   * It contains strings numbered first_addon_message..last_addon_message.
+   */
+  const char * const * addon_message_table; /* Non-library errors */
+  int first_addon_message;	/* code for first string in addon table */
+  int last_addon_message;	/* code for last string in addon table */
+};
+
+
+/* Progress monitor object */
+
+struct jpeg_progress_mgr {
+  JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
+
+  long pass_counter;		/* work units completed in this pass */
+  long pass_limit;		/* total number of work units in this pass */
+  int completed_passes;		/* passes completed so far */
+  int total_passes;		/* total number of passes expected */
+};
+
+
+/* Data destination object for compression */
+
+struct jpeg_destination_mgr {
+  JOCTET * next_output_byte;	/* => next byte to write in buffer */
+  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
+
+  JMETHOD(void, init_destination, (j_compress_ptr cinfo));
+  JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
+  JMETHOD(void, term_destination, (j_compress_ptr cinfo));
+};
+
+
+/* Data source object for decompression */
+
+struct jpeg_source_mgr {
+  const JOCTET * next_input_byte; /* => next byte to read from buffer */
+  size_t bytes_in_buffer;	/* # of bytes remaining in buffer */
+
+  JMETHOD(void, init_source, (j_decompress_ptr cinfo));
+  JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
+  JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
+  JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
+  JMETHOD(void, term_source, (j_decompress_ptr cinfo));
+};
+
+
+/* Memory manager object.
+ * Allocates "small" objects (a few K total), "large" objects (tens of K),
+ * and "really big" objects (virtual arrays with backing store if needed).
+ * The memory manager does not allow individual objects to be freed; rather,
+ * each created object is assigned to a pool, and whole pools can be freed
+ * at once.  This is faster and more convenient than remembering exactly what
+ * to free, especially where malloc()/free() are not too speedy.
+ * NB: alloc routines never return NULL.  They exit to error_exit if not
+ * successful.
+ */
+
+#define JPOOL_PERMANENT	0	/* lasts until master record is destroyed */
+#define JPOOL_IMAGE	1	/* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS	2
+
+typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
+typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
+struct jpeg_memory_mgr {
+  /* Method pointers */
+  JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+				size_t sizeofobject));
+  JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
+				     size_t sizeofobject));
+  JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+				     JDIMENSION samplesperrow,
+				     JDIMENSION numrows));
+  JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+				      JDIMENSION blocksperrow,
+				      JDIMENSION numrows));
+  JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+						  int pool_id,
+						  boolean pre_zero,
+						  JDIMENSION samplesperrow,
+						  JDIMENSION numrows,
+						  JDIMENSION maxaccess));
+  JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
+						  int pool_id,
+						  boolean pre_zero,
+						  JDIMENSION blocksperrow,
+						  JDIMENSION numrows,
+						  JDIMENSION maxaccess));
+  JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
+  JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+					   jvirt_sarray_ptr ptr,
+					   JDIMENSION start_row,
+					   JDIMENSION num_rows,
+					   boolean writable));
+  JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
+					    jvirt_barray_ptr ptr,
+					    JDIMENSION start_row,
+					    JDIMENSION num_rows,
+					    boolean writable));
+  JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
+  JMETHOD(void, self_destruct, (j_common_ptr cinfo));
+
+  /* Limit on memory allocation for this JPEG object.  (Note that this is
+   * merely advisory, not a guaranteed maximum; it only affects the space
+   * used for virtual-array buffers.)  May be changed by outer application
+   * after creating the JPEG object.
+   */
+  long max_memory_to_use;
+
+  /* Maximum allocation request accepted by alloc_large. */
+  long max_alloc_chunk;
+};
+
+
+/* Routine signature for application-supplied marker processing methods.
+ * Need not pass marker code since it is stored in cinfo->unread_marker.
+ */
+typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
+
+
+/* Declarations for routines called by application.
+ * The JPP macro hides prototype parameters from compilers that can't cope.
+ * Note JPP requires double parentheses.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JPP(arglist)	arglist
+#else
+#define JPP(arglist)	()
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers.
+ * We shorten external names to be unique in the first six letters, which
+ * is good enough for all known systems.
+ * (If your compiler itself needs names to be unique in less than 15 
+ * characters, you are out of luck.  Get a better compiler.)
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_error		jStdError
+#define jpeg_CreateCompress	jCreaCompress
+#define jpeg_CreateDecompress	jCreaDecompress
+#define jpeg_destroy_compress	jDestCompress
+#define jpeg_destroy_decompress	jDestDecompress
+#define jpeg_stdio_dest		jStdDest
+#define jpeg_stdio_src		jStdSrc
+#define jpeg_mem_dest		jMemDest
+#define jpeg_mem_src		jMemSrc
+#define jpeg_set_defaults	jSetDefaults
+#define jpeg_set_colorspace	jSetColorspace
+#define jpeg_default_colorspace	jDefColorspace
+#define jpeg_set_quality	jSetQuality
+#define jpeg_set_linear_quality	jSetLQuality
+#define jpeg_default_qtables	jDefQTables
+#define jpeg_add_quant_table	jAddQuantTable
+#define jpeg_quality_scaling	jQualityScaling
+#define jpeg_simple_progression	jSimProgress
+#define jpeg_suppress_tables	jSuppressTables
+#define jpeg_alloc_quant_table	jAlcQTable
+#define jpeg_alloc_huff_table	jAlcHTable
+#define jpeg_start_compress	jStrtCompress
+#define jpeg_write_scanlines	jWrtScanlines
+#define jpeg_finish_compress	jFinCompress
+#define jpeg_calc_jpeg_dimensions	jCjpegDimensions
+#define jpeg_write_raw_data	jWrtRawData
+#define jpeg_write_marker	jWrtMarker
+#define jpeg_write_m_header	jWrtMHeader
+#define jpeg_write_m_byte	jWrtMByte
+#define jpeg_write_tables	jWrtTables
+#define jpeg_read_header	jReadHeader
+#define jpeg_start_decompress	jStrtDecompress
+#define jpeg_read_scanlines	jReadScanlines
+#define jpeg_finish_decompress	jFinDecompress
+#define jpeg_read_raw_data	jReadRawData
+#define jpeg_has_multiple_scans	jHasMultScn
+#define jpeg_start_output	jStrtOutput
+#define jpeg_finish_output	jFinOutput
+#define jpeg_input_complete	jInComplete
+#define jpeg_new_colormap	jNewCMap
+#define jpeg_consume_input	jConsumeInput
+#define jpeg_core_output_dimensions	jCoreDimensions
+#define jpeg_calc_output_dimensions	jCalcDimensions
+#define jpeg_save_markers	jSaveMarkers
+#define jpeg_set_marker_processor	jSetMarker
+#define jpeg_read_coefficients	jReadCoefs
+#define jpeg_write_coefficients	jWrtCoefs
+#define jpeg_copy_critical_parameters	jCopyCrit
+#define jpeg_abort_compress	jAbrtCompress
+#define jpeg_abort_decompress	jAbrtDecompress
+#define jpeg_abort		jAbort
+#define jpeg_destroy		jDestroy
+#define jpeg_resync_to_restart	jResyncRestart
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Default error-management setup */
+EXTERN(struct jpeg_error_mgr *) jpeg_std_error
+	JPP((struct jpeg_error_mgr * err));
+
+/* Initialization of JPEG compression objects.
+ * jpeg_create_compress() and jpeg_create_decompress() are the exported
+ * names that applications should call.  These expand to calls on
+ * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
+ * passed for version mismatch checking.
+ * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
+ */
+#define jpeg_create_compress(cinfo) \
+    jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
+			(size_t) sizeof(struct jpeg_compress_struct))
+#define jpeg_create_decompress(cinfo) \
+    jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
+			  (size_t) sizeof(struct jpeg_decompress_struct))
+EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
+				      int version, size_t structsize));
+EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
+					int version, size_t structsize));
+/* Destruction of JPEG compression objects */
+EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
+
+/* Standard data source and destination managers: stdio streams. */
+/* Caller is responsible for opening the file before and closing after. */
+EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
+EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
+
+/* Data source and destination managers: memory buffers. */
+EXTERN(void) jpeg_mem_dest JPP((j_compress_ptr cinfo,
+			       unsigned char ** outbuffer,
+			       unsigned long * outsize));
+EXTERN(void) jpeg_mem_src JPP((j_decompress_ptr cinfo,
+			      unsigned char * inbuffer,
+			      unsigned long insize));
+
+/* Default parameter setup for compression */
+EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
+/* Compression parameter setup aids */
+EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
+				      J_COLOR_SPACE colorspace));
+EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
+				   boolean force_baseline));
+EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
+					  int scale_factor,
+					  boolean force_baseline));
+EXTERN(void) jpeg_default_qtables JPP((j_compress_ptr cinfo,
+				       boolean force_baseline));
+EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
+				       const unsigned int *basic_table,
+				       int scale_factor,
+				       boolean force_baseline));
+EXTERN(int) jpeg_quality_scaling JPP((int quality));
+EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+				       boolean suppress));
+EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
+EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
+
+/* Main entry points for compression */
+EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
+				      boolean write_all_tables));
+EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+					     JSAMPARRAY scanlines,
+					     JDIMENSION num_lines));
+EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
+
+/* Precalculate JPEG dimensions for current compression parameters. */
+EXTERN(void) jpeg_calc_jpeg_dimensions JPP((j_compress_ptr cinfo));
+
+/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+					    JSAMPIMAGE data,
+					    JDIMENSION num_lines));
+
+/* Write a special marker.  See libjpeg.txt concerning safe usage. */
+EXTERN(void) jpeg_write_marker
+	JPP((j_compress_ptr cinfo, int marker,
+	     const JOCTET * dataptr, unsigned int datalen));
+/* Same, but piecemeal. */
+EXTERN(void) jpeg_write_m_header
+	JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
+EXTERN(void) jpeg_write_m_byte
+	JPP((j_compress_ptr cinfo, int val));
+
+/* Alternate compression function: just write an abbreviated table file */
+EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
+
+/* Decompression startup: read start of JPEG datastream to see what's there */
+EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
+				  boolean require_image));
+/* Return value is one of: */
+#define JPEG_SUSPENDED		0 /* Suspended due to lack of input data */
+#define JPEG_HEADER_OK		1 /* Found valid image datastream */
+#define JPEG_HEADER_TABLES_ONLY	2 /* Found valid table-specs-only datastream */
+/* If you pass require_image = TRUE (normal case), you need not check for
+ * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
+ * JPEG_SUSPENDED is only possible if you use a data source module that can
+ * give a suspension return (the stdio source module doesn't).
+ */
+
+/* Main entry points for decompression */
+EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
+EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+					    JSAMPARRAY scanlines,
+					    JDIMENSION max_lines));
+EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
+
+/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+					   JSAMPIMAGE data,
+					   JDIMENSION max_lines));
+
+/* Additional entry points for buffered-image mode. */
+EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
+				       int scan_number));
+EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
+EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
+/* Return value is one of: */
+/* #define JPEG_SUSPENDED	0    Suspended due to lack of input data */
+#define JPEG_REACHED_SOS	1 /* Reached start of new scan */
+#define JPEG_REACHED_EOI	2 /* Reached end of image */
+#define JPEG_ROW_COMPLETED	3 /* Completed one iMCU row */
+#define JPEG_SCAN_COMPLETED	4 /* Completed last iMCU row of a scan */
+
+/* Precalculate output dimensions for current decompression parameters. */
+EXTERN(void) jpeg_core_output_dimensions JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
+
+/* Control saving of COM and APPn markers into marker_list. */
+EXTERN(void) jpeg_save_markers
+	JPP((j_decompress_ptr cinfo, int marker_code,
+	     unsigned int length_limit));
+
+/* Install a special processing method for COM or APPn markers. */
+EXTERN(void) jpeg_set_marker_processor
+	JPP((j_decompress_ptr cinfo, int marker_code,
+	     jpeg_marker_parser_method routine));
+
+/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
+EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
+					  jvirt_barray_ptr * coef_arrays));
+EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
+						j_compress_ptr dstinfo));
+
+/* If you choose to abort compression or decompression before completing
+ * jpeg_finish_(de)compress, then you need to clean up to release memory,
+ * temporary files, etc.  You can just call jpeg_destroy_(de)compress
+ * if you're done with the JPEG object, but if you want to clean it up and
+ * reuse it, call this:
+ */
+EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
+
+/* Generic versions of jpeg_abort and jpeg_destroy that work on either
+ * flavor of JPEG object.  These may be more convenient in some places.
+ */
+EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
+EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
+
+/* Default restart-marker-resync procedure for use by data source modules */
+EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
+					    int desired));
+
+
+/* These marker codes are exported since applications and data source modules
+ * are likely to want to use them.
+ */
+
+#define JPEG_RST0	0xD0	/* RST0 marker code */
+#define JPEG_EOI	0xD9	/* EOI marker code */
+#define JPEG_APP0	0xE0	/* APP0 marker code */
+#define JPEG_COM	0xFE	/* COM marker code */
+
+
+/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
+ * for structure definitions that are never filled in, keep it quiet by
+ * supplying dummy definitions for the various substructures.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef JPEG_INTERNALS		/* will be defined in jpegint.h */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+struct jpeg_comp_master { long dummy; };
+struct jpeg_c_main_controller { long dummy; };
+struct jpeg_c_prep_controller { long dummy; };
+struct jpeg_c_coef_controller { long dummy; };
+struct jpeg_marker_writer { long dummy; };
+struct jpeg_color_converter { long dummy; };
+struct jpeg_downsampler { long dummy; };
+struct jpeg_forward_dct { long dummy; };
+struct jpeg_entropy_encoder { long dummy; };
+struct jpeg_decomp_master { long dummy; };
+struct jpeg_d_main_controller { long dummy; };
+struct jpeg_d_coef_controller { long dummy; };
+struct jpeg_d_post_controller { long dummy; };
+struct jpeg_input_controller { long dummy; };
+struct jpeg_marker_reader { long dummy; };
+struct jpeg_entropy_decoder { long dummy; };
+struct jpeg_inverse_dct { long dummy; };
+struct jpeg_upsampler { long dummy; };
+struct jpeg_color_deconverter { long dummy; };
+struct jpeg_color_quantizer { long dummy; };
+#endif /* JPEG_INTERNALS */
+#endif /* INCOMPLETE_TYPES_BROKEN */
+
+
+/*
+ * The JPEG library modules define JPEG_INTERNALS before including this file.
+ * The internal structure declarations are read only when that is true.
+ * Applications using the library should not include jpegint.h, but may wish
+ * to include jerror.h.
+ */
+
+#ifdef JPEG_INTERNALS
+#include "jpegint.h"		/* fetch private declarations */
+#include "jerror.h"		/* fetch error codes too */
+#endif
+
+#ifdef __cplusplus
+#ifndef DONT_USE_EXTERN_C
+}
+#endif
+#endif
+
+#endif /* JPEGLIB_H */

+ 14 - 0
engine/compilers/android/jni/include/libjpeg/jversion.h

@@ -0,0 +1,14 @@
+/*
+ * jversion.h
+ *
+ * Copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains software version identification.
+ */
+
+
+#define JVERSION	"9  13-Jan-2013"
+
+#define JCOPYRIGHT	"Copyright (C) 2013, Thomas G. Lane, Guido Vollbeding"

+ 213 - 0
engine/compilers/android/jni/include/libjpeg/transupp.h

@@ -0,0 +1,213 @@
+/*
+ * transupp.h
+ *
+ * Copyright (C) 1997-2011, Thomas G. Lane, Guido Vollbeding.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for image transformation routines and
+ * other utility code used by the jpegtran sample application.  These are
+ * NOT part of the core JPEG library.  But we keep these routines separate
+ * from jpegtran.c to ease the task of maintaining jpegtran-like programs
+ * that have other user interfaces.
+ *
+ * NOTE: all the routines declared here have very specific requirements
+ * about when they are to be executed during the reading and writing of the
+ * source and destination files.  See the comments in transupp.c, or see
+ * jpegtran.c for an example of correct usage.
+ */
+
+/* If you happen not to want the image transform support, disable it here */
+#ifndef TRANSFORMS_SUPPORTED
+#define TRANSFORMS_SUPPORTED 1		/* 0 disables transform code */
+#endif
+
+/*
+ * Although rotating and flipping data expressed as DCT coefficients is not
+ * hard, there is an asymmetry in the JPEG format specification for images
+ * whose dimensions aren't multiples of the iMCU size.  The right and bottom
+ * image edges are padded out to the next iMCU boundary with junk data; but
+ * no padding is possible at the top and left edges.  If we were to flip
+ * the whole image including the pad data, then pad garbage would become
+ * visible at the top and/or left, and real pixels would disappear into the
+ * pad margins --- perhaps permanently, since encoders & decoders may not
+ * bother to preserve DCT blocks that appear to be completely outside the
+ * nominal image area.  So, we have to exclude any partial iMCUs from the
+ * basic transformation.
+ *
+ * Transpose is the only transformation that can handle partial iMCUs at the
+ * right and bottom edges completely cleanly.  flip_h can flip partial iMCUs
+ * at the bottom, but leaves any partial iMCUs at the right edge untouched.
+ * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
+ * The other transforms are defined as combinations of these basic transforms
+ * and process edge blocks in a way that preserves the equivalence.
+ *
+ * The "trim" option causes untransformable partial iMCUs to be dropped;
+ * this is not strictly lossless, but it usually gives the best-looking
+ * result for odd-size images.  Note that when this option is active,
+ * the expected mathematical equivalences between the transforms may not hold.
+ * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
+ * followed by -rot 180 -trim trims both edges.)
+ *
+ * We also offer a lossless-crop option, which discards data outside a given
+ * image region but losslessly preserves what is inside.  Like the rotate and
+ * flip transforms, lossless crop is restricted by the JPEG format: the upper
+ * left corner of the selected region must fall on an iMCU boundary.  If this
+ * does not hold for the given crop parameters, we silently move the upper left
+ * corner up and/or left to make it so, simultaneously increasing the region
+ * dimensions to keep the lower right crop corner unchanged.  (Thus, the
+ * output image covers at least the requested region, but may cover more.)
+ * The adjustment of the region dimensions may be optionally disabled.
+ *
+ * We also provide a lossless-resize option, which is kind of a lossless-crop
+ * operation in the DCT coefficient block domain - it discards higher-order
+ * coefficients and losslessly preserves lower-order coefficients of a
+ * sub-block.
+ *
+ * Rotate/flip transform, resize, and crop can be requested together in a
+ * single invocation.  The crop is applied last --- that is, the crop region
+ * is specified in terms of the destination image after transform/resize.
+ *
+ * We also offer a "force to grayscale" option, which simply discards the
+ * chrominance channels of a YCbCr image.  This is lossless in the sense that
+ * the luminance channel is preserved exactly.  It's not the same kind of
+ * thing as the rotate/flip transformations, but it's convenient to handle it
+ * as part of this package, mainly because the transformation routines have to
+ * be aware of the option to know how many components to work on.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jtransform_parse_crop_spec	jTrParCrop
+#define jtransform_request_workspace	jTrRequest
+#define jtransform_adjust_parameters	jTrAdjust
+#define jtransform_execute_transform	jTrExec
+#define jtransform_perfect_transform	jTrPerfect
+#define jcopy_markers_setup		jCMrkSetup
+#define jcopy_markers_execute		jCMrkExec
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * Codes for supported types of image transformations.
+ */
+
+typedef enum {
+	JXFORM_NONE,		/* no transformation */
+	JXFORM_FLIP_H,		/* horizontal flip */
+	JXFORM_FLIP_V,		/* vertical flip */
+	JXFORM_TRANSPOSE,	/* transpose across UL-to-LR axis */
+	JXFORM_TRANSVERSE,	/* transpose across UR-to-LL axis */
+	JXFORM_ROT_90,		/* 90-degree clockwise rotation */
+	JXFORM_ROT_180,		/* 180-degree rotation */
+	JXFORM_ROT_270		/* 270-degree clockwise (or 90 ccw) */
+} JXFORM_CODE;
+
+/*
+ * Codes for crop parameters, which can individually be unspecified,
+ * positive or negative for xoffset or yoffset,
+ * positive or forced for width or height.
+ */
+
+typedef enum {
+        JCROP_UNSET,
+        JCROP_POS,
+        JCROP_NEG,
+        JCROP_FORCE
+} JCROP_CODE;
+
+/*
+ * Transform parameters struct.
+ * NB: application must not change any elements of this struct after
+ * calling jtransform_request_workspace.
+ */
+
+typedef struct {
+  /* Options: set by caller */
+  JXFORM_CODE transform;	/* image transform operator */
+  boolean perfect;		/* if TRUE, fail if partial MCUs are requested */
+  boolean trim;			/* if TRUE, trim partial MCUs as needed */
+  boolean force_grayscale;	/* if TRUE, convert color image to grayscale */
+  boolean crop;			/* if TRUE, crop source image */
+
+  /* Crop parameters: application need not set these unless crop is TRUE.
+   * These can be filled in by jtransform_parse_crop_spec().
+   */
+  JDIMENSION crop_width;	/* Width of selected region */
+  JCROP_CODE crop_width_set;	/* (forced disables adjustment) */
+  JDIMENSION crop_height;	/* Height of selected region */
+  JCROP_CODE crop_height_set;	/* (forced disables adjustment) */
+  JDIMENSION crop_xoffset;	/* X offset of selected region */
+  JCROP_CODE crop_xoffset_set;	/* (negative measures from right edge) */
+  JDIMENSION crop_yoffset;	/* Y offset of selected region */
+  JCROP_CODE crop_yoffset_set;	/* (negative measures from bottom edge) */
+
+  /* Internal workspace: caller should not touch these */
+  int num_components;		/* # of components in workspace */
+  jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
+  JDIMENSION output_width;	/* cropped destination dimensions */
+  JDIMENSION output_height;
+  JDIMENSION x_crop_offset;	/* destination crop offsets measured in iMCUs */
+  JDIMENSION y_crop_offset;
+  int iMCU_sample_width;	/* destination iMCU size */
+  int iMCU_sample_height;
+} jpeg_transform_info;
+
+
+#if TRANSFORMS_SUPPORTED
+
+/* Parse a crop specification (written in X11 geometry style) */
+EXTERN(boolean) jtransform_parse_crop_spec
+	JPP((jpeg_transform_info *info, const char *spec));
+/* Request any required workspace */
+EXTERN(boolean) jtransform_request_workspace
+	JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
+/* Adjust output image parameters */
+EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
+	JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+	     jvirt_barray_ptr *src_coef_arrays,
+	     jpeg_transform_info *info));
+/* Execute the actual transformation, if any */
+EXTERN(void) jtransform_execute_transform
+	JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+	     jvirt_barray_ptr *src_coef_arrays,
+	     jpeg_transform_info *info));
+/* Determine whether lossless transformation is perfectly
+ * possible for a specified image and transformation.
+ */
+EXTERN(boolean) jtransform_perfect_transform
+	JPP((JDIMENSION image_width, JDIMENSION image_height,
+	     int MCU_width, int MCU_height,
+	     JXFORM_CODE transform));
+
+/* jtransform_execute_transform used to be called
+ * jtransform_execute_transformation, but some compilers complain about
+ * routine names that long.  This macro is here to avoid breaking any
+ * old source code that uses the original name...
+ */
+#define jtransform_execute_transformation	jtransform_execute_transform
+
+#endif /* TRANSFORMS_SUPPORTED */
+
+
+/*
+ * Support for copying optional markers from source to destination file.
+ */
+
+typedef enum {
+	JCOPYOPT_NONE,		/* copy no optional markers */
+	JCOPYOPT_COMMENTS,	/* copy only comment (COM) markers */
+	JCOPYOPT_ALL		/* copy all optional markers */
+} JCOPY_OPTION;
+
+#define JCOPYOPT_DEFAULT  JCOPYOPT_COMMENTS	/* recommended default */
+
+/* Setup decompression object to save desired markers in memory */
+EXTERN(void) jcopy_markers_setup
+	JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
+/* Copy markers saved in the given source object to the destination object */
+EXTERN(void) jcopy_markers_execute
+	JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+	     JCOPY_OPTION option));

+ 110 - 0
engine/compilers/android/jni/include/libpng/config.h

@@ -0,0 +1,110 @@
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the `feenableexcept' function. */
+/* #undef HAVE_FEENABLEEXCEPT */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `m' library (-lm). */
+#define HAVE_LIBM 1
+
+/* Define to 1 if you have the `z' library (-lz). */
+#define HAVE_LIBZ 1
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#define HAVE_MALLOC_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `memset' function. */
+#define HAVE_MEMSET 1
+
+/* Define to 1 if you have the `pow' function. */
+/* #undef HAVE_POW */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+   */
+#define LT_OBJDIR ".libs/"
+
+/* Name of package */
+#define PACKAGE "libpng"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "[email protected]"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libpng"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libpng 1.5.13"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libpng"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "1.5.13"
+
+/* Align row buffers */
+/* #undef PNG_ALIGNED_MEMORY_SUPPORTED */
+
+/* Enable ARM NEON optimizations */
+/* #undef PNG_ARM_NEON */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+/* #undef TM_IN_SYS_TIME */
+
+/* Version number of package */
+#define VERSION "1.5.13"
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to the equivalent of the C99 'restrict' keyword, or to
+   nothing if this is not supported.  Do not define if restrict is
+   supported directly.  */
+#define restrict __restrict
+/* Work around a bug in Sun C++: it does not support _Restrict or
+   __restrict__, even though the corresponding Sun C compiler ends up with
+   "#define restrict _Restrict" or "#define restrict __restrict__" in the
+   previous line.  Perhaps some future version of Sun C++ will work with
+   restrict; if so, hopefully it defines __RESTRICT like Sun C does.  */
+#if defined __SUNPRO_CC && !defined __RESTRICT
+# define _Restrict
+# define __restrict__
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */

+ 2674 - 0
engine/compilers/android/jni/include/libpng/png.h

@@ -0,0 +1,2674 @@
+
+/* png.h - header file for PNG reference library
+ *
+ * libpng version 1.5.13 - September 27, 2012
+ * Copyright (c) 1998-2012 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * This code is released under the libpng license (See LICENSE, below)
+ *
+ * Authors and maintainers:
+ *   libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
+ *   libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
+ *   libpng versions 0.97, January 1998, through 1.5.13 - September 27, 2012: Glenn
+ *   See also "Contributing Authors", below.
+ *
+ * Note about libpng version numbers:
+ *
+ *   Due to various miscommunications, unforeseen code incompatibilities
+ *   and occasional factors outside the authors' control, version numbering
+ *   on the library has not always been consistent and straightforward.
+ *   The following table summarizes matters since version 0.89c, which was
+ *   the first widely used release:
+ *
+ *    source                 png.h  png.h  shared-lib
+ *    version                string   int  version
+ *    -------                ------ -----  ----------
+ *    0.89c "1.0 beta 3"     0.89      89  1.0.89
+ *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
+ *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
+ *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
+ *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
+ *    0.97c                  0.97      97  2.0.97
+ *    0.98                   0.98      98  2.0.98
+ *    0.99                   0.99      98  2.0.99
+ *    0.99a-m                0.99      99  2.0.99
+ *    1.00                   1.00     100  2.1.0 [100 should be 10000]
+ *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
+ *    1.0.1       png.h string is   10001  2.1.0
+ *    1.0.1a-e    identical to the  10002  from here on, the shared library
+ *    1.0.2       source version)   10002  is 2.V where V is the source code
+ *    1.0.2a-b                      10003  version, except as noted.
+ *    1.0.3                         10003
+ *    1.0.3a-d                      10004
+ *    1.0.4                         10004
+ *    1.0.4a-f                      10005
+ *    1.0.5 (+ 2 patches)           10005
+ *    1.0.5a-d                      10006
+ *    1.0.5e-r                      10100 (not source compatible)
+ *    1.0.5s-v                      10006 (not binary compatible)
+ *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
+ *    1.0.6d-f                      10007 (still binary incompatible)
+ *    1.0.6g                        10007
+ *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
+ *    1.0.6i                        10007  10.6i
+ *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
+ *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
+ *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
+ *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
+ *    1.0.7                    1    10007  (still compatible)
+ *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
+ *    1.0.8rc1                 1    10008  2.1.0.8rc1
+ *    1.0.8                    1    10008  2.1.0.8
+ *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
+ *    1.0.9rc1                 1    10009  2.1.0.9rc1
+ *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
+ *    1.0.9rc2                 1    10009  2.1.0.9rc2
+ *    1.0.9                    1    10009  2.1.0.9
+ *    1.0.10beta1              1    10010  2.1.0.10beta1
+ *    1.0.10rc1                1    10010  2.1.0.10rc1
+ *    1.0.10                   1    10010  2.1.0.10
+ *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
+ *    1.0.11rc1                1    10011  2.1.0.11rc1
+ *    1.0.11                   1    10011  2.1.0.11
+ *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
+ *    1.0.12rc1                2    10012  2.1.0.12rc1
+ *    1.0.12                   2    10012  2.1.0.12
+ *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
+ *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
+ *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
+ *    1.2.0rc1                 3    10200  3.1.2.0rc1
+ *    1.2.0                    3    10200  3.1.2.0
+ *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
+ *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
+ *    1.2.1                    3    10201  3.1.2.1
+ *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
+ *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
+ *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
+ *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
+ *    1.0.13                  10    10013  10.so.0.1.0.13
+ *    1.2.2                   12    10202  12.so.0.1.2.2
+ *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
+ *    1.2.3                   12    10203  12.so.0.1.2.3
+ *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
+ *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
+ *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
+ *    1.0.14                  10    10014  10.so.0.1.0.14
+ *    1.2.4                   13    10204  12.so.0.1.2.4
+ *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
+ *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
+ *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
+ *    1.0.15                  10    10015  10.so.0.1.0.15
+ *    1.2.5                   13    10205  12.so.0.1.2.5
+ *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
+ *    1.0.16                  10    10016  10.so.0.1.0.16
+ *    1.2.6                   13    10206  12.so.0.1.2.6
+ *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
+ *    1.0.17rc1               10    10017  12.so.0.1.0.17rc1
+ *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
+ *    1.0.17                  10    10017  12.so.0.1.0.17
+ *    1.2.7                   13    10207  12.so.0.1.2.7
+ *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
+ *    1.0.18rc1-5             10    10018  12.so.0.1.0.18rc1-5
+ *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
+ *    1.0.18                  10    10018  12.so.0.1.0.18
+ *    1.2.8                   13    10208  12.so.0.1.2.8
+ *    1.2.9beta1-3            13    10209  12.so.0.1.2.9beta1-3
+ *    1.2.9beta4-11           13    10209  12.so.0.9[.0]
+ *    1.2.9rc1                13    10209  12.so.0.9[.0]
+ *    1.2.9                   13    10209  12.so.0.9[.0]
+ *    1.2.10beta1-7           13    10210  12.so.0.10[.0]
+ *    1.2.10rc1-2             13    10210  12.so.0.10[.0]
+ *    1.2.10                  13    10210  12.so.0.10[.0]
+ *    1.4.0beta1-5            14    10400  14.so.0.0[.0]
+ *    1.2.11beta1-4           13    10211  12.so.0.11[.0]
+ *    1.4.0beta7-8            14    10400  14.so.0.0[.0]
+ *    1.2.11                  13    10211  12.so.0.11[.0]
+ *    1.2.12                  13    10212  12.so.0.12[.0]
+ *    1.4.0beta9-14           14    10400  14.so.0.0[.0]
+ *    1.2.13                  13    10213  12.so.0.13[.0]
+ *    1.4.0beta15-36          14    10400  14.so.0.0[.0]
+ *    1.4.0beta37-87          14    10400  14.so.14.0[.0]
+ *    1.4.0rc01               14    10400  14.so.14.0[.0]
+ *    1.4.0beta88-109         14    10400  14.so.14.0[.0]
+ *    1.4.0rc02-08            14    10400  14.so.14.0[.0]
+ *    1.4.0                   14    10400  14.so.14.0[.0]
+ *    1.4.1beta01-03          14    10401  14.so.14.1[.0]
+ *    1.4.1rc01               14    10401  14.so.14.1[.0]
+ *    1.4.1beta04-12          14    10401  14.so.14.1[.0]
+ *    1.4.1                   14    10401  14.so.14.1[.0]
+ *    1.4.2                   14    10402  14.so.14.2[.0]
+ *    1.4.3                   14    10403  14.so.14.3[.0]
+ *    1.4.4                   14    10404  14.so.14.4[.0]
+ *    1.5.0beta01-58          15    10500  15.so.15.0[.0]
+ *    1.5.0rc01-07            15    10500  15.so.15.0[.0]
+ *    1.5.0                   15    10500  15.so.15.0[.0]
+ *    1.5.1beta01-11          15    10501  15.so.15.1[.0]
+ *    1.5.1rc01-02            15    10501  15.so.15.1[.0]
+ *    1.5.1                   15    10501  15.so.15.1[.0]
+ *    1.5.2beta01-03          15    10502  15.so.15.2[.0]
+ *    1.5.2rc01-03            15    10502  15.so.15.2[.0]
+ *    1.5.2                   15    10502  15.so.15.2[.0]
+ *    1.5.3beta01-10          15    10503  15.so.15.3[.0]
+ *    1.5.3rc01-02            15    10503  15.so.15.3[.0]
+ *    1.5.3beta11             15    10503  15.so.15.3[.0]
+ *    1.5.3 [omitted]
+ *    1.5.4beta01-08          15    10504  15.so.15.4[.0]
+ *    1.5.4rc01               15    10504  15.so.15.4[.0]
+ *    1.5.4                   15    10504  15.so.15.4[.0]
+ *    1.5.5beta01-08          15    10505  15.so.15.5[.0]
+ *    1.5.5rc01               15    10505  15.so.15.5[.0]
+ *    1.5.5                   15    10505  15.so.15.5[.0]
+ *    1.5.6beta01-07          15    10506  15.so.15.6[.0]
+ *    1.5.6rc01-03            15    10506  15.so.15.6[.0]
+ *    1.5.6                   15    10506  15.so.15.6[.0]
+ *    1.5.7beta01-05          15    10507  15.so.15.7[.0]
+ *    1.5.7rc01-03            15    10507  15.so.15.7[.0]
+ *    1.5.7                   15    10507  15.so.15.7[.0]
+ *    1.5.8beta01             15    10508  15.so.15.8[.0]
+ *    1.5.8rc01               15    10508  15.so.15.8[.0]
+ *    1.5.8                   15    10508  15.so.15.8[.0]
+ *    1.5.9beta01-02          15    10509  15.so.15.9[.0]
+ *    1.5.9rc01               15    10509  15.so.15.9[.0]
+ *    1.5.9                   15    10509  15.so.15.9[.0]
+ *    1.5.10beta01-05         15    10510  15.so.15.10[.0]
+ *    1.5.10                  15    10510  15.so.15.10[.0]
+ *    1.5.11beta01            15    10511  15.so.15.11[.0]
+ *    1.5.11rc01-05           15    10511  15.so.15.11[.0]
+ *    1.5.11                  15    10511  15.so.15.11[.0]
+ *    1.5.12                  15    10512  15.so.15.12[.0]
+ *    1.5.13beta01-02         15    10513  15.so.15.13[.0]
+ *    1.5.13rc01              15    10513  15.so.15.13[.0]
+ *    1.5.13                  15    10513  15.so.15.13[.0]
+ *
+ *   Henceforth the source version will match the shared-library major
+ *   and minor numbers; the shared-library major version number will be
+ *   used for changes in backward compatibility, as it is intended.  The
+ *   PNG_LIBPNG_VER macro, which is not used within libpng but is available
+ *   for applications, is an unsigned integer of the form xyyzz corresponding
+ *   to the source version x.y.z (leading zeros in y and z).  Beta versions
+ *   were given the previous public release number plus a letter, until
+ *   version 1.0.6j; from then on they were given the upcoming public
+ *   release number plus "betaNN" or "rcNN".
+ *
+ *   Binary incompatibility exists only when applications make direct access
+ *   to the info_ptr or png_ptr members through png.h, and the compiled
+ *   application is loaded with a different version of the library.
+ *
+ *   DLLNUM will change each time there are forward or backward changes
+ *   in binary compatibility (e.g., when a new feature is added).
+ *
+ * See libpng-manual.txt or libpng.3 for more information.  The PNG
+ * specification is available as a W3C Recommendation and as an ISO
+ * Specification, <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ */
+
+/*
+ * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
+ *
+ * If you modify libpng you may insert additional notices immediately following
+ * this sentence.
+ *
+ * This code is released under the libpng license.
+ *
+ * libpng versions 1.2.6, August 15, 2004, through 1.5.13, September 27, 2012, are
+ * Copyright (c) 2004, 2006-2012 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.2.5
+ * with the following individual added to the list of Contributing Authors:
+ *
+ *    Cosmin Truta
+ *
+ * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
+ * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.0.6
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Simon-Pierre Cadieux
+ *    Eric S. Raymond
+ *    Gilles Vollant
+ *
+ * and with the following additions to the disclaimer:
+ *
+ *    There is no warranty against interference with your enjoyment of the
+ *    library or against infringement.  There is no warranty that our
+ *    efforts or the library will fulfill any of your particular purposes
+ *    or needs.  This library is provided with all faults, and the entire
+ *    risk of satisfactory quality, performance, accuracy, and effort is with
+ *    the user.
+ *
+ * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+ * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-0.96,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Tom Lane
+ *    Glenn Randers-Pehrson
+ *    Willem van Schaik
+ *
+ * libpng versions 0.89, June 1996, through 0.96, May 1997, are
+ * Copyright (c) 1996, 1997 Andreas Dilger
+ * Distributed according to the same disclaimer and license as libpng-0.88,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    John Bowler
+ *    Kevin Bracey
+ *    Sam Bushell
+ *    Magnus Holmgren
+ *    Greg Roelofs
+ *    Tom Tanner
+ *
+ * libpng versions 0.5, May 1995, through 0.88, January 1996, are
+ * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+ *
+ * For the purposes of this copyright and license, "Contributing Authors"
+ * is defined as the following set of individuals:
+ *
+ *    Andreas Dilger
+ *    Dave Martindale
+ *    Guy Eric Schalnat
+ *    Paul Schmidt
+ *    Tim Wegner
+ *
+ * The PNG Reference Library is supplied "AS IS".  The Contributing Authors
+ * and Group 42, Inc. disclaim all warranties, expressed or implied,
+ * including, without limitation, the warranties of merchantability and of
+ * fitness for any purpose.  The Contributing Authors and Group 42, Inc.
+ * assume no liability for direct, indirect, incidental, special, exemplary,
+ * or consequential damages, which may result from the use of the PNG
+ * Reference Library, even if advised of the possibility of such damage.
+ *
+ * Permission is hereby granted to use, copy, modify, and distribute this
+ * source code, or portions hereof, for any purpose, without fee, subject
+ * to the following restrictions:
+ *
+ *   1. The origin of this source code must not be misrepresented.
+ *
+ *   2. Altered versions must be plainly marked as such and must not
+ *      be misrepresented as being the original source.
+ *
+ *   3. This Copyright notice may not be removed or altered from
+ *      any source or altered source distribution.
+ *
+ * The Contributing Authors and Group 42, Inc. specifically permit, without
+ * fee, and encourage the use of this source code as a component to
+ * supporting the PNG file format in commercial products.  If you use this
+ * source code in a product, acknowledgment is not required but would be
+ * appreciated.
+ */
+
+/*
+ * A "png_get_copyright" function is available, for convenient use in "about"
+ * boxes and the like:
+ *
+ *     printf("%s", png_get_copyright(NULL));
+ *
+ * Also, the PNG logo (in PNG format, of course) is supplied in the
+ * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
+ */
+
+/*
+ * Libpng is OSI Certified Open Source Software.  OSI Certified is a
+ * certification mark of the Open Source Initiative.
+ */
+
+/*
+ * The contributing authors would like to thank all those who helped
+ * with testing, bug fixes, and patience.  This wouldn't have been
+ * possible without all of you.
+ *
+ * Thanks to Frank J. T. Wojcik for helping with the documentation.
+ */
+
+/*
+ * Y2K compliance in libpng:
+ * =========================
+ *
+ *    September 27, 2012
+ *
+ *    Since the PNG Development group is an ad-hoc body, we can't make
+ *    an official declaration.
+ *
+ *    This is your unofficial assurance that libpng from version 0.71 and
+ *    upward through 1.5.13 are Y2K compliant.  It is my belief that
+ *    earlier versions were also Y2K compliant.
+ *
+ *    Libpng only has two year fields.  One is a 2-byte unsigned integer
+ *    that will hold years up to 65535.  The other holds the date in text
+ *    format, and will hold years up to 9999.
+ *
+ *    The integer is
+ *        "png_uint_16 year" in png_time_struct.
+ *
+ *    The string is
+ *        "char time_buffer[29]" in png_struct.  This will be no
+ *    longer used in libpng-1.6.0 and will be removed from libpng-1.7.0.
+ *
+ *    There are seven time-related functions:
+ *        png.c: png_convert_to_rfc_1123() in png.c
+ *          (formerly png_convert_to_rfc_1152() in error)
+ *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
+ *        png_convert_from_time_t() in pngwrite.c
+ *        png_get_tIME() in pngget.c
+ *        png_handle_tIME() in pngrutil.c, called in pngread.c
+ *        png_set_tIME() in pngset.c
+ *        png_write_tIME() in pngwutil.c, called in pngwrite.c
+ *
+ *    All handle dates properly in a Y2K environment.  The
+ *    png_convert_from_time_t() function calls gmtime() to convert from system
+ *    clock time, which returns (year - 1900), which we properly convert to
+ *    the full 4-digit year.  There is a possibility that applications using
+ *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
+ *    function, or that they are incorrectly passing only a 2-digit year
+ *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
+ *    but this is not under our control.  The libpng documentation has always
+ *    stated that it works with 4-digit years, and the APIs have been
+ *    documented as such.
+ *
+ *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
+ *    integer to hold the year, and can hold years as large as 65535.
+ *
+ *    zlib, upon which libpng depends, is also Y2K compliant.  It contains
+ *    no date-related code.
+ *
+ *       Glenn Randers-Pehrson
+ *       libpng maintainer
+ *       PNG Development Group
+ */
+
+#ifndef PNG_H
+#define PNG_H
+
+/* This is not the place to learn how to use libpng. The file libpng-manual.txt
+ * describes how to use libpng, and the file example.c summarizes it
+ * with some code on which to build.  This file is useful for looking
+ * at the actual function definitions and structure components.
+ *
+ * If you just need to read a PNG file and don't want to read the documentation
+ * skip to the end of this file and read the section entitled 'simplified API'.
+ */
+
+/* Version information for png.h - this should match the version in png.c */
+#define PNG_LIBPNG_VER_STRING "1.5.13"
+#define PNG_HEADER_VERSION_STRING \
+     " libpng version 1.5.13 - September 27, 2012\n"
+
+#define PNG_LIBPNG_VER_SONUM   15
+#define PNG_LIBPNG_VER_DLLNUM  15
+
+/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
+#define PNG_LIBPNG_VER_MAJOR   1
+#define PNG_LIBPNG_VER_MINOR   5
+#define PNG_LIBPNG_VER_RELEASE 13
+
+/* This should match the numeric part of the final component of
+ * PNG_LIBPNG_VER_STRING, omitting any leading zero:
+ */
+
+#define PNG_LIBPNG_VER_BUILD  0
+
+/* Release Status */
+#define PNG_LIBPNG_BUILD_ALPHA    1
+#define PNG_LIBPNG_BUILD_BETA     2
+#define PNG_LIBPNG_BUILD_RC       3
+#define PNG_LIBPNG_BUILD_STABLE   4
+#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
+
+/* Release-Specific Flags */
+#define PNG_LIBPNG_BUILD_PATCH    8 /* Can be OR'ed with
+                                       PNG_LIBPNG_BUILD_STABLE only */
+#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_SPECIAL */
+#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_PRIVATE */
+
+#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
+
+/* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
+ * We must not include leading zeros.
+ * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
+ * version 1.0.0 was mis-numbered 100 instead of 10000).  From
+ * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
+ */
+#define PNG_LIBPNG_VER 10513 /* 1.5.13 */
+
+/* Library configuration: these options cannot be changed after
+ * the library has been built.
+ */
+#ifndef PNGLCONF_H
+    /* If pnglibconf.h is missing, you can
+     * copy scripts/pnglibconf.h.prebuilt to pnglibconf.h
+     */
+#   include "pnglibconf.h"
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+#  ifndef PNG_BUILDING_SYMBOL_TABLE
+  /*
+   *   Standard header files (not needed for the version info or while
+   *   building symbol table -- see scripts/pnglibconf.dfa)
+   */
+#    ifdef PNG_SETJMP_SUPPORTED
+#      include <setjmp.h>
+#    endif
+
+    /* Need the time information for converting tIME chunks, it
+     * defines struct tm:
+     */
+#    ifdef PNG_CONVERT_tIME_SUPPORTED
+       /* "time.h" functions are not supported on all operating systems */
+#      include <time.h>
+#    endif
+#  endif
+
+/* Machine specific configuration. */
+#  include "pngconf.h"
+#endif
+
+/*
+ * Added at libpng-1.2.8
+ *
+ * Ref MSDN: Private as priority over Special
+ * VS_FF_PRIVATEBUILD File *was not* built using standard release
+ * procedures. If this value is given, the StringFileInfo block must
+ * contain a PrivateBuild string.
+ *
+ * VS_FF_SPECIALBUILD File *was* built by the original company using
+ * standard release procedures but is a variation of the standard
+ * file of the same version number. If this value is given, the
+ * StringFileInfo block must contain a SpecialBuild string.
+ */
+
+#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */
+#  define PNG_LIBPNG_BUILD_TYPE \
+       (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
+#else
+#  ifdef PNG_LIBPNG_SPECIALBUILD
+#    define PNG_LIBPNG_BUILD_TYPE \
+         (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
+#  else
+#    define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
+#  endif
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* Version information for C files, stored in png.c.  This had better match
+ * the version above.
+ */
+#define png_libpng_ver png_get_header_ver(NULL)
+
+/* This file is arranged in several sections:
+ *
+ * 1. Any configuration options that can be specified by for the application
+ *    code when it is built.  (Build time configuration is in pnglibconf.h)
+ * 2. Type definitions (base types are defined in pngconf.h), structure
+ *    definitions.
+ * 3. Exported library functions.
+ *
+ * The library source code has additional files (principally pngpriv.h) that
+ * allow configuration of the library.
+ */
+/* Section 1: run time configuration
+ * See pnglibconf.h for build time configuration
+ *
+ * Run time configuration allows the application to choose between
+ * implementations of certain arithmetic APIs.  The default is set
+ * at build time and recorded in pnglibconf.h, but it is safe to
+ * override these (and only these) settings.  Note that this won't
+ * change what the library does, only application code, and the
+ * settings can (and probably should) be made on a per-file basis
+ * by setting the #defines before including png.h
+ *
+ * Use macros to read integers from PNG data or use the exported
+ * functions?
+ *   PNG_USE_READ_MACROS: use the macros (see below)  Note that
+ *     the macros evaluate their argument multiple times.
+ *   PNG_NO_USE_READ_MACROS: call the relevant library function.
+ *
+ * Use the alternative algorithm for compositing alpha samples that
+ * does not use division?
+ *   PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division'
+ *      algorithm.
+ *   PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm.
+ *
+ * How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is
+ * false?
+ *   PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error
+ *      APIs to png_warning.
+ * Otherwise the calls are mapped to png_error.
+ */
+
+/* Section 2: type definitions, including structures and compile time
+ * constants.
+ * See pngconf.h for base types that vary by machine/system
+ */
+
+/* This triggers a compiler error in png.c, if png.c and png.h
+ * do not agree upon the version number.
+ */
+typedef char* png_libpng_version_1_5_13;
+
+/* Three color definitions.  The order of the red, green, and blue, (and the
+ * exact size) is not important, although the size of the fields need to
+ * be png_byte or png_uint_16 (as defined below).
+ */
+typedef struct png_color_struct
+{
+   png_byte red;
+   png_byte green;
+   png_byte blue;
+} png_color;
+typedef png_color FAR * png_colorp;
+typedef PNG_CONST png_color FAR * png_const_colorp;
+typedef png_color FAR * FAR * png_colorpp;
+
+typedef struct png_color_16_struct
+{
+   png_byte index;    /* used for palette files */
+   png_uint_16 red;   /* for use in red green blue files */
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 gray;  /* for use in grayscale files */
+} png_color_16;
+typedef png_color_16 FAR * png_color_16p;
+typedef PNG_CONST png_color_16 FAR * png_const_color_16p;
+typedef png_color_16 FAR * FAR * png_color_16pp;
+
+typedef struct png_color_8_struct
+{
+   png_byte red;   /* for use in red green blue files */
+   png_byte green;
+   png_byte blue;
+   png_byte gray;  /* for use in grayscale files */
+   png_byte alpha; /* for alpha channel files */
+} png_color_8;
+typedef png_color_8 FAR * png_color_8p;
+typedef PNG_CONST png_color_8 FAR * png_const_color_8p;
+typedef png_color_8 FAR * FAR * png_color_8pp;
+
+/*
+ * The following two structures are used for the in-core representation
+ * of sPLT chunks.
+ */
+typedef struct png_sPLT_entry_struct
+{
+   png_uint_16 red;
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 alpha;
+   png_uint_16 frequency;
+} png_sPLT_entry;
+typedef png_sPLT_entry FAR * png_sPLT_entryp;
+typedef PNG_CONST png_sPLT_entry FAR * png_const_sPLT_entryp;
+typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
+
+/*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
+ *  occupy the LSB of their respective members, and the MSB of each member
+ *  is zero-filled.  The frequency member always occupies the full 16 bits.
+ */
+
+typedef struct png_sPLT_struct
+{
+   png_charp name;           /* palette name */
+   png_byte depth;           /* depth of palette samples */
+   png_sPLT_entryp entries;  /* palette entries */
+   png_int_32 nentries;      /* number of palette entries */
+} png_sPLT_t;
+typedef png_sPLT_t FAR * png_sPLT_tp;
+typedef PNG_CONST png_sPLT_t FAR * png_const_sPLT_tp;
+typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
+
+#ifdef PNG_TEXT_SUPPORTED
+/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
+ * and whether that contents is compressed or not.  The "key" field
+ * points to a regular zero-terminated C string.  The "text" fields can be a
+ * regular C string, an empty string, or a NULL pointer.
+ * However, the structure returned by png_get_text() will always contain
+ * the "text" field as a regular zero-terminated C string (possibly
+ * empty), never a NULL pointer, so it can be safely used in printf() and
+ * other string-handling functions.  Note that the "itxt_length", "lang", and
+ * "lang_key" members of the structure only exist when the library is built
+ * with iTXt chunk support.  Prior to libpng-1.4.0 the library was built by
+ * default without iTXt support. Also note that when iTXt *is* supported,
+ * the "lang" and "lang_key" fields contain NULL pointers when the
+ * "compression" field contains * PNG_TEXT_COMPRESSION_NONE or
+ * PNG_TEXT_COMPRESSION_zTXt. Note that the "compression value" is not the
+ * same as what appears in the PNG tEXt/zTXt/iTXt chunk's "compression flag"
+ * which is always 0 or 1, or its "compression method" which is always 0.
+ */
+typedef struct png_text_struct
+{
+   int  compression;       /* compression value:
+                             -1: tEXt, none
+                              0: zTXt, deflate
+                              1: iTXt, none
+                              2: iTXt, deflate  */
+   png_charp key;          /* keyword, 1-79 character description of "text" */
+   png_charp text;         /* comment, may be an empty string (ie "")
+                              or a NULL pointer */
+   png_size_t text_length; /* length of the text string */
+   png_size_t itxt_length; /* length of the itxt string */
+   png_charp lang;         /* language code, 0-79 characters
+                              or a NULL pointer */
+   png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
+                              chars or a NULL pointer */
+} png_text;
+typedef png_text FAR * png_textp;
+typedef PNG_CONST png_text FAR * png_const_textp;
+typedef png_text FAR * FAR * png_textpp;
+#endif
+
+/* Supported compression types for text in PNG files (tEXt, and zTXt).
+ * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
+#define PNG_TEXT_COMPRESSION_NONE_WR -3
+#define PNG_TEXT_COMPRESSION_zTXt_WR -2
+#define PNG_TEXT_COMPRESSION_NONE    -1
+#define PNG_TEXT_COMPRESSION_zTXt     0
+#define PNG_ITXT_COMPRESSION_NONE     1
+#define PNG_ITXT_COMPRESSION_zTXt     2
+#define PNG_TEXT_COMPRESSION_LAST     3  /* Not a valid value */
+
+/* png_time is a way to hold the time in an machine independent way.
+ * Two conversions are provided, both from time_t and struct tm.  There
+ * is no portable way to convert to either of these structures, as far
+ * as I know.  If you know of a portable way, send it to me.  As a side
+ * note - PNG has always been Year 2000 compliant!
+ */
+typedef struct png_time_struct
+{
+   png_uint_16 year; /* full year, as in, 1995 */
+   png_byte month;   /* month of year, 1 - 12 */
+   png_byte day;     /* day of month, 1 - 31 */
+   png_byte hour;    /* hour of day, 0 - 23 */
+   png_byte minute;  /* minute of hour, 0 - 59 */
+   png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
+} png_time;
+typedef png_time FAR * png_timep;
+typedef PNG_CONST png_time FAR * png_const_timep;
+typedef png_time FAR * FAR * png_timepp;
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \
+    defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
+/* png_unknown_chunk is a structure to hold queued chunks for which there is
+ * no specific support.  The idea is that we can use this to queue
+ * up private chunks for output even though the library doesn't actually
+ * know about their semantics.
+ */
+typedef struct png_unknown_chunk_t
+{
+    png_byte name[5];
+    png_byte *data;
+    png_size_t size;
+
+    /* libpng-using applications should NOT directly modify this byte. */
+    png_byte location; /* mode of operation at read time */
+}
+
+
+png_unknown_chunk;
+typedef png_unknown_chunk FAR * png_unknown_chunkp;
+typedef PNG_CONST png_unknown_chunk FAR * png_const_unknown_chunkp;
+typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
+#endif
+
+/* Values for the unknown chunk location byte */
+
+#define PNG_HAVE_IHDR  0x01
+#define PNG_HAVE_PLTE  0x02
+#define PNG_AFTER_IDAT 0x08
+
+/* The complete definition of png_info has, as of libpng-1.5.0,
+ * been moved into a separate header file that is not accessible to
+ * applications.  Read libpng-manual.txt or libpng.3 for more info.
+ */
+typedef struct png_info_def png_info;
+typedef png_info FAR * png_infop;
+typedef PNG_CONST png_info FAR * png_const_infop;
+typedef png_info FAR * FAR * png_infopp;
+
+/* Maximum positive integer used in PNG is (2^31)-1 */
+#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
+#define PNG_UINT_32_MAX ((png_uint_32)(-1))
+#define PNG_SIZE_MAX ((png_size_t)(-1))
+
+/* These are constants for fixed point values encoded in the
+ * PNG specification manner (x100000)
+ */
+#define PNG_FP_1    100000
+#define PNG_FP_HALF  50000
+#define PNG_FP_MAX  ((png_fixed_point)0x7fffffffL)
+#define PNG_FP_MIN  (-PNG_FP_MAX)
+
+/* These describe the color_type field in png_info. */
+/* color type masks */
+#define PNG_COLOR_MASK_PALETTE    1
+#define PNG_COLOR_MASK_COLOR      2
+#define PNG_COLOR_MASK_ALPHA      4
+
+/* color types.  Note that not all combinations are legal */
+#define PNG_COLOR_TYPE_GRAY 0
+#define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
+#define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
+#define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
+#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
+/* aliases */
+#define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
+#define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
+
+/* This is for compression type. PNG 1.0-1.2 only define the single type. */
+#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
+#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
+
+/* This is for filter type. PNG 1.0-1.2 only define the single type. */
+#define PNG_FILTER_TYPE_BASE      0 /* Single row per-byte filtering */
+#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
+#define PNG_FILTER_TYPE_DEFAULT   PNG_FILTER_TYPE_BASE
+
+/* These are for the interlacing type.  These values should NOT be changed. */
+#define PNG_INTERLACE_NONE        0 /* Non-interlaced image */
+#define PNG_INTERLACE_ADAM7       1 /* Adam7 interlacing */
+#define PNG_INTERLACE_LAST        2 /* Not a valid value */
+
+/* These are for the oFFs chunk.  These values should NOT be changed. */
+#define PNG_OFFSET_PIXEL          0 /* Offset in pixels */
+#define PNG_OFFSET_MICROMETER     1 /* Offset in micrometers (1/10^6 meter) */
+#define PNG_OFFSET_LAST           2 /* Not a valid value */
+
+/* These are for the pCAL chunk.  These values should NOT be changed. */
+#define PNG_EQUATION_LINEAR       0 /* Linear transformation */
+#define PNG_EQUATION_BASE_E       1 /* Exponential base e transform */
+#define PNG_EQUATION_ARBITRARY    2 /* Arbitrary base exponential transform */
+#define PNG_EQUATION_HYPERBOLIC   3 /* Hyperbolic sine transformation */
+#define PNG_EQUATION_LAST         4 /* Not a valid value */
+
+/* These are for the sCAL chunk.  These values should NOT be changed. */
+#define PNG_SCALE_UNKNOWN         0 /* unknown unit (image scale) */
+#define PNG_SCALE_METER           1 /* meters per pixel */
+#define PNG_SCALE_RADIAN          2 /* radians per pixel */
+#define PNG_SCALE_LAST            3 /* Not a valid value */
+
+/* These are for the pHYs chunk.  These values should NOT be changed. */
+#define PNG_RESOLUTION_UNKNOWN    0 /* pixels/unknown unit (aspect ratio) */
+#define PNG_RESOLUTION_METER      1 /* pixels/meter */
+#define PNG_RESOLUTION_LAST       2 /* Not a valid value */
+
+/* These are for the sRGB chunk.  These values should NOT be changed. */
+#define PNG_sRGB_INTENT_PERCEPTUAL 0
+#define PNG_sRGB_INTENT_RELATIVE   1
+#define PNG_sRGB_INTENT_SATURATION 2
+#define PNG_sRGB_INTENT_ABSOLUTE   3
+#define PNG_sRGB_INTENT_LAST       4 /* Not a valid value */
+
+/* This is for text chunks */
+#define PNG_KEYWORD_MAX_LENGTH     79
+
+/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
+#define PNG_MAX_PALETTE_LENGTH    256
+
+/* These determine if an ancillary chunk's data has been successfully read
+ * from the PNG header, or if the application has filled in the corresponding
+ * data in the info_struct to be written into the output file.  The values
+ * of the PNG_INFO_<chunk> defines should NOT be changed.
+ */
+#define PNG_INFO_gAMA 0x0001
+#define PNG_INFO_sBIT 0x0002
+#define PNG_INFO_cHRM 0x0004
+#define PNG_INFO_PLTE 0x0008
+#define PNG_INFO_tRNS 0x0010
+#define PNG_INFO_bKGD 0x0020
+#define PNG_INFO_hIST 0x0040
+#define PNG_INFO_pHYs 0x0080
+#define PNG_INFO_oFFs 0x0100
+#define PNG_INFO_tIME 0x0200
+#define PNG_INFO_pCAL 0x0400
+#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
+#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
+#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
+#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#define PNG_INFO_IDAT 0x8000   /* ESR, 1.0.6 */
+
+/* This is used for the transformation routines, as some of them
+ * change these values for the row.  It also should enable using
+ * the routines for other purposes.
+ */
+typedef struct png_row_info_struct
+{
+   png_uint_32 width;    /* width of row */
+   png_size_t rowbytes;  /* number of bytes in row */
+   png_byte color_type;  /* color type of row */
+   png_byte bit_depth;   /* bit depth of row */
+   png_byte channels;    /* number of channels (1, 2, 3, or 4) */
+   png_byte pixel_depth; /* bits per pixel (depth * channels) */
+} png_row_info;
+
+typedef png_row_info FAR * png_row_infop;
+typedef png_row_info FAR * FAR * png_row_infopp;
+
+/* The complete definition of png_struct has, as of libpng-1.5.0,
+ * been moved into a separate header file that is not accessible to
+ * applications.  Read libpng-manual.txt or libpng.3 for more info.
+ */
+typedef struct png_struct_def png_struct;
+typedef PNG_CONST png_struct FAR * png_const_structp;
+typedef png_struct FAR * png_structp;
+
+/* These are the function types for the I/O functions and for the functions
+ * that allow the user to override the default I/O functions with his or her
+ * own.  The png_error_ptr type should match that of user-supplied warning
+ * and error functions, while the png_rw_ptr type should match that of the
+ * user read/write data functions.  Note that the 'write' function must not
+ * modify the buffer it is passed. The 'read' function, on the other hand, is
+ * expected to return the read data in the buffer.
+ */
+typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp));
+typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, png_size_t));
+typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp));
+typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32,
+    int));
+typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32,
+    int));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop));
+typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop));
+
+/* The following callback receives png_uint_32 row_number, int pass for the
+ * png_bytep data of the row.  When transforming an interlaced image the
+ * row number is the row number within the sub-image of the interlace pass, so
+ * the value will increase to the height of the sub-image (not the full image)
+ * then reset to 0 for the next pass.
+ *
+ * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
+ * find the output pixel (x,y) given an interlaced sub-image pixel
+ * (row,col,pass).  (See below for these macros.)
+ */
+typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep,
+    png_uint_32, int));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop,
+    png_bytep));
+#endif
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp,
+    png_unknown_chunkp));
+#endif
+#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
+typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp));
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+/* This must match the function definition in <setjmp.h>, and the application
+ * must include this before png.h to obtain the definition of jmp_buf.  The
+ * function is required to be PNG_NORETURN, but this is not checked.  If the
+ * function does return the application will crash via an abort() or similar
+ * system level call.
+ *
+ * If you get a warning here while building the library you may need to make
+ * changes to ensure that pnglibconf.h records the calling convention used by
+ * your compiler.  This may be very difficult - try using a different compiler
+ * to build the library!
+ */
+PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef);
+#endif
+
+/* Transform masks for the high-level interface */
+#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
+#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
+#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
+#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
+#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
+#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
+#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
+#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
+#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
+#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
+#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
+#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
+#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* write only */
+/* Added to libpng-1.2.34 */
+#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER
+#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */
+/* Added to libpng-1.4.0 */
+#define PNG_TRANSFORM_GRAY_TO_RGB   0x2000      /* read only */
+/* Added to libpng-1.5.4 */
+#define PNG_TRANSFORM_EXPAND_16     0x4000      /* read only */
+#define PNG_TRANSFORM_SCALE_16      0x8000      /* read only */
+
+/* Flags for MNG supported features */
+#define PNG_FLAG_MNG_EMPTY_PLTE     0x01
+#define PNG_FLAG_MNG_FILTER_64      0x04
+#define PNG_ALL_MNG_FEATURES        0x05
+
+/* NOTE: prior to 1.5 these functions had no 'API' style declaration,
+ * this allowed the zlib default functions to be used on Windows
+ * platforms.  In 1.5 the zlib default malloc (which just calls malloc and
+ * ignores the first argument) should be completely compatible with the
+ * following.
+ */
+typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp,
+    png_alloc_size_t));
+typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp));
+
+typedef png_struct FAR * FAR * png_structpp;
+
+/* Section 3: exported functions
+ * Here are the function definitions most commonly used.  This is not
+ * the place to find out how to use libpng.  See libpng-manual.txt for the
+ * full explanation, see example.c for the summary.  This just provides
+ * a simple one line description of the use of each function.
+ *
+ * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in
+ * pngconf.h and in the *.dfn files in the scripts directory.
+ *
+ *   PNG_EXPORT(ordinal, type, name, (args));
+ *
+ *       ordinal:    ordinal that is used while building
+ *                   *.def files. The ordinal value is only
+ *                   relevant when preprocessing png.h with
+ *                   the *.dfn files for building symbol table
+ *                   entries, and are removed by pngconf.h.
+ *       type:       return type of the function
+ *       name:       function name
+ *       args:       function arguments, with types
+ *
+ * When we wish to append attributes to a function prototype we use
+ * the PNG_EXPORTA() macro instead.
+ *
+ *   PNG_EXPORTA(ordinal, type, name, (args), attributes);
+ *
+ *       ordinal, type, name, and args: same as in PNG_EXPORT().
+ *       attributes: function attributes
+ */
+
+/* Returns the version number of the library */
+PNG_EXPORT(1, png_uint_32, png_access_version_number, (void));
+
+/* Tell lib we have already handled the first <num_bytes> magic bytes.
+ * Handling more than 8 bytes from the beginning of the file is an error.
+ */
+PNG_EXPORT(2, void, png_set_sig_bytes, (png_structp png_ptr, int num_bytes));
+
+/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
+ * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
+ * signature, and non-zero otherwise.  Having num_to_check == 0 or
+ * start > 7 will always fail (ie return non-zero).
+ */
+PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start,
+    png_size_t num_to_check));
+
+/* Simple signature checking function.  This is the same as calling
+ * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
+ */
+#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n))
+
+/* Allocate and initialize png_ptr struct for reading, and any other memory. */
+PNG_EXPORTA(4, png_structp, png_create_read_struct,
+    (png_const_charp user_png_ver, png_voidp error_ptr,
+    png_error_ptr error_fn, png_error_ptr warn_fn),
+    PNG_ALLOCATED);
+
+/* Allocate and initialize png_ptr struct for writing, and any other memory */
+PNG_EXPORTA(5, png_structp, png_create_write_struct,
+    (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
+    png_error_ptr warn_fn),
+    PNG_ALLOCATED);
+
+PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size,
+    (png_const_structp png_ptr));
+
+PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structp png_ptr,
+    png_size_t size));
+
+/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp
+ * match up.
+ */
+#ifdef PNG_SETJMP_SUPPORTED
+/* This function returns the jmp_buf built in to *png_ptr.  It must be
+ * supplied with an appropriate 'longjmp' function to use on that jmp_buf
+ * unless the default error function is overridden in which case NULL is
+ * acceptable.  The size of the jmp_buf is checked against the actual size
+ * allocated by the library - the call will return NULL on a mismatch
+ * indicating an ABI mismatch.
+ */
+PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structp png_ptr,
+    png_longjmp_ptr longjmp_fn, size_t jmp_buf_size));
+#  define png_jmpbuf(png_ptr) \
+      (*png_set_longjmp_fn((png_ptr), longjmp, sizeof (jmp_buf)))
+#else
+#  define png_jmpbuf(png_ptr) \
+      (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP)
+#endif
+/* This function should be used by libpng applications in place of
+ * longjmp(png_ptr->jmpbuf, val).  If longjmp_fn() has been set, it
+ * will use it; otherwise it will call PNG_ABORT().  This function was
+ * added in libpng-1.5.0.
+ */
+PNG_EXPORTA(9, void, png_longjmp, (png_structp png_ptr, int val),
+    PNG_NORETURN);
+
+#ifdef PNG_READ_SUPPORTED
+/* Reset the compression stream */
+PNG_EXPORT(10, int, png_reset_zstream, (png_structp png_ptr));
+#endif
+
+/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
+#ifdef PNG_USER_MEM_SUPPORTED
+PNG_EXPORTA(11, png_structp, png_create_read_struct_2,
+    (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
+    png_error_ptr warn_fn,
+    png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
+    PNG_ALLOCATED);
+PNG_EXPORTA(12, png_structp, png_create_write_struct_2,
+    (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
+    png_error_ptr warn_fn,
+    png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
+    PNG_ALLOCATED);
+#endif
+
+/* Write the PNG file signature. */
+PNG_EXPORT(13, void, png_write_sig, (png_structp png_ptr));
+
+/* Write a PNG chunk - size, type, (optional) data, CRC. */
+PNG_EXPORT(14, void, png_write_chunk, (png_structp png_ptr, png_const_bytep
+    chunk_name, png_const_bytep data, png_size_t length));
+
+/* Write the start of a PNG chunk - length and chunk name. */
+PNG_EXPORT(15, void, png_write_chunk_start, (png_structp png_ptr,
+    png_const_bytep chunk_name, png_uint_32 length));
+
+/* Write the data of a PNG chunk started with png_write_chunk_start(). */
+PNG_EXPORT(16, void, png_write_chunk_data, (png_structp png_ptr,
+    png_const_bytep data, png_size_t length));
+
+/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
+PNG_EXPORT(17, void, png_write_chunk_end, (png_structp png_ptr));
+
+/* Allocate and initialize the info structure */
+PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_structp png_ptr),
+    PNG_ALLOCATED);
+
+PNG_EXPORT(19, void, png_info_init_3, (png_infopp info_ptr,
+    png_size_t png_info_struct_size));
+
+/* Writes all the PNG information before the image. */
+PNG_EXPORT(20, void, png_write_info_before_PLTE,
+    (png_structp png_ptr, png_infop info_ptr));
+PNG_EXPORT(21, void, png_write_info,
+    (png_structp png_ptr, png_infop info_ptr));
+
+#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
+/* Read the information before the actual image data. */
+PNG_EXPORT(22, void, png_read_info,
+    (png_structp png_ptr, png_infop info_ptr));
+#endif
+
+#ifdef PNG_TIME_RFC1123_SUPPORTED
+PNG_EXPORT(23, png_const_charp, png_convert_to_rfc1123,
+    (png_structp png_ptr,
+    png_const_timep ptime));
+#endif
+
+#ifdef PNG_CONVERT_tIME_SUPPORTED
+/* Convert from a struct tm to png_time */
+PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime,
+    PNG_CONST struct tm FAR * ttime));
+
+/* Convert from time_t to png_time.  Uses gmtime() */
+PNG_EXPORT(25, void, png_convert_from_time_t,
+    (png_timep ptime, time_t ttime));
+#endif /* PNG_CONVERT_tIME_SUPPORTED */
+
+#ifdef PNG_READ_EXPAND_SUPPORTED
+/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
+PNG_EXPORT(26, void, png_set_expand, (png_structp png_ptr));
+PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structp png_ptr));
+PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structp png_ptr));
+PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_EXPAND_16_SUPPORTED
+/* Expand to 16-bit channels, forces conversion of palette to RGB and expansion
+ * of a tRNS chunk if present.
+ */
+PNG_EXPORT(221, void, png_set_expand_16, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+/* Use blue, green, red order for pixels. */
+PNG_EXPORT(30, void, png_set_bgr, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
+/* Expand the grayscale to 24-bit RGB if necessary. */
+PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
+/* Reduce RGB to grayscale. */
+#define PNG_ERROR_ACTION_NONE  1
+#define PNG_ERROR_ACTION_WARN  2
+#define PNG_ERROR_ACTION_ERROR 3
+#define PNG_RGB_TO_GRAY_DEFAULT (-1)/*for red/green coefficients*/
+
+PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structp png_ptr,
+    int error_action, double red, double green))
+PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structp png_ptr,
+    int error_action, png_fixed_point red, png_fixed_point green))
+
+PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structp
+    png_ptr));
+#endif
+
+#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
+PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth,
+    png_colorp palette));
+#endif
+
+#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
+/* How the alpha channel is interpreted - this affects how the color channels of
+ * a PNG file are returned when an alpha channel, or tRNS chunk in a palette
+ * file, is present.
+ *
+ * This has no effect on the way pixels are written into a PNG output
+ * datastream. The color samples in a PNG datastream are never premultiplied
+ * with the alpha samples.
+ *
+ * The default is to return data according to the PNG specification: the alpha
+ * channel is a linear measure of the contribution of the pixel to the
+ * corresponding composited pixel.  The gamma encoded color channels must be
+ * scaled according to the contribution and to do this it is necessary to undo
+ * the encoding, scale the color values, perform the composition and reencode
+ * the values.  This is the 'PNG' mode.
+ *
+ * The alternative is to 'associate' the alpha with the color information by
+ * storing color channel values that have been scaled by the alpha.  The
+ * advantage is that the color channels can be resampled (the image can be
+ * scaled) in this form.  The disadvantage is that normal practice is to store
+ * linear, not (gamma) encoded, values and this requires 16-bit channels for
+ * still images rather than the 8-bit channels that are just about sufficient if
+ * gamma encoding is used.  In addition all non-transparent pixel values,
+ * including completely opaque ones, must be gamma encoded to produce the final
+ * image.  This is the 'STANDARD', 'ASSOCIATED' or 'PREMULTIPLIED' mode (the
+ * latter being the two common names for associated alpha color channels.)
+ *
+ * Since it is not necessary to perform arithmetic on opaque color values so
+ * long as they are not to be resampled and are in the final color space it is
+ * possible to optimize the handling of alpha by storing the opaque pixels in
+ * the PNG format (adjusted for the output color space) while storing partially
+ * opaque pixels in the standard, linear, format.  The accuracy required for
+ * standard alpha composition is relatively low, because the pixels are
+ * isolated, therefore typically the accuracy loss in storing 8-bit linear
+ * values is acceptable.  (This is not true if the alpha channel is used to
+ * simulate transparency over large areas - use 16 bits or the PNG mode in
+ * this case!)  This is the 'OPTIMIZED' mode.  For this mode a pixel is
+ * treated as opaque only if the alpha value is equal to the maximum value.
+ *
+ * The final choice is to gamma encode the alpha channel as well.  This is
+ * broken because, in practice, no implementation that uses this choice
+ * correctly undoes the encoding before handling alpha composition.  Use this
+ * choice only if other serious errors in the software or hardware you use
+ * mandate it; the typical serious error is for dark halos to appear around
+ * opaque areas of the composited PNG image because of arithmetic overflow.
+ *
+ * The API function png_set_alpha_mode specifies which of these choices to use
+ * with an enumerated 'mode' value and the gamma of the required output:
+ */
+#define PNG_ALPHA_PNG           0 /* according to the PNG standard */
+#define PNG_ALPHA_STANDARD      1 /* according to Porter/Duff */
+#define PNG_ALPHA_ASSOCIATED    1 /* as above; this is the normal practice */
+#define PNG_ALPHA_PREMULTIPLIED 1 /* as above */
+#define PNG_ALPHA_OPTIMIZED     2 /* 'PNG' for opaque pixels, else 'STANDARD' */
+#define PNG_ALPHA_BROKEN        3 /* the alpha channel is gamma encoded */
+
+PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structp png_ptr, int mode,
+    double output_gamma))
+PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structp png_ptr,
+    int mode, png_fixed_point output_gamma))
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED)
+/* The output_gamma value is a screen gamma in libpng terminology: it expresses
+ * how to decode the output values, not how they are encoded.  The values used
+ * correspond to the normal numbers used to describe the overall gamma of a
+ * computer display system; for example 2.2 for an sRGB conformant system.  The
+ * values are scaled by 100000 in the _fixed version of the API (so 220000 for
+ * sRGB.)
+ *
+ * The inverse of the value is always used to provide a default for the PNG file
+ * encoding if it has no gAMA chunk and if png_set_gamma() has not been called
+ * to override the PNG gamma information.
+ *
+ * When the ALPHA_OPTIMIZED mode is selected the output gamma is used to encode
+ * opaque pixels however pixels with lower alpha values are not encoded,
+ * regardless of the output gamma setting.
+ *
+ * When the standard Porter Duff handling is requested with mode 1 the output
+ * encoding is set to be linear and the output_gamma value is only relevant
+ * as a default for input data that has no gamma information.  The linear output
+ * encoding will be overridden if png_set_gamma() is called - the results may be
+ * highly unexpected!
+ *
+ * The following numbers are derived from the sRGB standard and the research
+ * behind it.  sRGB is defined to be approximated by a PNG gAMA chunk value of
+ * 0.45455 (1/2.2) for PNG.  The value implicitly includes any viewing
+ * correction required to take account of any differences in the color
+ * environment of the original scene and the intended display environment; the
+ * value expresses how to *decode* the image for display, not how the original
+ * data was *encoded*.
+ *
+ * sRGB provides a peg for the PNG standard by defining a viewing environment.
+ * sRGB itself, and earlier TV standards, actually use a more complex transform
+ * (a linear portion then a gamma 2.4 power law) than PNG can express.  (PNG is
+ * limited to simple power laws.)  By saying that an image for direct display on
+ * an sRGB conformant system should be stored with a gAMA chunk value of 45455
+ * (11.3.3.2 and 11.3.3.5 of the ISO PNG specification) the PNG specification
+ * makes it possible to derive values for other display systems and
+ * environments.
+ *
+ * The Mac value is deduced from the sRGB based on an assumption that the actual
+ * extra viewing correction used in early Mac display systems was implemented as
+ * a power 1.45 lookup table.
+ *
+ * Any system where a programmable lookup table is used or where the behavior of
+ * the final display device characteristics can be changed requires system
+ * specific code to obtain the current characteristic.  However this can be
+ * difficult and most PNG gamma correction only requires an approximate value.
+ *
+ * By default, if png_set_alpha_mode() is not called, libpng assumes that all
+ * values are unencoded, linear, values and that the output device also has a
+ * linear characteristic.  This is only very rarely correct - it is invariably
+ * better to call png_set_alpha_mode() with PNG_DEFAULT_sRGB than rely on the
+ * default if you don't know what the right answer is!
+ *
+ * The special value PNG_GAMMA_MAC_18 indicates an older Mac system (pre Mac OS
+ * 10.6) which used a correction table to implement a somewhat lower gamma on an
+ * otherwise sRGB system.
+ *
+ * Both these values are reserved (not simple gamma values) in order to allow
+ * more precise correction internally in the future.
+ *
+ * NOTE: the following values can be passed to either the fixed or floating
+ * point APIs, but the floating point API will also accept floating point
+ * values.
+ */
+#define PNG_DEFAULT_sRGB -1       /* sRGB gamma and color space */
+#define PNG_GAMMA_MAC_18 -2       /* Old Mac '1.8' gamma and color space */
+#define PNG_GAMMA_sRGB   220000   /* Television standards--matches sRGB gamma */
+#define PNG_GAMMA_LINEAR PNG_FP_1 /* Linear */
+#endif
+
+/* The following are examples of calls to png_set_alpha_mode to achieve the
+ * required overall gamma correction and, where necessary, alpha
+ * premultiplication.
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
+ *    This is the default libpng handling of the alpha channel - it is not
+ *    pre-multiplied into the color components.  In addition the call states
+ *    that the output is for a sRGB system and causes all PNG files without gAMA
+ *    chunks to be assumed to be encoded using sRGB.
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
+ *    In this case the output is assumed to be something like an sRGB conformant
+ *    display preceeded by a power-law lookup table of power 1.45.  This is how
+ *    early Mac systems behaved.
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR);
+ *    This is the classic Jim Blinn approach and will work in academic
+ *    environments where everything is done by the book.  It has the shortcoming
+ *    of assuming that input PNG data with no gamma information is linear - this
+ *    is unlikely to be correct unless the PNG files where generated locally.
+ *    Most of the time the output precision will be so low as to show
+ *    significant banding in dark areas of the image.
+ *
+ * png_set_expand_16(pp);
+ * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_DEFAULT_sRGB);
+ *    This is a somewhat more realistic Jim Blinn inspired approach.  PNG files
+ *    are assumed to have the sRGB encoding if not marked with a gamma value and
+ *    the output is always 16 bits per component.  This permits accurate scaling
+ *    and processing of the data.  If you know that your input PNG files were
+ *    generated locally you might need to replace PNG_DEFAULT_sRGB with the
+ *    correct value for your system.
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_OPTIMIZED, PNG_DEFAULT_sRGB);
+ *    If you just need to composite the PNG image onto an existing background
+ *    and if you control the code that does this you can use the optimization
+ *    setting.  In this case you just copy completely opaque pixels to the
+ *    output.  For pixels that are not completely transparent (you just skip
+ *    those) you do the composition math using png_composite or png_composite_16
+ *    below then encode the resultant 8-bit or 16-bit values to match the output
+ *    encoding.
+ *
+ * Other cases
+ *    If neither the PNG nor the standard linear encoding work for you because
+ *    of the software or hardware you use then you have a big problem.  The PNG
+ *    case will probably result in halos around the image.  The linear encoding
+ *    will probably result in a washed out, too bright, image (it's actually too
+ *    contrasty.)  Try the ALPHA_OPTIMIZED mode above - this will probably
+ *    substantially reduce the halos.  Alternatively try:
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_BROKEN, PNG_DEFAULT_sRGB);
+ *    This option will also reduce the halos, but there will be slight dark
+ *    halos round the opaque parts of the image where the background is light.
+ *    In the OPTIMIZED mode the halos will be light halos where the background
+ *    is dark.  Take your pick - the halos are unavoidable unless you can get
+ *    your hardware/software fixed!  (The OPTIMIZED approach is slightly
+ *    faster.)
+ *
+ * When the default gamma of PNG files doesn't match the output gamma.
+ *    If you have PNG files with no gamma information png_set_alpha_mode allows
+ *    you to provide a default gamma, but it also sets the ouput gamma to the
+ *    matching value.  If you know your PNG files have a gamma that doesn't
+ *    match the output you can take advantage of the fact that
+ *    png_set_alpha_mode always sets the output gamma but only sets the PNG
+ *    default if it is not already set:
+ *
+ * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB);
+ * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC);
+ *    The first call sets both the default and the output gamma values, the
+ *    second call overrides the output gamma without changing the default.  This
+ *    is easier than achieving the same effect with png_set_gamma.  You must use
+ *    PNG_ALPHA_PNG for the first call - internal checking in png_set_alpha will
+ *    fire if more than one call to png_set_alpha_mode and png_set_background is
+ *    made in the same read operation, however multiple calls with PNG_ALPHA_PNG
+ *    are ignored.
+ */
+
+#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
+PNG_EXPORT(36, void, png_set_strip_alpha, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+PNG_EXPORT(37, void, png_set_swap_alpha, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+PNG_EXPORT(38, void, png_set_invert_alpha, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
+PNG_EXPORT(39, void, png_set_filler, (png_structp png_ptr, png_uint_32 filler,
+    int flags));
+/* The values of the PNG_FILLER_ defines should NOT be changed */
+#  define PNG_FILLER_BEFORE 0
+#  define PNG_FILLER_AFTER 1
+/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
+PNG_EXPORT(40, void, png_set_add_alpha,
+    (png_structp png_ptr, png_uint_32 filler,
+    int flags));
+#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+/* Swap bytes in 16-bit depth files. */
+PNG_EXPORT(41, void, png_set_swap, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
+/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
+PNG_EXPORT(42, void, png_set_packing, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \
+    defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+/* Swap packing order of pixels in bytes. */
+PNG_EXPORT(43, void, png_set_packswap, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+/* Converts files to legal bit depths. */
+PNG_EXPORT(44, void, png_set_shift, (png_structp png_ptr, png_const_color_8p
+    true_bits));
+#endif
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
+    defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* Have the code handle the interlacing.  Returns the number of passes.
+ * MUST be called before png_read_update_info or png_start_read_image,
+ * otherwise it will not have the desired effect.  Note that it is still
+ * necessary to call png_read_row or png_read_rows png_get_image_height
+ * times for each pass.
+*/
+PNG_EXPORT(45, int, png_set_interlace_handling, (png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+/* Invert monochrome files */
+PNG_EXPORT(46, void, png_set_invert_mono, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_BACKGROUND_SUPPORTED
+/* Handle alpha and tRNS by replacing with a background color.  Prior to
+ * libpng-1.5.4 this API must not be called before the PNG file header has been
+ * read.  Doing so will result in unexpected behavior and possible warnings or
+ * errors if the PNG file contains a bKGD chunk.
+ */
+PNG_FP_EXPORT(47, void, png_set_background, (png_structp png_ptr,
+    png_const_color_16p background_color, int background_gamma_code,
+    int need_expand, double background_gamma))
+PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structp png_ptr,
+    png_const_color_16p background_color, int background_gamma_code,
+    int need_expand, png_fixed_point background_gamma))
+#endif
+#ifdef PNG_READ_BACKGROUND_SUPPORTED
+#  define PNG_BACKGROUND_GAMMA_UNKNOWN 0
+#  define PNG_BACKGROUND_GAMMA_SCREEN  1
+#  define PNG_BACKGROUND_GAMMA_FILE    2
+#  define PNG_BACKGROUND_GAMMA_UNIQUE  3
+#endif
+
+#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
+/* Scale a 16-bit depth file down to 8-bit, accurately. */
+PNG_EXPORT(229, void, png_set_scale_16, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
+#define PNG_READ_16_TO_8 SUPPORTED /* Name prior to 1.5.4 */
+/* Strip the second byte of information from a 16-bit depth file. */
+PNG_EXPORT(48, void, png_set_strip_16, (png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_QUANTIZE_SUPPORTED
+/* Turn on quantizing, and reduce the palette to the number of colors
+ * available.
+ */
+PNG_EXPORT(49, void, png_set_quantize,
+    (png_structp png_ptr, png_colorp palette,
+    int num_palette, int maximum_colors, png_const_uint_16p histogram,
+    int full_quantize));
+#endif
+
+#ifdef PNG_READ_GAMMA_SUPPORTED
+/* The threshold on gamma processing is configurable but hard-wired into the
+ * library.  The following is the floating point variant.
+ */
+#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001)
+
+/* Handle gamma correction. Screen_gamma=(display_exponent).
+ * NOTE: this API simply sets the screen and file gamma values. It will
+ * therefore override the value for gamma in a PNG file if it is called after
+ * the file header has been read - use with care  - call before reading the PNG
+ * file for best results!
+ *
+ * These routines accept the same gamma values as png_set_alpha_mode (described
+ * above).  The PNG_GAMMA_ defines and PNG_DEFAULT_sRGB can be passed to either
+ * API (floating point or fixed.)  Notice, however, that the 'file_gamma' value
+ * is the inverse of a 'screen gamma' value.
+ */
+PNG_FP_EXPORT(50, void, png_set_gamma,
+    (png_structp png_ptr, double screen_gamma,
+    double override_file_gamma))
+PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structp png_ptr,
+    png_fixed_point screen_gamma, png_fixed_point override_file_gamma))
+#endif
+
+#ifdef PNG_WRITE_FLUSH_SUPPORTED
+/* Set how many lines between output flushes - 0 for no flushing */
+PNG_EXPORT(51, void, png_set_flush, (png_structp png_ptr, int nrows));
+/* Flush the current PNG output buffer */
+PNG_EXPORT(52, void, png_write_flush, (png_structp png_ptr));
+#endif
+
+/* Optional update palette with requested transformations */
+PNG_EXPORT(53, void, png_start_read_image, (png_structp png_ptr));
+
+/* Optional call to update the users info structure */
+PNG_EXPORT(54, void, png_read_update_info,
+    (png_structp png_ptr, png_infop info_ptr));
+
+#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
+/* Read one or more rows of image data. */
+PNG_EXPORT(55, void, png_read_rows, (png_structp png_ptr, png_bytepp row,
+    png_bytepp display_row, png_uint_32 num_rows));
+#endif
+
+#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
+/* Read a row of data. */
+PNG_EXPORT(56, void, png_read_row, (png_structp png_ptr, png_bytep row,
+    png_bytep display_row));
+#endif
+
+#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
+/* Read the whole image into memory at once. */
+PNG_EXPORT(57, void, png_read_image, (png_structp png_ptr, png_bytepp image));
+#endif
+
+/* Write a row of image data */
+PNG_EXPORT(58, void, png_write_row,
+    (png_structp png_ptr, png_const_bytep row));
+
+/* Write a few rows of image data: (*row) is not written; however, the type
+ * is declared as writeable to maintain compatibility with previous versions
+ * of libpng and to allow the 'display_row' array from read_rows to be passed
+ * unchanged to write_rows.
+ */
+PNG_EXPORT(59, void, png_write_rows, (png_structp png_ptr, png_bytepp row,
+    png_uint_32 num_rows));
+
+/* Write the image data */
+PNG_EXPORT(60, void, png_write_image,
+    (png_structp png_ptr, png_bytepp image));
+
+/* Write the end of the PNG file. */
+PNG_EXPORT(61, void, png_write_end,
+    (png_structp png_ptr, png_infop info_ptr));
+
+#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
+/* Read the end of the PNG file. */
+PNG_EXPORT(62, void, png_read_end, (png_structp png_ptr, png_infop info_ptr));
+#endif
+
+/* Free any memory associated with the png_info_struct */
+PNG_EXPORT(63, void, png_destroy_info_struct, (png_structp png_ptr,
+    png_infopp info_ptr_ptr));
+
+/* Free any memory associated with the png_struct and the png_info_structs */
+PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr,
+    png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
+
+/* Free any memory associated with the png_struct and the png_info_structs */
+PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr,
+    png_infopp info_ptr_ptr));
+
+/* Set the libpng method of handling chunk CRC errors */
+PNG_EXPORT(66, void, png_set_crc_action,
+    (png_structp png_ptr, int crit_action, int ancil_action));
+
+/* Values for png_set_crc_action() say how to handle CRC errors in
+ * ancillary and critical chunks, and whether to use the data contained
+ * therein.  Note that it is impossible to "discard" data in a critical
+ * chunk.  For versions prior to 0.90, the action was always error/quit,
+ * whereas in version 0.90 and later, the action for CRC errors in ancillary
+ * chunks is warn/discard.  These values should NOT be changed.
+ *
+ *      value                       action:critical     action:ancillary
+ */
+#define PNG_CRC_DEFAULT       0  /* error/quit          warn/discard data */
+#define PNG_CRC_ERROR_QUIT    1  /* error/quit          error/quit        */
+#define PNG_CRC_WARN_DISCARD  2  /* (INVALID)           warn/discard data */
+#define PNG_CRC_WARN_USE      3  /* warn/use data       warn/use data     */
+#define PNG_CRC_QUIET_USE     4  /* quiet/use data      quiet/use data    */
+#define PNG_CRC_NO_CHANGE     5  /* use current value   use current value */
+
+/* These functions give the user control over the scan-line filtering in
+ * libpng and the compression methods used by zlib.  These functions are
+ * mainly useful for testing, as the defaults should work with most users.
+ * Those users who are tight on memory or want faster performance at the
+ * expense of compression can modify them.  See the compression library
+ * header file (zlib.h) for an explination of the compression functions.
+ */
+
+/* Set the filtering method(s) used by libpng.  Currently, the only valid
+ * value for "method" is 0.
+ */
+PNG_EXPORT(67, void, png_set_filter,
+    (png_structp png_ptr, int method, int filters));
+
+/* Flags for png_set_filter() to say which filters to use.  The flags
+ * are chosen so that they don't conflict with real filter types
+ * below, in case they are supplied instead of the #defined constants.
+ * These values should NOT be changed.
+ */
+#define PNG_NO_FILTERS     0x00
+#define PNG_FILTER_NONE    0x08
+#define PNG_FILTER_SUB     0x10
+#define PNG_FILTER_UP      0x20
+#define PNG_FILTER_AVG     0x40
+#define PNG_FILTER_PAETH   0x80
+#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
+                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
+
+/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
+ * These defines should NOT be changed.
+ */
+#define PNG_FILTER_VALUE_NONE  0
+#define PNG_FILTER_VALUE_SUB   1
+#define PNG_FILTER_VALUE_UP    2
+#define PNG_FILTER_VALUE_AVG   3
+#define PNG_FILTER_VALUE_PAETH 4
+#define PNG_FILTER_VALUE_LAST  5
+
+#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* EXPERIMENTAL */
+/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
+ * defines, either the default (minimum-sum-of-absolute-differences), or
+ * the experimental method (weighted-minimum-sum-of-absolute-differences).
+ *
+ * Weights are factors >= 1.0, indicating how important it is to keep the
+ * filter type consistent between rows.  Larger numbers mean the current
+ * filter is that many times as likely to be the same as the "num_weights"
+ * previous filters.  This is cumulative for each previous row with a weight.
+ * There needs to be "num_weights" values in "filter_weights", or it can be
+ * NULL if the weights aren't being specified.  Weights have no influence on
+ * the selection of the first row filter.  Well chosen weights can (in theory)
+ * improve the compression for a given image.
+ *
+ * Costs are factors >= 1.0 indicating the relative decoding costs of a
+ * filter type.  Higher costs indicate more decoding expense, and are
+ * therefore less likely to be selected over a filter with lower computational
+ * costs.  There needs to be a value in "filter_costs" for each valid filter
+ * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
+ * setting the costs.  Costs try to improve the speed of decompression without
+ * unduly increasing the compressed image size.
+ *
+ * A negative weight or cost indicates the default value is to be used, and
+ * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
+ * The default values for both weights and costs are currently 1.0, but may
+ * change if good general weighting/cost heuristics can be found.  If both
+ * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
+ * to the UNWEIGHTED method, but with added encoding time/computation.
+ */
+PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structp png_ptr,
+    int heuristic_method, int num_weights, png_const_doublep filter_weights,
+    png_const_doublep filter_costs))
+PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed,
+    (png_structp png_ptr,
+    int heuristic_method, int num_weights, png_const_fixed_point_p
+    filter_weights, png_const_fixed_point_p filter_costs))
+#endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
+
+/* Heuristic used for row filter selection.  These defines should NOT be
+ * changed.
+ */
+#define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
+#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
+#define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
+#define PNG_FILTER_HEURISTIC_LAST       3  /* Not a valid value */
+
+#ifdef PNG_WRITE_SUPPORTED
+/* Set the library compression level.  Currently, valid values range from
+ * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
+ * (0 - no compression, 9 - "maximal" compression).  Note that tests have
+ * shown that zlib compression levels 3-6 usually perform as well as level 9
+ * for PNG images, and do considerably fewer caclulations.  In the future,
+ * these values may not correspond directly to the zlib compression levels.
+ */
+PNG_EXPORT(69, void, png_set_compression_level,
+    (png_structp png_ptr, int level));
+
+PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structp png_ptr,
+    int mem_level));
+
+PNG_EXPORT(71, void, png_set_compression_strategy, (png_structp png_ptr,
+    int strategy));
+
+/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
+ * smaller value of window_bits if it can do so safely.
+ */
+PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structp png_ptr,
+    int window_bits));
+
+PNG_EXPORT(73, void, png_set_compression_method, (png_structp png_ptr,
+    int method));
+#endif
+
+#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
+/* Also set zlib parameters for compressing non-IDAT chunks */
+PNG_EXPORT(222, void, png_set_text_compression_level,
+    (png_structp png_ptr, int level));
+
+PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structp png_ptr,
+    int mem_level));
+
+PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structp png_ptr,
+    int strategy));
+
+/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
+ * smaller value of window_bits if it can do so safely.
+ */
+PNG_EXPORT(225, void, png_set_text_compression_window_bits, (png_structp
+    png_ptr, int window_bits));
+
+PNG_EXPORT(226, void, png_set_text_compression_method, (png_structp png_ptr,
+    int method));
+#endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */
+
+/* These next functions are called for input/output, memory, and error
+ * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
+ * and call standard C I/O routines such as fread(), fwrite(), and
+ * fprintf().  These functions can be made to use other I/O routines
+ * at run time for those applications that need to handle I/O in a
+ * different manner by calling png_set_???_fn().  See libpng-manual.txt for
+ * more information.
+ */
+
+#ifdef PNG_STDIO_SUPPORTED
+/* Initialize the input/output for the PNG file to the default functions. */
+PNG_EXPORT(74, void, png_init_io, (png_structp png_ptr, png_FILE_p fp));
+#endif
+
+/* Replace the (error and abort), and warning functions with user
+ * supplied functions.  If no messages are to be printed you must still
+ * write and use replacement functions. The replacement error_fn should
+ * still do a longjmp to the last setjmp location if you are using this
+ * method of error handling.  If error_fn or warning_fn is NULL, the
+ * default function will be used.
+ */
+
+PNG_EXPORT(75, void, png_set_error_fn,
+    (png_structp png_ptr, png_voidp error_ptr,
+    png_error_ptr error_fn, png_error_ptr warning_fn));
+
+/* Return the user pointer associated with the error functions */
+PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structp png_ptr));
+
+/* Replace the default data output functions with a user supplied one(s).
+ * If buffered output is not used, then output_flush_fn can be set to NULL.
+ * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
+ * output_flush_fn will be ignored (and thus can be NULL).
+ * It is probably a mistake to use NULL for output_flush_fn if
+ * write_data_fn is not also NULL unless you have built libpng with
+ * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's
+ * default flush function, which uses the standard *FILE structure, will
+ * be used.
+ */
+PNG_EXPORT(77, void, png_set_write_fn, (png_structp png_ptr, png_voidp io_ptr,
+    png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
+
+/* Replace the default data input function with a user supplied one. */
+PNG_EXPORT(78, void, png_set_read_fn, (png_structp png_ptr, png_voidp io_ptr,
+    png_rw_ptr read_data_fn));
+
+/* Return the user pointer associated with the I/O functions */
+PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_structp png_ptr));
+
+PNG_EXPORT(80, void, png_set_read_status_fn, (png_structp png_ptr,
+    png_read_status_ptr read_row_fn));
+
+PNG_EXPORT(81, void, png_set_write_status_fn, (png_structp png_ptr,
+    png_write_status_ptr write_row_fn));
+
+#ifdef PNG_USER_MEM_SUPPORTED
+/* Replace the default memory allocation functions with user supplied one(s). */
+PNG_EXPORT(82, void, png_set_mem_fn, (png_structp png_ptr, png_voidp mem_ptr,
+    png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+/* Return the user pointer associated with the memory functions */
+PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
+PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structp png_ptr,
+    png_user_transform_ptr read_user_transform_fn));
+#endif
+
+#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
+PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structp png_ptr,
+    png_user_transform_ptr write_user_transform_fn));
+#endif
+
+#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
+PNG_EXPORT(86, void, png_set_user_transform_info, (png_structp png_ptr,
+    png_voidp user_transform_ptr, int user_transform_depth,
+    int user_transform_channels));
+/* Return the user pointer associated with the user transform functions */
+PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr,
+    (png_const_structp png_ptr));
+#endif
+
+#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
+/* Return information about the row currently being processed.  Note that these
+ * APIs do not fail but will return unexpected results if called outside a user
+ * transform callback.  Also note that when transforming an interlaced image the
+ * row number is the row number within the sub-image of the interlace pass, so
+ * the value will increase to the height of the sub-image (not the full image)
+ * then reset to 0 for the next pass.
+ *
+ * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
+ * find the output pixel (x,y) given an interlaced sub-image pixel
+ * (row,col,pass).  (See below for these macros.)
+ */
+PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structp));
+PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structp));
+#endif
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structp png_ptr,
+    png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
+PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structp png_ptr));
+#endif
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+/* Sets the function callbacks for the push reader, and a pointer to a
+ * user-defined structure available to the callback functions.
+ */
+PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structp png_ptr,
+    png_voidp progressive_ptr, png_progressive_info_ptr info_fn,
+    png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn));
+
+/* Returns the user pointer associated with the push read functions */
+PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, (png_const_structp png_ptr));
+
+/* Function to be called when data becomes available */
+PNG_EXPORT(92, void, png_process_data,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_bytep buffer, png_size_t buffer_size));
+
+/* A function which may be called *only* within png_process_data to stop the
+ * processing of any more data.  The function returns the number of bytes
+ * remaining, excluding any that libpng has cached internally.  A subsequent
+ * call to png_process_data must supply these bytes again.  If the argument
+ * 'save' is set to true the routine will first save all the pending data and
+ * will always return 0.
+ */
+PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structp, int save));
+
+/* A function which may be called *only* outside (after) a call to
+ * png_process_data.  It returns the number of bytes of data to skip in the
+ * input.  Normally it will return 0, but if it returns a non-zero value the
+ * application must skip than number of bytes of input data and pass the
+ * following data to the next call to png_process_data.
+ */
+PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structp));
+
+#ifdef PNG_READ_INTERLACING_SUPPORTED
+/* Function that combines rows.  'new_row' is a flag that should come from
+ * the callback and be non-NULL if anything needs to be done; the library
+ * stores its own version of the new data internally and ignores the passed
+ * in value.
+ */
+PNG_EXPORT(93, void, png_progressive_combine_row, (png_structp png_ptr,
+    png_bytep old_row, png_const_bytep new_row));
+#endif /* PNG_READ_INTERLACING_SUPPORTED */
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+PNG_EXPORTA(94, png_voidp, png_malloc,
+    (png_structp png_ptr, png_alloc_size_t size),
+    PNG_ALLOCATED);
+/* Added at libpng version 1.4.0 */
+PNG_EXPORTA(95, png_voidp, png_calloc,
+    (png_structp png_ptr, png_alloc_size_t size),
+    PNG_ALLOCATED);
+
+/* Added at libpng version 1.2.4 */
+PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_structp png_ptr,
+    png_alloc_size_t size), PNG_ALLOCATED);
+
+/* Frees a pointer allocated by png_malloc() */
+PNG_EXPORT(97, void, png_free, (png_structp png_ptr, png_voidp ptr));
+
+/* Free data that was allocated internally */
+PNG_EXPORT(98, void, png_free_data,
+    (png_structp png_ptr, png_infop info_ptr, png_uint_32 free_me, int num));
+
+/* Reassign responsibility for freeing existing data, whether allocated
+ * by libpng or by the application */
+PNG_EXPORT(99, void, png_data_freer,
+    (png_structp png_ptr, png_infop info_ptr, int freer, png_uint_32 mask));
+
+/* Assignments for png_data_freer */
+#define PNG_DESTROY_WILL_FREE_DATA 1
+#define PNG_SET_WILL_FREE_DATA 1
+#define PNG_USER_WILL_FREE_DATA 2
+/* Flags for png_ptr->free_me and info_ptr->free_me */
+#define PNG_FREE_HIST 0x0008
+#define PNG_FREE_ICCP 0x0010
+#define PNG_FREE_SPLT 0x0020
+#define PNG_FREE_ROWS 0x0040
+#define PNG_FREE_PCAL 0x0080
+#define PNG_FREE_SCAL 0x0100
+#define PNG_FREE_UNKN 0x0200
+#define PNG_FREE_LIST 0x0400
+#define PNG_FREE_PLTE 0x1000
+#define PNG_FREE_TRNS 0x2000
+#define PNG_FREE_TEXT 0x4000
+#define PNG_FREE_ALL  0x7fff
+#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
+
+#ifdef PNG_USER_MEM_SUPPORTED
+PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_structp png_ptr,
+    png_alloc_size_t size), PNG_ALLOCATED);
+PNG_EXPORT(101, void, png_free_default, (png_structp png_ptr, png_voidp ptr));
+#endif
+
+#ifdef PNG_ERROR_TEXT_SUPPORTED
+/* Fatal error in PNG image of libpng - can't continue */
+PNG_EXPORTA(102, void, png_error,
+    (png_structp png_ptr, png_const_charp error_message),
+    PNG_NORETURN);
+
+/* The same, but the chunk name is prepended to the error string. */
+PNG_EXPORTA(103, void, png_chunk_error, (png_structp png_ptr,
+    png_const_charp error_message), PNG_NORETURN);
+
+#else
+/* Fatal error in PNG image of libpng - can't continue */
+PNG_EXPORTA(104, void, png_err, (png_structp png_ptr), PNG_NORETURN);
+#endif
+
+#ifdef PNG_WARNINGS_SUPPORTED
+/* Non-fatal error in libpng.  Can continue, but may have a problem. */
+PNG_EXPORT(105, void, png_warning, (png_structp png_ptr,
+    png_const_charp warning_message));
+
+/* Non-fatal error in libpng, chunk name is prepended to message. */
+PNG_EXPORT(106, void, png_chunk_warning, (png_structp png_ptr,
+    png_const_charp warning_message));
+#endif
+
+#ifdef PNG_BENIGN_ERRORS_SUPPORTED
+/* Benign error in libpng.  Can continue, but may have a problem.
+ * User can choose whether to handle as a fatal error or as a warning. */
+#  undef png_benign_error
+PNG_EXPORT(107, void, png_benign_error, (png_structp png_ptr,
+    png_const_charp warning_message));
+
+/* Same, chunk name is prepended to message. */
+#  undef png_chunk_benign_error
+PNG_EXPORT(108, void, png_chunk_benign_error, (png_structp png_ptr,
+    png_const_charp warning_message));
+
+PNG_EXPORT(109, void, png_set_benign_errors,
+    (png_structp png_ptr, int allowed));
+#else
+#  ifdef PNG_ALLOW_BENIGN_ERRORS
+#    define png_benign_error png_warning
+#    define png_chunk_benign_error png_chunk_warning
+#  else
+#    define png_benign_error png_error
+#    define png_chunk_benign_error png_chunk_error
+#  endif
+#endif
+
+/* The png_set_<chunk> functions are for storing values in the png_info_struct.
+ * Similarly, the png_get_<chunk> calls are used to read values from the
+ * png_info_struct, either storing the parameters in the passed variables, or
+ * setting pointers into the png_info_struct where the data is stored.  The
+ * png_get_<chunk> functions return a non-zero value if the data was available
+ * in info_ptr, or return zero and do not change any of the parameters if the
+ * data was not available.
+ *
+ * These functions should be used instead of directly accessing png_info
+ * to avoid problems with future changes in the size and internal layout of
+ * png_info_struct.
+ */
+/* Returns "flag" if chunk data is valid in info_ptr. */
+PNG_EXPORT(110, png_uint_32, png_get_valid,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_uint_32 flag));
+
+/* Returns number of bytes needed to hold a transformed row. */
+PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+#ifdef PNG_INFO_IMAGE_SUPPORTED
+/* Returns row_pointers, which is an array of pointers to scanlines that was
+ * returned from png_read_png().
+ */
+PNG_EXPORT(112, png_bytepp, png_get_rows,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+/* Set row_pointers, which is an array of pointers to scanlines for use
+ * by png_write_png().
+ */
+PNG_EXPORT(113, void, png_set_rows, (png_structp png_ptr,
+    png_infop info_ptr, png_bytepp row_pointers));
+#endif
+
+/* Returns number of color channels in image. */
+PNG_EXPORT(114, png_byte, png_get_channels,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+#ifdef PNG_EASY_ACCESS_SUPPORTED
+/* Returns image width in pixels. */
+PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image height in pixels. */
+PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image bit_depth. */
+PNG_EXPORT(117, png_byte, png_get_bit_depth,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+/* Returns image color_type. */
+PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image filter_type. */
+PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image interlace_type. */
+PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image compression_type. */
+PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+
+/* Returns image resolution in pixels per meter, from pHYs chunk data. */
+PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+/* Returns pixel aspect ratio, computed from pHYs chunk data.  */
+PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio,
+    (png_const_structp png_ptr, png_const_infop info_ptr))
+PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed,
+    (png_const_structp png_ptr, png_const_infop info_ptr))
+
+/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
+PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(128, png_int_32, png_get_x_offset_microns,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(129, png_int_32, png_get_y_offset_microns,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+#endif /* PNG_EASY_ACCESS_SUPPORTED */
+
+/* Returns pointer to signature string read from PNG header */
+PNG_EXPORT(130, png_const_bytep, png_get_signature,
+    (png_const_structp png_ptr, png_infop info_ptr));
+
+#ifdef PNG_bKGD_SUPPORTED
+PNG_EXPORT(131, png_uint_32, png_get_bKGD,
+    (png_const_structp png_ptr, png_infop info_ptr,
+    png_color_16p *background));
+#endif
+
+#ifdef PNG_bKGD_SUPPORTED
+PNG_EXPORT(132, void, png_set_bKGD, (png_structp png_ptr, png_infop info_ptr,
+    png_const_color_16p background));
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structp png_ptr,
+   png_const_infop info_ptr, double *white_x, double *white_y, double *red_x,
+    double *red_y, double *green_x, double *green_y, double *blue_x,
+    double *blue_y))
+PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_structp png_ptr,
+    png_const_infop info_ptr, double *red_X, double *red_Y, double *red_Z,
+    double *green_X, double *green_Y, double *green_Z, double *blue_X,
+    double *blue_Y, double *blue_Z))
+#ifdef PNG_FIXED_POINT_SUPPORTED /* Otherwise not implemented */
+PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed,
+    (png_const_structp png_ptr,
+    png_const_infop info_ptr, png_fixed_point *int_white_x,
+    png_fixed_point *int_white_y, png_fixed_point *int_red_x,
+    png_fixed_point *int_red_y, png_fixed_point *int_green_x,
+    png_fixed_point *int_green_y, png_fixed_point *int_blue_x,
+    png_fixed_point *int_blue_y))
+#endif
+PNG_FIXED_EXPORT(231, png_uint_32, png_get_cHRM_XYZ_fixed,
+    (png_structp png_ptr, png_const_infop info_ptr,
+    png_fixed_point *int_red_X, png_fixed_point *int_red_Y,
+    png_fixed_point *int_red_Z, png_fixed_point *int_green_X,
+    png_fixed_point *int_green_Y, png_fixed_point *int_green_Z,
+    png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y,
+    png_fixed_point *int_blue_Z))
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+PNG_FP_EXPORT(135, void, png_set_cHRM,
+    (png_structp png_ptr, png_infop info_ptr,
+    double white_x, double white_y, double red_x, double red_y, double green_x,
+    double green_y, double blue_x, double blue_y))
+PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_structp png_ptr,
+    png_infop info_ptr, double red_X, double red_Y, double red_Z,
+    double green_X, double green_Y, double green_Z, double blue_X,
+    double blue_Y, double blue_Z))
+PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_structp png_ptr,
+    png_infop info_ptr, png_fixed_point int_white_x,
+    png_fixed_point int_white_y, png_fixed_point int_red_x,
+    png_fixed_point int_red_y, png_fixed_point int_green_x,
+    png_fixed_point int_green_y, png_fixed_point int_blue_x,
+    png_fixed_point int_blue_y))
+PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_structp png_ptr,
+    png_infop info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y,
+    png_fixed_point int_red_Z, png_fixed_point int_green_X,
+    png_fixed_point int_green_Y, png_fixed_point int_green_Z,
+    png_fixed_point int_blue_X, png_fixed_point int_blue_Y,
+    png_fixed_point int_blue_Z))
+#endif
+
+#ifdef PNG_gAMA_SUPPORTED
+PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    double *file_gamma))
+PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_fixed_point *int_file_gamma))
+#endif
+
+#ifdef PNG_gAMA_SUPPORTED
+PNG_FP_EXPORT(139, void, png_set_gAMA, (png_structp png_ptr,
+    png_infop info_ptr, double file_gamma))
+PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_structp png_ptr,
+    png_infop info_ptr, png_fixed_point int_file_gamma))
+#endif
+
+#ifdef PNG_hIST_SUPPORTED
+PNG_EXPORT(141, png_uint_32, png_get_hIST,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_uint_16p *hist));
+#endif
+
+#ifdef PNG_hIST_SUPPORTED
+PNG_EXPORT(142, void, png_set_hIST, (png_structp png_ptr,
+    png_infop info_ptr, png_const_uint_16p hist));
+#endif
+
+PNG_EXPORT(143, png_uint_32, png_get_IHDR,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type,
+    int *interlace_method, int *compression_method, int *filter_method));
+
+PNG_EXPORT(144, void, png_set_IHDR,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 width, png_uint_32 height, int bit_depth, int color_type,
+    int interlace_method, int compression_method, int filter_method));
+
+#ifdef PNG_oFFs_SUPPORTED
+PNG_EXPORT(145, png_uint_32, png_get_oFFs,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type));
+#endif
+
+#ifdef PNG_oFFs_SUPPORTED
+PNG_EXPORT(146, void, png_set_oFFs,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_int_32 offset_x, png_int_32 offset_y, int unit_type));
+#endif
+
+#ifdef PNG_pCAL_SUPPORTED
+PNG_EXPORT(147, png_uint_32, png_get_pCAL,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type,
+    int *nparams,
+    png_charp *units, png_charpp *params));
+#endif
+
+#ifdef PNG_pCAL_SUPPORTED
+PNG_EXPORT(148, void, png_set_pCAL, (png_structp png_ptr,
+    png_infop info_ptr,
+    png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type,
+    int nparams, png_const_charp units, png_charpp params));
+#endif
+
+#ifdef PNG_pHYs_SUPPORTED
+PNG_EXPORT(149, png_uint_32, png_get_pHYs,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
+#endif
+
+#ifdef PNG_pHYs_SUPPORTED
+PNG_EXPORT(150, void, png_set_pHYs,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+#endif
+
+PNG_EXPORT(151, png_uint_32, png_get_PLTE,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_colorp *palette, int *num_palette));
+
+PNG_EXPORT(152, void, png_set_PLTE,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_const_colorp palette, int num_palette));
+
+#ifdef PNG_sBIT_SUPPORTED
+PNG_EXPORT(153, png_uint_32, png_get_sBIT,
+    (png_const_structp png_ptr, png_infop info_ptr,
+    png_color_8p *sig_bit));
+#endif
+
+#ifdef PNG_sBIT_SUPPORTED
+PNG_EXPORT(154, void, png_set_sBIT,
+    (png_structp png_ptr, png_infop info_ptr, png_const_color_8p sig_bit));
+#endif
+
+#ifdef PNG_sRGB_SUPPORTED
+PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structp png_ptr,
+    png_const_infop info_ptr, int *file_srgb_intent));
+#endif
+
+#ifdef PNG_sRGB_SUPPORTED
+PNG_EXPORT(156, void, png_set_sRGB,
+    (png_structp png_ptr, png_infop info_ptr, int srgb_intent));
+PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_structp png_ptr,
+    png_infop info_ptr, int srgb_intent));
+#endif
+
+#ifdef PNG_iCCP_SUPPORTED
+PNG_EXPORT(158, png_uint_32, png_get_iCCP,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_charpp name, int *compression_type, png_bytepp profile,
+    png_uint_32 *proflen));
+#endif
+
+#ifdef PNG_iCCP_SUPPORTED
+PNG_EXPORT(159, void, png_set_iCCP,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_const_charp name, int compression_type, png_const_bytep profile,
+    png_uint_32 proflen));
+#endif
+
+#ifdef PNG_sPLT_SUPPORTED
+PNG_EXPORT(160, png_uint_32, png_get_sPLT,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_sPLT_tpp entries));
+#endif
+
+#ifdef PNG_sPLT_SUPPORTED
+PNG_EXPORT(161, void, png_set_sPLT,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_const_sPLT_tp entries, int nentries));
+#endif
+
+#ifdef PNG_TEXT_SUPPORTED
+/* png_get_text also returns the number of text chunks in *num_text */
+PNG_EXPORT(162, png_uint_32, png_get_text,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    png_textp *text_ptr, int *num_text));
+#endif
+
+/* Note while png_set_text() will accept a structure whose text,
+ * language, and  translated keywords are NULL pointers, the structure
+ * returned by png_get_text will always contain regular
+ * zero-terminated C strings.  They might be empty strings but
+ * they will never be NULL pointers.
+ */
+
+#ifdef PNG_TEXT_SUPPORTED
+PNG_EXPORT(163, void, png_set_text,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_const_textp text_ptr, int num_text));
+#endif
+
+#ifdef PNG_tIME_SUPPORTED
+PNG_EXPORT(164, png_uint_32, png_get_tIME,
+    (png_const_structp png_ptr, png_infop info_ptr, png_timep *mod_time));
+#endif
+
+#ifdef PNG_tIME_SUPPORTED
+PNG_EXPORT(165, void, png_set_tIME,
+    (png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time));
+#endif
+
+#ifdef PNG_tRNS_SUPPORTED
+PNG_EXPORT(166, png_uint_32, png_get_tRNS,
+    (png_const_structp png_ptr, png_infop info_ptr,
+    png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color));
+#endif
+
+#ifdef PNG_tRNS_SUPPORTED
+PNG_EXPORT(167, void, png_set_tRNS,
+    (png_structp png_ptr, png_infop info_ptr,
+    png_const_bytep trans_alpha, int num_trans,
+    png_const_color_16p trans_color));
+#endif
+
+#ifdef PNG_sCAL_SUPPORTED
+PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    int *unit, double *width, double *height))
+#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
+/* NOTE: this API is currently implemented using floating point arithmetic,
+ * consequently it can only be used on systems with floating point support.
+ * In any case the range of values supported by png_fixed_point is small and it
+ * is highly recommended that png_get_sCAL_s be used instead.
+ */
+PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed,
+    (png_structp png_ptr, png_const_infop info_ptr, int *unit,
+    png_fixed_point *width,
+    png_fixed_point *height))
+#endif
+PNG_EXPORT(169, png_uint_32, png_get_sCAL_s,
+    (png_const_structp png_ptr, png_const_infop info_ptr,
+    int *unit, png_charpp swidth, png_charpp sheight));
+
+PNG_FP_EXPORT(170, void, png_set_sCAL,
+    (png_structp png_ptr, png_infop info_ptr,
+    int unit, double width, double height))
+PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_structp png_ptr,
+   png_infop info_ptr, int unit, png_fixed_point width,
+   png_fixed_point height))
+PNG_EXPORT(171, void, png_set_sCAL_s,
+    (png_structp png_ptr, png_infop info_ptr,
+    int unit, png_const_charp swidth, png_const_charp sheight));
+#endif /* PNG_sCAL_SUPPORTED */
+
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+/* Provide a list of chunks and how they are to be handled, if the built-in
+   handling or default unknown chunk handling is not desired.  Any chunks not
+   listed will be handled in the default manner.  The IHDR and IEND chunks
+   must not be listed.  Because this turns off the default handling for chunks
+   that would otherwise be recognized the behavior of libpng transformations may
+   well become incorrect!
+      keep = 0: PNG_HANDLE_CHUNK_AS_DEFAULT: follow default behavior
+           = 1: PNG_HANDLE_CHUNK_NEVER:      do not keep
+           = 2: PNG_HANDLE_CHUNK_IF_SAFE:    keep only if safe-to-copy
+           = 3: PNG_HANDLE_CHUNK_ALWAYS:     keep even if unsafe-to-copy
+*/
+PNG_EXPORT(172, void, png_set_keep_unknown_chunks,
+    (png_structp png_ptr, int keep,
+    png_const_bytep chunk_list, int num_chunks));
+
+/* The handling code is returned; the result is therefore true (non-zero) if
+ * special handling is required, false for the default handling.
+ */
+PNG_EXPORT(173, int, png_handle_as_unknown, (png_structp png_ptr,
+    png_const_bytep chunk_name));
+#endif
+#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
+PNG_EXPORT(174, void, png_set_unknown_chunks, (png_structp png_ptr,
+    png_infop info_ptr, png_const_unknown_chunkp unknowns,
+    int num_unknowns));
+PNG_EXPORT(175, void, png_set_unknown_chunk_location,
+    (png_structp png_ptr, png_infop info_ptr, int chunk, int location));
+PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structp png_ptr,
+    png_const_infop info_ptr, png_unknown_chunkpp entries));
+#endif
+
+/* Png_free_data() will turn off the "valid" flag for anything it frees.
+ * If you need to turn it off for a chunk that your application has freed,
+ * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK);
+ */
+PNG_EXPORT(177, void, png_set_invalid,
+    (png_structp png_ptr, png_infop info_ptr, int mask));
+
+#ifdef PNG_INFO_IMAGE_SUPPORTED
+/* The "params" pointer is currently not used and is for future expansion. */
+PNG_EXPORT(178, void, png_read_png, (png_structp png_ptr, png_infop info_ptr,
+    int transforms, png_voidp params));
+PNG_EXPORT(179, void, png_write_png, (png_structp png_ptr, png_infop info_ptr,
+    int transforms, png_voidp params));
+#endif
+
+PNG_EXPORT(180, png_const_charp, png_get_copyright,
+    (png_const_structp png_ptr));
+PNG_EXPORT(181, png_const_charp, png_get_header_ver,
+    (png_const_structp png_ptr));
+PNG_EXPORT(182, png_const_charp, png_get_header_version,
+    (png_const_structp png_ptr));
+PNG_EXPORT(183, png_const_charp, png_get_libpng_ver,
+    (png_const_structp png_ptr));
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structp png_ptr,
+    png_uint_32 mng_features_permitted));
+#endif
+
+/* For use in png_set_keep_unknown, added to version 1.2.6 */
+#define PNG_HANDLE_CHUNK_AS_DEFAULT   0
+#define PNG_HANDLE_CHUNK_NEVER        1
+#define PNG_HANDLE_CHUNK_IF_SAFE      2
+#define PNG_HANDLE_CHUNK_ALWAYS       3
+
+/* Strip the prepended error numbers ("#nnn ") from error and warning
+ * messages before passing them to the error or warning handler.
+ */
+#ifdef PNG_ERROR_NUMBERS_SUPPORTED
+PNG_EXPORT(185, void, png_set_strip_error_numbers,
+    (png_structp png_ptr,
+    png_uint_32 strip_mode));
+#endif
+
+/* Added in libpng-1.2.6 */
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+PNG_EXPORT(186, void, png_set_user_limits, (png_structp png_ptr,
+    png_uint_32 user_width_max, png_uint_32 user_height_max));
+PNG_EXPORT(187, png_uint_32, png_get_user_width_max,
+    (png_const_structp png_ptr));
+PNG_EXPORT(188, png_uint_32, png_get_user_height_max,
+    (png_const_structp png_ptr));
+/* Added in libpng-1.4.0 */
+PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structp png_ptr,
+    png_uint_32 user_chunk_cache_max));
+PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max,
+    (png_const_structp png_ptr));
+/* Added in libpng-1.4.1 */
+PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structp png_ptr,
+    png_alloc_size_t user_chunk_cache_max));
+PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max,
+    (png_const_structp png_ptr));
+#endif
+
+#if defined(PNG_INCH_CONVERSIONS_SUPPORTED)
+PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch,
+    (png_const_structp png_ptr, png_const_infop info_ptr));
+
+PNG_FP_EXPORT(196, float, png_get_x_offset_inches,
+    (png_const_structp png_ptr, png_const_infop info_ptr))
+#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
+PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed,
+    (png_structp png_ptr, png_const_infop info_ptr))
+#endif
+
+PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structp png_ptr,
+    png_const_infop info_ptr))
+#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
+PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed,
+    (png_structp png_ptr, png_const_infop info_ptr))
+#endif
+
+#  ifdef PNG_pHYs_SUPPORTED
+PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structp png_ptr,
+    png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
+    int *unit_type));
+#  endif /* PNG_pHYs_SUPPORTED */
+#endif  /* PNG_INCH_CONVERSIONS_SUPPORTED */
+
+/* Added in libpng-1.4.0 */
+#ifdef PNG_IO_STATE_SUPPORTED
+PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_structp png_ptr));
+
+PNG_EXPORTA(200, png_const_bytep, png_get_io_chunk_name,
+    (png_structp png_ptr), PNG_DEPRECATED);
+PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type,
+    (png_const_structp png_ptr));
+
+/* The flags returned by png_get_io_state() are the following: */
+#  define PNG_IO_NONE        0x0000   /* no I/O at this moment */
+#  define PNG_IO_READING     0x0001   /* currently reading */
+#  define PNG_IO_WRITING     0x0002   /* currently writing */
+#  define PNG_IO_SIGNATURE   0x0010   /* currently at the file signature */
+#  define PNG_IO_CHUNK_HDR   0x0020   /* currently at the chunk header */
+#  define PNG_IO_CHUNK_DATA  0x0040   /* currently at the chunk data */
+#  define PNG_IO_CHUNK_CRC   0x0080   /* currently at the chunk crc */
+#  define PNG_IO_MASK_OP     0x000f   /* current operation: reading/writing */
+#  define PNG_IO_MASK_LOC    0x00f0   /* current location: sig/hdr/data/crc */
+#endif /* ?PNG_IO_STATE_SUPPORTED */
+
+/* Interlace support.  The following macros are always defined so that if
+ * libpng interlace handling is turned off the macros may be used to handle
+ * interlaced images within the application.
+ */
+#define PNG_INTERLACE_ADAM7_PASSES 7
+
+/* Two macros to return the first row and first column of the original,
+ * full, image which appears in a given pass.  'pass' is in the range 0
+ * to 6 and the result is in the range 0 to 7.
+ */
+#define PNG_PASS_START_ROW(pass) (((1&~(pass))<<(3-((pass)>>1)))&7)
+#define PNG_PASS_START_COL(pass) (((1& (pass))<<(3-(((pass)+1)>>1)))&7)
+
+/* A macro to return the offset between pixels in the output row for a pair of
+ * pixels in the input - effectively the inverse of the 'COL_SHIFT' macro that
+ * follows.  Note that ROW_OFFSET is the offset from one row to the next whereas
+ * COL_OFFSET is from one column to the next, within a row.
+ */
+#define PNG_PASS_ROW_OFFSET(pass) ((pass)>2?(8>>(((pass)-1)>>1)):8)
+#define PNG_PASS_COL_OFFSET(pass) (1<<((7-(pass))>>1))
+
+/* Two macros to help evaluate the number of rows or columns in each
+ * pass.  This is expressed as a shift - effectively log2 of the number or
+ * rows or columns in each 8x8 tile of the original image.
+ */
+#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
+#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
+
+/* Hence two macros to determine the number of rows or columns in a given
+ * pass of an image given its height or width.  In fact these macros may
+ * return non-zero even though the sub-image is empty, because the other
+ * dimension may be empty for a small image.
+ */
+#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
+   -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
+#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
+   -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
+
+/* For the reader row callbacks (both progressive and sequential) it is
+ * necessary to find the row in the output image given a row in an interlaced
+ * image, so two more macros:
+ */
+#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
+   (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
+#define PNG_COL_FROM_PASS_COL(xIn, pass) \
+   (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
+
+/* Two macros which return a boolean (0 or 1) saying whether the given row
+ * or column is in a particular pass.  These use a common utility macro that
+ * returns a mask for a given pass - the offset 'off' selects the row or
+ * column version.  The mask has the appropriate bit set for each column in
+ * the tile.
+ */
+#define PNG_PASS_MASK(pass,off) ( \
+   ((0x110145AF>>(((7-(off))-(pass))<<2)) & 0xF) | \
+   ((0x01145AF0>>(((7-(off))-(pass))<<2)) & 0xF0))
+
+#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
+   ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
+#define PNG_COL_IN_INTERLACE_PASS(x, pass) \
+   ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
+
+#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
+/* With these routines we avoid an integer divide, which will be slower on
+ * most machines.  However, it does take more operations than the corresponding
+ * divide method, so it may be slower on a few RISC systems.  There are two
+ * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
+ *
+ * Note that the rounding factors are NOT supposed to be the same!  128 and
+ * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
+ * standard method.
+ *
+ * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
+ */
+
+ /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
+
+#  define png_composite(composite, fg, alpha, bg)         \
+     { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \
+           * (png_uint_16)(alpha)                         \
+           + (png_uint_16)(bg)*(png_uint_16)(255          \
+           - (png_uint_16)(alpha)) + 128);                \
+       (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
+
+#  define png_composite_16(composite, fg, alpha, bg)       \
+     { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg)  \
+           * (png_uint_32)(alpha)                          \
+           + (png_uint_32)(bg)*(65535                      \
+           - (png_uint_32)(alpha)) + 32768);               \
+       (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
+
+#else  /* Standard method using integer division */
+
+#  define png_composite(composite, fg, alpha, bg)                          \
+     (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) +  \
+     (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) +       \
+     127) / 255)
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
+     (png_uint_32)(bg)*(png_uint_32)(65535 - (png_uint_32)(alpha)) +         \
+     32767) / 65535)
+#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
+
+#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
+PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf));
+PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf));
+PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf));
+#endif
+
+PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_structp png_ptr,
+    png_const_bytep buf));
+/* No png_get_int_16 -- may be added if there's a real need for it. */
+
+/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */
+#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
+PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i));
+#endif
+#ifdef PNG_SAVE_INT_32_SUPPORTED
+PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i));
+#endif
+
+/* Place a 16-bit number into a buffer in PNG byte order.
+ * The parameter is declared unsigned int, not png_uint_16,
+ * just to avoid potential problems on pre-ANSI C compilers.
+ */
+#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
+PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
+/* No png_save_int_16 -- may be added if there's a real need for it. */
+#endif
+
+#ifdef PNG_USE_READ_MACROS
+/* Inline macros to do direct reads of bytes from the input buffer.
+ * The png_get_int_32() routine assumes we are using two's complement
+ * format for negative values, which is almost certainly true.
+ */
+#  define png_get_uint_32(buf) \
+     (((png_uint_32)(*(buf)) << 24) + \
+      ((png_uint_32)(*((buf) + 1)) << 16) + \
+      ((png_uint_32)(*((buf) + 2)) << 8) + \
+      ((png_uint_32)(*((buf) + 3))))
+
+   /* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
+    * function) incorrectly returned a value of type png_uint_32.
+    */
+#  define png_get_uint_16(buf) \
+     ((png_uint_16) \
+      (((unsigned int)(*(buf)) << 8) + \
+       ((unsigned int)(*((buf) + 1)))))
+
+#  define png_get_int_32(buf) \
+     ((png_int_32)((*(buf) & 0x80) \
+      ? -((png_int_32)((png_get_uint_32(buf) ^ 0xffffffffL) + 1)) \
+      : (png_int_32)png_get_uint_32(buf)))
+#endif
+
+#if defined(PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED) || \
+    defined(PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED)
+PNG_EXPORT(234, void, png_set_check_for_invalid_index, (png_structp png_ptr,
+    int allowed));
+#endif
+
+/* Maintainer: Put new public prototypes here ^, in libpng.3, and project
+ * defs
+ */
+
+/* The last ordinal number (this is the *last* one already used; the next
+ * one to use is one more than this.)  Maintainer, remember to add an entry to
+ * scripts/symbols.def as well.
+ */
+#ifdef PNG_EXPORT_LAST_ORDINAL
+  PNG_EXPORT_LAST_ORDINAL(234);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PNG_VERSION_INFO_ONLY */
+/* Do not put anything past this line */
+#endif /* PNG_H */

+ 598 - 0
engine/compilers/android/jni/include/libpng/pngconf.h

@@ -0,0 +1,598 @@
+
+/* pngconf.h - machine configurable file for libpng
+ *
+ * libpng version 1.5.13 - September 27, 2012
+ *
+ * Copyright (c) 1998-2012 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * This code is released under the libpng license.
+ * For conditions of distribution and use, see the disclaimer
+ * and license in png.h
+ *
+ */
+
+/* Any machine specific code is near the front of this file, so if you
+ * are configuring libpng for a machine, you may want to read the section
+ * starting here down to where it starts to typedef png_color, png_text,
+ * and png_info.
+ */
+
+#ifndef PNGCONF_H
+#define PNGCONF_H
+
+#ifndef PNG_BUILDING_SYMBOL_TABLE
+/* PNG_NO_LIMITS_H may be used to turn off the use of the standard C
+ * definition file for  machine specific limits, this may impact the
+ * correctness of the definitions below (see uses of INT_MAX).
+ */
+#  ifndef PNG_NO_LIMITS_H
+#    include <limits.h>
+#  endif
+
+/* For the memory copy APIs (i.e. the standard definitions of these),
+ * because this file defines png_memcpy and so on the base APIs must
+ * be defined here.
+ */
+#  ifdef BSD
+#    include <strings.h>
+#  else
+#    include <string.h>
+#  endif
+
+/* For png_FILE_p - this provides the standard definition of a
+ * FILE
+ */
+#  ifdef PNG_STDIO_SUPPORTED
+#    include <stdio.h>
+#  endif
+#endif
+
+/* This controls optimization of the reading of 16 and 32 bit values
+ * from PNG files.  It can be set on a per-app-file basis - it
+ * just changes whether a macro is used when the function is called.
+ * The library builder sets the default; if read functions are not
+ * built into the library the macro implementation is forced on.
+ */
+#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED
+#  define PNG_USE_READ_MACROS
+#endif
+#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS)
+#  if PNG_DEFAULT_READ_MACROS
+#    define PNG_USE_READ_MACROS
+#  endif
+#endif
+
+/* COMPILER SPECIFIC OPTIONS.
+ *
+ * These options are provided so that a variety of difficult compilers
+ * can be used.  Some are fixed at build time (e.g. PNG_API_RULE
+ * below) but still have compiler specific implementations, others
+ * may be changed on a per-file basis when compiling against libpng.
+ */
+
+/* The PNGARG macro protects us against machines that don't have function
+ * prototypes (ie K&R style headers).  If your compiler does not handle
+ * function prototypes, define this macro and use the included ansi2knr.
+ * I've always been able to use _NO_PROTO as the indicator, but you may
+ * need to drag the empty declaration out in front of here, or change the
+ * ifdef to suit your own needs.
+ */
+#ifndef PNGARG
+
+#  ifdef OF /* zlib prototype munger */
+#    define PNGARG(arglist) OF(arglist)
+#  else
+
+#    ifdef _NO_PROTO
+#      define PNGARG(arglist) ()
+#    else
+#      define PNGARG(arglist) arglist
+#    endif /* _NO_PROTO */
+
+#  endif /* OF */
+
+#endif /* PNGARG */
+
+/* Function calling conventions.
+ * =============================
+ * Normally it is not necessary to specify to the compiler how to call
+ * a function - it just does it - however on x86 systems derived from
+ * Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems
+ * and some others) there are multiple ways to call a function and the
+ * default can be changed on the compiler command line.  For this reason
+ * libpng specifies the calling convention of every exported function and
+ * every function called via a user supplied function pointer.  This is
+ * done in this file by defining the following macros:
+ *
+ * PNGAPI    Calling convention for exported functions.
+ * PNGCBAPI  Calling convention for user provided (callback) functions.
+ * PNGCAPI   Calling convention used by the ANSI-C library (required
+ *           for longjmp callbacks and sometimes used internally to
+ *           specify the calling convention for zlib).
+ *
+ * These macros should never be overridden.  If it is necessary to
+ * change calling convention in a private build this can be done
+ * by setting PNG_API_RULE (which defaults to 0) to one of the values
+ * below to select the correct 'API' variants.
+ *
+ * PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout.
+ *                This is correct in every known environment.
+ * PNG_API_RULE=1 Use the operating system convention for PNGAPI and
+ *                the 'C' calling convention (from PNGCAPI) for
+ *                callbacks (PNGCBAPI).  This is no longer required
+ *                in any known environment - if it has to be used
+ *                please post an explanation of the problem to the
+ *                libpng mailing list.
+ *
+ * These cases only differ if the operating system does not use the C
+ * calling convention, at present this just means the above cases
+ * (x86 DOS/Windows sytems) and, even then, this does not apply to
+ * Cygwin running on those systems.
+ *
+ * Note that the value must be defined in pnglibconf.h so that what
+ * the application uses to call the library matches the conventions
+ * set when building the library.
+ */
+
+/* Symbol export
+ * =============
+ * When building a shared library it is almost always necessary to tell
+ * the compiler which symbols to export.  The png.h macro 'PNG_EXPORT'
+ * is used to mark the symbols.  On some systems these symbols can be
+ * extracted at link time and need no special processing by the compiler,
+ * on other systems the symbols are flagged by the compiler and just
+ * the declaration requires a special tag applied (unfortunately) in a
+ * compiler dependent way.  Some systems can do either.
+ *
+ * A small number of older systems also require a symbol from a DLL to
+ * be flagged to the program that calls it.  This is a problem because
+ * we do not know in the header file included by application code that
+ * the symbol will come from a shared library, as opposed to a statically
+ * linked one.  For this reason the application must tell us by setting
+ * the magic flag PNG_USE_DLL to turn on the special processing before
+ * it includes png.h.
+ *
+ * Four additional macros are used to make this happen:
+ *
+ * PNG_IMPEXP The magic (if any) to cause a symbol to be exported from
+ *            the build or imported if PNG_USE_DLL is set - compiler
+ *            and system specific.
+ *
+ * PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to
+ *                       'type', compiler specific.
+ *
+ * PNG_DLL_EXPORT Set to the magic to use during a libpng build to
+ *                make a symbol exported from the DLL.  Not used in the
+ *                public header files; see pngpriv.h for how it is used
+ *                in the libpng build.
+ *
+ * PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come
+ *                from a DLL - used to define PNG_IMPEXP when
+ *                PNG_USE_DLL is set.
+ */
+
+/* System specific discovery.
+ * ==========================
+ * This code is used at build time to find PNG_IMPEXP, the API settings
+ * and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL
+ * import processing is possible.  On Windows/x86 systems it also sets
+ * compiler-specific macros to the values required to change the calling
+ * conventions of the various functions.
+ */
+#if ( defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\
+      defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) ) &&\
+    ( defined(_X86_) || defined(_X64_) || defined(_M_IX86) ||\
+      defined(_M_X64) || defined(_M_IA64) )
+  /* Windows system (DOS doesn't support DLLs) running on x86/x64.  Includes
+   * builds under Cygwin or MinGW.  Also includes Watcom builds but these need
+   * special treatment because they are not compatible with GCC or Visual C
+   * because of different calling conventions.
+   */
+#  if PNG_API_RULE == 2
+    /* If this line results in an error, either because __watcall is not
+     * understood or because of a redefine just below you cannot use *this*
+     * build of the library with the compiler you are using.  *This* build was
+     * build using Watcom and applications must also be built using Watcom!
+     */
+#    define PNGCAPI __watcall
+#  endif
+
+#  if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
+#    define PNGCAPI __cdecl
+#    if PNG_API_RULE == 1
+#      define PNGAPI __stdcall
+#    endif
+#  else
+    /* An older compiler, or one not detected (erroneously) above,
+     * if necessary override on the command line to get the correct
+     * variants for the compiler.
+     */
+#    ifndef PNGCAPI
+#      define PNGCAPI _cdecl
+#    endif
+#    if PNG_API_RULE == 1 && !defined(PNGAPI)
+#      define PNGAPI _stdcall
+#    endif
+#  endif /* compiler/api */
+  /* NOTE: PNGCBAPI always defaults to PNGCAPI. */
+
+#  if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD)
+   ERROR: PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed
+#  endif
+
+#  if (defined(_MSC_VER) && _MSC_VER < 800) ||\
+      (defined(__BORLANDC__) && __BORLANDC__ < 0x500)
+    /* older Borland and MSC
+     * compilers used '__export' and required this to be after
+     * the type.
+     */
+#    ifndef PNG_EXPORT_TYPE
+#      define PNG_EXPORT_TYPE(type) type PNG_IMPEXP
+#    endif
+#    define PNG_DLL_EXPORT __export
+#  else /* newer compiler */
+#    define PNG_DLL_EXPORT __declspec(dllexport)
+#    ifndef PNG_DLL_IMPORT
+#      define PNG_DLL_IMPORT __declspec(dllimport)
+#    endif
+#  endif /* compiler */
+
+#else /* !Windows/x86 */
+#  if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
+#    define PNGAPI _System
+#  else /* !Windows/x86 && !OS/2 */
+    /* Use the defaults, or define PNG*API on the command line (but
+     * this will have to be done for every compile!)
+     */
+#  endif /* other system, !OS/2 */
+#endif /* !Windows/x86 */
+
+/* Now do all the defaulting . */
+#ifndef PNGCAPI
+#  define PNGCAPI
+#endif
+#ifndef PNGCBAPI
+#  define PNGCBAPI PNGCAPI
+#endif
+#ifndef PNGAPI
+#  define PNGAPI PNGCAPI
+#endif
+
+/* PNG_IMPEXP may be set on the compilation system command line or (if not set)
+ * then in an internal header file when building the library, otherwise (when
+ * using the library) it is set here.
+ */
+#ifndef PNG_IMPEXP
+#  if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT)
+     /* This forces use of a DLL, disallowing static linking */
+#    define PNG_IMPEXP PNG_DLL_IMPORT
+#  endif
+
+#  ifndef PNG_IMPEXP
+#    define PNG_IMPEXP
+#  endif
+#endif
+
+/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat
+ * 'attributes' as a storage class - the attributes go at the start of the
+ * function definition, and attributes are always appended regardless of the
+ * compiler.  This considerably simplifies these macros but may cause problems
+ * if any compilers both need function attributes and fail to handle them as
+ * a storage class (this is unlikely.)
+ */
+#ifndef PNG_FUNCTION
+#  define PNG_FUNCTION(type, name, args, attributes) attributes type name args
+#endif
+
+#ifndef PNG_EXPORT_TYPE
+#  define PNG_EXPORT_TYPE(type) PNG_IMPEXP type
+#endif
+
+   /* The ordinal value is only relevant when preprocessing png.h for symbol
+    * table entries, so we discard it here.  See the .dfn files in the
+    * scripts directory.
+    */
+#ifndef PNG_EXPORTA
+
+#  define PNG_EXPORTA(ordinal, type, name, args, attributes)\
+      PNG_FUNCTION(PNG_EXPORT_TYPE(type),(PNGAPI name),PNGARG(args), \
+        extern attributes)
+#endif
+
+/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument,
+ * so make something non-empty to satisfy the requirement:
+ */
+#define PNG_EMPTY /*empty list*/
+
+#define PNG_EXPORT(ordinal, type, name, args)\
+   PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY)
+
+/* Use PNG_REMOVED to comment out a removed interface. */
+#ifndef PNG_REMOVED
+#  define PNG_REMOVED(ordinal, type, name, args, attributes)
+#endif
+
+#ifndef PNG_CALLBACK
+#  define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args)
+#endif
+
+/* Support for compiler specific function attributes.  These are used
+ * so that where compiler support is available incorrect use of API
+ * functions in png.h will generate compiler warnings.
+ *
+ * Added at libpng-1.2.41.
+ */
+
+#ifndef PNG_NO_PEDANTIC_WARNINGS
+#  ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED
+#    define PNG_PEDANTIC_WARNINGS_SUPPORTED
+#  endif
+#endif
+
+#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED
+  /* Support for compiler specific function attributes.  These are used
+   * so that where compiler support is available incorrect use of API
+   * functions in png.h will generate compiler warnings.  Added at libpng
+   * version 1.2.41.
+   */
+#  if defined(__GNUC__)
+#    ifndef PNG_USE_RESULT
+#      define PNG_USE_RESULT __attribute__((__warn_unused_result__))
+#    endif
+#    ifndef PNG_NORETURN
+#      define PNG_NORETURN   __attribute__((__noreturn__))
+#    endif
+#    if __GNUC__ >= 3
+#      ifndef PNG_ALLOCATED
+#        define PNG_ALLOCATED  __attribute__((__malloc__))
+#      endif
+#      ifndef PNG_DEPRECATED
+#        define PNG_DEPRECATED __attribute__((__deprecated__))
+#      endif
+#      ifndef PNG_PRIVATE
+#        if 0 /* Doesn't work so we use deprecated instead*/
+#          define PNG_PRIVATE \
+            __attribute__((warning("This function is not exported by libpng.")))
+#        else
+#          define PNG_PRIVATE \
+            __attribute__((__deprecated__))
+#        endif
+#      endif
+#    endif /*  __GNUC__ >= 3 */
+#  endif /* __GNUC__ */
+
+#  if defined(_MSC_VER)  && (_MSC_VER >= 1300)
+#    ifndef PNG_USE_RESULT
+#      define PNG_USE_RESULT /* not supported */
+#    endif
+#    ifndef PNG_NORETURN
+#      define PNG_NORETURN __declspec(noreturn)
+#    endif
+#    ifndef PNG_ALLOCATED
+#      if (_MSC_VER >= 1400)
+#        define PNG_ALLOCATED __declspec(restrict)
+#      endif
+#    endif
+#    ifndef PNG_DEPRECATED
+#      define PNG_DEPRECATED __declspec(deprecated)
+#    endif
+#    ifndef PNG_PRIVATE
+#      define PNG_PRIVATE __declspec(deprecated)
+#    endif
+#  endif /* _MSC_VER */
+#endif /* PNG_PEDANTIC_WARNINGS */
+
+#ifndef PNG_DEPRECATED
+#  define PNG_DEPRECATED  /* Use of this function is deprecated */
+#endif
+#ifndef PNG_USE_RESULT
+#  define PNG_USE_RESULT  /* The result of this function must be checked */
+#endif
+#ifndef PNG_NORETURN
+#  define PNG_NORETURN    /* This function does not return */
+#endif
+#ifndef PNG_ALLOCATED
+#  define PNG_ALLOCATED   /* The result of the function is new memory */
+#endif
+#ifndef PNG_PRIVATE
+#  define PNG_PRIVATE     /* This is a private libpng function */
+#endif
+#ifndef PNG_FP_EXPORT     /* A floating point API. */
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+#     define PNG_FP_EXPORT(ordinal, type, name, args)\
+         PNG_EXPORT(ordinal, type, name, args);
+#  else                   /* No floating point APIs */
+#     define PNG_FP_EXPORT(ordinal, type, name, args)
+#  endif
+#endif
+#ifndef PNG_FIXED_EXPORT  /* A fixed point API. */
+#  ifdef PNG_FIXED_POINT_SUPPORTED
+#     define PNG_FIXED_EXPORT(ordinal, type, name, args)\
+         PNG_EXPORT(ordinal, type, name, args);
+#  else                   /* No fixed point APIs */
+#     define PNG_FIXED_EXPORT(ordinal, type, name, args)
+#  endif
+#endif
+
+/* The following uses const char * instead of char * for error
+ * and warning message functions, so some compilers won't complain.
+ * If you do not want to use const, define PNG_NO_CONST here.
+ *
+ * This should not change how the APIs are called, so it can be done
+ * on a per-file basis in the application.
+ */
+#ifndef PNG_CONST
+#  ifndef PNG_NO_CONST
+#    define PNG_CONST const
+#  else
+#    define PNG_CONST
+#  endif
+#endif
+
+/* Some typedefs to get us started.  These should be safe on most of the
+ * common platforms.  The typedefs should be at least as large as the
+ * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
+ * don't have to be exactly that size.  Some compilers dislike passing
+ * unsigned shorts as function parameters, so you may be better off using
+ * unsigned int for png_uint_16.
+ */
+
+#if defined(INT_MAX) && (INT_MAX > 0x7ffffffeL)
+typedef unsigned int png_uint_32;
+typedef int png_int_32;
+#else
+typedef unsigned long png_uint_32;
+typedef long png_int_32;
+#endif
+typedef unsigned short png_uint_16;
+typedef short png_int_16;
+typedef unsigned char png_byte;
+
+#ifdef PNG_NO_SIZE_T
+typedef unsigned int png_size_t;
+#else
+typedef size_t png_size_t;
+#endif
+#define png_sizeof(x) (sizeof (x))
+
+/* The following is needed for medium model support.  It cannot be in the
+ * pngpriv.h header.  Needs modification for other compilers besides
+ * MSC.  Model independent support declares all arrays and pointers to be
+ * large using the far keyword.  The zlib version used must also support
+ * model independent data.  As of version zlib 1.0.4, the necessary changes
+ * have been made in zlib.  The USE_FAR_KEYWORD define triggers other
+ * changes that are needed. (Tim Wegner)
+ */
+
+/* Separate compiler dependencies (problem here is that zlib.h always
+ * defines FAR. (SJT)
+ */
+#ifdef __BORLANDC__
+#  if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
+#    define LDATA 1
+#  else
+#    define LDATA 0
+#  endif
+  /* GRR:  why is Cygwin in here?  Cygwin is not Borland C... */
+#  if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
+#    define PNG_MAX_MALLOC_64K /* only used in build */
+#    if (LDATA != 1)
+#      ifndef FAR
+#        define FAR __far
+#      endif
+#      define USE_FAR_KEYWORD
+#    endif   /* LDATA != 1 */
+         /* Possibly useful for moving data out of default segment.
+          * Uncomment it if you want. Could also define FARDATA as
+          * const if your compiler supports it. (SJT)
+#        define FARDATA FAR
+          */
+#  endif  /* __WIN32__, __FLAT__, __CYGWIN__ */
+#endif   /* __BORLANDC__ */
+
+
+/* Suggest testing for specific compiler first before testing for
+ * FAR.  The Watcom compiler defines both __MEDIUM__ and M_I86MM,
+ * making reliance oncertain keywords suspect. (SJT)
+ */
+
+/* MSC Medium model */
+#ifdef FAR
+#  ifdef M_I86MM
+#    define USE_FAR_KEYWORD
+#    define FARDATA FAR
+#    include <dos.h>
+#  endif
+#endif
+
+/* SJT: default case */
+#ifndef FAR
+#  define FAR
+#endif
+
+/* At this point FAR is always defined */
+#ifndef FARDATA
+#  define FARDATA
+#endif
+
+/* Typedef for floating-point numbers that are converted
+ * to fixed-point with a multiple of 100,000, e.g., gamma
+ */
+typedef png_int_32 png_fixed_point;
+
+/* Add typedefs for pointers */
+typedef void                      FAR * png_voidp;
+typedef PNG_CONST void            FAR * png_const_voidp;
+typedef png_byte                  FAR * png_bytep;
+typedef PNG_CONST png_byte        FAR * png_const_bytep;
+typedef png_uint_32               FAR * png_uint_32p;
+typedef PNG_CONST png_uint_32     FAR * png_const_uint_32p;
+typedef png_int_32                FAR * png_int_32p;
+typedef PNG_CONST png_int_32      FAR * png_const_int_32p;
+typedef png_uint_16               FAR * png_uint_16p;
+typedef PNG_CONST png_uint_16     FAR * png_const_uint_16p;
+typedef png_int_16                FAR * png_int_16p;
+typedef PNG_CONST png_int_16      FAR * png_const_int_16p;
+typedef char                      FAR * png_charp;
+typedef PNG_CONST char            FAR * png_const_charp;
+typedef png_fixed_point           FAR * png_fixed_point_p;
+typedef PNG_CONST png_fixed_point FAR * png_const_fixed_point_p;
+typedef png_size_t                FAR * png_size_tp;
+typedef PNG_CONST png_size_t      FAR * png_const_size_tp;
+
+#ifdef PNG_STDIO_SUPPORTED
+typedef FILE            * png_FILE_p;
+#endif
+
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double           FAR * png_doublep;
+typedef PNG_CONST double FAR * png_const_doublep;
+#endif
+
+/* Pointers to pointers; i.e. arrays */
+typedef png_byte        FAR * FAR * png_bytepp;
+typedef png_uint_32     FAR * FAR * png_uint_32pp;
+typedef png_int_32      FAR * FAR * png_int_32pp;
+typedef png_uint_16     FAR * FAR * png_uint_16pp;
+typedef png_int_16      FAR * FAR * png_int_16pp;
+typedef PNG_CONST char  FAR * FAR * png_const_charpp;
+typedef char            FAR * FAR * png_charpp;
+typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * FAR * png_doublepp;
+#endif
+
+/* Pointers to pointers to pointers; i.e., pointer to array */
+typedef char            FAR * FAR * FAR * png_charppp;
+
+/* png_alloc_size_t is guaranteed to be no smaller than png_size_t,
+ * and no smaller than png_uint_32.  Casts from png_size_t or png_uint_32
+ * to png_alloc_size_t are not necessary; in fact, it is recommended
+ * not to use them at all so that the compiler can complain when something
+ * turns out to be problematic.
+ * Casts in the other direction (from png_alloc_size_t to png_size_t or
+ * png_uint_32) should be explicitly applied; however, we do not expect
+ * to encounter practical situations that require such conversions.
+ */
+#if defined(__TURBOC__) && !defined(__FLAT__)
+   typedef unsigned long png_alloc_size_t;
+#else
+#  if defined(_MSC_VER) && defined(MAXSEG_64K)
+     typedef unsigned long    png_alloc_size_t;
+#  else
+     /* This is an attempt to detect an old Windows system where (int) is
+      * actually 16 bits, in that case png_malloc must have an argument with a
+      * bigger size to accomodate the requirements of the library.
+      */
+#    if (defined(_Windows) || defined(_WINDOWS) || defined(_WINDOWS_)) && \
+        (!defined(INT_MAX) || INT_MAX <= 0x7ffffffeL)
+       typedef DWORD         png_alloc_size_t;
+#    else
+       typedef png_size_t    png_alloc_size_t;
+#    endif
+#  endif
+#endif
+
+#endif /* PNGCONF_H */

+ 157 - 0
engine/compilers/android/jni/include/libpng/pngdebug.h

@@ -0,0 +1,157 @@
+
+/* pngdebug.h - Debugging macros for libpng, also used in pngtest.c
+ *
+ * Copyright (c) 1998-2011 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Last changed in libpng 1.5.0 [January 6, 2011]
+ *
+ * This code is released under the libpng license.
+ * For conditions of distribution and use, see the disclaimer
+ * and license in png.h
+ */
+
+/* Define PNG_DEBUG at compile time for debugging information.  Higher
+ * numbers for PNG_DEBUG mean more debugging information.  This has
+ * only been added since version 0.95 so it is not implemented throughout
+ * libpng yet, but more support will be added as needed.
+ *
+ * png_debug[1-2]?(level, message ,arg{0-2})
+ *   Expands to a statement (either a simple expression or a compound
+ *   do..while(0) statement) that outputs a message with parameter
+ *   substitution if PNG_DEBUG is defined to 2 or more.  If PNG_DEBUG
+ *   is undefined, 0 or 1 every png_debug expands to a simple expression
+ *   (actually ((void)0)).
+ *
+ *   level: level of detail of message, starting at 0.  A level 'n'
+ *          message is preceded by 'n' tab characters (not implemented
+ *          on Microsoft compilers unless PNG_DEBUG_FILE is also
+ *          defined, to allow debug DLL compilation with no standard IO).
+ *   message: a printf(3) style text string.  A trailing '\n' is added
+ *            to the message.
+ *   arg: 0 to 2 arguments for printf(3) style substitution in message.
+ */
+#ifndef PNGDEBUG_H
+#define PNGDEBUG_H
+/* These settings control the formatting of messages in png.c and pngerror.c */
+/* Moved to pngdebug.h at 1.5.0 */
+#  ifndef PNG_LITERAL_SHARP
+#    define PNG_LITERAL_SHARP 0x23
+#  endif
+#  ifndef PNG_LITERAL_LEFT_SQUARE_BRACKET
+#    define PNG_LITERAL_LEFT_SQUARE_BRACKET 0x5b
+#  endif
+#  ifndef PNG_LITERAL_RIGHT_SQUARE_BRACKET
+#    define PNG_LITERAL_RIGHT_SQUARE_BRACKET 0x5d
+#  endif
+#  ifndef PNG_STRING_NEWLINE
+#    define PNG_STRING_NEWLINE "\n"
+#  endif
+
+#ifdef PNG_DEBUG
+#  if (PNG_DEBUG > 0)
+#    if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
+#      include <crtdbg.h>
+#      if (PNG_DEBUG > 1)
+#        ifndef _DEBUG
+#          define _DEBUG
+#        endif
+#        ifndef png_debug
+#          define png_debug(l,m)  _RPT0(_CRT_WARN,m PNG_STRING_NEWLINE)
+#        endif
+#        ifndef png_debug1
+#          define png_debug1(l,m,p1)  _RPT1(_CRT_WARN,m PNG_STRING_NEWLINE,p1)
+#        endif
+#        ifndef png_debug2
+#          define png_debug2(l,m,p1,p2) \
+             _RPT2(_CRT_WARN,m PNG_STRING_NEWLINE,p1,p2)
+#        endif
+#      endif
+#    else /* PNG_DEBUG_FILE || !_MSC_VER */
+#      ifndef PNG_STDIO_SUPPORTED
+#        include <stdio.h> /* not included yet */
+#      endif
+#      ifndef PNG_DEBUG_FILE
+#        define PNG_DEBUG_FILE stderr
+#      endif /* PNG_DEBUG_FILE */
+
+#      if (PNG_DEBUG > 1)
+/* Note: ["%s"m PNG_STRING_NEWLINE] probably does not work on
+ * non-ISO compilers
+ */
+#        ifdef __STDC__
+#          ifndef png_debug
+#            define png_debug(l,m) \
+       do { \
+       int num_tabs=l; \
+       fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
+       } while (0)
+#          endif
+#          ifndef png_debug1
+#            define png_debug1(l,m,p1) \
+       do { \
+       int num_tabs=l; \
+       fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
+       } while (0)
+#          endif
+#          ifndef png_debug2
+#            define png_debug2(l,m,p1,p2) \
+       do { \
+       int num_tabs=l; \
+       fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
+       } while (0)
+#          endif
+#        else /* __STDC __ */
+#          ifndef png_debug
+#            define png_debug(l,m) \
+       do { \
+       int num_tabs=l; \
+       char format[256]; \
+       snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
+         m,PNG_STRING_NEWLINE); \
+       fprintf(PNG_DEBUG_FILE,format); \
+       } while (0)
+#          endif
+#          ifndef png_debug1
+#            define png_debug1(l,m,p1) \
+       do { \
+       int num_tabs=l; \
+       char format[256]; \
+       snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
+         m,PNG_STRING_NEWLINE); \
+       fprintf(PNG_DEBUG_FILE,format,p1); \
+       } while (0)
+#          endif
+#          ifndef png_debug2
+#            define png_debug2(l,m,p1,p2) \
+       do { \
+       int num_tabs=l; \
+       char format[256]; \
+       snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
+         (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
+         m,PNG_STRING_NEWLINE); \
+       fprintf(PNG_DEBUG_FILE,format,p1,p2); \
+       } while (0)
+#          endif
+#        endif /* __STDC __ */
+#      endif /* (PNG_DEBUG > 1) */
+
+#    endif /* _MSC_VER */
+#  endif /* (PNG_DEBUG > 0) */
+#endif /* PNG_DEBUG */
+#ifndef png_debug
+#  define png_debug(l, m) ((void)0)
+#endif
+#ifndef png_debug1
+#  define png_debug1(l, m, p1) ((void)0)
+#endif
+#ifndef png_debug2
+#  define png_debug2(l, m, p1, p2) ((void)0)
+#endif
+#endif /* PNGDEBUG_H */

+ 269 - 0
engine/compilers/android/jni/include/libpng/pnginfo.h

@@ -0,0 +1,269 @@
+
+/* pnginfo.h - header file for PNG reference library
+ *
+ * Copyright (c) 1998-2011 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Last changed in libpng 1.5.0 [January 6, 2011]
+ *
+ * This code is released under the libpng license.
+ * For conditions of distribution and use, see the disclaimer
+ * and license in png.h
+ */
+
+ /* png_info is a structure that holds the information in a PNG file so
+ * that the application can find out the characteristics of the image.
+ * If you are reading the file, this structure will tell you what is
+ * in the PNG file.  If you are writing the file, fill in the information
+ * you want to put into the PNG file, using png_set_*() functions, then
+ * call png_write_info().
+ *
+ * The names chosen should be very close to the PNG specification, so
+ * consult that document for information about the meaning of each field.
+ *
+ * With libpng < 0.95, it was only possible to directly set and read the
+ * the values in the png_info_struct, which meant that the contents and
+ * order of the values had to remain fixed.  With libpng 0.95 and later,
+ * however, there are now functions that abstract the contents of
+ * png_info_struct from the application, so this makes it easier to use
+ * libpng with dynamic libraries, and even makes it possible to use
+ * libraries that don't have all of the libpng ancillary chunk-handing
+ * functionality.  In libpng-1.5.0 this was moved into a separate private
+ * file that is not visible to applications.
+ *
+ * The following members may have allocated storage attached that should be
+ * cleaned up before the structure is discarded: palette, trans, text,
+ * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
+ * splt_palettes, scal_unit, row_pointers, and unknowns.   By default, these
+ * are automatically freed when the info structure is deallocated, if they were
+ * allocated internally by libpng.  This behavior can be changed by means
+ * of the png_data_freer() function.
+ *
+ * More allocation details: all the chunk-reading functions that
+ * change these members go through the corresponding png_set_*
+ * functions.  A function to clear these members is available: see
+ * png_free_data().  The png_set_* functions do not depend on being
+ * able to point info structure members to any of the storage they are
+ * passed (they make their own copies), EXCEPT that the png_set_text
+ * functions use the same storage passed to them in the text_ptr or
+ * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
+ * functions do not make their own copies.
+ */
+#ifndef PNGINFO_H
+#define PNGINFO_H
+
+struct png_info_def
+{
+   /* the following are necessary for every PNG file */
+   png_uint_32 width;  /* width of image in pixels (from IHDR) */
+   png_uint_32 height; /* height of image in pixels (from IHDR) */
+   png_uint_32 valid;  /* valid chunk data (see PNG_INFO_ below) */
+   png_size_t rowbytes; /* bytes needed to hold an untransformed row */
+   png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
+   png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
+   png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
+   png_byte bit_depth;      /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
+   png_byte color_type;     /* see PNG_COLOR_TYPE_ below (from IHDR) */
+   /* The following three should have been named *_method not *_type */
+   png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
+   png_byte filter_type;    /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
+   png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+
+   /* The following is informational only on read, and not used on writes. */
+   png_byte channels;       /* number of data channels per pixel (1, 2, 3, 4) */
+   png_byte pixel_depth;    /* number of bits per pixel */
+   png_byte spare_byte;     /* to align the data, and for future use */
+   png_byte signature[8];   /* magic bytes read by libpng from start of file */
+
+   /* The rest of the data is optional.  If you are reading, check the
+    * valid field to see if the information in these are valid.  If you
+    * are writing, set the valid field to those chunks you want written,
+    * and initialize the appropriate fields below.
+    */
+
+#if defined(PNG_gAMA_SUPPORTED)
+   /* The gAMA chunk describes the gamma characteristics of the system
+    * on which the image was created, normally in the range [1.0, 2.5].
+    * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
+    */
+   png_fixed_point gamma;
+#endif
+
+#ifdef PNG_sRGB_SUPPORTED
+    /* GR-P, 0.96a */
+    /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
+   png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
+#endif
+
+#ifdef PNG_TEXT_SUPPORTED
+   /* The tEXt, and zTXt chunks contain human-readable textual data in
+    * uncompressed, compressed, and optionally compressed forms, respectively.
+    * The data in "text" is an array of pointers to uncompressed,
+    * null-terminated C strings. Each chunk has a keyword that describes the
+    * textual data contained in that chunk.  Keywords are not required to be
+    * unique, and the text string may be empty.  Any number of text chunks may
+    * be in an image.
+    */
+   int num_text; /* number of comments read or comments to write */
+   int max_text; /* current size of text array */
+   png_textp text; /* array of comments read or comments to write */
+#endif /* PNG_TEXT_SUPPORTED */
+
+#ifdef PNG_tIME_SUPPORTED
+   /* The tIME chunk holds the last time the displayed image data was
+    * modified.  See the png_time struct for the contents of this struct.
+    */
+   png_time mod_time;
+#endif
+
+#ifdef PNG_sBIT_SUPPORTED
+   /* The sBIT chunk specifies the number of significant high-order bits
+    * in the pixel data.  Values are in the range [1, bit_depth], and are
+    * only specified for the channels in the pixel data.  The contents of
+    * the low-order bits is not specified.  Data is valid if
+    * (valid & PNG_INFO_sBIT) is non-zero.
+    */
+   png_color_8 sig_bit; /* significant bits in color channels */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
+defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The tRNS chunk supplies transparency data for paletted images and
+    * other image types that don't need a full alpha channel.  There are
+    * "num_trans" transparency values for a paletted image, stored in the
+    * same order as the palette colors, starting from index 0.  Values
+    * for the data are in the range [0, 255], ranging from fully transparent
+    * to fully opaque, respectively.  For non-paletted images, there is a
+    * single color specified that should be treated as fully transparent.
+    * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
+    */
+   png_bytep trans_alpha;    /* alpha values for paletted image */
+   png_color_16 trans_color; /* transparent color for non-palette image */
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The bKGD chunk gives the suggested image background color if the
+    * display program does not have its own background color and the image
+    * is needs to composited onto a background before display.  The colors
+    * in "background" are normally in the same color space/depth as the
+    * pixel data.  Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
+    */
+   png_color_16 background;
+#endif
+
+#ifdef PNG_oFFs_SUPPORTED
+   /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
+    * and downwards from the top-left corner of the display, page, or other
+    * application-specific co-ordinate space.  See the PNG_OFFSET_ defines
+    * below for the unit types.  Valid if (valid & PNG_INFO_oFFs) non-zero.
+    */
+   png_int_32 x_offset; /* x offset on page */
+   png_int_32 y_offset; /* y offset on page */
+   png_byte offset_unit_type; /* offset units type */
+#endif
+
+#ifdef PNG_pHYs_SUPPORTED
+   /* The pHYs chunk gives the physical pixel density of the image for
+    * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
+    * defines below).  Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
+    */
+   png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
+   png_uint_32 y_pixels_per_unit; /* vertical pixel density */
+   png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
+#endif
+
+#ifdef PNG_hIST_SUPPORTED
+   /* The hIST chunk contains the relative frequency or importance of the
+    * various palette entries, so that a viewer can intelligently select a
+    * reduced-color palette, if required.  Data is an array of "num_palette"
+    * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
+    * is non-zero.
+    */
+   png_uint_16p hist;
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+   /* The cHRM chunk describes the CIE color characteristics of the monitor
+    * on which the PNG was created.  This data allows the viewer to do gamut
+    * mapping of the input image to ensure that the viewer sees the same
+    * colors in the image as the creator.  Values are in the range
+    * [0.0, 0.8].  Data valid if (valid & PNG_INFO_cHRM) non-zero.
+    */
+   png_fixed_point x_white;
+   png_fixed_point y_white;
+   png_fixed_point x_red;
+   png_fixed_point y_red;
+   png_fixed_point x_green;
+   png_fixed_point y_green;
+   png_fixed_point x_blue;
+   png_fixed_point y_blue;
+#endif
+
+#ifdef PNG_pCAL_SUPPORTED
+   /* The pCAL chunk describes a transformation between the stored pixel
+    * values and original physical data values used to create the image.
+    * The integer range [0, 2^bit_depth - 1] maps to the floating-point
+    * range given by [pcal_X0, pcal_X1], and are further transformed by a
+    * (possibly non-linear) transformation function given by "pcal_type"
+    * and "pcal_params" into "pcal_units".  Please see the PNG_EQUATION_
+    * defines below, and the PNG-Group's PNG extensions document for a
+    * complete description of the transformations and how they should be
+    * implemented, and for a description of the ASCII parameter strings.
+    * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
+    */
+   png_charp pcal_purpose;  /* pCAL chunk description string */
+   png_int_32 pcal_X0;      /* minimum value */
+   png_int_32 pcal_X1;      /* maximum value */
+   png_charp pcal_units;    /* Latin-1 string giving physical units */
+   png_charpp pcal_params;  /* ASCII strings containing parameter values */
+   png_byte pcal_type;      /* equation type (see PNG_EQUATION_ below) */
+   png_byte pcal_nparams;   /* number of parameters given in pcal_params */
+#endif
+
+/* New members added in libpng-1.0.6 */
+   png_uint_32 free_me;     /* flags items libpng is responsible for freeing */
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \
+ defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
+   /* Storage for unknown chunks that the library doesn't recognize. */
+   png_unknown_chunkp unknown_chunks;
+   int unknown_chunks_num;
+#endif
+
+#ifdef PNG_iCCP_SUPPORTED
+   /* iCCP chunk data. */
+   png_charp iccp_name;     /* profile name */
+   png_bytep iccp_profile;  /* International Color Consortium profile data */
+   png_uint_32 iccp_proflen;  /* ICC profile data length */
+   png_byte iccp_compression; /* Always zero */
+#endif
+
+#ifdef PNG_sPLT_SUPPORTED
+   /* Data on sPLT chunks (there may be more than one). */
+   png_sPLT_tp splt_palettes;
+   png_uint_32 splt_palettes_num;
+#endif
+
+#ifdef PNG_sCAL_SUPPORTED
+   /* The sCAL chunk describes the actual physical dimensions of the
+    * subject matter of the graphic.  The chunk contains a unit specification
+    * a byte value, and two ASCII strings representing floating-point
+    * values.  The values are width and height corresponsing to one pixel
+    * in the image.  Data values are valid if (valid & PNG_INFO_sCAL) is
+    * non-zero.
+    */
+   png_byte scal_unit;         /* unit of physical scale */
+   png_charp scal_s_width;     /* string containing height */
+   png_charp scal_s_height;    /* string containing width */
+#endif
+
+#ifdef PNG_INFO_IMAGE_SUPPORTED
+   /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS)
+      non-zero */
+   /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
+   png_bytepp row_pointers;        /* the image bits */
+#endif
+
+};
+#endif /* PNGINFO_H */

+ 180 - 0
engine/compilers/android/jni/include/libpng/pnglibconf.h

@@ -0,0 +1,180 @@
+/* pnglibconf.h - library build configuration */
+
+/* libpng version 1.5.13 - September 27, 2012 */
+
+/* Copyright (c) 1998-2011 Glenn Randers-Pehrson */
+
+/* This code is released under the libpng license. */
+/* For conditions of distribution and use, see the disclaimer */
+/* and license in png.h */
+
+/* pnglibconf.h */
+/* Machine generated file: DO NOT EDIT */
+/* Derived from: scripts/pnglibconf.dfa */
+#ifndef PNGLCONF_H
+#define PNGLCONF_H
+/* settings */
+#define PNG_COST_SHIFT 3
+#define PNG_GAMMA_THRESHOLD_FIXED 5000
+#define PNG_QUANTIZE_BLUE_BITS 5
+#define PNG_WEIGHT_SHIFT 8
+#define PNG_API_RULE 0
+#define PNG_CALLOC_SUPPORTED
+#define PNG_ZBUF_SIZE 8192
+#define PNG_QUANTIZE_GREEN_BITS 5
+#define PNG_sCAL_PRECISION 5
+#define PNG_QUANTIZE_RED_BITS 5
+#define PNG_DEFAULT_READ_MACROS 1
+#define PNG_MAX_GAMMA_8 11
+/* end of settings */
+/* options */
+#define PNG_IO_STATE_SUPPORTED 1
+#define PNG_BENIGN_ERRORS_SUPPORTED 1
+#define PNG_WRITE_SUPPORTED 1
+#define PNG_EASY_ACCESS_SUPPORTED 1
+#define PNG_INFO_IMAGE_SUPPORTED 1
+#define PNG_TIME_RFC1123_SUPPORTED 1
+#define PNG_WRITE_FILTER_SUPPORTED 1
+#define PNG_FIXED_POINT_SUPPORTED 1
+#define PNG_READ_SUPPORTED 1
+#define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED 1
+#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED 1
+#define PNG_WRITE_FLUSH_SUPPORTED 1
+#define PNG_WRITE_INTERLACING_SUPPORTED 1
+#define PNG_WRITE_TRANSFORMS_SUPPORTED 1
+#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED 1
+#define PNG_INCH_CONVERSIONS_SUPPORTED 1
+#define PNG_USER_MEM_SUPPORTED 1
+#define PNG_SETJMP_SUPPORTED 1
+#define PNG_WARNINGS_SUPPORTED 1
+#define PNG_FLOATING_POINT_SUPPORTED 1
+#define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED 1
+#define PNG_READ_QUANTIZE_SUPPORTED 1
+#define PNG_READ_16BIT_SUPPORTED 1
+#define PNG_ALIGN_MEMORY_SUPPORTED 1
+/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/
+#define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED 1
+#define PNG_SEQUENTIAL_READ_SUPPORTED 1
+#define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED 1
+#define PNG_WRITE_SHIFT_SUPPORTED 1
+#define PNG_ERROR_TEXT_SUPPORTED 1
+#define PNG_WRITE_FILLER_SUPPORTED 1
+#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED 1
+/*#undef PNG_SAFE_LIMITS_SUPPORTED*/
+#define PNG_WRITE_16BIT_SUPPORTED 1
+#define PNG_WRITE_SWAP_ALPHA_SUPPORTED 1
+#define PNG_POINTER_INDEXING_SUPPORTED 1
+#define PNG_FLOATING_ARITHMETIC_SUPPORTED 1
+#define PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED 1
+#define PNG_MNG_FEATURES_SUPPORTED 1
+#define PNG_STDIO_SUPPORTED 1
+#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED 1
+#define PNG_WRITE_PACKSWAP_SUPPORTED 1
+#define PNG_READ_INTERLACING_SUPPORTED 1
+#define PNG_READ_COMPOSITE_NODIV_SUPPORTED 1
+#define PNG_PROGRESSIVE_READ_SUPPORTED 1
+#define PNG_READ_INT_FUNCTIONS_SUPPORTED 1
+#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED 1
+#define PNG_WRITE_INVERT_SUPPORTED 1
+#define PNG_WRITE_PACK_SUPPORTED 1
+#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED 1
+#define PNG_16BIT_SUPPORTED 1
+#define PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED 1
+#define PNG_WRITE_cHRM_SUPPORTED 1
+#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED 1
+#define PNG_WRITE_BGR_SUPPORTED 1
+#define PNG_WRITE_sBIT_SUPPORTED 1
+#define PNG_READ_sBIT_SUPPORTED 1
+#define PNG_READ_TRANSFORMS_SUPPORTED 1
+#define PNG_READ_EXPAND_16_SUPPORTED 1
+#define PNG_WRITE_SWAP_SUPPORTED 1
+#define PNG_READ_SWAP_SUPPORTED 1
+#define PNG_WRITE_oFFs_SUPPORTED 1
+#define PNG_READ_oFFs_SUPPORTED 1
+#define PNG_WRITE_USER_TRANSFORM_SUPPORTED 1
+#define PNG_WRITE_tIME_SUPPORTED 1
+#define PNG_WRITE_INVERT_ALPHA_SUPPORTED 1
+#define PNG_READ_tIME_SUPPORTED 1
+#define PNG_READ_PACKSWAP_SUPPORTED 1
+#define PNG_USER_LIMITS_SUPPORTED 1
+#define PNG_READ_GRAY_TO_RGB_SUPPORTED 1
+#define PNG_READ_STRIP_16_TO_8_SUPPORTED 1
+#define PNG_READ_SCALE_16_TO_8_SUPPORTED 1
+#define PNG_READ_USER_CHUNKS_SUPPORTED 1
+#define PNG_READ_OPT_PLTE_SUPPORTED 1
+#define PNG_UNKNOWN_CHUNKS_SUPPORTED 1
+#define PNG_WRITE_gAMA_SUPPORTED 1
+#define PNG_SET_USER_LIMITS_SUPPORTED 1
+#define PNG_WRITE_iCCP_SUPPORTED 1
+#define PNG_READ_iCCP_SUPPORTED 1
+#define PNG_READ_SHIFT_SUPPORTED 1
+#define PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED 1
+#define PNG_READ_EXPAND_SUPPORTED 1
+#define PNG_WRITE_iTXt_SUPPORTED 1
+#define PNG_READ_iTXt_SUPPORTED 1
+#define PNG_READ_SWAP_ALPHA_SUPPORTED 1
+#define PNG_CONSOLE_IO_SUPPORTED 1
+#define PNG_sBIT_SUPPORTED 1
+#define PNG_WRITE_sRGB_SUPPORTED 1
+#define PNG_READ_sRGB_SUPPORTED 1
+#define PNG_READ_ALPHA_MODE_SUPPORTED 1
+#define PNG_WRITE_sCAL_SUPPORTED 1
+#define PNG_READ_sCAL_SUPPORTED 1
+#define PNG_USER_CHUNKS_SUPPORTED 1
+#define PNG_oFFs_SUPPORTED 1
+#define PNG_READ_GAMMA_SUPPORTED 1
+#define PNG_WRITE_pHYs_SUPPORTED 1
+#define PNG_WRITE_tRNS_SUPPORTED 1
+#define PNG_READ_pHYs_SUPPORTED 1
+#define PNG_READ_tRNS_SUPPORTED 1
+#define PNG_READ_RGB_TO_GRAY_SUPPORTED 1
+#define PNG_tIME_SUPPORTED 1
+#define PNG_WRITE_bKGD_SUPPORTED 1
+#define PNG_READ_bKGD_SUPPORTED 1
+#define PNG_WRITE_zTXt_SUPPORTED 1
+#define PNG_WRITE_pCAL_SUPPORTED 1
+#define PNG_READ_zTXt_SUPPORTED 1
+#define PNG_READ_pCAL_SUPPORTED 1
+#define PNG_WRITE_hIST_SUPPORTED 1
+#define PNG_READ_hIST_SUPPORTED 1
+#define PNG_WRITE_sPLT_SUPPORTED 1
+#define PNG_READ_sPLT_SUPPORTED 1
+#define PNG_READ_INVERT_ALPHA_SUPPORTED 1
+#define PNG_iCCP_SUPPORTED 1
+#define PNG_CONVERT_tIME_SUPPORTED 1
+#define PNG_READ_FILLER_SUPPORTED 1
+#define PNG_READ_USER_TRANSFORM_SUPPORTED 1
+#define PNG_READ_PACK_SUPPORTED 1
+#define PNG_READ_BACKGROUND_SUPPORTED 1
+#define PNG_iTXt_SUPPORTED 1
+#define PNG_READ_cHRM_SUPPORTED 1
+#define PNG_USER_TRANSFORM_INFO_SUPPORTED 1
+#define PNG_sRGB_SUPPORTED 1
+#define PNG_SET_CHUNK_CACHE_LIMIT_SUPPORTED 1
+#define PNG_USER_TRANSFORM_PTR_SUPPORTED 1
+#define PNG_sCAL_SUPPORTED 1
+#define PNG_READ_BGR_SUPPORTED 1
+#define PNG_READ_INVERT_SUPPORTED 1
+#define PNG_READ_COMPRESSED_TEXT_SUPPORTED 1
+#define PNG_pHYs_SUPPORTED 1
+#define PNG_tRNS_SUPPORTED 1
+#define PNG_bKGD_SUPPORTED 1
+#define PNG_pCAL_SUPPORTED 1
+#define PNG_zTXt_SUPPORTED 1
+#define PNG_READ_TEXT_SUPPORTED 1
+#define PNG_hIST_SUPPORTED 1
+#define PNG_READ_STRIP_ALPHA_SUPPORTED 1
+#define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED 1
+#define PNG_sPLT_SUPPORTED 1
+#define PNG_READ_gAMA_SUPPORTED 1
+#define PNG_SAVE_INT_32_SUPPORTED 1
+#define PNG_cHRM_SUPPORTED 1
+#define PNG_CHECK_cHRM_SUPPORTED 1
+#define PNG_gAMA_SUPPORTED 1
+#define PNG_READ_tEXt_SUPPORTED 1
+#define PNG_WRITE_TEXT_SUPPORTED 1
+#define PNG_TEXT_SUPPORTED 1
+#define PNG_WRITE_tEXt_SUPPORTED 1
+#define PNG_tEXt_SUPPORTED 1
+/* end of options */
+#endif /* PNGLCONF_H */

+ 1675 - 0
engine/compilers/android/jni/include/libpng/pngpriv.h

@@ -0,0 +1,1675 @@
+
+/* pngpriv.h - private declarations for use inside libpng
+ *
+ * For conditions of distribution and use, see copyright notice in png.h
+ * Copyright (c) 1998-2012 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Last changed in libpng 1.5.10 [March 29, 2012]
+ *
+ * This code is released under the libpng license.
+ * For conditions of distribution and use, see the disclaimer
+ * and license in png.h
+ */
+
+/* The symbols declared in this file (including the functions declared
+ * as PNG_EXTERN) are PRIVATE.  They are not part of the libpng public
+ * interface, and are not recommended for use by regular applications.
+ * Some of them may become public in the future; others may stay private,
+ * change in an incompatible way, or even disappear.
+ * Although the libpng users are not forbidden to include this header,
+ * they should be well aware of the issues that may arise from doing so.
+ */
+
+#ifndef PNGPRIV_H
+#define PNGPRIV_H
+
+/* Feature Test Macros.  The following are defined here to ensure that correctly
+ * implemented libraries reveal the APIs libpng needs to build and hide those
+ * that are not needed and potentially damaging to the compilation.
+ *
+ * Feature Test Macros must be defined before any system header is included (see
+ * POSIX 1003.1 2.8.2 "POSIX Symbols."
+ *
+ * These macros only have an effect if the operating system supports either
+ * POSIX 1003.1 or C99, or both.  On other operating systems (particularly
+ * Windows/Visual Studio) there is no effect; the OS specific tests below are
+ * still required (as of 2011-05-02.)
+ */
+#define _POSIX_SOURCE 1 /* Just the POSIX 1003.1 and C89 APIs */
+
+/* This is required for the definition of abort(), used as a last ditch
+ * error handler when all else fails.
+ */
+#include <stdlib.h>
+
+/* This is used to find 'offsetof', used below for alignment tests. */
+#include <stddef.h>
+
+#define PNGLIB_BUILD /*libpng is being built, not used*/
+
+#ifdef PNG_USER_CONFIG
+#  include "pngusr.h"
+   /* These should have been defined in pngusr.h */
+#  ifndef PNG_USER_PRIVATEBUILD
+#    define PNG_USER_PRIVATEBUILD "Custom libpng build"
+#  endif
+#  ifndef PNG_USER_DLLFNAME_POSTFIX
+#    define PNG_USER_DLLFNAME_POSTFIX "Cb"
+#  endif
+#endif
+
+/* Is this a build of a DLL where compilation of the object modules requires
+ * different preprocessor settings to those required for a simple library?  If
+ * so PNG_BUILD_DLL must be set.
+ *
+ * If libpng is used inside a DLL but that DLL does not export the libpng APIs
+ * PNG_BUILD_DLL must not be set.  To avoid the code below kicking in build a
+ * static library of libpng then link the DLL against that.
+ */
+#ifndef PNG_BUILD_DLL
+#  ifdef DLL_EXPORT
+      /* This is set by libtool when files are compiled for a DLL; libtool
+       * always compiles twice, even on systems where it isn't necessary.  Set
+       * PNG_BUILD_DLL in case it is necessary:
+       */
+#     define PNG_BUILD_DLL
+#  else
+#     ifdef _WINDLL
+         /* This is set by the Microsoft Visual Studio IDE in projects that
+          * build a DLL.  It can't easily be removed from those projects (it
+          * isn't visible in the Visual Studio UI) so it is a fairly reliable
+          * indication that PNG_IMPEXP needs to be set to the DLL export
+          * attributes.
+          */
+#        define PNG_BUILD_DLL
+#     else
+#        ifdef __DLL__
+            /* This is set by the Borland C system when compiling for a DLL
+             * (as above.)
+             */
+#           define PNG_BUILD_DLL
+#        else
+            /* Add additional compiler cases here. */
+#        endif
+#     endif
+#  endif
+#endif /* Setting PNG_BUILD_DLL if required */
+
+/* See pngconf.h for more details: the builder of the library may set this on
+ * the command line to the right thing for the specific compilation system or it
+ * may be automagically set above (at present we know of no system where it does
+ * need to be set on the command line.)
+ *
+ * PNG_IMPEXP must be set here when building the library to prevent pngconf.h
+ * setting it to the "import" setting for a DLL build.
+ */
+#ifndef PNG_IMPEXP
+#  ifdef PNG_BUILD_DLL
+#     define PNG_IMPEXP PNG_DLL_EXPORT
+#  else
+      /* Not building a DLL, or the DLL doesn't require specific export
+       * definitions.
+       */
+#     define PNG_IMPEXP
+#  endif
+#endif
+
+/* No warnings for private or deprecated functions in the build: */
+#ifndef PNG_DEPRECATED
+#  define PNG_DEPRECATED
+#endif
+#ifndef PNG_PRIVATE
+#  define PNG_PRIVATE
+#endif
+
+#include "png.h"
+#include "pnginfo.h"
+#include "pngstruct.h"
+
+/* pngconf.h does not set PNG_DLL_EXPORT unless it is required, so: */
+#ifndef PNG_DLL_EXPORT
+#  define PNG_DLL_EXPORT
+#endif
+
+/* SECURITY and SAFETY:
+ *
+ * By default libpng is built without any internal limits on image size,
+ * individual heap (png_malloc) allocations or the total amount of memory used.
+ * If PNG_SAFE_LIMITS_SUPPORTED is defined, however, the limits below are used
+ * (unless individually overridden).  These limits are believed to be fairly
+ * safe, but builders of secure systems should verify the values against the
+ * real system capabilities.
+ */
+
+#ifdef PNG_SAFE_LIMITS_SUPPORTED
+   /* 'safe' limits */
+#  ifndef PNG_USER_WIDTH_MAX
+#     define PNG_USER_WIDTH_MAX 1000000
+#  endif
+#  ifndef PNG_USER_HEIGHT_MAX
+#     define PNG_USER_HEIGHT_MAX 1000000
+#  endif
+#  ifndef PNG_USER_CHUNK_CACHE_MAX
+#     define PNG_USER_CHUNK_CACHE_MAX 128
+#  endif
+#  ifndef PNG_USER_CHUNK_MALLOC_MAX
+#     define PNG_USER_CHUNK_MALLOC_MAX 8000000
+#  endif
+#else
+   /* values for no limits */
+#  ifndef PNG_USER_WIDTH_MAX
+#     define PNG_USER_WIDTH_MAX 0x7fffffff
+#  endif
+#  ifndef PNG_USER_HEIGHT_MAX
+#     define PNG_USER_HEIGHT_MAX 0x7fffffff
+#  endif
+#  ifndef PNG_USER_CHUNK_CACHE_MAX
+#     define PNG_USER_CHUNK_CACHE_MAX 0
+#  endif
+#  ifndef PNG_USER_CHUNK_MALLOC_MAX
+#     define PNG_USER_CHUNK_MALLOC_MAX 0
+#  endif
+#endif
+
+/* This is used for 16 bit gamma tables - only the top level pointers are const,
+ * this could be changed:
+ */
+typedef PNG_CONST png_uint_16p FAR * png_const_uint_16pp;
+
+/* Added at libpng-1.2.9 */
+/* Moved to pngpriv.h at libpng-1.5.0 */
+
+/* config.h is created by and PNG_CONFIGURE_LIBPNG is set by the "configure"
+ * script.  We may need it here to get the correct configuration on things
+ * like limits.
+ */
+#ifdef PNG_CONFIGURE_LIBPNG
+#  ifdef HAVE_CONFIG_H
+#    include "config.h"
+#  endif
+#endif
+
+/* Moved to pngpriv.h at libpng-1.5.0 */
+/* NOTE: some of these may have been used in external applications as
+ * these definitions were exposed in pngconf.h prior to 1.5.
+ */
+
+/* If you are running on a machine where you cannot allocate more
+ * than 64K of memory at once, uncomment this.  While libpng will not
+ * normally need that much memory in a chunk (unless you load up a very
+ * large file), zlib needs to know how big of a chunk it can use, and
+ * libpng thus makes sure to check any memory allocation to verify it
+ * will fit into memory.
+ *
+ * zlib provides 'MAXSEG_64K' which, if defined, indicates the
+ * same limit and pngconf.h (already included) sets the limit
+ * if certain operating systems are detected.
+ */
+#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
+#  define PNG_MAX_MALLOC_64K
+#endif
+
+#ifndef PNG_UNUSED
+/* Unused formal parameter warnings are silenced using the following macro
+ * which is expected to have no bad effects on performance (optimizing
+ * compilers will probably remove it entirely).  Note that if you replace
+ * it with something other than whitespace, you must include the terminating
+ * semicolon.
+ */
+#  define PNG_UNUSED(param) (void)param;
+#endif
+
+/* Just a little check that someone hasn't tried to define something
+ * contradictory.
+ */
+#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
+#  undef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 65536L
+#endif
+
+/* PNG_STATIC is used to mark internal file scope functions if they need to be
+ * accessed for implementation tests (see the code in tests/?*).
+ */
+#ifndef PNG_STATIC
+#   define PNG_STATIC static
+#endif
+
+/* C99 restrict is used where possible, to do this 'restrict' is defined as
+ * empty if we can't be sure it is supported.  configure builds have already
+ * done this work.
+ */
+#ifdef PNG_CONFIGURE_LIBPNG
+#  define PNG_RESTRICT restrict
+#else
+   /* Modern compilers support restrict, but assume not for anything not
+    * recognized here:
+    */
+#  if defined __GNUC__ || defined _MSC_VER || defined __WATCOMC__
+#     define PNG_RESTRICT restrict
+#  else
+#     define PNG_RESTRICT
+#  endif
+#endif
+
+/* If warnings or errors are turned off the code is disabled or redirected here.
+ * From 1.5.4 functions have been added to allow very limited formatting of
+ * error and warning messages - this code will also be disabled here.
+ */
+#ifdef PNG_WARNINGS_SUPPORTED
+#  define PNG_WARNING_PARAMETERS(p) png_warning_parameters p;
+#else
+#  define png_warning(s1,s2) ((void)(s1))
+#  define png_chunk_warning(s1,s2) ((void)(s1))
+#  define png_warning_parameter(p,number,string) ((void)0)
+#  define png_warning_parameter_unsigned(p,number,format,value) ((void)0)
+#  define png_warning_parameter_signed(p,number,format,value) ((void)0)
+#  define png_formatted_warning(pp,p,message) ((void)(pp))
+#  define PNG_WARNING_PARAMETERS(p)
+#endif
+#ifndef PNG_ERROR_TEXT_SUPPORTED
+#  define png_error(s1,s2) png_err(s1)
+#  define png_chunk_error(s1,s2) png_err(s1)
+#  define png_fixed_error(s1,s2) png_err(s1)
+#endif
+
+/* C allows up-casts from (void*) to any pointer and (const void*) to any
+ * pointer to a const object.  C++ regards this as a type error and requires an
+ * explicit, static, cast and provides the static_cast<> rune to ensure that
+ * const is not cast away.
+ */
+#ifdef __cplusplus
+#  define png_voidcast(type, value) static_cast<type>(value)
+#else
+#  define png_voidcast(type, value) (value)
+#endif /* __cplusplus */
+
+#ifndef PNG_EXTERN
+/* The functions exported by PNG_EXTERN are internal functions, which
+ * aren't usually used outside the library (as far as I know), so it is
+ * debatable if they should be exported at all.  In the future, when it
+ * is possible to have run-time registry of chunk-handling functions,
+ * some of these might be made available again.
+ *
+ * 1.5.7: turned the use of 'extern' back on, since it is localized to pngpriv.h
+ * it should be safe now (it is unclear why it was turned off.)
+ */
+#  define PNG_EXTERN extern
+#endif
+
+/* Some fixed point APIs are still required even if not exported because
+ * they get used by the corresponding floating point APIs.  This magic
+ * deals with this:
+ */
+#ifdef PNG_FIXED_POINT_SUPPORTED
+#  define PNGFAPI PNGAPI
+#else
+#  define PNGFAPI /* PRIVATE */
+#endif
+
+/* Other defines specific to compilers can go here.  Try to keep
+ * them inside an appropriate ifdef/endif pair for portability.
+ */
+#if defined(PNG_FLOATING_POINT_SUPPORTED) ||\
+    defined(PNG_FLOATING_ARITHMETIC_SUPPORTED)
+   /* png.c requires the following ANSI-C constants if the conversion of
+    * floating point to ASCII is implemented therein:
+    *
+    *  DBL_DIG  Maximum number of decimal digits (can be set to any constant)
+    *  DBL_MIN  Smallest normalized fp number (can be set to an arbitrary value)
+    *  DBL_MAX  Maximum floating point number (can be set to an arbitrary value)
+    */
+#  include <float.h>
+
+#  if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
+    defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
+     /* We need to check that <math.h> hasn't already been included earlier
+      * as it seems it doesn't agree with <fp.h>, yet we should really use
+      * <fp.h> if possible.
+      */
+#    if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
+#      include <fp.h>
+#    endif
+#  else
+#    include <math.h>
+#  endif
+#  if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
+     /* Amiga SAS/C: We must include builtin FPU functions when compiling using
+      * MATH=68881
+      */
+#    include <m68881.h>
+#  endif
+#endif
+
+/* This provides the non-ANSI (far) memory allocation routines. */
+#if defined(__TURBOC__) && defined(__MSDOS__)
+#  include <mem.h>
+#  include <alloc.h>
+#endif
+
+#if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \
+    defined(_WIN32) || defined(__WIN32__)
+#  include <windows.h>  /* defines _WINDOWS_ macro */
+#endif
+
+/* Moved here around 1.5.0beta36 from pngconf.h */
+/* Users may want to use these so they are not private.  Any library
+ * functions that are passed far data must be model-independent.
+ */
+
+/* Memory model/platform independent fns */
+#ifndef PNG_ABORT
+#  ifdef _WINDOWS_
+#    define PNG_ABORT() ExitProcess(0)
+#  else
+#    define PNG_ABORT() abort()
+#  endif
+#endif
+
+#ifdef USE_FAR_KEYWORD
+/* Use this to make far-to-near assignments */
+#  define CHECK   1
+#  define NOCHECK 0
+#  define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
+#  define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
+#  define png_strlen  _fstrlen
+#  define png_memcmp  _fmemcmp    /* SJT: added */
+#  define png_memcpy  _fmemcpy
+#  define png_memset  _fmemset
+#else
+#  ifdef _WINDOWS_  /* Favor Windows over C runtime fns */
+#    define CVT_PTR(ptr)         (ptr)
+#    define CVT_PTR_NOCHECK(ptr) (ptr)
+#    define png_strlen  lstrlenA
+#    define png_memcmp  memcmp
+#    define png_memcpy  CopyMemory
+#    define png_memset  memset
+#  else
+#    define CVT_PTR(ptr)         (ptr)
+#    define CVT_PTR_NOCHECK(ptr) (ptr)
+#    define png_strlen  strlen
+#    define png_memcmp  memcmp      /* SJT: added */
+#    define png_memcpy  memcpy
+#    define png_memset  memset
+#  endif
+#endif
+
+/* These macros may need to be architecture dependent. */
+#define PNG_ALIGN_NONE   0 /* do not use data alignment */
+#define PNG_ALIGN_ALWAYS 1 /* assume unaligned accesses are OK */
+#ifdef offsetof
+#  define PNG_ALIGN_OFFSET 2 /* use offsetof to determine alignment */
+#else
+#  define PNG_ALIGN_OFFSET -1 /* prevent the use of this */
+#endif
+#define PNG_ALIGN_SIZE   3 /* use sizeof to determine alignment */
+
+#ifndef PNG_ALIGN_TYPE
+   /* Default to using aligned access optimizations and requiring alignment to a
+    * multiple of the data type size.  Override in a compiler specific fashion
+    * if necessary by inserting tests here:
+    */
+#  define PNG_ALIGN_TYPE PNG_ALIGN_SIZE
+#endif
+
+#if PNG_ALIGN_TYPE == PNG_ALIGN_SIZE
+   /* This is used because in some compiler implementations non-aligned
+    * structure members are supported, so the offsetof approach below fails.
+    * Set PNG_ALIGN_TO_SIZE=0 for compiler combinations where unaligned access
+    * is good for performance.  Do not do this unless you have tested the result
+    * and understand it.
+    */
+#  define png_alignof(type) (sizeof (type))
+#else
+#  if PNG_ALIGN_TYPE == PNG_ALIGN_OFFSET
+#     define png_alignof(type) offsetof(struct{char c; type t;}, t)
+#  else
+#     if PNG_ALIGN_TYPE == PNG_ALIGN_ALWAYS
+#        define png_alignof(type) (1)
+#     endif
+      /* Else leave png_alignof undefined to prevent use thereof */
+#  endif
+#endif
+
+/* This implicitly assumes alignment is always to a power of 2. */
+#ifdef png_alignof
+#  define png_isaligned(ptr, type)\
+   ((((const char*)ptr-(const char*)0) & (png_alignof(type)-1)) == 0)
+#else
+#  define png_isaligned(ptr, type) 0
+#endif
+
+/* End of memory model/platform independent support */
+/* End of 1.5.0beta36 move from pngconf.h */
+
+/* CONSTANTS and UTILITY MACROS
+ * These are used internally by libpng and not exposed in the API
+ */
+
+/* Various modes of operation.  Note that after an init, mode is set to
+ * zero automatically when the structure is created.  Three of these
+ * are defined in png.h because they need to be visible to applications
+ * that call png_set_unknown_chunk().
+ */
+/* #define PNG_HAVE_IHDR            0x01 (defined in png.h) */
+/* #define PNG_HAVE_PLTE            0x02 (defined in png.h) */
+#define PNG_HAVE_IDAT               0x04
+/* #define PNG_AFTER_IDAT           0x08 (defined in png.h) */
+#define PNG_HAVE_IEND               0x10
+#define PNG_HAVE_gAMA               0x20
+#define PNG_HAVE_cHRM               0x40
+#define PNG_HAVE_sRGB               0x80
+#define PNG_HAVE_CHUNK_HEADER      0x100
+#define PNG_WROTE_tIME             0x200
+#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
+#define PNG_BACKGROUND_IS_GRAY     0x800
+#define PNG_HAVE_PNG_SIGNATURE    0x1000
+#define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
+#define PNG_HAVE_iCCP             0x4000
+
+/* Flags for the transformations the PNG library does on the image data */
+#define PNG_BGR                 0x0001
+#define PNG_INTERLACE           0x0002
+#define PNG_PACK                0x0004
+#define PNG_SHIFT               0x0008
+#define PNG_SWAP_BYTES          0x0010
+#define PNG_INVERT_MONO         0x0020
+#define PNG_QUANTIZE            0x0040
+#define PNG_COMPOSE             0x0080     /* Was PNG_BACKGROUND */
+#define PNG_BACKGROUND_EXPAND   0x0100
+#define PNG_EXPAND_16           0x0200     /* Added to libpng 1.5.2 */
+#define PNG_16_TO_8             0x0400     /* Becomes 'chop' in 1.5.4 */
+#define PNG_RGBA                0x0800
+#define PNG_EXPAND              0x1000
+#define PNG_GAMMA               0x2000
+#define PNG_GRAY_TO_RGB         0x4000
+#define PNG_FILLER              0x8000
+#define PNG_PACKSWAP           0x10000
+#define PNG_SWAP_ALPHA         0x20000
+#define PNG_STRIP_ALPHA        0x40000
+#define PNG_INVERT_ALPHA       0x80000
+#define PNG_USER_TRANSFORM    0x100000
+#define PNG_RGB_TO_GRAY_ERR   0x200000
+#define PNG_RGB_TO_GRAY_WARN  0x400000
+#define PNG_RGB_TO_GRAY       0x600000 /* two bits, RGB_TO_GRAY_ERR|WARN */
+#define PNG_ENCODE_ALPHA      0x800000 /* Added to libpng-1.5.4 */
+#define PNG_ADD_ALPHA         0x1000000 /* Added to libpng-1.2.7 */
+#define PNG_EXPAND_tRNS       0x2000000 /* Added to libpng-1.2.9 */
+#define PNG_SCALE_16_TO_8     0x4000000 /* Added to libpng-1.5.4 */
+                       /*   0x8000000 unused */
+                       /*  0x10000000 unused */
+                       /*  0x20000000 unused */
+                       /*  0x40000000 unused */
+/* Flags for png_create_struct */
+#define PNG_STRUCT_PNG   0x0001
+#define PNG_STRUCT_INFO  0x0002
+
+/* Scaling factor for filter heuristic weighting calculations */
+#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
+#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
+
+/* Flags for the png_ptr->flags rather than declaring a byte for each one */
+#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
+#define PNG_FLAG_ZLIB_CUSTOM_LEVEL        0x0002
+#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL    0x0004
+#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS  0x0008
+#define PNG_FLAG_ZLIB_CUSTOM_METHOD       0x0010
+#define PNG_FLAG_ZLIB_FINISHED            0x0020
+#define PNG_FLAG_ROW_INIT                 0x0040
+#define PNG_FLAG_FILLER_AFTER             0x0080
+#define PNG_FLAG_CRC_ANCILLARY_USE        0x0100
+#define PNG_FLAG_CRC_ANCILLARY_NOWARN     0x0200
+#define PNG_FLAG_CRC_CRITICAL_USE         0x0400
+#define PNG_FLAG_CRC_CRITICAL_IGNORE      0x0800
+#define PNG_FLAG_ASSUME_sRGB              0x1000  /* Added to libpng-1.5.4 */
+#define PNG_FLAG_OPTIMIZE_ALPHA           0x2000  /* Added to libpng-1.5.4 */
+#define PNG_FLAG_DETECT_UNINITIALIZED     0x4000  /* Added to libpng-1.5.4 */
+#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS      0x8000
+#define PNG_FLAG_KEEP_UNSAFE_CHUNKS       0x10000
+#define PNG_FLAG_LIBRARY_MISMATCH         0x20000
+#define PNG_FLAG_STRIP_ERROR_NUMBERS      0x40000
+#define PNG_FLAG_STRIP_ERROR_TEXT         0x80000
+#define PNG_FLAG_MALLOC_NULL_MEM_OK       0x100000
+                                  /*      0x200000  unused */
+                                  /*      0x400000  unused */
+#define PNG_FLAG_BENIGN_ERRORS_WARN       0x800000  /* Added to libpng-1.4.0 */
+#define PNG_FLAG_ZTXT_CUSTOM_STRATEGY    0x1000000  /* 5 lines added */
+#define PNG_FLAG_ZTXT_CUSTOM_LEVEL       0x2000000  /* to libpng-1.5.4 */
+#define PNG_FLAG_ZTXT_CUSTOM_MEM_LEVEL   0x4000000
+#define PNG_FLAG_ZTXT_CUSTOM_WINDOW_BITS 0x8000000
+#define PNG_FLAG_ZTXT_CUSTOM_METHOD      0x10000000
+                                  /*     0x20000000  unused */
+                                  /*     0x40000000  unused */
+
+#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
+                                     PNG_FLAG_CRC_ANCILLARY_NOWARN)
+
+#define PNG_FLAG_CRC_CRITICAL_MASK  (PNG_FLAG_CRC_CRITICAL_USE | \
+                                     PNG_FLAG_CRC_CRITICAL_IGNORE)
+
+#define PNG_FLAG_CRC_MASK           (PNG_FLAG_CRC_ANCILLARY_MASK | \
+                                     PNG_FLAG_CRC_CRITICAL_MASK)
+
+/* zlib.h declares a magic type 'uInt' that limits the amount of data that zlib
+ * can handle at once.  This type need be no larger than 16 bits (so maximum of
+ * 65535), this define allows us to discover how big it is, but limited by the
+ * maximuum for png_size_t.  The value can be overriden in a library build
+ * (pngusr.h, or set it in CPPFLAGS) and it works to set it to a considerably
+ * lower value (e.g. 255 works).  A lower value may help memory usage (slightly)
+ * and may even improve performance on some systems (and degrade it on others.)
+ */
+#ifndef ZLIB_IO_MAX
+#  define ZLIB_IO_MAX ((uInt)-1)
+#endif
+
+/* Save typing and make code easier to understand */
+
+#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
+   abs((int)((c1).green) - (int)((c2).green)) + \
+   abs((int)((c1).blue) - (int)((c2).blue)))
+
+/* Added to libpng-1.2.6 JB */
+#define PNG_ROWBYTES(pixel_bits, width) \
+    ((pixel_bits) >= 8 ? \
+    ((png_size_t)(width) * (((png_size_t)(pixel_bits)) >> 3)) : \
+    (( ((png_size_t)(width) * ((png_size_t)(pixel_bits))) + 7) >> 3) )
+
+/* PNG_OUT_OF_RANGE returns true if value is outside the range
+ * ideal-delta..ideal+delta.  Each argument is evaluated twice.
+ * "ideal" and "delta" should be constants, normally simple
+ * integers, "value" a variable. Added to libpng-1.2.6 JB
+ */
+#define PNG_OUT_OF_RANGE(value, ideal, delta) \
+   ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
+
+/* Conversions between fixed and floating point, only defined if
+ * required (to make sure the code doesn't accidentally use float
+ * when it is supposedly disabled.)
+ */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+/* The floating point conversion can't overflow, though it can and
+ * does lose accuracy relative to the original fixed point value.
+ * In practice this doesn't matter because png_fixed_point only
+ * stores numbers with very low precision.  The png_ptr and s
+ * arguments are unused by default but are there in case error
+ * checking becomes a requirement.
+ */
+#define png_float(png_ptr, fixed, s) (.00001 * (fixed))
+
+/* The fixed point conversion performs range checking and evaluates
+ * its argument multiple times, so must be used with care.  The
+ * range checking uses the PNG specification values for a signed
+ * 32 bit fixed point value except that the values are deliberately
+ * rounded-to-zero to an integral value - 21474 (21474.83 is roughly
+ * (2^31-1) * 100000). 's' is a string that describes the value being
+ * converted.
+ *
+ * NOTE: this macro will raise a png_error if the range check fails,
+ * therefore it is normally only appropriate to use this on values
+ * that come from API calls or other sources where an out of range
+ * error indicates a programming error, not a data error!
+ *
+ * NOTE: by default this is off - the macro is not used - because the
+ * function call saves a lot of code.
+ */
+#ifdef PNG_FIXED_POINT_MACRO_SUPPORTED
+#define png_fixed(png_ptr, fp, s) ((fp) <= 21474 && (fp) >= -21474 ?\
+    ((png_fixed_point)(100000 * (fp))) : (png_fixed_error(png_ptr, s),0))
+#else
+PNG_EXTERN png_fixed_point png_fixed PNGARG((png_structp png_ptr, double fp,
+   png_const_charp text));
+#endif
+#endif
+
+/* Constants for known chunk types.  If you need to add a chunk, define the name
+ * here.  For historical reasons these constants have the form png_<name>; i.e.
+ * the prefix is lower case.  Please use decimal values as the parameters to
+ * match the ISO PNG specification and to avoid relying on the C locale
+ * interpretation of character values.
+ *
+ * Prior to 1.5.6 these constants were strings, as of 1.5.6 png_uint_32 values
+ * are computed and a new macro (PNG_STRING_FROM_CHUNK) added to allow a string
+ * to be generated if required.
+ *
+ * PNG_32b correctly produces a value shifted by up to 24 bits, even on
+ * architectures where (int) is only 16 bits.
+ */
+#define PNG_32b(b,s) ((png_uint_32)(b) << (s))
+#define PNG_CHUNK(b1,b2,b3,b4) \
+   (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
+
+#define png_IHDR PNG_CHUNK( 73,  72,  68,  82)
+#define png_IDAT PNG_CHUNK( 73,  68,  65,  84)
+#define png_IEND PNG_CHUNK( 73,  69,  78,  68)
+#define png_PLTE PNG_CHUNK( 80,  76,  84,  69)
+#define png_bKGD PNG_CHUNK( 98,  75,  71,  68)
+#define png_cHRM PNG_CHUNK( 99,  72,  82,  77)
+#define png_gAMA PNG_CHUNK(103,  65,  77,  65)
+#define png_hIST PNG_CHUNK(104,  73,  83,  84)
+#define png_iCCP PNG_CHUNK(105,  67,  67,  80)
+#define png_iTXt PNG_CHUNK(105,  84,  88, 116)
+#define png_oFFs PNG_CHUNK(111,  70,  70, 115)
+#define png_pCAL PNG_CHUNK(112,  67,  65,  76)
+#define png_sCAL PNG_CHUNK(115,  67,  65,  76)
+#define png_pHYs PNG_CHUNK(112,  72,  89, 115)
+#define png_sBIT PNG_CHUNK(115,  66,  73,  84)
+#define png_sPLT PNG_CHUNK(115,  80,  76,  84)
+#define png_sRGB PNG_CHUNK(115,  82,  71,  66)
+#define png_sTER PNG_CHUNK(115,  84,  69,  82)
+#define png_tEXt PNG_CHUNK(116,  69,  88, 116)
+#define png_tIME PNG_CHUNK(116,  73,  77,  69)
+#define png_tRNS PNG_CHUNK(116,  82,  78,  83)
+#define png_zTXt PNG_CHUNK(122,  84,  88, 116)
+
+/* The following will work on (signed char*) strings, whereas the get_uint_32
+ * macro will fail on top-bit-set values because of the sign extension.
+ */
+#define PNG_CHUNK_FROM_STRING(s)\
+   PNG_CHUNK(0xff&(s)[0], 0xff&(s)[1], 0xff&(s)[2], 0xff&(s)[3])
+
+/* This uses (char), not (png_byte) to avoid warnings on systems where (char) is
+ * signed and the argument is a (char[])  This macro will fail miserably on
+ * systems where (char) is more than 8 bits.
+ */
+#define PNG_STRING_FROM_CHUNK(s,c)\
+   (void)(((char*)(s))[0]=(char)((c)>>24), ((char*)(s))[1]=(char)((c)>>16),\
+   ((char*)(s))[2]=(char)((c)>>8), ((char*)(s))[3]=(char)((c)))
+
+/* Do the same but terminate with a null character. */
+#define PNG_CSTRING_FROM_CHUNK(s,c)\
+   (void)(PNG_STRING_FROM_CHUNK(s,c), ((char*)(s))[4] = 0)
+
+/* Test on flag values as defined in the spec (section 5.4): */
+#define PNG_CHUNK_ANCILLIARY(c)   (1 & ((c) >> 29))
+#define PNG_CHUNK_CRITICAL(c)     (!PNG_CHUNK_ANCILLIARY(c))
+#define PNG_CHUNK_PRIVATE(c)      (1 & ((c) >> 21))
+#define PNG_CHUNK_RESERVED(c)     (1 & ((c) >> 13))
+#define PNG_CHUNK_SAFE_TO_COPY(c) (1 & ((c) >>  5))
+
+/* Gamma values (new at libpng-1.5.4): */
+#define PNG_GAMMA_MAC_OLD 151724  /* Assume '1.8' is really 2.2/1.45! */
+#define PNG_GAMMA_MAC_INVERSE 65909
+#define PNG_GAMMA_sRGB_INVERSE 45455
+
+
+/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* These functions are used internally in the code.  They generally
+ * shouldn't be used unless you are writing code to add or replace some
+ * functionality in libpng.  More information about most functions can
+ * be found in the files where the functions are located.
+ */
+
+/* Check the user version string for compatibility, returns false if the version
+ * numbers aren't compatible.
+ */
+PNG_EXTERN int png_user_version_check(png_structp png_ptr,
+   png_const_charp user_png_ver);
+
+/* Allocate memory for an internal libpng struct */
+PNG_EXTERN PNG_FUNCTION(png_voidp,png_create_struct,PNGARG((int type)),
+   PNG_ALLOCATED);
+
+/* Free memory from internal libpng struct */
+PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
+
+PNG_EXTERN PNG_FUNCTION(png_voidp,png_create_struct_2,
+   PNGARG((int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)),
+   PNG_ALLOCATED);
+PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
+    png_free_ptr free_fn, png_voidp mem_ptr));
+
+/* Free any memory that info_ptr points to and reset struct. */
+PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+
+/* Function to allocate memory for zlib.  PNGAPI is disallowed. */
+PNG_EXTERN PNG_FUNCTION(voidpf,png_zalloc,PNGARG((voidpf png_ptr, uInt items,
+   uInt size)),PNG_ALLOCATED);
+
+/* Function to free memory for zlib.  PNGAPI is disallowed. */
+PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
+
+/* Next four functions are used internally as callbacks.  PNGCBAPI is required
+ * but not PNG_EXPORT.  PNGAPI added at libpng version 1.2.3, changed to
+ * PNGCBAPI at 1.5.0
+ */
+
+PNG_EXTERN void PNGCBAPI png_default_read_data PNGARG((png_structp png_ptr,
+    png_bytep data, png_size_t length));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void PNGCBAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
+    png_bytep buffer, png_size_t length));
+#endif
+
+PNG_EXTERN void PNGCBAPI png_default_write_data PNGARG((png_structp png_ptr,
+    png_bytep data, png_size_t length));
+
+#ifdef PNG_WRITE_FLUSH_SUPPORTED
+#  ifdef PNG_STDIO_SUPPORTED
+PNG_EXTERN void PNGCBAPI png_default_flush PNGARG((png_structp png_ptr));
+#  endif
+#endif
+
+/* Reset the CRC variable */
+PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
+
+/* Write the "data" buffer to whatever output you are using */
+PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr,
+    png_const_bytep data, png_size_t length));
+
+/* Read and check the PNG file signature */
+PNG_EXTERN void png_read_sig PNGARG((png_structp png_ptr, png_infop info_ptr));
+
+/* Read the chunk header (length + type name) */
+PNG_EXTERN png_uint_32 png_read_chunk_header PNGARG((png_structp png_ptr));
+
+/* Read data from whatever input you are using into the "data" buffer */
+PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
+    png_size_t length));
+
+/* Read bytes into buf, and update png_ptr->crc */
+PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
+    png_size_t length));
+
+/* Decompress data in a chunk that uses compression */
+#if defined(PNG_READ_COMPRESSED_TEXT_SUPPORTED)
+PNG_EXTERN void png_decompress_chunk PNGARG((png_structp png_ptr,
+    int comp_type, png_size_t chunklength, png_size_t prefix_length,
+    png_size_t *data_length));
+#endif
+
+/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
+PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
+
+/* Read the CRC from the file and compare it to the libpng calculated CRC */
+PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
+
+/* Calculate the CRC over a section of data.  Note that we are only
+ * passing a maximum of 64K on systems that have this as a memory limit,
+ * since this is the maximum buffer size we can specify.
+ */
+PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr,
+    png_const_bytep ptr, png_size_t length));
+
+#ifdef PNG_WRITE_FLUSH_SUPPORTED
+PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
+#endif
+
+/* Write various chunks */
+
+/* Write the IHDR chunk, and update the png_struct with the necessary
+ * information.
+ */
+PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
+    png_uint_32 height,
+    int bit_depth, int color_type, int compression_method, int filter_method,
+    int interlace_method));
+
+PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr,
+    png_const_colorp palette, png_uint_32 num_pal));
+
+PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
+    png_size_t length));
+
+PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
+
+#ifdef PNG_WRITE_gAMA_SUPPORTED
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
+#  endif
+#  ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr,
+    png_fixed_point file_gamma));
+#  endif
+#endif
+
+#ifdef PNG_WRITE_sBIT_SUPPORTED
+PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr,
+    png_const_color_8p sbit, int color_type));
+#endif
+
+#ifdef PNG_WRITE_cHRM_SUPPORTED
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
+    double white_x, double white_y,
+    double red_x, double red_y, double green_x, double green_y,
+    double blue_x, double blue_y));
+#  endif
+PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
+    png_fixed_point int_white_x, png_fixed_point int_white_y,
+    png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+    int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+    png_fixed_point int_blue_y));
+#endif
+
+#ifdef PNG_WRITE_sRGB_SUPPORTED
+PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
+    int intent));
+#endif
+
+#ifdef PNG_WRITE_iCCP_SUPPORTED
+PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
+    png_const_charp name, int compression_type,
+    png_const_charp profile, int proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#ifdef PNG_WRITE_sPLT_SUPPORTED
+PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
+    png_const_sPLT_tp palette));
+#endif
+
+#ifdef PNG_WRITE_tRNS_SUPPORTED
+PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr,
+    png_const_bytep trans, png_const_color_16p values, int number,
+    int color_type));
+#endif
+
+#ifdef PNG_WRITE_bKGD_SUPPORTED
+PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
+    png_const_color_16p values, int color_type));
+#endif
+
+#ifdef PNG_WRITE_hIST_SUPPORTED
+PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr,
+    png_const_uint_16p hist, int num_hist));
+#endif
+
+/* Chunks that have keywords */
+#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
+    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
+    png_const_charp key, png_charpp new_key));
+#endif
+
+#ifdef PNG_WRITE_tEXt_SUPPORTED
+PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_const_charp key,
+    png_const_charp text, png_size_t text_len));
+#endif
+
+#ifdef PNG_WRITE_zTXt_SUPPORTED
+PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_const_charp key,
+    png_const_charp text, png_size_t text_len, int compression));
+#endif
+
+#ifdef PNG_WRITE_iTXt_SUPPORTED
+PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
+    int compression, png_const_charp key, png_const_charp lang,
+    png_const_charp lang_key, png_const_charp text));
+#endif
+
+#ifdef PNG_TEXT_SUPPORTED  /* Added at version 1.0.14 and 1.2.4 */
+PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_const_textp text_ptr, int num_text));
+#endif
+
+#ifdef PNG_WRITE_oFFs_SUPPORTED
+PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
+    png_int_32 x_offset, png_int_32 y_offset, int unit_type));
+#endif
+
+#ifdef PNG_WRITE_pCAL_SUPPORTED
+PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
+    png_int_32 X0, png_int_32 X1, int type, int nparams,
+    png_const_charp units, png_charpp params));
+#endif
+
+#ifdef PNG_WRITE_pHYs_SUPPORTED
+PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
+    png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
+    int unit_type));
+#endif
+
+#ifdef PNG_WRITE_tIME_SUPPORTED
+PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
+    png_const_timep mod_time));
+#endif
+
+#ifdef PNG_WRITE_sCAL_SUPPORTED
+PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
+    int unit, png_const_charp width, png_const_charp height));
+#endif
+
+/* Called when finished processing a row of data */
+PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
+
+/* Internal use only.   Called before first row of data */
+PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
+
+/* Combine a row of data, dealing with alpha, etc. if requested.  'row' is an
+ * array of png_ptr->width pixels.  If the image is not interlaced or this
+ * is the final pass this just does a png_memcpy, otherwise the "display" flag
+ * is used to determine whether to copy pixels that are not in the current pass.
+ *
+ * Because 'png_do_read_interlace' (below) replicates pixels this allows this
+ * function to achieve the documented 'blocky' appearance during interlaced read
+ * if display is 1 and the 'sparkle' appearance, where existing pixels in 'row'
+ * are not changed if they are not in the current pass, when display is 0.
+ *
+ * 'display' must be 0 or 1, otherwise the memcpy will be done regardless.
+ *
+ * The API always reads from the png_struct row buffer and always assumes that
+ * it is full width (png_do_read_interlace has already been called.)
+ *
+ * This function is only ever used to write to row buffers provided by the
+ * caller of the relevant libpng API and the row must have already been
+ * transformed by the read transformations.
+ *
+ * The PNG_USE_COMPILE_TIME_MASKS option causes generation of pre-computed
+ * bitmasks for use within the code, otherwise runtime generated masks are used.
+ * The default is compile time masks.
+ */
+#ifndef PNG_USE_COMPILE_TIME_MASKS
+#  define PNG_USE_COMPILE_TIME_MASKS 1
+#endif
+PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
+    int display));
+
+#ifdef PNG_READ_INTERLACING_SUPPORTED
+/* Expand an interlaced row: the 'row_info' describes the pass data that has
+ * been read in and must correspond to the pixels in 'row', the pixels are
+ * expanded (moved apart) in 'row' to match the final layout, when doing this
+ * the pixels are *replicated* to the intervening space.  This is essential for
+ * the correct operation of png_combine_row, above.
+ */
+PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
+    png_bytep row, int pass, png_uint_32 transformations));
+#endif
+
+/* GRR TO DO (2.0 or whenever):  simplify other internal calling interfaces */
+
+#ifdef PNG_WRITE_INTERLACING_SUPPORTED
+/* Grab pixels out of a row for an interlaced pass */
+PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
+    png_bytep row, int pass));
+#endif
+
+/* Unfilter a row: check the filter value before calling this, there is no point
+ * calling it for PNG_FILTER_VALUE_NONE.
+ */
+PNG_EXTERN void png_read_filter_row PNGARG((png_structp pp, png_row_infop
+    row_info, png_bytep row, png_const_bytep prev_row, int filter));
+
+PNG_EXTERN void png_read_filter_row_up_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_sub3_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_sub4_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_avg3_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_avg4_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_paeth3_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+PNG_EXTERN void png_read_filter_row_paeth4_neon PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep prev_row));
+
+/* Choose the best filter to use and filter the row data */
+PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
+    png_row_infop row_info));
+
+/* Finish a row while reading, dealing with interlacing passes, etc. */
+PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
+
+/* Initialize the row buffers, etc. */
+PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
+
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+/* Optional call to update the users info structure */
+PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+#endif
+
+/* These are the functions that do the transformations */
+#ifdef PNG_READ_FILLER_SUPPORTED
+PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
+    png_bytep row, png_uint_32 filler, png_uint_32 flags));
+#endif
+
+#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
+PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
+PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
+PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
+PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
+    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_strip_channel PNGARG((png_row_infop row_info,
+    png_bytep row, int at_start));
+#endif
+
+#ifdef PNG_16BIT_SUPPORTED
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \
+    defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
+PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr,
+    png_row_infop row_info, png_bytep row));
+#endif
+
+#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
+PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_PACK_SUPPORTED
+PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_SHIFT_SUPPORTED
+PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_color_8p sig_bits));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
+PNG_EXTERN void png_do_scale_16_to_8 PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
+PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_READ_QUANTIZE_SUPPORTED
+PNG_EXTERN void png_do_quantize PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_bytep palette_lookup,
+    png_const_bytep quantize_lookup));
+
+#  ifdef PNG_CORRECT_PALETTE_SUPPORTED
+PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
+    png_colorp palette, int num_palette));
+#  endif
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+#ifdef PNG_WRITE_PACK_SUPPORTED
+PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 bit_depth));
+#endif
+
+#ifdef PNG_WRITE_SHIFT_SUPPORTED
+PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_color_8p bit_depth));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
+    defined(PNG_READ_ALPHA_MODE_SUPPORTED)
+PNG_EXTERN void png_do_compose PNGARG((png_row_infop row_info,
+    png_bytep row, png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_GAMMA_SUPPORTED
+PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info,
+    png_bytep row, png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
+PNG_EXTERN void png_do_encode_alpha PNGARG((png_row_infop row_info,
+   png_bytep row, png_structp png_ptr));
+#endif
+
+#ifdef PNG_READ_EXPAND_SUPPORTED
+PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_colorp palette, png_const_bytep trans,
+    int num_trans));
+PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
+    png_bytep row, png_const_color_16p trans_color));
+#endif
+
+#ifdef PNG_READ_EXPAND_16_SUPPORTED
+PNG_EXTERN void png_do_expand_16 PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+/* The following decodes the appropriate chunks, and does error correction,
+ * then calls the appropriate callback for the chunk if it is valid.
+ */
+
+/* Decode the IHDR chunk */
+PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+
+#ifdef PNG_READ_bKGD_SUPPORTED
+PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_cHRM_SUPPORTED
+PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_gAMA_SUPPORTED
+PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_hIST_SUPPORTED
+PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_iCCP_SUPPORTED
+PNG_EXTERN void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif /* PNG_READ_iCCP_SUPPORTED */
+
+#ifdef PNG_READ_iTXt_SUPPORTED
+PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_oFFs_SUPPORTED
+PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_pCAL_SUPPORTED
+PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_pHYs_SUPPORTED
+PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_sBIT_SUPPORTED
+PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_sCAL_SUPPORTED
+PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_sPLT_SUPPORTED
+PNG_EXTERN void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif /* PNG_READ_sPLT_SUPPORTED */
+
+#ifdef PNG_READ_sRGB_SUPPORTED
+PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_tEXt_SUPPORTED
+PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_tIME_SUPPORTED
+PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_tRNS_SUPPORTED
+PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+#ifdef PNG_READ_zTXt_SUPPORTED
+PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+    png_uint_32 length));
+#endif
+
+PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_uint_32 length));
+
+PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
+    png_uint_32 chunk_name));
+
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+/* Exactly as png_handle_as_unknown() except that the argument is a 32-bit chunk
+ * name, not a string.
+ */
+PNG_EXTERN int png_chunk_unknown_handling PNGARG((png_structp png_ptr,
+    png_uint_32 chunk_name));
+#endif
+
+/* Handle the transformations for reading and writing */
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr,
+   png_row_infop row_info));
+#endif
+#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
+PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr,
+   png_row_infop row_info));
+#endif
+
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
+    png_uint_32 length));
+PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
+    png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
+    png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
+PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
+#  ifdef PNG_READ_tEXt_SUPPORTED
+PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+#  endif
+#  ifdef PNG_READ_zTXt_SUPPORTED
+PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+#  endif
+#  ifdef PNG_READ_iTXt_SUPPORTED
+PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
+    png_infop info_ptr));
+#  endif
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
+    png_bytep row));
+PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
+    png_bytep row));
+#endif
+
+/* Added at libpng version 1.4.0 */
+#ifdef PNG_CHECK_cHRM_SUPPORTED
+PNG_EXTERN int png_check_cHRM_fixed PNGARG((png_structp png_ptr,
+    png_fixed_point int_white_x, png_fixed_point int_white_y,
+    png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+    int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+    png_fixed_point int_blue_y));
+#endif
+
+#ifdef PNG_CHECK_cHRM_SUPPORTED
+/* Added at libpng version 1.2.34 and 1.4.0 */
+/* Currently only used by png_check_cHRM_fixed */
+PNG_EXTERN void png_64bit_product PNGARG((long v1, long v2,
+    unsigned long *hi_product, unsigned long *lo_product));
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+/* Added at libpng version 1.5.5 */
+typedef struct png_xy
+{
+   png_fixed_point redx, redy;
+   png_fixed_point greenx, greeny;
+   png_fixed_point bluex, bluey;
+   png_fixed_point whitex, whitey;
+} png_xy;
+
+typedef struct png_XYZ
+{
+   png_fixed_point redX, redY, redZ;
+   png_fixed_point greenX, greenY, greenZ;
+   png_fixed_point blueX, blueY, blueZ;
+} png_XYZ;
+
+/* The conversion APIs return 0 on success, non-zero on a parameter error. They
+ * allow conversion between the above representations of a color encoding.  When
+ * converting from XYZ end points to chromaticities the absolute magnitude of
+ * the end points is lost, when converting back the sum of the Y values of the
+ * three end points will be 1.0
+ */
+PNG_EXTERN int png_xy_from_XYZ PNGARG((png_xy *xy, png_XYZ XYZ));
+PNG_EXTERN int png_XYZ_from_xy PNGARG((png_XYZ *XYZ, png_xy xy));
+PNG_EXTERN int png_XYZ_from_xy_checked PNGARG((png_structp png_ptr,
+   png_XYZ *XYZ, png_xy xy));
+#endif
+
+/* Added at libpng version 1.4.0 */
+PNG_EXTERN void png_check_IHDR PNGARG((png_structp png_ptr,
+    png_uint_32 width, png_uint_32 height, int bit_depth,
+    int color_type, int interlace_type, int compression_type,
+    int filter_type));
+
+/* Added at libpng version 1.5.10 */
+#if defined(PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED) || \
+    defined(PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED)
+PNG_EXTERN void png_do_check_palette_indexes PNGARG((png_structp png_ptr,
+    png_row_infop row_info));
+#endif
+
+/* Free all memory used by the read (old method - NOT DLL EXPORTED) */
+PNG_EXTERN void png_read_destroy PNGARG((png_structp png_ptr,
+    png_infop info_ptr, png_infop end_info_ptr));
+
+/* Free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
+PNG_EXTERN void png_write_destroy PNGARG((png_structp png_ptr));
+
+#ifdef USE_FAR_KEYWORD  /* memory model conversion function */
+PNG_EXTERN void *png_far_to_near PNGARG((png_structp png_ptr, png_voidp ptr,
+    int check));
+#endif /* USE_FAR_KEYWORD */
+
+#if defined(PNG_FLOATING_POINT_SUPPORTED) && defined(PNG_ERROR_TEXT_SUPPORTED)
+PNG_EXTERN PNG_FUNCTION(void, png_fixed_error, (png_structp png_ptr,
+   png_const_charp name),PNG_NORETURN);
+#endif
+
+/* Puts 'string' into 'buffer' at buffer[pos], taking care never to overwrite
+ * the end.  Always leaves the buffer nul terminated.  Never errors out (and
+ * there is no error code.)
+ */
+PNG_EXTERN size_t png_safecat(png_charp buffer, size_t bufsize, size_t pos,
+    png_const_charp string);
+
+/* Various internal functions to handle formatted warning messages, currently
+ * only implemented for warnings.
+ */
+#if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_TIME_RFC1123_SUPPORTED)
+/* Utility to dump an unsigned value into a buffer, given a start pointer and
+ * and end pointer (which should point just *beyond* the end of the buffer!)
+ * Returns the pointer to the start of the formatted string.  This utility only
+ * does unsigned values.
+ */
+PNG_EXTERN png_charp png_format_number(png_const_charp start, png_charp end,
+   int format, png_alloc_size_t number);
+
+/* Convenience macro that takes an array: */
+#define PNG_FORMAT_NUMBER(buffer,format,number) \
+   png_format_number(buffer, buffer + (sizeof buffer), format, number)
+
+/* Suggested size for a number buffer (enough for 64 bits and a sign!) */
+#define PNG_NUMBER_BUFFER_SIZE 24
+
+/* These are the integer formats currently supported, the name is formed from
+ * the standard printf(3) format string.
+ */
+#define PNG_NUMBER_FORMAT_u     1 /* chose unsigned API! */
+#define PNG_NUMBER_FORMAT_02u   2
+#define PNG_NUMBER_FORMAT_d     1 /* chose signed API! */
+#define PNG_NUMBER_FORMAT_02d   2
+#define PNG_NUMBER_FORMAT_x     3
+#define PNG_NUMBER_FORMAT_02x   4
+#define PNG_NUMBER_FORMAT_fixed 5 /* choose the signed API */
+#endif
+
+#ifdef PNG_WARNINGS_SUPPORTED
+/* New defines and members adding in libpng-1.5.4 */
+#  define PNG_WARNING_PARAMETER_SIZE 32
+#  define PNG_WARNING_PARAMETER_COUNT 8
+
+/* An l-value of this type has to be passed to the APIs below to cache the
+ * values of the parameters to a formatted warning message.
+ */
+typedef char png_warning_parameters[PNG_WARNING_PARAMETER_COUNT][
+   PNG_WARNING_PARAMETER_SIZE];
+
+PNG_EXTERN void png_warning_parameter(png_warning_parameters p, int number,
+    png_const_charp string);
+    /* Parameters are limited in size to PNG_WARNING_PARAMETER_SIZE characters,
+     * including the trailing '\0'.
+     */
+PNG_EXTERN void png_warning_parameter_unsigned(png_warning_parameters p,
+    int number, int format, png_alloc_size_t value);
+    /* Use png_alloc_size_t because it is an unsigned type as big as any we
+     * need to output.  Use the following for a signed value.
+     */
+PNG_EXTERN void png_warning_parameter_signed(png_warning_parameters p,
+    int number, int format, png_int_32 value);
+
+PNG_EXTERN void png_formatted_warning(png_structp png_ptr,
+    png_warning_parameters p, png_const_charp message);
+    /* 'message' follows the X/Open approach of using @1, @2 to insert
+     * parameters previously supplied using the above functions.  Errors in
+     * specifying the paramters will simple result in garbage substitutions.
+     */
+#endif
+
+/* ASCII to FP interfaces, currently only implemented if sCAL
+ * support is required.
+ */
+#if defined(PNG_READ_sCAL_SUPPORTED)
+/* MAX_DIGITS is actually the maximum number of characters in an sCAL
+ * width or height, derived from the precision (number of significant
+ * digits - a build time settable option) and assumpitions about the
+ * maximum ridiculous exponent.
+ */
+#define PNG_sCAL_MAX_DIGITS (PNG_sCAL_PRECISION+1/*.*/+1/*E*/+10/*exponent*/)
+
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_ascii_from_fp PNGARG((png_structp png_ptr, png_charp ascii,
+    png_size_t size, double fp, unsigned int precision));
+#endif /* FLOATING_POINT */
+
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_ascii_from_fixed PNGARG((png_structp png_ptr,
+    png_charp ascii, png_size_t size, png_fixed_point fp));
+#endif /* FIXED_POINT */
+#endif /* READ_sCAL */
+
+#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
+/* An internal API to validate the format of a floating point number.
+ * The result is the index of the next character.  If the number is
+ * not valid it will be the index of a character in the supposed number.
+ *
+ * The format of a number is defined in the PNG extensions specification
+ * and this API is strictly conformant to that spec, not anyone elses!
+ *
+ * The format as a regular expression is:
+ *
+ * [+-]?[0-9]+.?([Ee][+-]?[0-9]+)?
+ *
+ * or:
+ *
+ * [+-]?.[0-9]+(.[0-9]+)?([Ee][+-]?[0-9]+)?
+ *
+ * The complexity is that either integer or fraction must be present and the
+ * fraction is permitted to have no digits only if the integer is present.
+ *
+ * NOTE: The dangling E problem.
+ *   There is a PNG valid floating point number in the following:
+ *
+ *       PNG floating point numb1.ers are not greedy.
+ *
+ *   Working this out requires *TWO* character lookahead (because of the
+ *   sign), the parser does not do this - it will fail at the 'r' - this
+ *   doesn't matter for PNG sCAL chunk values, but it requires more care
+ *   if the value were ever to be embedded in something more complex.  Use
+ *   ANSI-C strtod if you need the lookahead.
+ */
+/* State table for the parser. */
+#define PNG_FP_INTEGER    0  /* before or in integer */
+#define PNG_FP_FRACTION   1  /* before or in fraction */
+#define PNG_FP_EXPONENT   2  /* before or in exponent */
+#define PNG_FP_STATE      3  /* mask for the above */
+#define PNG_FP_SAW_SIGN   4  /* Saw +/- in current state */
+#define PNG_FP_SAW_DIGIT  8  /* Saw a digit in current state */
+#define PNG_FP_SAW_DOT   16  /* Saw a dot in current state */
+#define PNG_FP_SAW_E     32  /* Saw an E (or e) in current state */
+#define PNG_FP_SAW_ANY   60  /* Saw any of the above 4 */
+
+/* These three values don't affect the parser.  They are set but not used.
+ */
+#define PNG_FP_WAS_VALID 64  /* Preceding substring is a valid fp number */
+#define PNG_FP_NEGATIVE 128  /* A negative number, including "-0" */
+#define PNG_FP_NONZERO  256  /* A non-zero value */
+#define PNG_FP_STICKY   448  /* The above three flags */
+
+/* This is available for the caller to store in 'state' if required.  Do not
+ * call the parser after setting it (the parser sometimes clears it.)
+ */
+#define PNG_FP_INVALID  512  /* Available for callers as a distinct value */
+
+/* Result codes for the parser (boolean - true meants ok, false means
+ * not ok yet.)
+ */
+#define PNG_FP_MAYBE      0  /* The number may be valid in the future */
+#define PNG_FP_OK         1  /* The number is valid */
+
+/* Tests on the sticky non-zero and negative flags.  To pass these checks
+ * the state must also indicate that the whole number is valid - this is
+ * achieved by testing PNG_FP_SAW_DIGIT (see the implementation for why this
+ * is equivalent to PNG_FP_OK above.)
+ */
+#define PNG_FP_NZ_MASK (PNG_FP_SAW_DIGIT | PNG_FP_NEGATIVE | PNG_FP_NONZERO)
+   /* NZ_MASK: the string is valid and a non-zero negative value */
+#define PNG_FP_Z_MASK (PNG_FP_SAW_DIGIT | PNG_FP_NONZERO)
+   /* Z MASK: the string is valid and a non-zero value. */
+   /* PNG_FP_SAW_DIGIT: the string is valid. */
+#define PNG_FP_IS_ZERO(state) (((state) & PNG_FP_Z_MASK) == PNG_FP_SAW_DIGIT)
+#define PNG_FP_IS_POSITIVE(state) (((state) & PNG_FP_NZ_MASK) == PNG_FP_Z_MASK)
+#define PNG_FP_IS_NEGATIVE(state) (((state) & PNG_FP_NZ_MASK) == PNG_FP_NZ_MASK)
+
+/* The actual parser.  This can be called repeatedly, it updates
+ * the index into the string and the state variable (which must
+ * be initialzed to 0).  It returns a result code, as above.  There
+ * is no point calling the parser any more if it fails to advance to
+ * the end of the string - it is stuck on an invalid character (or
+ * terminated by '\0').
+ *
+ * Note that the pointer will consume an E or even an E+ then leave
+ * a 'maybe' state even though a preceding integer.fraction is valid.
+ * The PNG_FP_WAS_VALID flag indicates that a preceding substring was
+ * a valid number.  It's possible to recover from this by calling
+ * the parser again (from the start, with state 0) but with a string
+ * that omits the last character (i.e. set the size to the index of
+ * the problem character.)  This has not been tested within libpng.
+ */
+PNG_EXTERN int png_check_fp_number PNGARG((png_const_charp string,
+    png_size_t size, int *statep, png_size_tp whereami));
+
+/* This is the same but it checks a complete string and returns true
+ * only if it just contains a floating point number.  As of 1.5.4 this
+ * function also returns the state at the end of parsing the number if
+ * it was valid (otherwise it returns 0.)  This can be used for testing
+ * for negative or zero values using the sticky flag.
+ */
+PNG_EXTERN int png_check_fp_string PNGARG((png_const_charp string,
+    png_size_t size));
+#endif /* pCAL || sCAL */
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) ||\
+    defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
+/* Added at libpng version 1.5.0 */
+/* This is a utility to provide a*times/div (rounded) and indicate
+ * if there is an overflow.  The result is a boolean - false (0)
+ * for overflow, true (1) if no overflow, in which case *res
+ * holds the result.
+ */
+PNG_EXTERN int png_muldiv PNGARG((png_fixed_point_p res, png_fixed_point a,
+    png_int_32 multiplied_by, png_int_32 divided_by));
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
+/* Same deal, but issue a warning on overflow and return 0. */
+PNG_EXTERN png_fixed_point png_muldiv_warn PNGARG((png_structp png_ptr,
+    png_fixed_point a, png_int_32 multiplied_by, png_int_32 divided_by));
+#endif
+
+#ifdef PNG_READ_GAMMA_SUPPORTED
+/* Calculate a reciprocal - used for gamma values.  This returns
+ * 0 if the argument is 0 in order to maintain an undefined value,
+ * there are no warnings.
+ */
+PNG_EXTERN png_fixed_point png_reciprocal PNGARG((png_fixed_point a));
+
+/* The same but gives a reciprocal of the product of two fixed point
+ * values.  Accuracy is suitable for gamma calculations but this is
+ * not exact - use png_muldiv for that.
+ */
+PNG_EXTERN png_fixed_point png_reciprocal2 PNGARG((png_fixed_point a,
+    png_fixed_point b));
+#endif
+
+#ifdef PNG_READ_GAMMA_SUPPORTED
+/* Internal fixed point gamma correction.  These APIs are called as
+ * required to convert single values - they don't need to be fast,
+ * they are not used when processing image pixel values.
+ *
+ * While the input is an 'unsigned' value it must actually be the
+ * correct bit value - 0..255 or 0..65535 as required.
+ */
+PNG_EXTERN png_uint_16 png_gamma_correct PNGARG((png_structp png_ptr,
+    unsigned int value, png_fixed_point gamma_value));
+PNG_EXTERN int png_gamma_significant PNGARG((png_fixed_point gamma_value));
+PNG_EXTERN png_uint_16 png_gamma_16bit_correct PNGARG((unsigned int value,
+    png_fixed_point gamma_value));
+PNG_EXTERN png_byte png_gamma_8bit_correct PNGARG((unsigned int value,
+    png_fixed_point gamma_value));
+PNG_EXTERN void png_destroy_gamma_table(png_structp png_ptr);
+PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr,
+    int bit_depth));
+#endif
+
+/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
+
+#include "pngdebug.h"
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PNGPRIV_H */

+ 358 - 0
engine/compilers/android/jni/include/libpng/pngstruct.h

@@ -0,0 +1,358 @@
+
+/* pngstruct.h - header file for PNG reference library
+ *
+ * Copyright (c) 1998-2012 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Last changed in libpng 1.5.9 [February 18, 2012]
+ *
+ * This code is released under the libpng license.
+ * For conditions of distribution and use, see the disclaimer
+ * and license in png.h
+ */
+
+/* The structure that holds the information to read and write PNG files.
+ * The only people who need to care about what is inside of this are the
+ * people who will be modifying the library for their own special needs.
+ * It should NOT be accessed directly by an application.
+ */
+
+#ifndef PNGSTRUCT_H
+#define PNGSTRUCT_H
+/* zlib.h defines the structure z_stream, an instance of which is included
+ * in this structure and is required for decompressing the LZ compressed
+ * data in PNG files.
+ */
+#include "zlib.h"
+
+struct png_struct_def
+{
+#ifdef PNG_SETJMP_SUPPORTED
+   jmp_buf longjmp_buffer;    /* used in png_error */
+   png_longjmp_ptr longjmp_fn;/* setjmp non-local goto function. */
+#endif
+   png_error_ptr error_fn;    /* function for printing errors and aborting */
+#ifdef PNG_WARNINGS_SUPPORTED
+   png_error_ptr warning_fn;  /* function for printing warnings */
+#endif
+   png_voidp error_ptr;       /* user supplied struct for error functions */
+   png_rw_ptr write_data_fn;  /* function for writing output data */
+   png_rw_ptr read_data_fn;   /* function for reading input data */
+   png_voidp io_ptr;          /* ptr to application struct for I/O functions */
+
+#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
+   png_user_transform_ptr read_user_transform_fn; /* user read transform */
+#endif
+
+#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
+   png_user_transform_ptr write_user_transform_fn; /* user write transform */
+#endif
+
+/* These were added in libpng-1.0.2 */
+#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_voidp user_transform_ptr; /* user supplied struct for user transform */
+   png_byte user_transform_depth;    /* bit depth of user transformed pixels */
+   png_byte user_transform_channels; /* channels in user transformed pixels */
+#endif
+#endif
+
+   png_uint_32 mode;          /* tells us where we are in the PNG file */
+   png_uint_32 flags;         /* flags indicating various things to libpng */
+   png_uint_32 transformations; /* which transformations to perform */
+
+   z_stream zstream;          /* pointer to decompression structure (below) */
+   png_bytep zbuf;            /* buffer for zlib */
+   uInt zbuf_size;            /* size of zbuf (typically 65536) */
+#ifdef PNG_WRITE_SUPPORTED
+
+/* Added in 1.5.4: state to keep track of whether the zstream has been
+ * initialized and if so whether it is for IDAT or some other chunk.
+ */
+#define PNG_ZLIB_UNINITIALIZED 0
+#define PNG_ZLIB_FOR_IDAT      1
+#define PNG_ZLIB_FOR_TEXT      2 /* anything other than IDAT */
+#define PNG_ZLIB_USE_MASK      3 /* bottom two bits */
+#define PNG_ZLIB_IN_USE        4 /* a flag value */
+
+   png_uint_32 zlib_state;       /* State of zlib initialization */
+/* End of material added at libpng 1.5.4 */
+
+   int zlib_level;            /* holds zlib compression level */
+   int zlib_method;           /* holds zlib compression method */
+   int zlib_window_bits;      /* holds zlib compression window bits */
+   int zlib_mem_level;        /* holds zlib compression memory level */
+   int zlib_strategy;         /* holds zlib compression strategy */
+#endif
+/* Added at libpng 1.5.4 */
+#if defined(PNG_WRITE_COMPRESSED_TEXT_SUPPORTED) || \
+    defined(PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED)
+   int zlib_text_level;            /* holds zlib compression level */
+   int zlib_text_method;           /* holds zlib compression method */
+   int zlib_text_window_bits;      /* holds zlib compression window bits */
+   int zlib_text_mem_level;        /* holds zlib compression memory level */
+   int zlib_text_strategy;         /* holds zlib compression strategy */
+#endif
+/* End of material added at libpng 1.5.4 */
+
+   png_uint_32 width;         /* width of image in pixels */
+   png_uint_32 height;        /* height of image in pixels */
+   png_uint_32 num_rows;      /* number of rows in current pass */
+   png_uint_32 usr_width;     /* width of row at start of write */
+   png_size_t rowbytes;       /* size of row in bytes */
+   png_uint_32 iwidth;        /* width of current interlaced row in pixels */
+   png_uint_32 row_number;    /* current row in interlace pass */
+   png_uint_32 chunk_name;    /* PNG_CHUNK() id of current chunk */
+   png_bytep prev_row;        /* buffer to save previous (unfiltered) row.
+                               * This is a pointer into big_prev_row
+                               */
+   png_bytep row_buf;         /* buffer to save current (unfiltered) row.
+                               * This is a pointer into big_row_buf
+                               */
+   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
+   png_bytep up_row;          /* buffer to save "up" row when filtering */
+   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
+   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
+   png_size_t info_rowbytes;  /* Added in 1.5.4: cache of updated row bytes */
+
+   png_uint_32 idat_size;     /* current IDAT size for read */
+   png_uint_32 crc;           /* current chunk CRC value */
+   png_colorp palette;        /* palette from the input file */
+   png_uint_16 num_palette;   /* number of color entries in palette */
+
+/* Added at libpng-1.5.10 */
+#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
+   int num_palette_max;       /* maximum palette index found in IDAT */
+#endif
+
+   png_uint_16 num_trans;     /* number of transparency values */
+   png_byte compression;      /* file compression type (always 0) */
+   png_byte filter;           /* file filter type (always 0) */
+   png_byte interlaced;       /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+   png_byte pass;             /* current interlace pass (0 - 6) */
+   png_byte do_filter;        /* row filter flags (see PNG_FILTER_ below ) */
+   png_byte color_type;       /* color type of file */
+   png_byte bit_depth;        /* bit depth of file */
+   png_byte usr_bit_depth;    /* bit depth of users row: write only */
+   png_byte pixel_depth;      /* number of bits per pixel */
+   png_byte channels;         /* number of channels in file */
+   png_byte usr_channels;     /* channels at start of write: write only */
+   png_byte sig_bytes;        /* magic bytes read/written from start of file */
+   png_byte maximum_pixel_depth;
+                              /* pixel depth used for the row buffers */
+   png_byte transformed_pixel_depth;
+                              /* pixel depth after read/write transforms */
+   png_byte io_chunk_string[5];
+                              /* string name of chunk */
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+   png_uint_16 filler;           /* filler bytes for pixel expansion */
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
+   defined(PNG_READ_ALPHA_MODE_SUPPORTED)
+   png_byte background_gamma_type;
+   png_fixed_point background_gamma;
+   png_color_16 background;   /* background color in screen gamma space */
+#ifdef PNG_READ_GAMMA_SUPPORTED
+   png_color_16 background_1; /* background normalized to gamma 1.0 */
+#endif
+#endif /* PNG_bKGD_SUPPORTED */
+
+#ifdef PNG_WRITE_FLUSH_SUPPORTED
+   png_flush_ptr output_flush_fn; /* Function for flushing output */
+   png_uint_32 flush_dist;    /* how many rows apart to flush, 0 - no flush */
+   png_uint_32 flush_rows;    /* number of rows written since last flush */
+#endif
+
+#ifdef PNG_READ_GAMMA_SUPPORTED
+   int gamma_shift;      /* number of "insignificant" bits in 16-bit gamma */
+   png_fixed_point gamma;        /* file gamma value */
+   png_fixed_point screen_gamma; /* screen gamma value (display_exponent) */
+
+   png_bytep gamma_table;     /* gamma table for 8-bit depth files */
+   png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
+#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
+   defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
+   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+   png_bytep gamma_from_1;    /* converts from 1.0 to screen */
+   png_bytep gamma_to_1;      /* converts from file to 1.0 */
+   png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
+   png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
+#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
+   png_color_8 sig_bit;       /* significant bits in each available channel */
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+   png_color_8 shift;         /* shift for significant bit tranformation */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
+ || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep trans_alpha;           /* alpha values for paletted files */
+   png_color_16 trans_color;  /* transparent color for non-paletted files */
+#endif
+
+   png_read_status_ptr read_row_fn;   /* called after each row is decoded */
+   png_write_status_ptr write_row_fn; /* called after each row is encoded */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+   png_progressive_info_ptr info_fn; /* called after header data fully read */
+   png_progressive_row_ptr row_fn;   /* called after a prog. row is decoded */
+   png_progressive_end_ptr end_fn;   /* called after image is complete */
+   png_bytep save_buffer_ptr;        /* current location in save_buffer */
+   png_bytep save_buffer;            /* buffer for previously read data */
+   png_bytep current_buffer_ptr;     /* current location in current_buffer */
+   png_bytep current_buffer;         /* buffer for recently used data */
+   png_uint_32 push_length;          /* size of current input chunk */
+   png_uint_32 skip_length;          /* bytes to skip in input data */
+   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
+   png_size_t save_buffer_max;       /* total size of save_buffer */
+   png_size_t buffer_size;           /* total amount of available input data */
+   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
+   int process_mode;                 /* what push library is currently doing */
+   int cur_palette;                  /* current push library palette index */
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
+/* For the Borland special 64K segment handler */
+   png_bytepp offset_table_ptr;
+   png_bytep offset_table;
+   png_uint_16 offset_table_number;
+   png_uint_16 offset_table_count;
+   png_uint_16 offset_table_count_free;
+#endif
+
+#ifdef PNG_READ_QUANTIZE_SUPPORTED
+   png_bytep palette_lookup; /* lookup table for quantizing */
+   png_bytep quantize_index; /* index translation for palette files */
+#endif
+
+#if defined(PNG_READ_QUANTIZE_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
+   png_uint_16p hist;                /* histogram */
+#endif
+
+#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
+   png_byte heuristic_method;        /* heuristic for row filter selection */
+   png_byte num_prev_filters;        /* number of weights for previous rows */
+   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
+   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
+   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
+   png_uint_16p filter_costs;        /* relative filter calculation cost */
+   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
+#endif
+
+#ifdef PNG_TIME_RFC1123_SUPPORTED
+   /* This is going to be unused in libpng16 and removed from libpng17 */
+   char time_buffer[29]; /* String to hold RFC 1123 time text */
+#endif
+
+/* New members added in libpng-1.0.6 */
+
+   png_uint_32 free_me;    /* flags items libpng is responsible for freeing */
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+   png_voidp user_chunk_ptr;
+   png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
+#endif
+
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+   int num_chunk_list;
+   png_bytep chunk_list;
+#endif
+
+#ifdef PNG_READ_sRGB_SUPPORTED
+   /* Added in 1.5.5 to record an sRGB chunk in the png. */
+   png_byte is_sRGB;
+#endif
+
+/* New members added in libpng-1.0.3 */
+#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
+   png_byte rgb_to_gray_status;
+   /* Added in libpng 1.5.5 to record setting of coefficients: */
+   png_byte rgb_to_gray_coefficients_set;
+   /* These were changed from png_byte in libpng-1.0.6 */
+   png_uint_16 rgb_to_gray_red_coeff;
+   png_uint_16 rgb_to_gray_green_coeff;
+   /* deleted in 1.5.5: rgb_to_gray_blue_coeff; */
+#endif
+
+/* New member added in libpng-1.0.4 (renamed in 1.0.9) */
+#if defined(PNG_MNG_FEATURES_SUPPORTED)
+/* Changed from png_byte to png_uint_32 at version 1.2.0 */
+   png_uint_32 mng_features_permitted;
+#endif
+
+/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+   png_byte filter_type;
+#endif
+
+/* New members added in libpng-1.2.0 */
+
+/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
+#ifdef PNG_USER_MEM_SUPPORTED
+   png_voidp mem_ptr;             /* user supplied struct for mem functions */
+   png_malloc_ptr malloc_fn;      /* function for allocating memory */
+   png_free_ptr free_fn;          /* function for freeing memory */
+#endif
+
+/* New member added in libpng-1.0.13 and 1.2.0 */
+   png_bytep big_row_buf;         /* buffer to save current (unfiltered) row */
+
+#ifdef PNG_READ_QUANTIZE_SUPPORTED
+/* The following three members were added at version 1.0.14 and 1.2.4 */
+   png_bytep quantize_sort;          /* working sort array */
+   png_bytep index_to_palette;       /* where the original index currently is
+                                        in the palette */
+   png_bytep palette_to_index;       /* which original index points to this
+                                         palette color */
+#endif
+
+/* New members added in libpng-1.0.16 and 1.2.6 */
+   png_byte compression_type;
+
+#ifdef PNG_USER_LIMITS_SUPPORTED
+   png_uint_32 user_width_max;
+   png_uint_32 user_height_max;
+
+   /* Added in libpng-1.4.0: Total number of sPLT, text, and unknown
+    * chunks that can be stored (0 means unlimited).
+    */
+   png_uint_32 user_chunk_cache_max;
+
+   /* Total memory that a zTXt, sPLT, iTXt, iCCP, or unknown chunk
+    * can occupy when decompressed.  0 means unlimited.
+    */
+   png_alloc_size_t user_chunk_malloc_max;
+#endif
+
+/* New member added in libpng-1.0.25 and 1.2.17 */
+#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
+   /* Storage for unknown chunk that the library doesn't recognize. */
+   png_unknown_chunk unknown_chunk;
+#endif
+
+/* New member added in libpng-1.2.26 */
+  png_size_t old_big_row_buf_size;
+
+/* New member added in libpng-1.2.30 */
+  png_charp chunkdata;  /* buffer for reading chunk data */
+
+#ifdef PNG_IO_STATE_SUPPORTED
+/* New member added in libpng-1.4.0 */
+   png_uint_32 io_state;
+#endif
+
+/* New member added in libpng-1.5.6 */
+   png_bytep big_prev_row;
+
+   void (*read_filter[PNG_FILTER_VALUE_LAST-1])(png_row_infop row_info,
+      png_bytep row, png_const_bytep prev_row);
+};
+#endif /* PNGSTRUCT_H */

+ 3 - 0
engine/compilers/android/lint.xml

@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<lint>
+</lint>

+ 14 - 0
engine/compilers/android/project.properties

@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-17

二進制
engine/compilers/android/res/drawable-hdpi/ic_launcher.png


二進制
engine/compilers/android/res/drawable-ldpi/ic_launcher.png


二進制
engine/compilers/android/res/drawable-mdpi/ic_launcher.png


二進制
engine/compilers/android/res/drawable-xhdpi/ic_launcher.png


+ 3 - 0
engine/compilers/android/res/menu/activity_main.xml

@@ -0,0 +1,3 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+</menu>

+ 11 - 0
engine/compilers/android/res/values-v11/styles.xml

@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.NoTitleBar.Fullscreen">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>

+ 12 - 0
engine/compilers/android/res/values-v14/styles.xml

@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.NoTitleBar.Fullscreen">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>

+ 5 - 0
engine/compilers/android/res/values/strings.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">Torque2D</string>
+
+</resources>

+ 20 - 0
engine/compilers/android/res/values/styles.xml

@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.NoTitleBar.Fullscreen">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>

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

@@ -0,0 +1,50 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/AndroidAlerts.h"
+
+//-----------------------------------------------------------------------------
+void Platform::AlertOK(const char *windowTitle, const char *message)
+{
+	//TODO: alertok
+}
+//-----------------------------------------------------------------------------
+bool Platform::AlertOKCancel(const char *windowTitle, const char *message)
+{
+	//TODO: AlertOKCancel
+	return false;
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::AlertRetry(const char *windowTitle, const char *message)
+{//retry/cancel
+	
+	//TODO: alertRetry
+	return false;
+}
+
+
+bool Platform::AlertYesNo(const char *windowTitle, const char *message)
+{
+	//TODO: alertYesNo
+	return false;
+}

+ 37 - 0
engine/source/platformAndroid/AndroidAlerts.h

@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+//-----------------------------------------------------------------------------
+/// Puts the current thread in a modal state & shows the alert.
+/// This should only be called from the main thread. 
+/// If you call it from any other thread, bad things will happen. So don't.
+/// The 'main thread' here means the program's thread zero. The first thread.
+/// In multithreaded Torque, this is NOT the game loop thread.
+/// On the Mac, events and alerts have to happen in thread zero.
+//-----------------------------------------------------------------------------
+
+
+
+
+
+
+

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

@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/AndroidUtil.h"
+#include "platform/platformAL.h"
+
+ConsoleFunction(doDeviceVibrate, void, 1, 1, "Makes the device do a quick vibration. Only works on the iPhone line of devices - the iPod Touch line does not have vibration functionality.")  
+{  
+	//TODO: vibrate
+}  
+
+namespace Audio
+{
+	
+	/*!  The MacOS X build links against the OpenAL framework.
+     It can be built to use either an internal framework, or the system framework.
+     Since OpenAL is weak-linked in at compile time, we don't need to init anything.
+     Stub it out...
+	 */
+	bool OpenALDLLInit() {  return true; }
+	
+	/*!   Stubbed out, see the note on OpenALDLLInit().  
+	 */
+	void OpenALDLLShutdown() { }   
+	
+	
+} // namespace Audio
+
+
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//TODO: ???
+typedef ALvoid	AL_APIENTRY	(*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value);
+ALvoid  alcMacOSXMixerOutputRateProc(const ALdouble value)
+{
+	static	alcMacOSXMixerOutputRateProcPtr	proc = NULL;
+    
+    if (proc == NULL) {
+        proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate");
+    }
+    
+    if (proc)
+        proc(value);
+	
+    return;
+}

+ 61 - 0
engine/source/platformAndroid/AndroidCPUInfo.cpp

@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "console/console.h"
+#include "string/stringTable.h"
+#include <math.h>
+
+
+
+
+void Processor::init()
+{
+	
+   Con::printf("System & Processor Information:");
+
+   Con::printf("   Android version: %0.0f", platState.osVersion );
+
+	// -Mat FIXME: USE SYSTEM FUNCTION to get version number for 
+	//just use OS version for now
+   Con::printf("   CarbonLib version: %0.0f", platState.osVersion );
+   
+   Con::printf("   Physical RAM: %dMB", 128);
+
+   Con::printf("   Logical RAM: %dMB", 128);
+
+   PlatformSystemInfo.processor.mhz = 412;
+
+   //PlatformSystemInfo.processor.type =  ARM_1176;
+   PlatformSystemInfo.processor.name = StringTable->insert("ARM 1176");
+
+   PlatformSystemInfo.processor.properties = CPU_PROP_PPCMIN;
+
+	Con::printf("   %s, %d Mhz", PlatformSystemInfo.processor.name, PlatformSystemInfo.processor.mhz);
+   if (PlatformSystemInfo.processor.properties & CPU_PROP_PPCMIN)
+      Con::printf("   FPU detected");
+   if (PlatformSystemInfo.processor.properties & CPU_PROP_ALTIVEC)
+      Con::printf("   AltiVec detected");
+
+   Con::printf(" ");
+}
+

+ 173 - 0
engine/source/platformAndroid/AndroidConsole.cpp

@@ -0,0 +1,173 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/AndroidConsole.h"
+#include "platform/event.h"
+#include "game/gameInterface.h"
+#include "platform/threads/thread.h"
+
+#include <stdio.h>
+
+// TODO: convert this to use ncurses.
+
+AndroidConsole *gConsole = NULL;
+
+ConsoleFunction(enableWinConsole, void, 2, 2, "(bool enable)")
+{
+   if (gConsole)
+      gConsole->enable(dAtob(argv[1]));
+}
+
+ConsoleFunction(enableDebugOutput, void, 2, 2, "(bool enable)")
+{
+	if (gConsole)
+		gConsole->enableDebugOutput(dAtob(argv[1]));
+}
+
+static void AndroidConsoleConsumer(ConsoleLogEntry::Level, const char *line)
+{
+   if (gConsole)
+      gConsole->processConsoleLine(line);
+}
+
+static void AndroidConsoleInputLoopThread(S32 *arg)
+{
+   if(!gConsole)
+      return;
+   gConsole->inputLoop();
+}
+
+void AndroidConsole::create()
+{
+   gConsole = new AndroidConsole();
+}
+
+void AndroidConsole::destroy()
+{
+   if (gConsole)
+      delete gConsole;
+   gConsole = NULL;
+}
+
+void AndroidConsole::enable(bool enabled)
+{
+   if (gConsole == NULL) return;
+   
+   consoleEnabled = enabled;
+   if(consoleEnabled)
+   {
+      printf("Initializing Console...\n");
+      new Thread((ThreadRunFunction)AndroidConsoleInputLoopThread,0,true);
+      printf("Console Initialized.\n");
+
+      printf("%s", Con::getVariable("Con::Prompt"));
+   }
+   else
+   {
+      printf("Deactivating Console.");
+   }
+}
+
+//%PUAP%
+void AndroidConsole::enableDebugOutput(bool enabled)
+{
+	if (gConsole == NULL) return;
+	debugOutputEnabled = enabled;
+}
+
+
+bool AndroidConsole::isEnabled()
+{
+   if ( !gConsole )
+      return false;
+
+   return gConsole->consoleEnabled;
+}
+
+
+AndroidConsole::AndroidConsole()
+{
+   consoleEnabled = false;
+   clearInBuf();
+   
+   Con::addConsumer(AndroidConsoleConsumer);
+}
+
+AndroidConsole::~AndroidConsole()
+{
+   Con::removeConsumer(AndroidConsoleConsumer);
+}
+
+void AndroidConsole::processConsoleLine(const char *consoleLine)
+{
+   if(consoleEnabled)
+   {
+         printf("%s\n", consoleLine);
+   }
+	//%PUAP%
+	if(debugOutputEnabled)
+	{
+		printf("%s\n", consoleLine);
+	}
+
+}
+
+void AndroidConsole::clearInBuf()
+{
+   dMemset(inBuf, 0, MaxConsoleLineSize);
+   inBufPos=0;
+}
+
+void AndroidConsole::inputLoop()
+{
+   Con::printf("Console Input Thread Started");
+   unsigned char c;
+   while(consoleEnabled)
+   {
+      c = fgetc(stdin);
+      if(c == '\n')
+      {
+         // exec the line
+         dStrcpy(postEvent.data, inBuf);
+         postEvent.size = ConsoleEventHeaderSize + dStrlen(inBuf) + 1;
+         Con::printf("=> %s",postEvent.data);
+         Game->postEvent(postEvent);
+         // clear the buffer
+         clearInBuf();
+         // display the prompt. Note that we're using real printf, not Con::printf...
+         printf("=> ");
+      }
+      else
+      {
+         // add it to the buffer.
+         inBuf[inBufPos++] = c;
+         // if we're full, clear & warn.
+         if(inBufPos >= MaxConsoleLineSize-1)
+         {
+            clearInBuf();
+            Con::warnf("Line to long, discarding the last 512 bytes...");
+         }
+      }
+   }
+   Con::printf("Console Input Thread Stopped");
+}

+ 65 - 0
engine/source/platformAndroid/AndroidConsole.h

@@ -0,0 +1,65 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef _ANDROIDCONSOLE_H_
+#define _ANDROIDCONSOLE_H_
+
+#ifndef _CONSOLE_H_
+#include "console/console.h"
+#endif
+#ifndef _EVENT_H_
+#include "Platform/event.h"
+#endif
+
+
+class AndroidConsole
+{
+private:
+   bool consoleEnabled;
+	bool debugOutputEnabled;
+   
+   U32   inBufPos;
+   char  inBuf[MaxConsoleLineSize];
+   ConsoleEvent postEvent;
+   
+   void clearInBuf();
+   
+public:
+   static void create();
+   static void destroy();
+   static bool isEnabled();
+
+   AndroidConsole();
+   ~AndroidConsole();
+   void enable(bool);
+	//%PUAP%
+	void enableDebugOutput( bool );
+
+   void processConsoleLine(const char *consoleLine);
+   
+   void  inputLoop();
+
+};
+
+extern AndroidConsole *gConsole;
+
+#endif

+ 60 - 0
engine/source/platformAndroid/AndroidDialogs.cpp

@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "sim/simBase.h"
+#include "platform/nativeDialogs/fileDialog.h"
+#include "platform/threads/mutex.h"
+#include "memory/safeDelete.h"
+#include "math/mMath.h"
+#include "string/Unicode.h"
+#include "console/consoleTypes.h"
+#include "platform/threads/thread.h"
+
+bool FileDialog::Execute()
+{
+    return true;
+}
+
+//-----------------------------------------------------------------------------
+// Default Path Property - String Validated on Write
+//-----------------------------------------------------------------------------
+bool FileDialog::setDefaultPath(void* obj, const char* data)
+{
+
+   if( !data )
+      return true;
+
+   return true;
+
+};
+
+//-----------------------------------------------------------------------------
+// Default File Property - String Validated on Write
+//-----------------------------------------------------------------------------
+bool FileDialog::setDefaultFile(void* obj, const char* data)
+{
+   if( !data )
+      return true;
+
+   return true;
+};

+ 110 - 0
engine/source/platformAndroid/AndroidEvents.cpp

@@ -0,0 +1,110 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/event.h"
+#include "platform/platformInput.h"
+#include "game/gameInterface.h"
+#include "platform/threads/thread.h"
+#include "platform/platformVideo.h"
+#include <pthread.h>
+
+#include "platformAndroid/AndroidUtil.h"
+#include "platformAndroid/AndroidEvents.h"
+#include "platformAndroid/AndroidAlerts.h"
+#include "gui/guiCanvas.h"
+
+
+
+/*
+EventHandlerRef gWinMouseEventHandlerRef  = NULL;
+EventHandlerRef gAppMouseEventHandlerRef  = NULL;
+*/
+
+
+
+//-----------------------------------------------------------------------------
+static void _OnActivate(bool activating)
+{
+   if(activating)
+   {
+      Input::activate();
+      Game->refreshWindow();
+      platState.backgrounded = false;
+      pthread_kill((pthread_t)platState.torqueThreadId, SIGALRM);
+   }
+   else
+   {
+      Input::deactivate();
+      platState.backgrounded = true;
+   }
+}
+
+//-----------------------------------------------------------------------------
+// here we manually poll for events, and send them to the dispatcher.
+// we only use this in single-threaded mode.
+static void _AndroidPollEvents()
+{
+}
+
+
+
+//-----------------------------------------------------------------------------
+void Platform::enableKeyboardTranslation(void)
+{
+	platState.tsmActive=true;
+}
+
+//-----------------------------------------------------------------------------
+void Platform::disableKeyboardTranslation(void)
+{
+	platState.tsmActive=false;
+}
+
+
+void Platform::setMouseLock(bool locked)
+{
+}
+
+
+
+
+//-----------------------------------------------------------------------------
+void Platform::process()
+{
+	// TODO: HID input
+	
+	// ProcessMessages() manually polls for events when we are single threaded
+	//   if(ThreadManager::isCurrentThread(platState.firstThreadId))
+	//     _AndroidPollEvents();
+	
+	// Some things do not get carbon events, we must always poll for them.
+	// HID ( usb gamepad et al ) input, for instance.
+	Input::process();
+	
+	if(platState.ctxNeedsUpdate)
+	{
+		//aglUpdateContext(platState.ctx);
+		platState.ctxNeedsUpdate=false;
+	}
+}
+

+ 76 - 0
engine/source/platformAndroid/AndroidEvents.h

@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef MAC_CARB_EVENTS_H
+#define MAC_CARB_EVENTS_H
+
+/// Hides the mouse cursor when the mouse is locked, when we are in fullscreen
+/// mode, and when the cursor is inside the window bounds.
+/// Optionally takes the cursor location, in window local coords.
+//void AndroidCheckHideCursor(S32 x=-1, S32 y=-1);
+
+/// Hides or shows the system mouse cursor, regardless of the mouse position,
+/// and tracks the hidden state.
+//void AndroidSetHideCursor(bool shouldHide);
+
+/// Install event loop timer, replacing any existing event loop timer.
+/// This is useful for updating the sleep time
+void AndroidRunEventLoopTimer(S32 intervalMs);
+
+/// Install event handlers on the current window & on the app.
+void AndroidInstallCarbonEventHandlers(void);
+
+/// Remove all event handlers, except the alert event handlers.
+void AndroidRemoveCarbonEventHandlers(void);
+
+/// Install event handlers for custom Torque inter-thread communication.
+///  This must be called before starting multithreaded execution in main().
+void AndroidInstallTorqueCarbonEventHandlers(void);
+
+/// Handle an HICommand that comes from a native MacOSX menu.
+/// Returns false if the command can't be handled.
+bool AndroidHandleMenuCommand(void* hiCommand);
+
+/// create an event of class kEventClassTorque, and send it to the main thread
+void AndroidSendTorqueEventToMain( U32 eventKind, void* userData = NULL );
+
+/// event type for alerts. The event class is an arbitrary val, it must not collide w/ kEventApp* .
+const U32 kEventClassTorque   = 'TORQ';
+const U32 kEventTorqueAlert   = 1;
+const U32 kEventTorqueFadeInWindow = 2;
+const U32 kEventTorqueFadeOutWindow = 3;
+const U32 kEventTorqueReleaseWindow = 4;
+const U32 kEventTorqueShowMenuBar = 5;
+const U32 kEventTorqueModalDialog = 6;
+const U32 kEventTorqueDrawMenuBar = 7;
+
+const U32 kEventParamTorqueData           = 'tDAT'; // typeVoidPtr void*
+//const U32 kEventParamTorqueSemaphorePtr   = 'tSEM'; // typeVoidPtr void*
+//const U32 kEventParamTorqueDialogRef      = 'tDRF'; // typeDialogRef DialogRef
+//const U32 kEventParamTorqueHitPtr         = 'tHIT'; // typeVoidPtr U32*
+//const U32 typeDialogRef                   = 'dlog'; // oddly, not provided in Frameworks.
+
+
+// this command id is used for all dynamically created menus.
+const U32 kHICommandTorque = 'TORQ';
+
+#endif

+ 964 - 0
engine/source/platformAndroid/AndroidFileio.cpp

@@ -0,0 +1,964 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platform/platform.h"
+#include "platformAndroid/platformAndroid.h"
+#include "platform/platformFileIO.h"
+#include "collection/vector.h"
+#include "string/stringTable.h"
+#include "console/console.h"
+#include "debug/profiler.h"
+#include "io/resource/resourceManager.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <utime.h>
+
+#include <sys/types.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+
+//TODO: file io still needs some work...
+
+#define MAX_MAC_PATH_LONG     2048
+
+//-----------------------------------------------------------------------------
+//#if defined(TORQUE_OS_MAC_OSX)
+#include <CoreFoundation/CFBundle.h>
+//#else
+//#include <CFBundle.h>
+//#endif
+
+//-----------------------------------------------------------------------------
+bool Platform::fileDelete(const char * name)
+{
+   if(!name )
+      return(false);
+   
+   if (dStrlen(name) > MAX_MAC_PATH_LONG)
+      Con::warnf("Platform::FileDelete() - Filename length is pretty long...");
+   
+   return(remove(name) == 0); // remove returns 0 on success
+}
+
+
+//-----------------------------------------------------------------------------
+bool dFileTouch(const char *path)
+{
+   if (!path || !*path) 
+      return false;
+   
+   // set file at path's modification and access times to now.
+   return( utimes( path, NULL) == 0); // utimes returns 0 on success.
+}
+
+//-----------------------------------------------------------------------------
+// Constructors & Destructor
+//-----------------------------------------------------------------------------
+
+//-----------------------------------------------------------------------------
+// After construction, the currentStatus will be Closed and the capabilities
+// will be 0.
+//-----------------------------------------------------------------------------
+File::File()
+: currentStatus(Closed), capability(0)
+{
+   handle = NULL;
+}
+
+//-----------------------------------------------------------------------------
+// insert a copy constructor here... (currently disabled)
+//-----------------------------------------------------------------------------
+
+//-----------------------------------------------------------------------------
+// Destructor
+//-----------------------------------------------------------------------------
+File::~File()
+{
+   close();
+   handle = NULL;
+}
+
+
+//-----------------------------------------------------------------------------
+// Open a file in the mode specified by openMode (Read, Write, or ReadWrite).
+// Truncate the file if the mode is either Write or ReadWrite and truncate is
+// true.
+//
+// Sets capability appropriate to the openMode.
+// Returns the currentStatus of the file.
+//-----------------------------------------------------------------------------
+File::Status File::open(const char *filename, const AccessMode openMode)
+{
+   if (dStrlen(filename) > MAX_MAC_PATH_LONG)
+      Con::warnf("File::open: Filename length is pretty long...");
+   
+   // Close the file if it was already open...
+   if (currentStatus != Closed)
+      close();
+   
+   // create the appropriate type of file...
+   switch (openMode)
+   {
+      case Read:
+         handle = (void *)fopen(filename, "rb"); // read only
+         break;
+      case Write:
+         handle = (void *)fopen(filename, "wb"); // write only
+         break;
+      case ReadWrite:
+         handle = (void *)fopen(filename, "ab+"); // write(append) and read
+         break;
+      case WriteAppend:
+         handle = (void *)fopen(filename, "ab"); // write(append) only
+         break;
+      default:
+         AssertFatal(false, "File::open: bad access mode");
+   }
+   
+   // handle not created successfully
+   if (handle == NULL)                
+      return setStatus();
+   
+   // successfully created file, so set the file capabilities...
+   switch (openMode)
+   {
+      case Read:
+         capability = FileRead;
+         break;
+      case Write:
+      case WriteAppend:
+         capability = FileWrite;
+         break;
+      case ReadWrite:
+         capability = FileRead | FileWrite;
+         break;
+      default:
+         AssertFatal(false, "File::open: bad access mode");
+   }
+   
+   // must set the file status before setting the position.
+   currentStatus = Ok;
+   
+   if (openMode == ReadWrite)
+      setPosition(0);
+   
+   // success!
+   return currentStatus;                                
+}
+
+//-----------------------------------------------------------------------------
+// Get the current position of the file pointer.
+//-----------------------------------------------------------------------------
+U32 File::getPosition() const
+{
+   AssertFatal(currentStatus != Closed , "File::getPosition: file closed");
+   AssertFatal(handle != NULL, "File::getPosition: invalid file handle");
+   
+   return ftell((FILE*)handle);
+}
+
+//-----------------------------------------------------------------------------
+// Set the position of the file pointer.
+// Absolute and relative positioning is supported via the absolutePos
+// parameter.
+//
+// If positioning absolutely, position MUST be positive - an IOError results if
+// position is negative.
+// Position can be negative if positioning relatively, however positioning
+// before the start of the file is an IOError.
+//
+// Returns the currentStatus of the file.
+//-----------------------------------------------------------------------------
+File::Status File::setPosition(S32 position, bool absolutePos)
+{
+   AssertFatal(Closed != currentStatus, "File::setPosition: file closed");
+   AssertFatal(handle != NULL, "File::setPosition: invalid file handle");
+   
+   if (currentStatus != Ok && currentStatus != EOS )
+      return currentStatus;
+   
+   U32 finalPos;
+   if(absolutePos)
+   {
+      // absolute position
+      AssertFatal(0 <= position, "File::setPosition: negative absolute position");
+      // position beyond EOS is OK
+      fseek((FILE*)handle, position, SEEK_SET);
+      finalPos = ftell((FILE*)handle);
+   }
+   else
+   {
+      // relative position
+      AssertFatal((getPosition() + position) >= 0, "File::setPosition: negative relative position");
+      // position beyond EOS is OK
+      fseek((FILE*)handle, position, SEEK_CUR);
+      finalPos = ftell((FILE*)handle);
+   }
+   
+   // ftell returns -1 on error. set error status
+   if (0xffffffff == finalPos)
+      return setStatus();
+
+   // success, at end of file
+   else if (finalPos >= getSize())
+      return currentStatus = EOS;
+
+   // success!
+   else
+      return currentStatus = Ok;
+}
+
+//-----------------------------------------------------------------------------
+// Get the size of the file in bytes.
+// It is an error to query the file size for a Closed file, or for one with an
+// error status.
+//-----------------------------------------------------------------------------
+U32 File::getSize() const
+{
+   AssertWarn(Closed != currentStatus, "File::getSize: file closed");
+   AssertFatal(handle != NULL, "File::getSize: invalid file handle");
+   
+   if (Ok == currentStatus || EOS == currentStatus)
+   {
+      struct stat statData;
+      
+      if(fstat(fileno((FILE*)handle), &statData) != 0)
+         return 0;
+      
+      // return the size in bytes
+      return statData.st_size;
+   }
+   
+   return 0;
+}
+
+//-----------------------------------------------------------------------------
+// Flush the file.
+// It is an error to flush a read-only file.
+// Returns the currentStatus of the file.
+//-----------------------------------------------------------------------------
+File::Status File::flush()
+{
+   AssertFatal(Closed != currentStatus, "File::flush: file closed");
+   AssertFatal(handle != NULL, "File::flush: invalid file handle");
+   AssertFatal(true == hasCapability(FileWrite), "File::flush: cannot flush a read-only file");
+   
+   if (fflush((FILE*)handle) != 0)
+      return setStatus();
+   else
+      return currentStatus = Ok;
+}
+
+//-----------------------------------------------------------------------------
+// Close the File.
+//
+// Returns the currentStatus
+//-----------------------------------------------------------------------------
+File::Status File::close()
+{
+   // check if it's already closed...
+   if (Closed == currentStatus)
+      return currentStatus;
+   
+   // it's not, so close it...
+   if (handle != NULL)
+   {
+      if (fclose((FILE*)handle) != 0)
+         return setStatus();
+   }
+   handle = NULL;
+   return currentStatus = Closed;
+}
+
+//-----------------------------------------------------------------------------
+// Self-explanatory.
+//-----------------------------------------------------------------------------
+File::Status File::getStatus() const
+{
+   return currentStatus;
+}
+
+//-----------------------------------------------------------------------------
+// Sets and returns the currentStatus when an error has been encountered.
+//-----------------------------------------------------------------------------
+File::Status File::setStatus()
+{
+   switch (errno)
+   {
+      case EACCES:   // permission denied
+         currentStatus = IOError;
+         break;
+      case EBADF:   // Bad File Pointer
+      case EINVAL:   // Invalid argument
+      case ENOENT:   // file not found
+      case ENAMETOOLONG:
+      default:
+         currentStatus = UnknownError;
+   }
+   
+   return currentStatus;
+}
+
+//-----------------------------------------------------------------------------
+// Sets and returns the currentStatus to status.
+//-----------------------------------------------------------------------------
+File::Status File::setStatus(File::Status status)
+{
+   return currentStatus = status;
+}
+
+//-----------------------------------------------------------------------------
+// Read from a file.
+// The number of bytes to read is passed in size, the data is returned in src.
+// The number of bytes read is available in bytesRead if a non-Null pointer is
+// provided.
+//-----------------------------------------------------------------------------
+File::Status File::read(U32 size, char *dst, U32 *bytesRead)
+{
+   AssertFatal(Closed != currentStatus, "File::read: file closed");
+   AssertFatal(handle != NULL, "File::read: invalid file handle");
+   AssertFatal(NULL != dst, "File::read: NULL destination pointer");
+   AssertFatal(true == hasCapability(FileRead), "File::read: file lacks capability");
+   AssertWarn(0 != size, "File::read: size of zero");
+   
+   if (Ok != currentStatus || 0 == size)
+      return currentStatus;
+   
+   // read from stream
+   U32 nBytes = fread(dst, 1, size, (FILE*)handle);
+   
+   // did we hit the end of the stream?
+   if( nBytes != size)
+      currentStatus = EOS;
+   
+   // if bytesRead is a valid pointer, send number of bytes read there.
+   if(bytesRead)
+      *bytesRead = nBytes;
+     
+   // successfully read size bytes
+   return currentStatus;
+}
+
+//-----------------------------------------------------------------------------
+// Write to a file.
+// The number of bytes to write is passed in size, the data is passed in src.
+// The number of bytes written is available in bytesWritten if a non-Null
+// pointer is provided.
+//-----------------------------------------------------------------------------
+File::Status File::write(U32 size, const char *src, U32 *bytesWritten)
+{
+   AssertFatal(Closed != currentStatus, "File::write: file closed");
+   AssertFatal(handle != NULL, "File::write: invalid file handle");
+   AssertFatal(NULL != src, "File::write: NULL source pointer");
+   AssertFatal(true == hasCapability(FileWrite), "File::write: file lacks capability");
+   AssertWarn(0 != size, "File::write: size of zero");
+   
+   if ((Ok != currentStatus && EOS != currentStatus) || 0 == size)
+      return currentStatus;
+
+   // write bytes to the stream
+   U32 nBytes = fwrite(src, 1, size,(FILE*)handle);
+   
+   // if we couldn't write everything, we've got a problem. set error status.
+   if(nBytes != size)
+      setStatus();
+   
+   // if bytesWritten is a valid pointer, put number of bytes read there.
+   if(bytesWritten)
+      *bytesWritten = nBytes;
+   
+   // return current File status, whether good or ill.
+   return currentStatus;
+}
+
+
+//-----------------------------------------------------------------------------
+// Self-explanatory.
+//-----------------------------------------------------------------------------
+bool File::hasCapability(Capability cap) const
+{
+   return (0 != (U32(cap) & capability));
+}
+
+//-----------------------------------------------------------------------------
+S32 Platform::compareFileTimes(const FileTime &a, const FileTime &b)
+{
+   if(a > b)
+      return 1;
+   if(a < b)
+      return -1;
+   return 0;
+}
+
+
+//-----------------------------------------------------------------------------
+// either time param COULD be null.
+//-----------------------------------------------------------------------------
+bool Platform::getFileTimes(const char *path, FileTime *createTime, FileTime *modifyTime)
+{
+   // MacOSX is NOT guaranteed to be running off a HFS volume,
+   // and UNIX does not keep a record of a file's creation time anywhere.
+   // So instead of creation time we return changed time,
+   // just like the Linux platform impl does.
+   
+   if (!path || !*path) 
+      return false;
+   
+   struct stat statData;
+   
+   if (stat(path, &statData) == -1)
+      return false;
+   
+   if(createTime)
+      *createTime = statData.st_ctime;
+   
+   if(modifyTime)
+      *modifyTime = statData.st_mtime;
+   
+   return true;
+}
+
+
+//-----------------------------------------------------------------------------
+bool Platform::createPath(const char *file)
+{
+    //<Mat> needless console noise
+   //Con::warnf("creating path %s",file);
+   // if the path exists, we're done.
+   struct stat statData;
+   if( stat(file, &statData) == 0 )
+   { 
+      return true;               // exists, rejoice.
+   }
+   
+   // get the parent path.
+   // we're not using basename because it's not thread safe.
+   const U32 len = dStrlen(file) + 1;
+   char parent[len];
+   bool isDirPath = false;
+   
+   dSprintf(parent, len, "%s", file);
+
+   if(parent[len - 2] == '/')
+   {
+      parent[len - 2] = '\0';    // cut off the trailing slash, if there is one
+      isDirPath = true;          // we got a trailing slash, so file is a directory.
+   }
+   
+   // recusively create the parent path.
+   // only recurse if newpath has a slash that isn't a leading slash.
+   char *slash = dStrrchr(parent,'/');
+   if( slash && slash != parent)
+   {
+      // snip the path just after the last slash.
+      slash[1] = '\0';
+      // recusively create the parent path. fail if parent path creation failed.
+      if(!Platform::createPath(parent))
+         return false;
+   }
+   
+   // create *file if it is a directory path.
+   if(isDirPath)
+   {
+      // try to create the directory
+      if( mkdir(file, 0777) != 0) // app may reside in global apps dir, and so must be writable to all.
+         return false;
+   }
+   
+   return true;
+}
+
+
+#pragma mark ---- Directories ----
+//-----------------------------------------------------------------------------
+StringTableEntry Platform::getCurrentDirectory()
+{
+   // get the current directory, the one that would be opened if we did a fopen(".")
+   char* cwd = getcwd(NULL, 0);
+   StringTableEntry ret = StringTable->insert(cwd);
+   free(cwd);
+   return ret;
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::setCurrentDirectory(StringTableEntry newDir)
+{
+   return (chdir(newDir) == 0);
+}
+
+//-----------------------------------------------------------------------------
+void Platform::openFolder(const char* path )
+{
+   // TODO: users can still run applications by calling openfolder on an app bundle.
+   // this may be a bad thing.
+   if(!Platform::isDirectory(path))
+   {
+      Con::errorf(avar("Error: not a directory: %s",path));
+      return;
+   }
+   
+   const char* arg = avar("open '%s'", path);
+   U32 ret = system(arg);
+   if(ret != 0)
+      Con::printf(strerror(errno));
+}
+
+static bool isMainDotCsPresent(char *dir)
+{ 
+   char maincsbuf[MAX_MAC_PATH_LONG];
+   const char *maincsname = "/main.cs";
+   const U32 len = dStrlen(dir) + dStrlen(maincsname)+1;
+   AssertISV(len < MAX_MAC_PATH_LONG, "Sorry, path is too long, I can't run from this folder.");
+   
+   dSprintf(maincsbuf,MAX_MAC_PATH_LONG,"%s%s", dir, maincsname);
+   
+   return Platform::isFile(maincsbuf);
+}
+
+//-----------------------------------------------------------------------------
+/// Finds and sets the current working directory.
+/// Torque tries to automatically detect whether you have placed the game files 
+/// inside or outside the application's bundle. It checks for the presence of 
+/// the file 'main.cs'. If it finds it, Torque will assume that the other game
+/// files are there too. If Torque does not see 'main.cs' inside its bundle, it
+/// will assume the files are outside the bundle.
+/// Since you probably don't want to copy the game files into the app every time
+/// you build, you will want to leave them outside the bundle for development.
+///
+/// Placing all content inside the application bundle gives a much better user
+/// experience when you distribute your app.
+StringTableEntry Platform::getExecutablePath()
+{
+   if(platState.mainDotCsDir) 
+      return platState.mainDotCsDir;
+      
+   char cwd_buf[MAX_MAC_PATH_LONG];
+   CFBundleRef mainBundle = CFBundleGetMainBundle();
+   CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
+   
+   bool inside = true;
+   bool outside = false;
+   bool done = false;
+   
+   while(!done)
+   {
+      // first look for game content inside the application bundle.
+      // then we look outside the bundle
+      // then we assume it's a tool, and the "bundle" = the binary file.
+      CFURLRef workingUrl;
+      if(inside)
+         workingUrl = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault,bundleUrl,CFSTR("Contents/Resources"),true);
+      else if(outside)
+         workingUrl = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, bundleUrl);
+      else
+      {
+         workingUrl = bundleUrl;
+         CFRetain(workingUrl); // so that we can release bundleUrl twice.
+      }
+      
+      CFStringRef workingString = CFURLCopyFileSystemPath(workingUrl, kCFURLPOSIXPathStyle);
+      CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
+      CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
+      CFStringGetCString(normalizedString, cwd_buf, sizeof(cwd_buf)-1, kCFStringEncodingUTF8);
+      
+      // if we dont see main.cs inside the bundle, try again looking outside
+      // we're done if we find it, or if we find it neither inside or outside.
+      if( isMainDotCsPresent(cwd_buf) || ( !inside && !outside))
+         done = true;
+      
+      if(inside)
+         inside = false, outside = true;
+      else if(outside)
+         outside = false;
+         
+      CFRelease(workingUrl);
+      CFRelease(workingString);
+      CFRelease(normalizedString);   
+   }
+   
+   //CFRelease(mainBundle);   // apple docs say to release this, but that causes a sigsegv(11)
+   CFRelease(bundleUrl);
+   
+//   chdir(cwd_buf);            // set the current working directory.
+   
+   char* ret = NULL;
+   if(StringTable)
+      platState.mainDotCsDir = StringTable->insert(cwd_buf);
+   else
+      ret = dStrdup(cwd_buf);
+   
+   return ret ? ret : platState.mainDotCsDir;
+}
+
+//-----------------------------------------------------------------------------
+StringTableEntry Platform::getExecutableName()
+{
+   char path_buf[MAX_MAC_PATH_LONG];
+   // get a cfurl to the executable name
+   CFBundleRef mainBundle = CFBundleGetMainBundle();
+   CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
+
+   // get a cfstring of just the app name
+   CFStringRef workingString = CFURLCopyLastPathComponent(bundleUrl);
+   CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, workingString);
+   CFStringNormalize(normalizedString,kCFStringNormalizationFormC);
+   CFStringGetCString(normalizedString, path_buf, sizeof(path_buf)-1, kCFStringEncodingUTF8);
+   
+   CFRelease(bundleUrl);
+   CFRelease(workingString);
+   CFRelease(normalizedString);
+   
+   return StringTable->insert(path_buf);   
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::isFile(const char *path)
+{
+   if (!path || !*path) 
+      return false;
+   
+   // make sure we can stat the file
+   struct stat statData;
+   if( stat(path, &statData) < 0 )
+      return false;
+   
+   // now see if it's a regular file
+   if( (statData.st_mode & S_IFMT) == S_IFREG)
+      return true;
+   
+   return false;
+}
+
+
+//-----------------------------------------------------------------------------
+bool Platform::isDirectory(const char *path)
+{
+   if (!path || !*path) 
+      return false;
+   
+   // make sure we can stat the file
+   struct stat statData;
+   if( stat(path, &statData) < 0 )
+      return false;
+   
+   // now see if it's a directory
+   if( (statData.st_mode & S_IFMT) == S_IFDIR)
+      return true;
+   
+   return false;
+}
+
+
+S32 Platform::getFileSize(const char* pFilePath)
+{
+   if (!pFilePath || !*pFilePath) 
+      return 0;
+   
+   struct stat statData;
+   if( stat(pFilePath, &statData) < 0 )
+      return 0;
+   
+   // and return it's size in bytes
+   return (S32)statData.st_size;
+}
+
+
+//-----------------------------------------------------------------------------
+bool Platform::isSubDirectory(const char *pathParent, const char *pathSub)
+{
+   char fullpath[MAX_MAC_PATH_LONG];
+   dStrcpyl(fullpath, MAX_MAC_PATH_LONG, pathParent, "/", pathSub, NULL);
+   return isDirectory((const char *)fullpath);
+}
+
+//-----------------------------------------------------------------------------
+// utility for platform::hasSubDirectory() and platform::dumpDirectories()
+// ensures that the entry is a directory, and isnt on the ignore lists.
+inline bool isGoodDirectory(dirent* entry)
+{
+   return (entry->d_type == DT_DIR                          // is a dir
+           && dStrcmp(entry->d_name,".") != 0                 // not here
+           && dStrcmp(entry->d_name,"..") != 0                // not parent
+           && !Platform::isExcludedDirectory(entry->d_name)); // not excluded
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::hasSubDirectory(const char *path) 
+{
+   DIR *dir;
+   dirent *entry;
+   
+   dir = opendir(path);
+   if(!dir)
+      return false; // we got a bad path, so no, it has no subdirectory.
+   
+   while( true )
+   {
+       entry = readdir(dir);
+       if ( entry == NULL )
+           break;
+       
+      if(isGoodDirectory(entry) ) 
+      {
+         closedir(dir);
+         return true; // we have a subdirectory, that isnt on the exclude list.
+      }
+   }
+   
+   closedir(dir);
+   return false; // either this dir had no subdirectories, or they were all on the exclude list.
+}
+
+//-----------------------------------------------------------------------------
+bool recurseDumpDirectories(const char *basePath, const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
+{
+   DIR *dir;
+   dirent *entry;
+   const U32 len = dStrlen(basePath) + dStrlen(path) + 2;
+   char pathbuf[len];
+   
+   // construct the file path
+   dSprintf(pathbuf, len, "%s/%s", basePath, path);
+   
+   // be sure it opens.
+   dir = opendir(pathbuf);
+   if(!dir)
+      return false;
+   
+   // look inside the current directory
+   while( true )
+   {
+       entry = readdir(dir);
+       if ( entry == NULL )
+           break;
+       
+      // we just want directories.
+      if(!isGoodDirectory(entry))
+         continue;
+      
+      // TODO: better unicode file name handling
+      //      // Apple's file system stores unicode file names in decomposed form.
+      //      // ATSUI will not reliably draw out just the accent character by itself,
+      //      // so our text renderer has no chance of rendering decomposed form unicode.
+      //      // We have to convert the entry name to precomposed normalized form.
+      //      CFStringRef cfdname = CFStringCreateWithCString(NULL,entry->d_name,kCFStringEncodingUTF8);
+      //      CFMutableStringRef cfentryName = CFStringCreateMutableCopy(NULL,0,cfdname);
+      //      CFStringNormalize(cfentryName,kCFStringNormalizationFormC);
+      //      
+      //      U32 entryNameLen = CFStringGetLength(cfentryName) * 4 + 1;
+      //      char entryName[entryNameLen];
+      //      CFStringGetCString(cfentryName, entryName, entryNameLen, kCFStringEncodingUTF8);
+      //      entryName[entryNameLen-1] = NULL; // sometimes, CFStringGetCString() doesn't null terminate.
+      //      CFRelease(cfentryName);
+      //      CFRelease(cfdname);
+      
+      // construct the new path string, we'll need this below.
+      const U32 newpathlen = dStrlen(path) + dStrlen(entry->d_name) + 2;
+      char newpath[newpathlen];
+      if(dStrlen(path) > 0)
+      {
+          dSprintf(newpath, newpathlen, "%s/%s", path, entry->d_name);
+      }
+      else
+      {
+         dSprintf(newpath, newpathlen, "%s", entry->d_name);
+      }
+      
+      // we have a directory, add it to the list.
+      if( noBasePath )
+      {
+         directoryVector.push_back(StringTable->insert(newpath));
+      }
+      else
+      {
+         const U32 fullpathlen = dStrlen(basePath) + dStrlen(newpath) + 2;
+         char fullpath[fullpathlen];
+         dSprintf(fullpath, fullpathlen, "%s/%s",basePath,newpath);
+         directoryVector.push_back(StringTable->insert(fullpath));
+      }
+      
+      // and recurse into it, unless we've run out of depth
+      if( depth != 0) // passing a val of -1 as the recurse depth means go forever
+         recurseDumpDirectories(basePath, newpath, directoryVector, depth-1, noBasePath);
+   }
+   closedir(dir);
+   return true;
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::dumpDirectories(const char *path, Vector<StringTableEntry> &directoryVector, S32 depth, bool noBasePath)
+{
+   PROFILE_START(dumpDirectories);
+
+   ResourceManager->initExcludedDirectories();
+
+   const S32 len = dStrlen(path)+1;
+   char newpath[len];
+   dSprintf(newpath, len, "%s", path);
+   if(newpath[len - 1] == '/')
+      newpath[len - 1] = '\0'; // cut off the trailing slash, if there is one
+   
+    // Insert base path to follow what Windows does.
+    if ( !noBasePath )
+        directoryVector.push_back(StringTable->insert(newpath));
+   
+    bool ret = recurseDumpDirectories(newpath, "", directoryVector, depth, noBasePath);
+   PROFILE_END();
+   
+   return ret;
+}
+
+//-----------------------------------------------------------------------------
+static bool recurseDumpPath(const char* curPath, Vector<Platform::FileInfo>& fileVector, U32 depth)
+{
+   DIR *dir;
+   dirent *entry;
+   
+   // be sure it opens.
+   dir = opendir(curPath);
+   if(!dir)
+      return false;
+   
+   // look inside the current directory
+   while( true )
+   {
+       entry = readdir(dir);
+       if ( entry == NULL )
+           break;
+       
+      // construct the full file path. we need this to get the file size and to recurse
+      const U32 len = dStrlen(curPath) + entry->d_namlen + 2;
+      char pathbuf[len];
+      dSprintf( pathbuf, len, "%s/%s", curPath, entry->d_name);
+      
+      // ok, deal with directories and files seperately.
+      if( entry->d_type == DT_DIR )
+      {
+         if( depth == 0)
+            continue;
+         
+         // filter out dirs we dont want.
+         if( !isGoodDirectory(entry) )
+            continue;
+         
+         // recurse into the dir
+         recurseDumpPath( pathbuf, fileVector, depth-1);
+      }
+      else
+      {
+         //add the file entry to the list
+         // unlike recurseDumpDirectories(), we need to return more complex info here.
+          //<Mat> commented this out in case we ever want a dir file printout again
+          //printf( "File Name: %s ", entry->d_name );
+         const U32 fileSize = Platform::getFileSize(pathbuf);
+         fileVector.increment();
+         Platform::FileInfo& rInfo = fileVector.last();
+         rInfo.pFullPath = StringTable->insert(curPath);
+         rInfo.pFileName = StringTable->insert(entry->d_name);
+         rInfo.fileSize  = fileSize;
+      }
+   }
+   closedir(dir);
+   return true;
+   
+}
+
+
+//-----------------------------------------------------------------------------
+bool Platform::dumpPath(const char *path, Vector<Platform::FileInfo>& fileVector, S32 depth)
+{
+   PROFILE_START(dumpPath);
+    const S32 len = dStrlen(path) + 1;
+   char newpath[len];
+   
+    dSprintf(newpath, len, "%s", path);
+    
+   if(newpath[len - 2] == '/')
+      newpath[len - 2] = '\0'; // cut off the trailing slash, if there is one
+   
+   bool ret = recurseDumpPath( newpath, fileVector, depth);
+   PROFILE_END();
+   
+   return ret;
+}
+
+//-----------------------------------------------------------------------------
+#if defined(TORQUE_DEBUG)
+ConsoleFunction(testHasSubdir,void,2,2,"tests platform::hasSubDirectory") {
+   Con::printf("testing %s",argv[1]);
+   Platform::addExcludedDirectory(".svn");
+   if(Platform::hasSubDirectory(argv[1]))
+      Con::printf(" has subdir");
+   else
+      Con::printf(" does not have subdir");
+}
+
+ConsoleFunction(testDumpDirectories,void,4,4,"testDumpDirectories('path', int depth, bool noBasePath)") {
+   Vector<StringTableEntry> paths;
+   S32 depth = dAtoi(argv[2]);
+   
+   Platform::addExcludedDirectory(".svn");
+   
+   Platform::dumpDirectories(argv[1],paths,dAtoi(argv[2]),dAtob(argv[3]));
+   
+   Con::printf("Dumping directories starting from %s with depth %i", argv[1],depth);
+   
+   for(Vector<StringTableEntry>::iterator itr = paths.begin(); itr != paths.end(); itr++) {
+      Con::printf(*itr);
+   }
+   
+}
+
+ConsoleFunction(testDumpPaths, void, 3, 3, "testDumpPaths('path', int depth)")
+{
+   Vector<Platform::FileInfo> files;
+   S32 depth = dAtoi(argv[2]);
+   
+   Platform::addExcludedDirectory(".svn");
+   
+   Platform::dumpPath(argv[1], files, depth);
+   
+   for(Vector<Platform::FileInfo>::iterator itr = files.begin(); itr != files.end(); itr++) {
+      Con::printf("%s/%s",itr->pFullPath, itr->pFileName);
+   }
+}
+
+//-----------------------------------------------------------------------------
+ConsoleFunction(testFileTouch, bool , 2,2, "testFileTouch('path')")
+{
+   return dFileTouch(argv[1]);
+}
+
+ConsoleFunction(testGetFileTimes, bool, 2,2, "testGetFileTimes('path')")
+{
+   FileTime create, modify;
+   bool ok;
+   ok = Platform::getFileTimes(argv[1],&create, &modify);
+   Con::printf("%s Platform::getFileTimes %i, %i", ok ? "+OK" : "-FAIL", create, modify);
+    return ok;
+}
+
+#endif

+ 231 - 0
engine/source/platformAndroid/AndroidFont.cpp

@@ -0,0 +1,231 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import "platform/platform.h"
+#import "platformAndroid/platformAndroid.h"
+#import "platformAndroid/AndroidFont.h"
+#import "string/Unicode.h"
+
+//------------------------------------------------------------------------------
+// New Unicode capable font class.
+PlatformFont *createPlatformFont(const char *name, U32 size, U32 charset /* = TGE_ANSI_CHARSET */)
+{
+    PlatformFont *retFont = new AndroidFont;
+
+    if(retFont->create(name, size, charset))
+        return retFont;
+
+    delete retFont;
+    return NULL;
+}
+
+//------------------------------------------------------------------------------
+
+void PlatformFont::enumeratePlatformFonts( Vector<StringTableEntry>& fonts )
+{
+}
+
+//------------------------------------------------------------------------------
+
+AndroidFont::AndroidFont()
+{
+    // Reset the rendering color-space.
+    mColorSpace = NULL;
+}
+
+//------------------------------------------------------------------------------
+
+AndroidFont::~AndroidFont()
+{
+}
+
+//------------------------------------------------------------------------------
+
+bool AndroidFont::create( const char* name, U32 size, U32 charset )
+{
+    // Sanity!
+    AssertFatal( name != NULL, "Cannot create a NULL font name." );
+    //TODO: font create
+    /*
+    // Generate compatible font name.
+    CFStringRef fontName = CFStringCreateWithCString( kCFAllocatorDefault, name, kCFStringEncodingUTF8 );
+    
+    // Sanity!
+    if ( !fontName )
+    {
+        Con::errorf("Could not handle font name of '%s'.", name );
+        return false;
+    }
+    
+    // Use Windows as a baseline (96 DPI) and adjust accordingly.
+    F32 scaledSize = size * (72.0f/96.0f);
+    scaledSize = mRound(scaledSize);
+    
+    // Create the font reference.
+    mFontRef = CTFontCreateWithName( fontName, scaledSize, NULL );
+    
+    // Sanity!
+    if ( !mFontRef )
+    {
+        Con::errorf( "Could not generate a font reference to font name '%s' of size '%d'", name, size );
+        return false;
+    }
+    
+    // Fetch font metrics.
+    CGFloat ascent = CTFontGetAscent( mFontRef );
+    CGFloat descent = CTFontGetDescent( mFontRef );
+    
+    // Set baseline.
+    mBaseline = (U32)mRound(ascent);
+    
+    // Set height.
+    mHeight = (U32)mRound( ascent + descent );
+    
+    // Create a gray-scale color-space.
+    mColorSpace = CGColorSpaceCreateDeviceGray();
+    */
+    // Return status.
+    return true;
+}
+
+//------------------------------------------------------------------------------
+
+bool AndroidFont::isValidChar( const UTF8* str ) const
+{
+    // since only low order characters are invalid, and since those characters
+    // are single codeunits in UTF8, we can safely cast here.
+    return isValidChar((UTF16)*str);
+}
+
+//------------------------------------------------------------------------------
+
+bool AndroidFont::isValidChar( const UTF16 character) const
+{
+    // We cut out the ASCII control chars here. Only printable characters are valid.
+    // 0x20 == 32 == space
+    if( character < 0x20 )
+        return false;
+    
+    return true;
+}
+
+//------------------------------------------------------------------------------
+
+PlatformFont::CharInfo& AndroidFont::getCharInfo(const UTF8 *str) const
+{
+    return getCharInfo( oneUTF32toUTF16(oneUTF8toUTF32(str,NULL)) );
+}
+
+//------------------------------------------------------------------------------
+
+PlatformFont::CharInfo& AndroidFont::getCharInfo(const UTF16 character) const
+{
+    // Declare and clear out the CharInfo that will be returned.
+    static PlatformFont::CharInfo characterInfo;
+    dMemset(&characterInfo, 0, sizeof(characterInfo));
+    
+    // prep values for GFont::addBitmap()
+    characterInfo.bitmapIndex = 0;
+    characterInfo.xOffset = 0;
+    characterInfo.yOffset = 0;
+    
+    //TODO: getcharinfo
+    /*
+    CGGlyph characterGlyph;
+    CGRect characterBounds;
+    CGSize characterAdvances;
+    UniChar unicodeCharacter = character;
+    
+    // Fetch font glyphs.
+    if ( !CTFontGetGlyphsForCharacters( mFontRef, &unicodeCharacter, &characterGlyph, (CFIndex)1) )
+    {
+        // Sanity!
+        AssertFatal( false, "Cannot create font glyph." );
+    }
+    
+    // Fetch glyph bounding box.
+    CTFontGetBoundingRectsForGlyphs( mFontRef, kCTFontHorizontalOrientation, &characterGlyph, &characterBounds, (CFIndex)1 );
+    
+    // Fetch glyph advances.
+    CTFontGetAdvancesForGlyphs( mFontRef, kCTFontHorizontalOrientation, &characterGlyph, &characterAdvances, (CFIndex)1 );
+    
+    // Set character metrics,
+    characterInfo.xOrigin = (S32)mRound( characterBounds.origin.x );
+    characterInfo.yOrigin = (S32)mRound( characterBounds.origin.y );
+    characterInfo.width = (U32)mCeil( characterBounds.size.width ) + 2;
+    characterInfo.height = (U32)mCeil( characterBounds.size.height ) + 2;
+    characterInfo.xIncrement = (S32)mRound( characterAdvances.width );
+    
+    // Finish if character is undrawable.
+    if ( characterInfo.width == 0 && characterInfo.height == 0 )
+        return characterInfo;
+    
+    // Clamp character minimum width.
+    if ( characterInfo.width == 0 )
+        characterInfo.width = 2;
+    
+    if ( characterInfo.height == 0 )
+        characterInfo.height = 1;
+    
+    
+    // Allocate a bitmap surface.
+    const U32 bitmapSize = characterInfo.width * characterInfo.height;
+    characterInfo.bitmapData = new U8[bitmapSize];
+    dMemset(characterInfo.bitmapData, 0x00, bitmapSize);
+    
+    // Create a bitmap context.
+    CGContextRef bitmapContext = CGBitmapContextCreate( characterInfo.bitmapData, characterInfo.width, characterInfo.height, 8, characterInfo.width, mColorSpace, kCGImageAlphaNone );
+    
+    // Sanity!
+    AssertFatal( bitmapContext != NULL, "Cannot create font context." );
+    
+    // Render font anti-aliased if font is arbitrarily small.
+    CGContextSetShouldAntialias( bitmapContext, true);
+    CGContextSetShouldSmoothFonts( bitmapContext, true);
+    CGContextSetRenderingIntent( bitmapContext, kCGRenderingIntentAbsoluteColorimetric);
+    CGContextSetInterpolationQuality( bitmapContext, kCGInterpolationNone);
+    CGContextSetGrayFillColor( bitmapContext, 1.0, 1.0);
+    CGContextSetTextDrawingMode( bitmapContext,  kCGTextFill);
+    
+    // Draw glyph.
+    CGPoint renderOrigin;
+    renderOrigin.x = -characterInfo.xOrigin;
+    renderOrigin.y = -characterInfo.yOrigin;
+    CTFontDrawGlyphs( mFontRef, &characterGlyph, &renderOrigin, 1, bitmapContext );
+    
+#if 0
+    Con::printf("Width:%f, Height:%f, OriginX:%f, OriginY:%f",
+                characterBounds.size.width,
+                characterBounds.size.height,
+                characterBounds.origin.x,
+                characterBounds.origin.y );
+#endif
+    
+    // Adjust the y origin for the glyph size.
+    characterInfo.yOrigin += characterInfo.height;// + mHeight;
+    
+    // Release the bitmap context.
+    CGContextRelease( bitmapContext );
+    */
+    // Return character information.
+    return characterInfo;
+}

+ 59 - 0
engine/source/platformAndroid/AndroidFont.h

@@ -0,0 +1,59 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platform/platformFont.h"
+#import <CoreText/CoreText.h>
+
+class AndroidFont : public PlatformFont
+{
+private:
+    
+    // Font reference.
+    //TODO: CTFontRef       mFontRef;
+    
+    // Distance from drawing point to typographic baseline.
+    // Think of the drawing point as the upper left corner of a text box.
+    // NOTE: 'baseline' is synonymous with 'ascent' in Torque.
+    U32             mBaseline;
+    
+    // Distance between lines.
+    U32             mHeight;
+    
+public:
+    AndroidFont();
+    virtual ~AndroidFont();
+    
+    /// Look up the requested font, cache style, layout, colorspace, and some metrics.
+    virtual bool create( const char* name, U32 size, U32 charset = TGE_ANSI_CHARSET);
+    
+    /// Determine if the character requested is a drawable character, or if it should be ignored.
+    virtual bool isValidChar( const UTF16 character) const;
+    virtual bool isValidChar( const UTF8* str) const;
+    
+    /// Get some vertical data on the font at large. Useful for drawing multiline text, and sizing text boxes.
+    virtual U32 getFontHeight() const { return mHeight; }
+    virtual U32 getFontBaseLine() const { return mBaseline; }
+    
+    // Draw the character to a temporary bitmap, and fill the CharInfo with various text metrics.
+    virtual PlatformFont::CharInfo &getCharInfo(const UTF16 character) const;
+    virtual PlatformFont::CharInfo &getCharInfo(const UTF8 *str) const;
+};

+ 245 - 0
engine/source/platformAndroid/AndroidGL.cpp

@@ -0,0 +1,245 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+// Many OSX frameworks include OpenTransport, and OT's new operator conflicts 
+// with our redefinition of 'new', so we have to pre-include platformAndroid.h,
+// which contains the workaround.
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/platformGL.h"
+#include "platformAndroid/AndroidUtil.h"
+
+#include "console/console.h"
+#include "graphics/dgl.h"
+
+GLState gGLState;
+
+bool gOpenGLDisablePT          = false;
+bool gOpenGLDisableCVA         = false;
+bool gOpenGLDisableTEC         = false;
+bool gOpenGLDisableARBMT       = false;
+bool gOpenGLDisableFC          = true; //false;
+bool gOpenGLDisableTCompress   = false;
+bool gOpenGLNoEnvColor         = false;
+float gOpenGLGammaCorrection   = 0.5;
+bool gOpenGLNoDrawArraysAlpha  = false;
+
+//-----------------------------------------------------------------------------
+/// These stubs are legacy stuff for the d3d wrapper layer.
+// The code that requires these stubs should probably be ifdef'd out of any non w32 build
+//-----------------------------------------------------------------------------
+GLboolean glAvailableVertexBufferEXT() {   return(false); }
+GLint glAllocateVertexBufferEXT(GLsizei size, GLint format, GLboolean preserve) {   return(0); }
+void* glLockVertexBufferEXT(GLint handle, GLsizei size) {   return(NULL); }
+void glUnlockVertexBufferEXT(GLint handle) {}
+void glSetVertexBufferEXT(GLint handle) {}
+void glOffsetVertexBufferEXT(GLint handle, GLuint offset) {}
+void glFillVertexBufferEXT(GLint handle, GLint first, GLsizei count) {}
+void glFreeVertexBufferEXT(GLint handle) {}
+
+
+// Find out which extensions are available for this renderer. 
+void getGLCapabilities( )
+{
+   AssertFatal(platState.ctx, "getGLCapabilities() was called before a monitor was chosen!");
+
+   // silently create an opengl context on the current display,
+   // so that we can get valid renderer and capability info.
+   // we save off the current context so that we can silently restore it.
+   // the user should not be aware of this little shuffle.
+   //CGLContextObj curr_ctx = CGLGetCurrentContext ();
+   //CGLContextObj temp_ctx =  getContextForCapsCheck();
+   /*
+   if(!temp_ctx)
+   {
+      Con::errorf("OpenGL may not be set up correctly!");
+      return;
+   }
+   */
+   //CGLSetCurrentContext(temp_ctx);
+
+   // Get the OpenGL info strings we'll need
+   const char* pVendString    = (const char*) glGetString( GL_VENDOR );
+   const char* pRendString    = (const char*) glGetString( GL_RENDERER );
+   const char* pVersString    = (const char*) glGetString( GL_VERSION );
+   const char* pExtString     = (const char*) glGetString( GL_EXTENSIONS );
+
+   // Output some driver info to the console:
+   Con::printf( "OpenGL driver information:" );
+   if ( pVendString )
+      Con::printf( "  Vendor: %s", pVendString );
+   if ( pRendString )
+      Con::printf( "  Renderer: %s", pRendString );
+   if ( pVersString )
+      Con::printf( "  Version: %s", pVersString );
+
+   // pre-clear the structure
+   dMemset(&gGLState, 0, sizeof(gGLState));
+
+   if(pExtString)
+   {
+      // EXT_paletted_texture ========================================
+      if (dStrstr(pExtString, (const char*)"GL_EXT_paletted_texture") != NULL)
+         gGLState.suppPalettedTexture = true;
+      
+      // EXT_compiled_vertex_array ========================================
+      gGLState.suppLockedArrays = false;
+      if (dStrstr(pExtString, (const char*)"GL_EXT_compiled_vertex_array") != NULL)
+         gGLState.suppLockedArrays = true;
+
+      // ARB_multitexture ========================================
+      if (dStrstr(pExtString, (const char*)"GL_ARB_multitexture") != NULL)
+		  gGLState.suppARBMultitexture = true;
+      
+      // EXT_blend_color
+      if(dStrstr(pExtString, (const char*)"GL_EXT_blend_color") != NULL)
+         gGLState.suppEXTblendcolor = true;
+
+      // EXT_blend_minmax
+      if(dStrstr(pExtString, (const char*)"GL_EXT_blend_minmax") != NULL)
+         gGLState.suppEXTblendminmax = true;
+
+      // NV_vertex_array_range ========================================
+      // does not appear to be supported by apple, at all. ( as of 10.4.3 )
+      // GL_APPLE_vertex_array_range is similar, and may be nearly identical.
+      if (dStrstr(pExtString, (const char*)"GL_NV_vertex_array_range") != NULL)
+         gGLState.suppVertexArrayRange = true;
+      
+
+      // EXT_fog_coord ========================================
+      if (dStrstr(pExtString, (const char*)"GL_EXT_fog_coord") != NULL)
+         gGLState.suppFogCoord = true;
+      
+      // ARB_texture_compression ========================================
+      if (dStrstr(pExtString, (const char*)"GL_ARB_texture_compression") != NULL)
+         gGLState.suppTextureCompression = true;
+
+      // 3DFX_texture_compression_FXT1 ========================================
+      if (dStrstr(pExtString, (const char*)"GL_3DFX_texture_compression_FXT1") != NULL)
+         gGLState.suppFXT1 = true;
+
+      // EXT_texture_compression_S3TC ========================================
+      if (dStrstr(pExtString, (const char*)"GL_EXT_texture_compression_s3tc") != NULL)
+         gGLState.suppS3TC = true;
+
+      // EXT_vertex_buffer ========================================
+      // This extension is deprecated, and not supported by Apple. ( 10.4.3 )
+      // Instead, the ARB Vertex Buffer extension is supported.
+      // The new extension has a different API, so TGE should be updated to use it.
+      if (dStrstr(pExtString, (const char*)"GL_EXT_vertex_buffer") != NULL)
+         gGLState.suppVertexBuffer = true;
+
+      // Anisotropic filtering ========================================
+      gGLState.suppTexAnisotropic    = (dStrstr(pExtString, (const char*)"GL_EXT_texture_filter_anisotropic") != NULL);
+      if (gGLState.suppTexAnisotropic)
+         glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gGLState.maxAnisotropy);
+
+      // Binary states, i.e., no supporting functions  ========================================
+      // NOTE:
+      // Some of these have multiple representations, via EXT and|or ARB and|or NV and|or SGIS ... etc.
+      // Check all relative versions.
+      
+      gGLState.suppPackedPixels      = (dStrstr(pExtString, (const char*)"GL_EXT_packed_pixels") != NULL);
+      gGLState.suppPackedPixels     |= (dStrstr(pExtString, (const char*)"GL_APPLE_packed_pixel") != NULL);
+
+      gGLState.suppTextureEnvCombine = (dStrstr(pExtString, (const char*)"GL_EXT_texture_env_combine") != NULL);
+      gGLState.suppTextureEnvCombine|= (dStrstr(pExtString, (const char*)"GL_ARB_texture_env_combine") != NULL);
+
+      gGLState.suppEdgeClamp         = (dStrstr(pExtString, (const char*)"GL_EXT_texture_edge_clamp") != NULL);
+      gGLState.suppEdgeClamp        |= (dStrstr(pExtString, (const char*)"GL_SGIS_texture_edge_clamp") != NULL);
+      gGLState.suppEdgeClamp        |= (dStrstr(pExtString, (const char*)"GL_ARB_texture_border_clamp") != NULL);
+	   gGLState.suppEdgeClamp		= true; //TODO does android support edge clamp?
+
+      gGLState.suppTexEnvAdd         = (dStrstr(pExtString, (const char*)"GL_ARB_texture_env_add") != NULL);
+      gGLState.suppTexEnvAdd        |= (dStrstr(pExtString, (const char*)"GL_EXT_texture_env_add") != NULL);
+
+   }
+   
+   // Texture combine units  ========================================
+//   if (gGLState.suppARBMultitexture)
+//      glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &gGLState.maxTextureUnits);
+	  gGLState.suppARBMultitexture = false;
+      gGLState.maxTextureUnits = 1;
+
+   // Swap interval ========================================
+   // Mac inherently supports a swap interval via AGL-set-integer.
+   gGLState.suppSwapInterval = true;
+
+   // FSAA support, TODO: check for ARB multisample support
+   // multisample support should be checked via CGL
+   gGLState.maxFSAASamples = 4;
+
+   // dump found extensions to the console... 
+   Con::printf("OpenGL Init: Enabled Extensions");
+   if (gGLState.suppARBMultitexture)    Con::printf("  ARB_multitexture (Max Texture Units: %d)", gGLState.maxTextureUnits);
+   if (gGLState.suppEXTblendcolor)      Con::printf("  EXT_blend_color");
+   if (gGLState.suppEXTblendminmax)     Con::printf("  EXT_blend_minmax");
+   if (gGLState.suppPalettedTexture)    Con::printf("  EXT_paletted_texture");
+   if (gGLState.suppLockedArrays)       Con::printf("  EXT_compiled_vertex_array");
+   if (gGLState.suppVertexArrayRange)   Con::printf("  NV_vertex_array_range");
+   if (gGLState.suppTextureEnvCombine)  Con::printf("  EXT_texture_env_combine");
+   if (gGLState.suppPackedPixels)       Con::printf("  EXT_packed_pixels");
+   if (gGLState.suppFogCoord)           Con::printf("  EXT_fog_coord");
+   if (gGLState.suppTextureCompression) Con::printf("  ARB_texture_compression");
+   if (gGLState.suppS3TC)               Con::printf("  EXT_texture_compression_s3tc");
+   if (gGLState.suppFXT1)               Con::printf("  3DFX_texture_compression_FXT1");
+   if (gGLState.suppTexEnvAdd)          Con::printf("  (ARB|EXT)_texture_env_add");
+   if (gGLState.suppTexAnisotropic)     Con::printf("  EXT_texture_filter_anisotropic (Max anisotropy: %f)", gGLState.maxAnisotropy);
+   if (gGLState.suppSwapInterval)       Con::printf("  Vertical Sync");
+   if (gGLState.maxFSAASamples)         Con::printf("  ATI_FSAA");
+
+   Con::warnf("OpenGL Init: Disabled Extensions");
+   if (!gGLState.suppARBMultitexture)    Con::warnf("  ARB_multitexture");
+   if (!gGLState.suppEXTblendcolor)      Con::warnf("  EXT_blend_color");
+   if (!gGLState.suppEXTblendminmax)     Con::warnf("  EXT_blend_minmax");
+   if (!gGLState.suppPalettedTexture)    Con::warnf("  EXT_paletted_texture");
+   if (!gGLState.suppLockedArrays)       Con::warnf("  EXT_compiled_vertex_array");
+   if (!gGLState.suppVertexArrayRange)   Con::warnf("  NV_vertex_array_range");
+   if (!gGLState.suppTextureEnvCombine)  Con::warnf("  EXT_texture_env_combine");
+   if (!gGLState.suppPackedPixels)       Con::warnf("  EXT_packed_pixels");
+   if (!gGLState.suppFogCoord)           Con::warnf("  EXT_fog_coord");
+   if (!gGLState.suppTextureCompression) Con::warnf("  ARB_texture_compression");
+   if (!gGLState.suppS3TC)               Con::warnf("  EXT_texture_compression_s3tc");
+   if (!gGLState.suppFXT1)               Con::warnf("  3DFX_texture_compression_FXT1");
+   if (!gGLState.suppTexEnvAdd)          Con::warnf("  (ARB|EXT)_texture_env_add");
+   if (!gGLState.suppTexAnisotropic)     Con::warnf("  EXT_texture_filter_anisotropic");
+   if (!gGLState.suppSwapInterval)       Con::warnf("  Vertical Sync");
+   if (!gGLState.maxFSAASamples)         Con::warnf("  ATI_FSAA");
+   Con::printf("");
+
+   // Set some console variables:
+   Con::setBoolVariable( "$FogCoordSupported", gGLState.suppFogCoord );
+   Con::setBoolVariable( "$TextureCompressionSupported", gGLState.suppTextureCompression );
+   Con::setBoolVariable( "$AnisotropySupported", gGLState.suppTexAnisotropic );
+   Con::setBoolVariable( "$PalettedTextureSupported", gGLState.suppPalettedTexture );
+   Con::setBoolVariable( "$SwapIntervalSupported", gGLState.suppSwapInterval );
+
+   if (!gGLState.suppPalettedTexture && Con::getBoolVariable("$pref::OpenGL::forcePalettedTexture",false))
+   {
+      Con::setBoolVariable("$pref::OpenGL::forcePalettedTexture", false);
+      Con::setBoolVariable("$pref::OpenGL::force16BitTexture", true);
+   }
+
+   // get fsaa samples. default to normal, no antialiasing
+   // TODO: clamp this against ARB_multisample capabilities.
+   gFSAASamples = Con::getIntVariable("$pref::OpenGL::numFSAASamples", 1);
+
+}

+ 662 - 0
engine/source/platformAndroid/AndroidGL2ES.cpp

@@ -0,0 +1,662 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+//
+//  AndroidGL2ES.mm
+//  TGE
+//
+//  Created by Puap Puap on 7/31/08.
+//  Copyright 2008 Pick Up And Play. All rights reserved.
+//
+
+#import "AndroidGL2ES.h"
+#import "platform/platformAssert.h"
+#import "AndroidOGLVideo.h"
+
+#include "math/mMatrix.h"
+#include "math/mPoint.h"
+
+
+#define	INV_255		0.0039215686f
+#define	INV_32767	3.0518509476e-5f
+
+/* EAGL and GL functions calling wrappers that log on error */
+#define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) Con::printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? 0 : 1); })
+#define CHECK_GL_ERROR() ({ int __error = glGetError(); if(__error) Con::printf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? 0 : 1); })
+// define this to print out glErrors, un-define to get rid of it
+#define TEST_FOR_OPENGL_ERRORS CHECK_GL_ERROR();
+
+    
+/////////////////////////////////////////////////////////////////////////////
+//
+//    Wrapper around the matrix stack ops, to see if ever have over/underflow
+//
+extern "C"
+{
+static GLenum currentMatrixMode = GL_MODELVIEW;
+static int currentProjStackDepth = 0;
+    static GLfloat projStack[256];
+static int currentTexStackDepth = 0;
+    static GLfloat texStack[256];
+static int currentModelStackDepth = 0;
+    static GLfloat modStack[256];
+    
+#undef glPushMatrix // temporarily
+void AndroidGLPushMatrix() {
+    GLint depth;
+    switch (currentMatrixMode) {
+        case GL_MODELVIEW:
+            if (currentModelStackDepth > 15) {
+                AssertFatal( 0, "ModelView Stack overflow" );
+            } else {
+                glGetFloatv( GL_MODELVIEW_MATRIX, &modStack[currentModelStackDepth*16] );
+                currentModelStackDepth++;
+                glGetIntegerv( GL_MODELVIEW_STACK_DEPTH, &depth );
+//				AssertWarn( (currentModelStackDepth > depth), "Native ModelView stack depth has been exceeded" );
+            }
+            break;
+        case GL_PROJECTION:
+            if (currentProjStackDepth > 15) {
+                AssertFatal( 0, "Projection Stack overflow" );
+            } else {
+                glGetFloatv( GL_PROJECTION_MATRIX, &projStack[currentProjStackDepth*16] );
+                currentProjStackDepth++;
+                glGetIntegerv( GL_PROJECTION_STACK_DEPTH, &depth );
+//				AssertWarn( (currentProjStackDepth > depth), "Native Projection stack depth has been exceeded" );
+            }
+            break;
+        case GL_TEXTURE:
+            if (currentTexStackDepth > 15) {
+                AssertFatal( 0, "Texture Stack overflow" );
+            } else {
+                glGetFloatv( GL_TEXTURE_MATRIX, &texStack[currentTexStackDepth*16] );
+                currentTexStackDepth++;
+                glGetIntegerv( GL_TEXTURE_STACK_DEPTH, &depth );
+//				AssertWarn( (currentTexStackDepth > depth), "Native Texture stack depth has been exceeded" );
+            }
+            break;
+        default:
+            glPushMatrix();
+            GLenum err;
+            err = glGetError();
+            AssertFatal( !(err == GL_STACK_OVERFLOW), "GL Stack overflow" );
+            break;
+    }
+}
+#define glPushMatrix AndroidGLPushMatrix
+    
+#undef glPopMatrix // temporarily
+void AndroidGLPopMatrix() {
+    switch (currentMatrixMode) {
+        case GL_MODELVIEW:
+            if (currentModelStackDepth <= 0) {
+                AssertFatal( 0, "ModelView Stack underflow" );
+            } else {
+                currentModelStackDepth--;
+                glLoadMatrixf( &modStack[currentModelStackDepth*16] );
+            }
+            break;
+        case GL_PROJECTION:
+            if (currentProjStackDepth <= 0) {
+                AssertFatal( 0, "Projection Stack underflow" );
+            } else {
+                currentProjStackDepth--;
+                glLoadMatrixf( &projStack[currentProjStackDepth*16] );
+            }
+            break;
+        case GL_TEXTURE:
+            if (currentTexStackDepth <= 0) {
+                AssertFatal( 0, "Texture Stack underflow" );
+            } else {
+                currentTexStackDepth--;
+                glLoadMatrixf( &texStack[currentTexStackDepth*16] );
+            }
+            break;
+        default:
+            glPopMatrix();
+            GLenum err;
+            err = glGetError();
+            AssertFatal( !(err == GL_STACK_UNDERFLOW), "GL Stack underflow" );
+            break;
+    }
+}
+#define glPopMatrix AndroidGLPopMatrix
+
+#undef glMatrixMode // temporarily
+void AndroidGLMatrixMode( GLenum mode ) {
+    currentMatrixMode = mode;
+    glMatrixMode( mode );
+}
+#define glMatrixMode AndroidGLMatrixMode // redefine for everyone else
+}	
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//    The following API functions are wrappers to add opengl functionality to opengl-es
+//
+static GLint beginEndMode = -1;
+// tex coord array
+static GLfloat * beginEndTexCoord2f = NULL; // 2 entries per coord
+static int beginEndTexCoord2f_alloc = 0; // number of bytes allocated to the array
+static int beginEndTexCoord2f_size = 0; // number of coords in the array
+// vertex array
+static GLfloat * beginEndVertex = NULL; // 4 entries per vertex
+static int beginEndVertex_alloc = 0; // number of bytes allocated to the array
+static int beginEndVertex_size = 0; // number of vertexes in the array
+// color array -- needed if glColor is called inside begin/end
+static GLfloat * beginEndColor = NULL; // 4 entries per color
+static int beginEndColor_size = 0; // number of colors in the array
+// normal array
+static GLfloat * beginEndNormal = NULL; // 3 entries per normal
+static int beginEndNormal_alloc = 0; // number of bytes allocated to the array
+static int beginEndNormal_size = 0; // number of normals in the array
+
+// macros to handle re-sizing the arrays as needed
+#define CHECK_ARRAY_SIZE( ppArray, pAlloc, pSize, nType, nGroup ) \
+    if (*ppArray == NULL) { \
+        *pAlloc =  32 * sizeof(nType) * nGroup; \
+        *ppArray = (nType*)dMalloc( 32 * sizeof(nType) * nGroup ); \
+    } \
+    if (*pSize >= *pAlloc / (nGroup * sizeof(nType))) { \
+        *ppArray = (nType*)dRealloc( *ppArray, 2 * (*pAlloc) ); \
+        *pAlloc *= 2; \
+    }
+    
+    
+void glBegin( GLint mode )
+{
+    if (beginEndMode >= 0) {
+        AssertFatal(0, "glBegin(): called without a glEnd");
+    }
+    beginEndMode = mode;
+    beginEndTexCoord2f_size = 0;
+    beginEndVertex_size = 0;
+    beginEndColor_size = 0;
+    beginEndNormal_size = 0;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+
+void glEnd()
+{
+    if (beginEndMode < 0) {
+        AssertFatal(0, "glEnd(): called without a glBegin");
+    }
+    
+    if (beginEndVertex_size > 0) {
+        glEnableClientState( GL_VERTEX_ARRAY );
+        glVertexPointer( 4, GL_FLOAT, 4*sizeof(GL_FLOAT), beginEndVertex );
+    }
+    if (beginEndNormal_size > 0) {
+        glEnableClientState( GL_NORMAL_ARRAY );
+        glNormalPointer( GL_FLOAT, 3*sizeof(GL_FLOAT), beginEndNormal );
+    }
+    if (beginEndColor_size > 0) {
+        glEnableClientState( GL_COLOR_ARRAY );
+        glColorPointer( 4, GL_FLOAT, 4*sizeof(GL_FLOAT), beginEndColor );
+    }
+    if (beginEndTexCoord2f_size > 0) {
+        glEnableClientState( GL_TEXTURE_COORD_ARRAY );
+        glTexCoordPointer( 2, GL_FLOAT, 2*sizeof(GL_FLOAT), beginEndTexCoord2f );
+    }
+
+    switch (beginEndMode) {
+        case GL_POINTS:
+            glDrawArrays( GL_POINTS, 0, beginEndVertex_size );
+            break;
+        case GL_LINES:
+            glDrawArrays( GL_LINES, 0, beginEndVertex_size );
+            break;
+        case GL_LINE_STRIP:
+            glDrawArrays( GL_LINE_STRIP, 0, beginEndVertex_size );
+            break;
+        case GL_LINE_LOOP:
+            glDrawArrays( GL_LINE_LOOP, 0, beginEndVertex_size );
+            break;
+        case GL_TRIANGLES:
+            glDrawArrays( GL_TRIANGLES, 0, beginEndVertex_size );
+            break;
+        case GL_TRIANGLE_STRIP:
+            glDrawArrays( GL_TRIANGLE_STRIP, 0, beginEndVertex_size );
+            break;
+        case GL_TRIANGLE_FAN:
+            glDrawArrays( GL_TRIANGLE_FAN, 0, beginEndVertex_size );
+            break;
+        case GL_QUADS:
+#if 1 // %%PUAP%% TESTING
+            // for now, just draw a couple lines to indicate the edges of the quads
+            glDrawArrays( GL_LINES, 0, beginEndVertex_size );
+#else
+            // draw these as individual pairs of triangle_strips
+            glDrawArrays( GL_TRIANGLE_STRIP, 0, beginEndVertex_size );
+#endif
+            break;
+        case GL_QUAD_STRIP:
+#if 1 // %%PUAP%% TESTING
+            glDrawArrays( GL_LINES, 0, beginEndVertex_size );
+#endif
+            break;
+        case GL_POLYGON:
+            // see if it is really just a triangle...
+            if (beginEndVertex_size == 3) {
+                glDrawArrays( GL_TRIANGLES, 0, 3 );
+            } else 
+            // see if it is really just a quad...
+            if (beginEndVertex_size == 4) {
+                glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
+            } else
+                AssertFatal( 0, "glBegin(GL_POLYGON): this method call needs to be implemented");
+            break;
+    }
+    
+    if (beginEndVertex_size > 0) {
+        glDisableClientState( GL_VERTEX_ARRAY );
+    }
+    if (beginEndNormal_size > 0) {
+        glDisableClientState( GL_NORMAL_ARRAY );
+    }
+    if (beginEndColor_size > 0) {
+        glDisableClientState( GL_COLOR_ARRAY );
+    }
+    if (beginEndTexCoord2f_size > 0) {
+        glDisableClientState( GL_TEXTURE_COORD_ARRAY );
+    }
+    beginEndMode = -1;	
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+
+void glTexCoord2f( GLfloat x, GLfloat y)
+{
+    AssertFatal( (beginEndMode >= 0), "glTexCoord2f(): called outside glBegin/glEnd");
+    CHECK_ARRAY_SIZE( &beginEndTexCoord2f, &beginEndTexCoord2f_alloc, &beginEndTexCoord2f_size, GLfloat, 2 );
+    beginEndTexCoord2f[ beginEndTexCoord2f_size*2 ] = x;
+    beginEndTexCoord2f[ beginEndTexCoord2f_size*2+1 ] = y;
+    beginEndTexCoord2f_size++;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex4f( GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex3f(): called outside glBegin/glEnd");
+    CHECK_ARRAY_SIZE( &beginEndVertex, &beginEndVertex_alloc, &beginEndVertex_size, GLfloat, 4 );
+    beginEndVertex[ beginEndVertex_size*4 ] = x;
+    beginEndVertex[ beginEndVertex_size*4+1 ] = y;
+    beginEndVertex[ beginEndVertex_size*4+2 ] = z;
+    beginEndVertex[ beginEndVertex_size*4+3 ] = w;
+    beginEndVertex_size++;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex2f( GLfloat x, GLfloat y )
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex2f(): called outside glBegin/glEnd");
+    glVertex4f( x, y, 0.0f, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex3f( GLfloat x, GLfloat y, GLfloat z )
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex3f(): called outside glBegin/glEnd");
+    glVertex4f( x, y, z, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex2fv( const F32 * pv )
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex2fv(): called outside glBegin/glEnd");
+    glVertex4f( pv[0], pv[1], 0.0f, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex2i( GLint x, GLint y)
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex2i(): called outside glBegin/glEnd");
+    glVertex4f( GLfloat(x), GLfloat(y), 0.0f, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex3fv( const F32 * pv )
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex3fv(): called outside glBegin/glEnd");
+    glVertex4f( pv[0], pv[1], pv[2], 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glVertex4fv( const F32 * pv )
+{
+    AssertFatal( (beginEndMode >= 0), "glVertex3fv(): called outside glBegin/glEnd");
+    glVertex4f( pv[0], pv[1], pv[2], pv[3] );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glNormal3f( GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+    AssertFatal( (beginEndMode >= 0), "glNormal3f(): called outside glBegin/glEnd");
+    CHECK_ARRAY_SIZE( &beginEndNormal, &beginEndNormal_alloc, &beginEndNormal_size, GLfloat, 3 );
+    beginEndNormal[ beginEndNormal_size*3 ] = x;
+    beginEndNormal[ beginEndNormal_size*3+1 ] = y;
+    beginEndNormal[ beginEndNormal_size*3+2 ] = z;
+    beginEndNormal_size++;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glNormal3fv( const F32 * pv)
+{
+    AssertFatal( (beginEndMode >= 0), "glNormal3fv(): called outside glBegin/glEnd");
+    glNormal3f( pv[0], pv[1], pv[2] );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glColor3fv( const F32 * pv)
+{
+    glColor4f( pv[0], pv[1], pv[2], 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glColor4fv( const F32 * pv)
+{
+    glColor4f( pv[0], pv[1], pv[2], pv[3] );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glActiveTextureARB( GLint index )
+{
+    glActiveTexture( index );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glMultiTexCoord2fARB( GLint, GLfloat, GLfloat)
+{
+    AssertWarn( 0, "glMultiTexCoord2fARB(): this method call needs to be implemented");
+}
+void glPushAttrib( GLint )
+{
+    AssertWarn( 0, "glPushAttrib(): this method call needs to be implemented");
+}
+void glPopAttrib()
+{
+    AssertWarn( 0, "glPopAttrib(): this method call needs to be implemented");
+}
+//void glOrtho( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
+//{
+//	GLfloat tx = -(right+left)/(right-left);
+//	GLfloat ty = -(top+bottom)/(top-bottom);
+//	GLfloat tz = -(zFar+zNear)/(zFar-zNear);
+//	MatrixF m = MatrixF(true);
+//	((F32*)m)[0] = 2.0f/(right-left);
+//	((F32*)m)[3] = tx;
+//	((F32*)m)[5] = 2.0f/(top-bottom);
+//	((F32*)m)[7] = ty;
+//	((F32*)m)[10] = -2.0f/(zFar-zNear);
+//	((F32*)m)[11] = tz;
+//	
+//	glMultMatrixf( (F32*)(m.transpose())); // make col major for opengl
+//}
+//void glFrustum( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar )
+//{
+//	MatrixF m = MatrixF(true);
+//	((F32*)m)[0] = 2.0f*zNear/(right-left);
+//	((F32*)m)[2] = (right+left)/(right-left);
+//	((F32*)m)[5] = 2.0f*zNear/(top-bottom);
+//	((F32*)m)[6] = (top+bottom)/(top-bottom);
+//	((F32*)m)[10] = -(zFar+zNear)/(zFar-zNear);
+//	((F32*)m)[11] = -2.0f*zFar*zNear/(zFar-zNear);
+//	((F32*)m)[14] = -1.0f;
+//	((F32*)m)[15] = 0.0f;
+//	
+//	glMultMatrixf( (F32*)(m.transpose())); // make col major for opengl
+//}
+void glReadBuffer( GLint )
+{
+    AssertWarn( 0, "glReadBuffer(): this method call needs to be implemented");
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glClientActiveTextureARB( GLint texture )
+{
+    glClientActiveTexture( texture );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glColor3i( GLint  r, GLint g, GLint b )
+{
+    glColor4f( ((GLfloat)r) * INV_32767, ((GLfloat)g) * INV_32767, ((GLfloat)b) * INV_32767, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glColor3ubv( const GLubyte *v )
+{
+    glColor4f( ((GLfloat)v[0]) * INV_255, ((GLfloat)v[1]) * INV_255, ((GLfloat)v[2]) * INV_255, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glColor4ubv( const GLubyte *v )
+{
+    glColor4f( ((GLfloat)v[0]) * INV_255, ((GLfloat)v[1]) * INV_255, ((GLfloat)v[2]) * INV_255, ((GLfloat)v[3]) * INV_255 );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glRecti( GLint x1, GLint y1, GLint x2, GLint y2 )
+{
+    AssertFatal( beginEndMode<0, "glRecti(): called inside glBegin/glEnd");
+    glBegin(GL_LINE_LOOP);
+    glVertex2i(x1, y1);
+    glVertex2i(x2, y1);
+    glVertex2i(x2, y2);
+    glVertex2i(x1, y2);
+    glEnd();
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+
+void glGetDoublev( GLint pname, GLdouble * params )
+{
+    int i;
+    GLfloat fparams[16];
+    glGetFloatv( pname, fparams );
+    AssertFatal((glGetError() == GL_NO_ERROR), "glGetDoublev parameter invalid");
+    params[0] = (double)fparams[0]; 
+    if ((pname == GL_ALIASED_POINT_SIZE_RANGE) ||
+        (pname == GL_ALIASED_LINE_WIDTH_RANGE) ||
+        (pname == GL_DEPTH_RANGE) ||
+        (pname == GL_MAX_VIEWPORT_DIMS) ||
+        (pname == GL_SMOOTH_LINE_WIDTH_RANGE) ||
+        (pname == GL_SMOOTH_POINT_SIZE_RANGE)) {
+        // 2 items
+        params[1] = (double)fparams[1];
+        return;
+    }
+    if ((pname == GL_COLOR_CLEAR_VALUE) ||
+        (pname == GL_COLOR_WRITEMASK) ||
+        (pname == GL_FOG_COLOR) ||
+        (pname == GL_LIGHT_MODEL_AMBIENT) ||
+        (pname == GL_SCISSOR_BOX) ||
+        (pname == GL_VIEWPORT) ) {
+        // 4 items
+        params[1] = (double)fparams[1];
+        params[2] = (double)fparams[2];
+        params[3] = (double)fparams[3];
+        return;
+    }
+    if ((pname == GL_PROJECTION_MATRIX) ||
+        //Luma: Added MODDELVIEW support
+        (pname == GL_MODELVIEW_MATRIX) ||
+        //(pname == GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS) ||
+        //(pname == GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS) ||  
+        (pname == GL_TEXTURE_MATRIX) ) {
+        // 16 items
+        for (i=1; i<16; i++) {
+            params[i] = (double)fparams[i];
+        }
+        return;
+    }
+}
+void glPolygonMode( GLint, GLint )
+{
+    //AssertFatal( 0, "glPolygonMode(): this method call needs to be implemented");
+}
+void glLockArraysEXT( GLint, GLint )
+{
+    AssertFatal( 0, "glLockArraysEXT(): this method call needs to be implemented");
+}
+void glUnlockArraysEXT()
+{
+    AssertFatal( 0, "glUnlockArraysEXT(): this method call needs to be implemented");
+}
+void glColor3ub( GLint r, GLint g, GLint b )
+{
+    glColor4f( ((GLfloat)r) * INV_255, ((GLfloat)g) * INV_255, ((GLfloat)b) * INV_255, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+void glFogi( GLint pname, GLint param )
+{
+    glFogf( pname, (GLfloat)param );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+/*	-Mat note: only guiCanvas uses this, and before adding this GL2ES stuff we didn't need to use it (it was one of the first things if'ed out)
+void glDrawBuffer( GLint buffid )
+{
+    ((EAGLView *)platState.ctx).currentRenderBuffer = buffid;
+    TEST_FOR_OPENGL_ERRORS
+}
+*/
+void glColorTableEXT( GLint, GLint, GLint, GLint, GLint, const ColorI * )
+{
+    AssertFatal( 0, "glColorTableEXT(): this method call needs to be implemented");
+}
+void glBlendColorEXT( GLfloat, GLfloat, GLfloat, GLfloat )
+{
+    AssertFatal( 0, "glBlendColorEXT(): this method call needs to be implemented");
+}
+void glBlendEquationEXT( GLint )
+{
+    AssertFatal( 0, "glBlendEquationEXT(): this method call needs to be implemented");
+}
+void glArrayElement( GLint )
+{
+    AssertFatal( 0, "glArrayElement(): this method call needs to be implemented");
+}
+void glFogCoordPointerEXT(GLenum, GLsizei, void *)
+{
+    AssertFatal( 0, "glFogCoordPointerEXT(): this method call needs to be implemented");
+}
+//void glDepthRange( GLfloat, GLfloat )
+//{
+//	AssertFatal( 0, "glDepthRange(): this method call needs to be implemented");
+//}
+void glTexGeni( GLenum coord, GLenum pname, GLint param )
+{
+    AssertFatal( 0, "glTexGeni(): this method call needs to be implemented");
+}
+void glTexGenfv( GLenum coord, GLenum pname, const GLfloat *params )
+{
+    AssertFatal( 0, "glTexGenfv(): this method call needs to be implemented");
+}
+void glClipPlane( GLuint plane, GLdouble * equation )
+{
+    GLfloat fequ[4];
+    fequ[0] = (GLfloat)equation[0];
+    fequ[1] = (GLfloat)equation[1];
+    fequ[2] = (GLfloat)equation[2];
+    fequ[3] = (GLfloat)equation[3];
+    glClipPlanef( plane, fequ );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+}
+GLboolean glAreTexturesResident( GLsizei, const GLuint *, GLboolean*)
+{
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+    return GL_FALSE;
+}
+
+void gluOrtho2D( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top )
+{
+    glOrtho( left, right, bottom, top, -1.0f, 1.0f );
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+//	GLfloat zNear = -1.0f;
+//	GLfloat zFar = 1.0f;
+//	GLfloat tx = -(right+left)/(right-left);
+//	GLfloat ty = -(top+bottom)/(top-bottom);
+//	GLfloat tz = -(zFar+zNear)/(zFar-zNear);
+//	MatrixF m = MatrixF(true);
+//		((F32*)m)[0] = 2.0f/(right-left);
+//		((F32*)m)[3] = tx;
+//		((F32*)m)[5] = 2.0f/(top-bottom);
+//		((F32*)m)[7] = ty;
+//		((F32*)m)[10] = -2.0f/(zFar-zNear);
+//		((F32*)m)[11] = tz;
+//	
+//	glMultMatrixf( (F32*)(m.transpose())); // make col major for opengl
+}
+GLint gluProject( GLdouble objx, GLdouble objy, GLdouble objz, const F64 *model, const F64 * proj, const GLint * vp, F64 * winx, F64 * winy, F64 * winz )
+{
+    Vector4F v = Vector4F( objx, objy, objz, 1.0f );
+    MatrixF pmat = MatrixF( false );
+        for (int i=0; i<16; i++) { ((F32*)pmat)[i] = (float)proj[i]; }
+    MatrixF mmat = MatrixF( false );
+        for (int i=0; i<16; i++) { ((F32*)mmat)[i] = (float)model[i]; }
+        
+    //Luma:	Projection fix
+    mmat.transpose();
+    pmat.transpose();
+    (pmat.mul(mmat)).mul(v);
+    
+    //Luma:	Projection fix
+    if(v.w == 0.0f)
+    {
+        return GL_FALSE;
+    }
+    F32		invW = 1.0f / v.w;
+    v.x *= invW;
+    v.y *= invW;
+    v.z *= invW;
+        
+    *winx = (GLfloat)vp[0] + (GLfloat)vp[2] * (v.x + 1.0f) * 0.5f;
+    *winy = (GLfloat)vp[1] + (GLfloat)vp[3] * (v.y + 1.0f) * 0.5f;
+    *winz = (v.z + 1.0f) * 0.5f;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+    return GL_TRUE;
+}
+GLint gluUnProject( GLdouble winx, GLdouble winy, GLdouble winz, const F64 *model, const F64 * proj, const GLint * vp, F64 * x, F64 * y, F64 * z )
+{
+    Vector4F v = Vector4F( 2.0f*(winx-vp[0])/vp[2] - 1.0f, 2.0f*(winy-vp[1])/vp[2] - 1.0f, 2.0f*vp[2] - 1.0f, 1.0f );
+    MatrixF pmat = MatrixF( false );
+    for (int i=0; i<16; i++) { ((F32*)pmat)[i] = (float)proj[i]; }
+    MatrixF mmat = MatrixF( false );
+    for (int i=0; i<16; i++) { ((F32*)mmat)[i] = (float)model[i]; }
+    mmat = pmat.mul(mmat);
+
+    mmat = mmat.inverse();
+    mmat.mul( v );
+    *x = v.x;
+    *y = v.y;
+    *z = v.z;
+    int glError;
+    glError = TEST_FOR_OPENGL_ERRORS
+    return GL_TRUE;
+}

+ 1442 - 0
engine/source/platformAndroid/AndroidGL2ES.h

@@ -0,0 +1,1442 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+//
+//  AndroidGL2ES.h
+//  TGE
+//
+//  Created by Puap Puap on 7/31/08.
+//  Copyright 2008 Pick Up And Play. All rights reserved.
+//
+
+#ifndef _GL2ES_H_
+#define _GL2ES_H_
+
+
+#include "platform/types.h"
+
+#include "OpenGLES/ES1/gl.h"
+#include "OpenGLES/ES1/glext.h"
+
+extern "C"
+{
+void AndroidGLPushMatrix();
+void AndroidGLPopMatrix();
+void AndroidGLMatrixMode( GLenum mode );
+}
+
+// help out the shallow matrix stacks...
+#define glPushMatrix AndroidGLPushMatrix
+#define glPopMatrix AndroidGLPopMatrix
+#define glMatrixMode AndroidGLMatrixMode
+
+class ColorI;
+
+// defines that need functional workarounds
+//
+//typedef unsigned int GLenum;
+//typedef unsigned char GLboolean;
+//typedef unsigned int GLbitfield;
+//typedef signed char GLbyte;
+//typedef short GLshort;
+//typedef int GLint;
+//typedef int GLsizei;
+//typedef unsigned char GLubyte;
+//typedef unsigned short GLushort;
+//typedef unsigned int GLuint;
+//typedef float GLfloat;
+//typedef float GLclampf;
+//typedef double GLdouble;
+//typedef double GLclampd;
+//typedef void GLvoid;
+//typedef int GLfixed;
+//typedef int GLclampx;
+//
+///* AccumOp */
+//#define GL_ACCUM                          0x0100
+//#define GL_LOAD                           0x0101
+//#define GL_RETURN                         0x0102
+//#define GL_MULT                           0x0103
+//#define GL_ADD                            0x0104
+//
+///* AlphaFunction */
+//#define GL_NEVER                          0x0200
+//#define GL_LESS                           0x0201
+//#define GL_EQUAL                          0x0202
+//#define GL_LEQUAL                         0x0203
+//#define GL_GREATER                        0x0204
+//#define GL_NOTEQUAL                       0x0205
+//#define GL_GEQUAL                         0x0206
+//#define GL_ALWAYS                         0x0207
+//
+///* AttribMask */
+//#define GL_CURRENT_BIT                    0x00000001
+//#define GL_POINT_BIT                      0x00000002
+//#define GL_LINE_BIT                       0x00000004
+//#define GL_POLYGON_BIT                    0x00000008
+//#define GL_POLYGON_STIPPLE_BIT            0x00000010
+//#define GL_PIXEL_MODE_BIT                 0x00000020
+//#define GL_LIGHTING_BIT                   0x00000040
+//#define GL_FOG_BIT                        0x00000080
+//#define GL_DEPTH_BUFFER_BIT               0x00000100
+//#define GL_ACCUM_BUFFER_BIT               0x00000200
+//#define GL_STENCIL_BUFFER_BIT             0x00000400
+//#define GL_VIEWPORT_BIT                   0x00000800
+//#define GL_TRANSFORM_BIT                  0x00001000
+//#define GL_ENABLE_BIT                     0x00002000
+//#define GL_COLOR_BUFFER_BIT               0x00004000
+//#define GL_HINT_BIT                       0x00008000
+//#define GL_EVAL_BIT                       0x00010000
+//#define GL_LIST_BIT                       0x00020000
+//#define GL_TEXTURE_BIT                    0x00040000
+//#define GL_SCISSOR_BIT                    0x00080000
+//#define GL_ALL_ATTRIB_BITS                0x000fffff
+//
+///* BeginMode */
+//#define GL_POINTS                         0x0000
+//#define GL_LINES                          0x0001
+//#define GL_LINE_LOOP                      0x0002
+//#define GL_LINE_STRIP                     0x0003
+//#define GL_TRIANGLES                      0x0004
+//#define GL_TRIANGLE_STRIP                 0x0005
+//#define GL_TRIANGLE_FAN                   0x0006
+#define GL_QUADS                          0x0007
+#define GL_QUAD_STRIP                     0x0008
+#define GL_POLYGON                        0x0009
+//
+///* BlendingFactorDest */
+//#define GL_ZERO                           0
+//#define GL_ONE                            1
+//#define GL_SRC_COLOR                      0x0300
+//#define GL_ONE_MINUS_SRC_COLOR            0x0301
+//#define GL_SRC_ALPHA                      0x0302
+//#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+//#define GL_DST_ALPHA                      0x0304
+//#define GL_ONE_MINUS_DST_ALPHA            0x0305
+//
+///* BlendingFactorSrc */
+///*      GL_ZERO */
+///*      GL_ONE */
+//#define GL_DST_COLOR                      0x0306
+//#define GL_ONE_MINUS_DST_COLOR            0x0307
+//#define GL_SRC_ALPHA_SATURATE             0x0308
+///*      GL_SRC_ALPHA */
+///*      GL_ONE_MINUS_SRC_ALPHA */
+///*      GL_DST_ALPHA */
+///*      GL_ONE_MINUS_DST_ALPHA */
+//
+///* Boolean */
+//#define GL_TRUE                           1
+//#define GL_FALSE                          0
+//
+///* ClearBufferMask */
+///*      GL_COLOR_BUFFER_BIT */
+///*      GL_ACCUM_BUFFER_BIT */
+///*      GL_STENCIL_BUFFER_BIT */
+///*      GL_DEPTH_BUFFER_BIT */
+//
+///* ClientArrayType */
+///*      GL_VERTEX_ARRAY */
+///*      GL_NORMAL_ARRAY */
+///*      GL_COLOR_ARRAY */
+///*      GL_INDEX_ARRAY */
+///*      GL_TEXTURE_COORD_ARRAY */
+///*      GL_EDGE_FLAG_ARRAY */
+//
+///* ClipPlaneName */
+//#define GL_CLIP_PLANE0                    0x3000
+//#define GL_CLIP_PLANE1                    0x3001
+//#define GL_CLIP_PLANE2                    0x3002
+//#define GL_CLIP_PLANE3                    0x3003
+//#define GL_CLIP_PLANE4                    0x3004
+//#define GL_CLIP_PLANE5                    0x3005
+//
+///* ColorMaterialFace */
+///*      GL_FRONT */
+///*      GL_BACK */
+///*      GL_FRONT_AND_BACK */
+//
+///* ColorMaterialParameter */
+///*      GL_AMBIENT */
+///*      GL_DIFFUSE */
+///*      GL_SPECULAR */
+///*      GL_EMISSION */
+///*      GL_AMBIENT_AND_DIFFUSE */
+//
+///* ColorPointerType */
+///*      GL_BYTE */
+///*      GL_UNSIGNED_BYTE */
+///*      GL_SHORT */
+///*      GL_UNSIGNED_SHORT */
+///*      GL_INT */
+///*      GL_UNSIGNED_INT */
+///*      GL_FLOAT */
+///*      GL_DOUBLE */
+//
+///* CullFaceMode */
+///*      GL_FRONT */
+///*      GL_BACK */
+///*      GL_FRONT_AND_BACK */
+//
+///* DataType */
+//#define GL_BYTE                           0x1400
+//#define GL_UNSIGNED_BYTE                  0x1401
+//#define GL_SHORT                          0x1402
+//#define GL_UNSIGNED_SHORT                 0x1403
+//#define GL_INT                            0x1404
+#define GL_UNSIGNED_INT                   0x1405
+//#define GL_FLOAT                          0x1406
+//#define GL_2_BYTES                        0x1407
+//#define GL_3_BYTES                        0x1408
+//#define GL_4_BYTES                        0x1409
+//#define GL_DOUBLE                         0x140A
+//#define GL_FIXED                          0x140C
+//
+///* DepthFunction */
+///*      GL_NEVER */
+///*      GL_LESS */
+///*      GL_EQUAL */
+///*      GL_LEQUAL */
+///*      GL_GREATER */
+///*      GL_NOTEQUAL */
+///*      GL_GEQUAL */
+///*      GL_ALWAYS */
+//
+///* DrawBufferMode */
+//#define GL_NONE                           0
+//#define GL_FRONT_LEFT                     0x0400
+//#define GL_FRONT_RIGHT                    0x0401
+//#define GL_BACK_LEFT                      0x0402
+//#define GL_BACK_RIGHT                     0x0403
+//#define GL_FRONT                          0x0404
+//#define GL_BACK                           0x0405
+//#define GL_LEFT                           0x0406
+//#define GL_RIGHT                          0x0407
+//#define GL_FRONT_AND_BACK                 0x0408
+//#define GL_AUX0                           0x0409
+//#define GL_AUX1                           0x040A
+//#define GL_AUX2                           0x040B
+//#define GL_AUX3                           0x040C
+//
+///* Enable */
+///*      GL_FOG */
+///*      GL_LIGHTING */
+///*      GL_TEXTURE_1D */
+///*      GL_TEXTURE_2D */
+///*      GL_LINE_STIPPLE */
+///*      GL_POLYGON_STIPPLE */
+///*      GL_CULL_FACE */
+///*      GL_ALPHA_TEST */
+///*      GL_BLEND */
+///*      GL_INDEX_LOGIC_OP */
+///*      GL_COLOR_LOGIC_OP */
+///*      GL_DITHER */
+///*      GL_STENCIL_TEST */
+///*      GL_DEPTH_TEST */
+///*      GL_CLIP_PLANE0 */
+///*      GL_CLIP_PLANE1 */
+///*      GL_CLIP_PLANE2 */
+///*      GL_CLIP_PLANE3 */
+///*      GL_CLIP_PLANE4 */
+///*      GL_CLIP_PLANE5 */
+///*      GL_LIGHT0 */
+///*      GL_LIGHT1 */
+///*      GL_LIGHT2 */
+///*      GL_LIGHT3 */
+///*      GL_LIGHT4 */
+///*      GL_LIGHT5 */
+///*      GL_LIGHT6 */
+///*      GL_LIGHT7 */
+///*      GL_TEXTURE_GEN_S */
+///*      GL_TEXTURE_GEN_T */
+///*      GL_TEXTURE_GEN_R */
+///*      GL_TEXTURE_GEN_Q */
+///*      GL_MAP1_VERTEX_3 */
+///*      GL_MAP1_VERTEX_4 */
+///*      GL_MAP1_COLOR_4 */
+///*      GL_MAP1_INDEX */
+///*      GL_MAP1_NORMAL */
+///*      GL_MAP1_TEXTURE_COORD_1 */
+///*      GL_MAP1_TEXTURE_COORD_2 */
+///*      GL_MAP1_TEXTURE_COORD_3 */
+///*      GL_MAP1_TEXTURE_COORD_4 */
+///*      GL_MAP2_VERTEX_3 */
+///*      GL_MAP2_VERTEX_4 */
+///*      GL_MAP2_COLOR_4 */
+///*      GL_MAP2_INDEX */
+///*      GL_MAP2_NORMAL */
+///*      GL_MAP2_TEXTURE_COORD_1 */
+///*      GL_MAP2_TEXTURE_COORD_2 */
+///*      GL_MAP2_TEXTURE_COORD_3 */
+///*      GL_MAP2_TEXTURE_COORD_4 */
+///*      GL_POINT_SMOOTH */
+///*      GL_LINE_SMOOTH */
+///*      GL_POLYGON_SMOOTH */
+///*      GL_SCISSOR_TEST */
+///*      GL_COLOR_MATERIAL */
+///*      GL_NORMALIZE */
+///*      GL_AUTO_NORMAL */
+///*      GL_VERTEX_ARRAY */
+///*      GL_NORMAL_ARRAY */
+///*      GL_COLOR_ARRAY */
+///*      GL_INDEX_ARRAY */
+///*      GL_TEXTURE_COORD_ARRAY */
+///*      GL_EDGE_FLAG_ARRAY */
+///*      GL_POLYGON_OFFSET_POINT */
+///*      GL_POLYGON_OFFSET_LINE */
+///*      GL_POLYGON_OFFSET_FILL */
+//
+///* ErrorCode */
+//#define GL_NO_ERROR                       0
+//#define GL_INVALID_ENUM                   0x0500
+//#define GL_INVALID_VALUE                  0x0501
+//#define GL_INVALID_OPERATION              0x0502
+//#define GL_STACK_OVERFLOW                 0x0503
+//#define GL_STACK_UNDERFLOW                0x0504
+//#define GL_OUT_OF_MEMORY                  0x0505
+//
+///* FeedBackMode */
+//#define GL_2D                             0x0600
+//#define GL_3D                             0x0601
+//#define GL_3D_COLOR                       0x0602
+//#define GL_3D_COLOR_TEXTURE               0x0603
+//#define GL_4D_COLOR_TEXTURE               0x0604
+//
+///* FeedBackToken */
+//#define GL_PASS_THROUGH_TOKEN             0x0700
+//#define GL_POINT_TOKEN                    0x0701
+//#define GL_LINE_TOKEN                     0x0702
+//#define GL_POLYGON_TOKEN                  0x0703
+//#define GL_BITMAP_TOKEN                   0x0704
+//#define GL_DRAW_PIXEL_TOKEN               0x0705
+//#define GL_COPY_PIXEL_TOKEN               0x0706
+//#define GL_LINE_RESET_TOKEN               0x0707
+//
+///* FogMode */
+///*      GL_LINEAR */
+//#define GL_EXP                            0x0800
+//#define GL_EXP2                           0x0801
+//
+//
+///* FogParameter */
+///*      GL_FOG_COLOR */
+///*      GL_FOG_DENSITY */
+///*      GL_FOG_END */
+///*      GL_FOG_INDEX */
+///*      GL_FOG_MODE */
+///*      GL_FOG_START */
+//
+#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450
+#define GL_FOG_COORDINATE_EXT 0x8451
+#define GL_FRAGMENT_DEPTH_EXT 0x8452
+//#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453
+//#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454
+//#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
+//#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
+#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 
+//
+///* FrontFaceDirection */
+//#define GL_CW                             0x0900
+//#define GL_CCW                            0x0901
+//
+///* GetMapTarget */
+//#define GL_COEFF                          0x0A00
+//#define GL_ORDER                          0x0A01
+//#define GL_DOMAIN                         0x0A02
+//
+///* GetPixelMap */
+///*      GL_PIXEL_MAP_I_TO_I */
+///*      GL_PIXEL_MAP_S_TO_S */
+///*      GL_PIXEL_MAP_I_TO_R */
+///*      GL_PIXEL_MAP_I_TO_G */
+///*      GL_PIXEL_MAP_I_TO_B */
+///*      GL_PIXEL_MAP_I_TO_A */
+///*      GL_PIXEL_MAP_R_TO_R */
+///*      GL_PIXEL_MAP_G_TO_G */
+///*      GL_PIXEL_MAP_B_TO_B */
+///*      GL_PIXEL_MAP_A_TO_A */
+//
+///* GetPointerTarget */
+///*      GL_VERTEX_ARRAY_POINTER */
+///*      GL_NORMAL_ARRAY_POINTER */
+///*      GL_COLOR_ARRAY_POINTER */
+///*      GL_INDEX_ARRAY_POINTER */
+///*      GL_TEXTURE_COORD_ARRAY_POINTER */
+///*      GL_EDGE_FLAG_ARRAY_POINTER */
+//
+///* GetTarget */
+//#define GL_CURRENT_COLOR                  0x0B00
+//#define GL_CURRENT_INDEX                  0x0B01
+//#define GL_CURRENT_NORMAL                 0x0B02
+//#define GL_CURRENT_TEXTURE_COORDS         0x0B03
+//#define GL_CURRENT_RASTER_COLOR           0x0B04
+//#define GL_CURRENT_RASTER_INDEX           0x0B05
+//#define GL_CURRENT_RASTER_TEXTURE_COORDS  0x0B06
+//#define GL_CURRENT_RASTER_POSITION        0x0B07
+//#define GL_CURRENT_RASTER_POSITION_VALID  0x0B08
+//#define GL_CURRENT_RASTER_DISTANCE        0x0B09
+//#define GL_POINT_SMOOTH                   0x0B10
+//#define GL_POINT_SIZE                     0x0B11
+//#define GL_POINT_SIZE_RANGE               0x0B12
+//#define GL_POINT_SIZE_GRANULARITY         0x0B13
+//#define GL_LINE_SMOOTH                    0x0B20
+//#define GL_LINE_WIDTH                     0x0B21
+//#define GL_LINE_WIDTH_RANGE               0x0B22
+//#define GL_LINE_WIDTH_GRANULARITY         0x0B23
+//#define GL_LINE_STIPPLE                   0x0B24
+//#define GL_LINE_STIPPLE_PATTERN           0x0B25
+//#define GL_LINE_STIPPLE_REPEAT            0x0B26
+//#define GL_LIST_MODE                      0x0B30
+//#define GL_MAX_LIST_NESTING               0x0B31
+//#define GL_LIST_BASE                      0x0B32
+//#define GL_LIST_INDEX                     0x0B33
+#define GL_POLYGON_MODE                   0x0B40
+//#define GL_POLYGON_SMOOTH                 0x0B41
+//#define GL_POLYGON_STIPPLE                0x0B42
+//#define GL_EDGE_FLAG                      0x0B43
+//#define GL_CULL_FACE                      0x0B44
+//#define GL_CULL_FACE_MODE                 0x0B45
+//#define GL_FRONT_FACE                     0x0B46
+//#define GL_LIGHTING                       0x0B50
+//#define GL_LIGHT_MODEL_LOCAL_VIEWER       0x0B51
+//#define GL_LIGHT_MODEL_TWO_SIDE           0x0B52
+//#define GL_LIGHT_MODEL_AMBIENT            0x0B53
+//#define GL_SHADE_MODEL                    0x0B54
+//#define GL_COLOR_MATERIAL_FACE            0x0B55
+//#define GL_COLOR_MATERIAL_PARAMETER       0x0B56
+//#define GL_COLOR_MATERIAL                 0x0B57
+//#define GL_FOG                            0x0B60
+//#define GL_FOG_INDEX                      0x0B61
+//#define GL_FOG_DENSITY                    0x0B62
+//#define GL_FOG_START                      0x0B63
+//#define GL_FOG_END                        0x0B64
+//#define GL_FOG_MODE                       0x0B65
+//#define GL_FOG_COLOR                      0x0B66
+//#define GL_DEPTH_RANGE                    0x0B70
+//#define GL_DEPTH_TEST                     0x0B71
+//#define GL_DEPTH_WRITEMASK                0x0B72
+//#define GL_DEPTH_CLEAR_VALUE              0x0B73
+//#define GL_DEPTH_FUNC                     0x0B74
+//#define GL_ACCUM_CLEAR_VALUE              0x0B80
+//#define GL_STENCIL_TEST                   0x0B90
+//#define GL_STENCIL_CLEAR_VALUE            0x0B91
+//#define GL_STENCIL_FUNC                   0x0B92
+//#define GL_STENCIL_VALUE_MASK             0x0B93
+//#define GL_STENCIL_FAIL                   0x0B94
+//#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+//#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+//#define GL_STENCIL_REF                    0x0B97
+//#define GL_STENCIL_WRITEMASK              0x0B98
+//#define GL_MATRIX_MODE                    0x0BA0
+//#define GL_NORMALIZE                      0x0BA1
+//#define GL_VIEWPORT                       0x0BA2
+//#define GL_MODELVIEW_STACK_DEPTH          0x0BA3
+//#define GL_PROJECTION_STACK_DEPTH         0x0BA4
+//#define GL_TEXTURE_STACK_DEPTH            0x0BA5
+//#define GL_MODELVIEW_MATRIX               0x0BA6
+//#define GL_PROJECTION_MATRIX              0x0BA7
+//#define GL_TEXTURE_MATRIX                 0x0BA8
+//#define GL_ATTRIB_STACK_DEPTH             0x0BB0
+//#define GL_CLIENT_ATTRIB_STACK_DEPTH      0x0BB1
+//#define GL_ALPHA_TEST                     0x0BC0
+//#define GL_ALPHA_TEST_FUNC                0x0BC1
+//#define GL_ALPHA_TEST_REF                 0x0BC2
+//#define GL_DITHER                         0x0BD0
+//#define GL_BLEND_DST                      0x0BE0
+//#define GL_BLEND_SRC                      0x0BE1
+//#define GL_BLEND                          0x0BE2
+//#define GL_LOGIC_OP_MODE                  0x0BF0
+//#define GL_INDEX_LOGIC_OP                 0x0BF1
+//#define GL_COLOR_LOGIC_OP                 0x0BF2
+//#define GL_AUX_BUFFERS                    0x0C00
+//#define GL_DRAW_BUFFER                    0x0C01
+//#define GL_READ_BUFFER                    0x0C02
+//#define GL_SCISSOR_BOX                    0x0C10
+//#define GL_SCISSOR_TEST                   0x0C11
+//#define GL_INDEX_CLEAR_VALUE              0x0C20
+//#define GL_INDEX_WRITEMASK                0x0C21
+//#define GL_COLOR_CLEAR_VALUE              0x0C22
+//#define GL_COLOR_WRITEMASK                0x0C23
+//#define GL_INDEX_MODE                     0x0C30
+//#define GL_RGBA_MODE                      0x0C31
+//#define GL_DOUBLEBUFFER                   0x0C32
+//#define GL_STEREO                         0x0C33
+//#define GL_RENDER_MODE                    0x0C40
+//#define GL_PERSPECTIVE_CORRECTION_HINT    0x0C50
+//#define GL_POINT_SMOOTH_HINT              0x0C51
+//#define GL_LINE_SMOOTH_HINT               0x0C52
+//#define GL_POLYGON_SMOOTH_HINT            0x0C53
+//#define GL_FOG_HINT                       0x0C54
+#define GL_TEXTURE_GEN_S                  0x0C60
+#define GL_TEXTURE_GEN_T                  0x0C61
+//#define GL_TEXTURE_GEN_R                  0x0C62
+//#define GL_TEXTURE_GEN_Q                  0x0C63
+//#define GL_PIXEL_MAP_I_TO_I               0x0C70
+//#define GL_PIXEL_MAP_S_TO_S               0x0C71
+//#define GL_PIXEL_MAP_I_TO_R               0x0C72
+//#define GL_PIXEL_MAP_I_TO_G               0x0C73
+//#define GL_PIXEL_MAP_I_TO_B               0x0C74
+//#define GL_PIXEL_MAP_I_TO_A               0x0C75
+//#define GL_PIXEL_MAP_R_TO_R               0x0C76
+//#define GL_PIXEL_MAP_G_TO_G               0x0C77
+//#define GL_PIXEL_MAP_B_TO_B               0x0C78
+//#define GL_PIXEL_MAP_A_TO_A               0x0C79
+//#define GL_PIXEL_MAP_I_TO_I_SIZE          0x0CB0
+//#define GL_PIXEL_MAP_S_TO_S_SIZE          0x0CB1
+//#define GL_PIXEL_MAP_I_TO_R_SIZE          0x0CB2
+//#define GL_PIXEL_MAP_I_TO_G_SIZE          0x0CB3
+//#define GL_PIXEL_MAP_I_TO_B_SIZE          0x0CB4
+//#define GL_PIXEL_MAP_I_TO_A_SIZE          0x0CB5
+//#define GL_PIXEL_MAP_R_TO_R_SIZE          0x0CB6
+//#define GL_PIXEL_MAP_G_TO_G_SIZE          0x0CB7
+//#define GL_PIXEL_MAP_B_TO_B_SIZE          0x0CB8
+//#define GL_PIXEL_MAP_A_TO_A_SIZE          0x0CB9
+//#define GL_UNPACK_SWAP_BYTES              0x0CF0
+//#define GL_UNPACK_LSB_FIRST               0x0CF1
+//#define GL_UNPACK_ROW_LENGTH              0x0CF2
+//#define GL_UNPACK_SKIP_ROWS               0x0CF3
+//#define GL_UNPACK_SKIP_PIXELS             0x0CF4
+//#define GL_UNPACK_ALIGNMENT               0x0CF5
+//#define GL_PACK_SWAP_BYTES                0x0D00
+//#define GL_PACK_LSB_FIRST                 0x0D01
+//#define GL_PACK_ROW_LENGTH                0x0D02
+//#define GL_PACK_SKIP_ROWS                 0x0D03
+//#define GL_PACK_SKIP_PIXELS               0x0D04
+//#define GL_PACK_ALIGNMENT                 0x0D05
+//#define GL_MAP_COLOR                      0x0D10
+//#define GL_MAP_STENCIL                    0x0D11
+//#define GL_INDEX_SHIFT                    0x0D12
+//#define GL_INDEX_OFFSET                   0x0D13
+//#define GL_RED_SCALE                      0x0D14
+//#define GL_RED_BIAS                       0x0D15
+//#define GL_ZOOM_X                         0x0D16
+//#define GL_ZOOM_Y                         0x0D17
+//#define GL_GREEN_SCALE                    0x0D18
+//#define GL_GREEN_BIAS                     0x0D19
+//#define GL_BLUE_SCALE                     0x0D1A
+//#define GL_BLUE_BIAS                      0x0D1B
+//#define GL_ALPHA_SCALE                    0x0D1C
+//#define GL_ALPHA_BIAS                     0x0D1D
+//#define GL_DEPTH_SCALE                    0x0D1E
+//#define GL_DEPTH_BIAS                     0x0D1F
+//#define GL_MAX_EVAL_ORDER                 0x0D30
+//#define GL_MAX_LIGHTS                     0x0D31
+//#define GL_MAX_CLIP_PLANES                0x0D32
+//#define GL_MAX_TEXTURE_SIZE               0x0D33
+//#define GL_MAX_PIXEL_MAP_TABLE            0x0D34
+//#define GL_MAX_ATTRIB_STACK_DEPTH         0x0D35
+//#define GL_MAX_MODELVIEW_STACK_DEPTH      0x0D36
+//#define GL_MAX_NAME_STACK_DEPTH           0x0D37
+//#define GL_MAX_PROJECTION_STACK_DEPTH     0x0D38
+//#define GL_MAX_TEXTURE_STACK_DEPTH        0x0D39
+//#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+//#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH  0x0D3B
+//#define GL_SUBPIXEL_BITS                  0x0D50
+//#define GL_INDEX_BITS                     0x0D51
+//#define GL_RED_BITS                       0x0D52
+//#define GL_GREEN_BITS                     0x0D53
+//#define GL_BLUE_BITS                      0x0D54
+//#define GL_ALPHA_BITS                     0x0D55
+//#define GL_DEPTH_BITS                     0x0D56
+//#define GL_STENCIL_BITS                   0x0D57
+//#define GL_ACCUM_RED_BITS                 0x0D58
+//#define GL_ACCUM_GREEN_BITS               0x0D59
+//#define GL_ACCUM_BLUE_BITS                0x0D5A
+//#define GL_ACCUM_ALPHA_BITS               0x0D5B
+//#define GL_NAME_STACK_DEPTH               0x0D70
+//#define GL_AUTO_NORMAL                    0x0D80
+//#define GL_MAP1_COLOR_4                   0x0D90
+//#define GL_MAP1_INDEX                     0x0D91
+//#define GL_MAP1_NORMAL                    0x0D92
+//#define GL_MAP1_TEXTURE_COORD_1           0x0D93
+//#define GL_MAP1_TEXTURE_COORD_2           0x0D94
+//#define GL_MAP1_TEXTURE_COORD_3           0x0D95
+//#define GL_MAP1_TEXTURE_COORD_4           0x0D96
+//#define GL_MAP1_VERTEX_3                  0x0D97
+//#define GL_MAP1_VERTEX_4                  0x0D98
+//#define GL_MAP2_COLOR_4                   0x0DB0
+//#define GL_MAP2_INDEX                     0x0DB1
+//#define GL_MAP2_NORMAL                    0x0DB2
+//#define GL_MAP2_TEXTURE_COORD_1           0x0DB3
+//#define GL_MAP2_TEXTURE_COORD_2           0x0DB4
+//#define GL_MAP2_TEXTURE_COORD_3           0x0DB5
+//#define GL_MAP2_TEXTURE_COORD_4           0x0DB6
+//#define GL_MAP2_VERTEX_3                  0x0DB7
+//#define GL_MAP2_VERTEX_4                  0x0DB8
+//#define GL_MAP1_GRID_DOMAIN               0x0DD0
+//#define GL_MAP1_GRID_SEGMENTS             0x0DD1
+//#define GL_MAP2_GRID_DOMAIN               0x0DD2
+//#define GL_MAP2_GRID_SEGMENTS             0x0DD3
+//#define GL_TEXTURE_1D                     0x0DE0
+//#define GL_TEXTURE_2D                     0x0DE1
+//#define GL_FEEDBACK_BUFFER_POINTER        0x0DF0
+//#define GL_FEEDBACK_BUFFER_SIZE           0x0DF1
+//#define GL_FEEDBACK_BUFFER_TYPE           0x0DF2
+//#define GL_SELECTION_BUFFER_POINTER       0x0DF3
+//#define GL_SELECTION_BUFFER_SIZE          0x0DF4
+///*      GL_TEXTURE_BINDING_1D */
+///*      GL_TEXTURE_BINDING_2D */
+///*      GL_VERTEX_ARRAY */
+///*      GL_NORMAL_ARRAY */
+///*      GL_COLOR_ARRAY */
+///*      GL_INDEX_ARRAY */
+///*      GL_TEXTURE_COORD_ARRAY */
+///*      GL_EDGE_FLAG_ARRAY */
+///*      GL_VERTEX_ARRAY_SIZE */
+///*      GL_VERTEX_ARRAY_TYPE */
+///*      GL_VERTEX_ARRAY_STRIDE */
+///*      GL_NORMAL_ARRAY_TYPE */
+///*      GL_NORMAL_ARRAY_STRIDE */
+///*      GL_COLOR_ARRAY_SIZE */
+///*      GL_COLOR_ARRAY_TYPE */
+///*      GL_COLOR_ARRAY_STRIDE */
+///*      GL_INDEX_ARRAY_TYPE */
+///*      GL_INDEX_ARRAY_STRIDE */
+///*      GL_TEXTURE_COORD_ARRAY_SIZE */
+///*      GL_TEXTURE_COORD_ARRAY_TYPE */
+///*      GL_TEXTURE_COORD_ARRAY_STRIDE */
+///*      GL_EDGE_FLAG_ARRAY_STRIDE */
+///*      GL_POLYGON_OFFSET_FACTOR */
+///*      GL_POLYGON_OFFSET_UNITS */
+//
+///* GetTextureParameter */
+///*      GL_TEXTURE_MAG_FILTER */
+///*      GL_TEXTURE_MIN_FILTER */
+///*      GL_TEXTURE_WRAP_S */
+///*      GL_TEXTURE_WRAP_T */
+//#define GL_TEXTURE_WIDTH                  0x1000
+//#define GL_TEXTURE_HEIGHT                 0x1001
+//#define GL_TEXTURE_INTERNAL_FORMAT        0x1003
+#define GL_TEXTURE_BORDER_COLOR           0x1004
+//#define GL_TEXTURE_BORDER                 0x1005
+///*      GL_TEXTURE_RED_SIZE */
+///*      GL_TEXTURE_GREEN_SIZE */
+///*      GL_TEXTURE_BLUE_SIZE */
+///*      GL_TEXTURE_ALPHA_SIZE */
+///*      GL_TEXTURE_LUMINANCE_SIZE */
+///*      GL_TEXTURE_INTENSITY_SIZE */
+///*      GL_TEXTURE_PRIORITY */
+///*      GL_TEXTURE_RESIDENT */
+//
+///* HintMode */
+//#define GL_DONT_CARE                      0x1100
+//#define GL_FASTEST                        0x1101
+//#define GL_NICEST                         0x1102
+//
+///* HintTarget */
+///*      GL_PERSPECTIVE_CORRECTION_HINT */
+///*      GL_POINT_SMOOTH_HINT */
+///*      GL_LINE_SMOOTH_HINT */
+///*      GL_POLYGON_SMOOTH_HINT */
+///*      GL_FOG_HINT */
+///*      GL_PHONG_HINT */
+//
+///* IndexPointerType */
+///*      GL_SHORT */
+///*      GL_INT */
+///*      GL_FLOAT */
+///*      GL_DOUBLE */
+//
+///* LightModelParameter */
+///*      GL_LIGHT_MODEL_AMBIENT */
+///*      GL_LIGHT_MODEL_LOCAL_VIEWER */
+///*      GL_LIGHT_MODEL_TWO_SIDE */
+//
+///* LightName */
+//#define GL_LIGHT0                         0x4000
+//#define GL_LIGHT1                         0x4001
+//#define GL_LIGHT2                         0x4002
+//#define GL_LIGHT3                         0x4003
+//#define GL_LIGHT4                         0x4004
+//#define GL_LIGHT5                         0x4005
+//#define GL_LIGHT6                         0x4006
+//#define GL_LIGHT7                         0x4007
+//
+///* LightParameter */
+//#define GL_AMBIENT                        0x1200
+//#define GL_DIFFUSE                        0x1201
+//#define GL_SPECULAR                       0x1202
+//#define GL_POSITION                       0x1203
+//#define GL_SPOT_DIRECTION                 0x1204
+//#define GL_SPOT_EXPONENT                  0x1205
+//#define GL_SPOT_CUTOFF                    0x1206
+//#define GL_CONSTANT_ATTENUATION           0x1207
+//#define GL_LINEAR_ATTENUATION             0x1208
+//#define GL_QUADRATIC_ATTENUATION          0x1209
+//
+///* InterleavedArrays */
+///*      GL_V2F */
+///*      GL_V3F */
+///*      GL_C4UB_V2F */
+///*      GL_C4UB_V3F */
+///*      GL_C3F_V3F */
+///*      GL_N3F_V3F */
+///*      GL_C4F_N3F_V3F */
+///*      GL_T2F_V3F */
+///*      GL_T4F_V4F */
+///*      GL_T2F_C4UB_V3F */
+///*      GL_T2F_C3F_V3F */
+///*      GL_T2F_N3F_V3F */
+///*      GL_T2F_C4F_N3F_V3F */
+///*      GL_T4F_C4F_N3F_V4F */
+//
+///* ListMode */
+//#define GL_COMPILE                        0x1300
+//#define GL_COMPILE_AND_EXECUTE            0x1301
+//
+///* ListNameType */
+///*      GL_BYTE */
+///*      GL_UNSIGNED_BYTE */
+///*      GL_SHORT */
+///*      GL_UNSIGNED_SHORT */
+///*      GL_INT */
+///*      GL_UNSIGNED_INT */
+///*      GL_FLOAT */
+///*      GL_2_BYTES */
+///*      GL_3_BYTES */
+///*      GL_4_BYTES */
+//
+///* LogicOp */
+//#define GL_CLEAR                          0x1500
+//#define GL_AND                            0x1501
+//#define GL_AND_REVERSE                    0x1502
+//#define GL_COPY                           0x1503
+//#define GL_AND_INVERTED                   0x1504
+//#define GL_NOOP                           0x1505
+//#define GL_XOR                            0x1506
+//#define GL_OR                             0x1507
+//#define GL_NOR                            0x1508
+//#define GL_EQUIV                          0x1509
+//#define GL_INVERT                         0x150A
+//#define GL_OR_REVERSE                     0x150B
+//#define GL_COPY_INVERTED                  0x150C
+//#define GL_OR_INVERTED                    0x150D
+//#define GL_NAND                           0x150E
+//#define GL_SET                            0x150F
+//
+///* MapTarget */
+///*      GL_MAP1_COLOR_4 */
+///*      GL_MAP1_INDEX */
+///*      GL_MAP1_NORMAL */
+///*      GL_MAP1_TEXTURE_COORD_1 */
+///*      GL_MAP1_TEXTURE_COORD_2 */
+///*      GL_MAP1_TEXTURE_COORD_3 */
+///*      GL_MAP1_TEXTURE_COORD_4 */
+///*      GL_MAP1_VERTEX_3 */
+///*      GL_MAP1_VERTEX_4 */
+///*      GL_MAP2_COLOR_4 */
+///*      GL_MAP2_INDEX */
+///*      GL_MAP2_NORMAL */
+///*      GL_MAP2_TEXTURE_COORD_1 */
+///*      GL_MAP2_TEXTURE_COORD_2 */
+///*      GL_MAP2_TEXTURE_COORD_3 */
+///*      GL_MAP2_TEXTURE_COORD_4 */
+///*      GL_MAP2_VERTEX_3 */
+///*      GL_MAP2_VERTEX_4 */
+//
+///* MaterialFace */
+///*      GL_FRONT */
+///*      GL_BACK */
+///*      GL_FRONT_AND_BACK */
+//
+///* MaterialParameter */
+//#define GL_EMISSION                       0x1600
+//#define GL_SHININESS                      0x1601
+//#define GL_AMBIENT_AND_DIFFUSE            0x1602
+//#define GL_COLOR_INDEXES                  0x1603
+///*      GL_AMBIENT */
+///*      GL_DIFFUSE */
+///*      GL_SPECULAR */
+//
+///* MatrixMode */
+//#define GL_MODELVIEW                      0x1700
+//#define GL_PROJECTION                     0x1701
+//#define GL_TEXTURE                        0x1702
+//
+///* MeshMode1 */
+///*      GL_POINT */
+///*      GL_LINE */
+//
+///* MeshMode2 */
+///*      GL_POINT */
+///*      GL_LINE */
+///*      GL_FILL */
+//
+///* NormalPointerType */
+///*      GL_BYTE */
+///*      GL_SHORT */
+///*      GL_INT */
+///*      GL_FLOAT */
+///*      GL_DOUBLE */
+//
+///* PixelCopyType */
+//#define GL_COLOR                          0x1800
+//#define GL_DEPTH                          0x1801
+//#define GL_STENCIL                        0x1802
+//
+///* PixelFormat */
+#define GL_COLOR_INDEX                    0x1900
+//#define GL_STENCIL_INDEX                  0x1901
+//#define GL_DEPTH_COMPONENT                0x1902
+//#define GL_RED                            0x1903
+//#define GL_GREEN                          0x1904
+//#define GL_BLUE                           0x1905
+//#define GL_ALPHA                          0x1906
+//#define GL_RGB                            0x1907
+//#define GL_RGBA                           0x1908
+//#define GL_LUMINANCE                      0x1909
+//#define GL_LUMINANCE_ALPHA                0x190A
+//#define GL_BGR					          0x80E0
+//#define GL_BGRA					          0x80E1
+//
+///* PixelMap */
+///*      GL_PIXEL_MAP_I_TO_I */
+///*      GL_PIXEL_MAP_S_TO_S */
+///*      GL_PIXEL_MAP_I_TO_R */
+///*      GL_PIXEL_MAP_I_TO_G */
+///*      GL_PIXEL_MAP_I_TO_B */
+///*      GL_PIXEL_MAP_I_TO_A */
+///*      GL_PIXEL_MAP_R_TO_R */
+///*      GL_PIXEL_MAP_G_TO_G */
+///*      GL_PIXEL_MAP_B_TO_B */
+///*      GL_PIXEL_MAP_A_TO_A */
+//
+///* PixelStore */
+///*      GL_UNPACK_SWAP_BYTES */
+///*      GL_UNPACK_LSB_FIRST */
+///*      GL_UNPACK_ROW_LENGTH */
+///*      GL_UNPACK_SKIP_ROWS */
+///*      GL_UNPACK_SKIP_PIXELS */
+///*      GL_UNPACK_ALIGNMENT */
+///*      GL_PACK_SWAP_BYTES */
+///*      GL_PACK_LSB_FIRST */
+///*      GL_PACK_ROW_LENGTH */
+///*      GL_PACK_SKIP_ROWS */
+///*      GL_PACK_SKIP_PIXELS */
+///*      GL_PACK_ALIGNMENT */
+//
+///* PixelTransfer */
+///*      GL_MAP_COLOR */
+///*      GL_MAP_STENCIL */
+///*      GL_INDEX_SHIFT */
+///*      GL_INDEX_OFFSET */
+///*      GL_RED_SCALE */
+///*      GL_RED_BIAS */
+///*      GL_GREEN_SCALE */
+///*      GL_GREEN_BIAS */
+///*      GL_BLUE_SCALE */
+///*      GL_BLUE_BIAS */
+///*      GL_ALPHA_SCALE */
+///*      GL_ALPHA_BIAS */
+///*      GL_DEPTH_SCALE */
+///*      GL_DEPTH_BIAS */
+//
+///* PixelType */
+//#define GL_BITMAP                         0x1A00
+///*      GL_BYTE */
+///*      GL_UNSIGNED_BYTE */
+///*      GL_SHORT */
+///*      GL_UNSIGNED_SHORT */
+///*      GL_INT */
+///*      GL_UNSIGNED_INT */
+///*      GL_FLOAT */
+//
+///* PolygonMode */
+//#define GL_POINT                          0x1B00
+#define GL_LINE                           0x1B01
+#define GL_FILL                           0x1B02
+//
+///* ReadBufferMode */
+///*      GL_FRONT_LEFT */
+///*      GL_FRONT_RIGHT */
+///*      GL_BACK_LEFT */
+///*      GL_BACK_RIGHT */
+///*      GL_FRONT */
+///*      GL_BACK */
+///*      GL_LEFT */
+///*      GL_RIGHT */
+///*      GL_AUX0 */
+///*      GL_AUX1 */
+///*      GL_AUX2 */
+///*      GL_AUX3 */
+//
+///* RenderingMode */
+//#define GL_RENDER                         0x1C00
+//#define GL_FEEDBACK                       0x1C01
+//#define GL_SELECT                         0x1C02
+//
+///* ShadingModel */
+//#define GL_FLAT                           0x1D00
+//#define GL_SMOOTH                         0x1D01
+//
+//
+///* StencilFunction */
+///*      GL_NEVER */
+///*      GL_LESS */
+///*      GL_EQUAL */
+///*      GL_LEQUAL */
+///*      GL_GREATER */
+///*      GL_NOTEQUAL */
+///*      GL_GEQUAL */
+///*      GL_ALWAYS */
+//
+///* StencilOp */
+///*      GL_ZERO */
+//#define GL_KEEP                           0x1E00
+//#define GL_REPLACE                        0x1E01
+//#define GL_INCR                           0x1E02
+//#define GL_DECR                           0x1E03
+///*      GL_INVERT */
+//
+///* StringName */
+//#define GL_VENDOR                         0x1F00
+//#define GL_RENDERER                       0x1F01
+//#define GL_VERSION                        0x1F02
+//#define GL_EXTENSIONS                     0x1F03
+//
+///* TextureCoordName */
+#define GL_S                              0x2000
+#define GL_T                              0x2001
+//#define GL_R                              0x2002
+//#define GL_Q                              0x2003
+//
+///* TexCoordPointerType */
+///*      GL_SHORT */
+///*      GL_INT */
+///*      GL_FLOAT */
+///*      GL_DOUBLE */
+//
+///* TextureEnvMode */
+//#define GL_MODULATE                       0x2100
+//#define GL_DECAL                          0x2101
+///*      GL_BLEND */
+///*      GL_REPLACE */
+//
+///* TextureEnvParameter */
+//#define GL_TEXTURE_ENV_MODE               0x2200
+//#define GL_TEXTURE_ENV_COLOR              0x2201
+//
+///* TextureEnvTarget */
+//#define GL_TEXTURE_ENV                    0x2300
+//
+///* TextureGenMode */
+//#define GL_EYE_LINEAR                     0x2400
+#define GL_OBJECT_LINEAR                  0x2401
+#define GL_SPHERE_MAP                     0x2402
+//
+///* TextureGenParameter */
+#define GL_TEXTURE_GEN_MODE               0x2500
+#define GL_OBJECT_PLANE                   0x2501
+//#define GL_EYE_PLANE                      0x2502
+//
+///* TextureMagFilter */
+//#define GL_NEAREST                        0x2600
+//#define GL_LINEAR                         0x2601
+//
+///* TextureMinFilter */
+///*      GL_NEAREST */
+///*      GL_LINEAR */
+//#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+//#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+//#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+//#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+//
+///* TextureParameterName */
+//#define GL_TEXTURE_MAG_FILTER             0x2800
+//#define GL_TEXTURE_MIN_FILTER             0x2801
+//#define GL_TEXTURE_WRAP_S                 0x2802
+//#define GL_TEXTURE_WRAP_T                 0x2803
+///*      GL_TEXTURE_BORDER_COLOR */
+///*      GL_TEXTURE_PRIORITY */
+//
+///* TextureTarget */
+///*      GL_TEXTURE_1D */
+///*      GL_TEXTURE_2D */
+///*      GL_PROXY_TEXTURE_1D */
+///*      GL_PROXY_TEXTURE_2D */
+//
+///* TextureWrapMode */
+#define GL_CLAMP                          0x2900
+//#define GL_REPEAT                         0x2901
+//
+//#define GL_TEXTURE0                       0x84C0
+//#define GL_TEXTURE1                       0x84C1
+//#define GL_TEXTURE2                       0x84C2
+//#define GL_TEXTURE3                       0x84C3
+//#define GL_TEXTURE4                       0x84C4
+//#define GL_TEXTURE5                       0x84C5
+//#define GL_TEXTURE6                       0x84C6
+//#define GL_TEXTURE7                       0x84C7
+//#define GL_TEXTURE8                       0x84C8
+//#define GL_TEXTURE9                       0x84C9
+//#define GL_TEXTURE10                      0x84CA
+//#define GL_TEXTURE11                      0x84CB
+//#define GL_TEXTURE12                      0x84CC
+//#define GL_TEXTURE13                      0x84CD
+//#define GL_TEXTURE14                      0x84CE
+//#define GL_TEXTURE15                      0x84CF
+//#define GL_TEXTURE16                      0x84D0
+//#define GL_TEXTURE17                      0x84D1
+//#define GL_TEXTURE18                      0x84D2
+//#define GL_TEXTURE19                      0x84D3
+//#define GL_TEXTURE20                      0x84D4
+//#define GL_TEXTURE21                      0x84D5
+//#define GL_TEXTURE22                      0x84D6
+//#define GL_TEXTURE23                      0x84D7
+//#define GL_TEXTURE24                      0x84D8
+//#define GL_TEXTURE25                      0x84D9
+//#define GL_TEXTURE26                      0x84DA
+//#define GL_TEXTURE27                      0x84DB
+//#define GL_TEXTURE28                      0x84DC
+//#define GL_TEXTURE29                      0x84DD
+//#define GL_TEXTURE30                      0x84DE
+//#define GL_TEXTURE31                      0x84DF
+//#define GL_ACTIVE_TEXTURE                 0x84E0
+//#define GL_CLIENT_ACTIVE_TEXTURE          0x84E1
+//#define GL_MAX_TEXTURE_UNITS              0x84E2
+//#define GL_TRANSPOSE_MODELVIEW_MATRIX     0x84E3
+//#define GL_TRANSPOSE_PROJECTION_MATRIX    0x84E4
+//#define GL_TRANSPOSE_TEXTURE_MATRIX       0x84E5
+//#define GL_TRANSPOSE_COLOR_MATRIX         0x84E6
+//#define GL_MULTISAMPLE                    0x809D
+//#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+//#define GL_SAMPLE_ALPHA_TO_ONE            0x809F
+//#define GL_SAMPLE_COVERAGE                0x80A0
+//#define GL_SAMPLE_BUFFERS                 0x80A8
+//#define GL_SAMPLES                        0x80A9
+//#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+//#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+//#define GL_MULTISAMPLE_BIT                0x20000000
+//#define GL_NORMAL_MAP                     0x8511
+//#define GL_REFLECTION_MAP                 0x8512
+//#define GL_TEXTURE_CUBE_MAP               0x8513
+//#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
+//#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
+//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
+//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
+//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
+//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
+//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
+//#define GL_PROXY_TEXTURE_CUBE_MAP         0x851B
+//#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+//#define GL_COMPRESSED_ALPHA               0x84E9
+//#define GL_COMPRESSED_LUMINANCE           0x84EA
+//#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB
+//#define GL_COMPRESSED_INTENSITY           0x84EC
+//#define GL_COMPRESSED_RGB                 0x84ED
+//#define GL_COMPRESSED_RGBA                0x84EE
+//#define GL_TEXTURE_COMPRESSION_HINT       0x84EF
+//#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE  0x86A0
+//#define GL_TEXTURE_COMPRESSED             0x86A1
+//#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+//#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+//#define GL_CLAMP_TO_BORDER                0x812D
+//#define GL_COMBINE                        0x8570
+//#define GL_COMBINE_RGB                    0x8571
+//#define GL_COMBINE_ALPHA                  0x8572
+#define GL_SOURCE0_RGB                    0x8580
+#define GL_SOURCE1_RGB                    0x8581
+#define GL_SOURCE2_RGB                    0x8582
+#define GL_SOURCE0_ALPHA                  0x8588
+#define GL_SOURCE1_ALPHA                  0x8589
+#define GL_SOURCE2_ALPHA                  0x858A
+//#define GL_OPERAND0_RGB                   0x8590
+//#define GL_OPERAND1_RGB                   0x8591
+//#define GL_OPERAND2_RGB                   0x8592
+//#define GL_OPERAND0_ALPHA                 0x8598
+//#define GL_OPERAND1_ALPHA                 0x8599
+//#define GL_OPERAND2_ALPHA                 0x859A
+//#define GL_RGB_SCALE                      0x8573
+//#define GL_ADD_SIGNED                     0x8574
+//#define GL_INTERPOLATE                    0x8575
+//#define GL_SUBTRACT                       0x84E7
+//#define GL_CONSTANT                       0x8576
+//#define GL_PRIMARY_COLOR                  0x8577
+//#define GL_PREVIOUS                       0x8578
+//#define GL_DOT3_RGB                       0x86AE
+//#define GL_DOT3_RGBA                      0x86AF
+//
+///* VertexPointerType */
+///*      GL_SHORT */
+///*      GL_INT */
+///*      GL_FLOAT */
+///*      GL_DOUBLE */
+//
+///* ClientAttribMask */
+//#define GL_CLIENT_PIXEL_STORE_BIT         0x00000001
+//#define GL_CLIENT_VERTEX_ARRAY_BIT        0x00000002
+//#define GL_CLIENT_ALL_ATTRIB_BITS         0xffffffff
+//
+///* polygon_offset */
+//#define GL_POLYGON_OFFSET_FACTOR          0x8038
+//#define GL_POLYGON_OFFSET_UNITS           0x2A00
+//#define GL_POLYGON_OFFSET_POINT           0x2A01
+//#define GL_POLYGON_OFFSET_LINE            0x2A02
+//#define GL_POLYGON_OFFSET_FILL            0x8037
+//
+///* texture */
+//#define GL_ALPHA4                         0x803B
+//#define GL_ALPHA8                         0x803C
+//#define GL_ALPHA12                        0x803D
+//#define GL_ALPHA16                        0x803E
+//#define GL_LUMINANCE4                     0x803F
+//#define GL_LUMINANCE8                     0x8040
+//#define GL_LUMINANCE12                    0x8041
+//#define GL_LUMINANCE16                    0x8042
+//#define GL_LUMINANCE4_ALPHA4              0x8043
+//#define GL_LUMINANCE6_ALPHA2              0x8044
+//#define GL_LUMINANCE8_ALPHA8              0x8045
+//#define GL_LUMINANCE12_ALPHA4             0x8046
+//#define GL_LUMINANCE12_ALPHA12            0x8047
+//#define GL_LUMINANCE16_ALPHA16            0x8048
+#define GL_INTENSITY                      0x8049
+//#define GL_INTENSITY4                     0x804A
+//#define GL_INTENSITY8                     0x804B
+//#define GL_INTENSITY12                    0x804C
+//#define GL_INTENSITY16                    0x804D
+//#define GL_R3_G3_B2                       0x2A10
+//#define GL_RGB4                           0x804F
+#define GL_RGB5                           0x8050
+#define GL_RGB8                           0x8051
+//#define GL_RGB10                          0x8052
+//#define GL_RGB12                          0x8053
+//#define GL_RGB16                          0x8054
+//#define GL_RGBA2                          0x8055
+#define GL_RGBA4                          0x8056
+#define GL_RGB5_A1                        0x8057
+#define GL_RGBA8                          0x8058
+//#define GL_RGB10_A2                       0x8059
+//#define GL_RGBA12                         0x805A
+//#define GL_RGBA16                         0x805B
+//#define GL_TEXTURE_RED_SIZE               0x805C
+//#define GL_TEXTURE_GREEN_SIZE             0x805D
+//#define GL_TEXTURE_BLUE_SIZE              0x805E
+//#define GL_TEXTURE_ALPHA_SIZE             0x805F
+//#define GL_TEXTURE_LUMINANCE_SIZE         0x8060
+//#define GL_TEXTURE_INTENSITY_SIZE         0x8061
+//#define GL_PROXY_TEXTURE_1D               0x8063
+//#define GL_PROXY_TEXTURE_2D               0x8064
+//
+///* texture_object */
+//#define GL_TEXTURE_PRIORITY               0x8066
+//#define GL_TEXTURE_RESIDENT               0x8067
+//#define GL_TEXTURE_BINDING_1D             0x8068
+//#define GL_TEXTURE_BINDING_2D             0x8069
+//
+///* vertex_array */
+//#define GL_VERTEX_ARRAY                   0x8074
+//#define GL_NORMAL_ARRAY                   0x8075
+//#define GL_COLOR_ARRAY                    0x8076
+//#define GL_INDEX_ARRAY                    0x8077
+//#define GL_TEXTURE_COORD_ARRAY            0x8078
+//#define GL_EDGE_FLAG_ARRAY                0x8079
+//#define GL_VERTEX_ARRAY_SIZE              0x807A
+//#define GL_VERTEX_ARRAY_TYPE              0x807B
+//#define GL_VERTEX_ARRAY_STRIDE            0x807C
+//#define GL_NORMAL_ARRAY_TYPE              0x807E
+//#define GL_NORMAL_ARRAY_STRIDE            0x807F
+//#define GL_COLOR_ARRAY_SIZE               0x8081
+//#define GL_COLOR_ARRAY_TYPE               0x8082
+//#define GL_COLOR_ARRAY_STRIDE             0x8083
+//#define GL_INDEX_ARRAY_TYPE               0x8085
+//#define GL_INDEX_ARRAY_STRIDE             0x8086
+//#define GL_TEXTURE_COORD_ARRAY_SIZE       0x8088
+//#define GL_TEXTURE_COORD_ARRAY_TYPE       0x8089
+//#define GL_TEXTURE_COORD_ARRAY_STRIDE     0x808A
+//#define GL_EDGE_FLAG_ARRAY_STRIDE         0x808C
+//#define GL_VERTEX_ARRAY_POINTER           0x808E
+//#define GL_NORMAL_ARRAY_POINTER           0x808F
+//#define GL_COLOR_ARRAY_POINTER            0x8090
+//#define GL_INDEX_ARRAY_POINTER            0x8091
+//#define GL_TEXTURE_COORD_ARRAY_POINTER    0x8092
+//#define GL_EDGE_FLAG_ARRAY_POINTER        0x8093
+//#define GL_V2F                            0x2A20
+//#define GL_V3F                            0x2A21
+//#define GL_C4UB_V2F                       0x2A22
+//#define GL_C4UB_V3F                       0x2A23
+//#define GL_C3F_V3F                        0x2A24
+//#define GL_N3F_V3F                        0x2A25
+//#define GL_C4F_N3F_V3F                    0x2A26
+//#define GL_T2F_V3F                        0x2A27
+//#define GL_T4F_V4F                        0x2A28
+//#define GL_T2F_C4UB_V3F                   0x2A29
+//#define GL_T2F_C3F_V3F                    0x2A2A
+//#define GL_T2F_N3F_V3F                    0x2A2B
+//#define GL_T2F_C4F_N3F_V3F                0x2A2C
+//#define GL_T4F_C4F_N3F_V4F                0x2A2D
+//
+///* Extensions */
+//#define GL_EXT_vertex_array               1
+//#define GL_EXT_bgra                       1
+//#define GL_EXT_paletted_texture           1
+//#define GL_WIN_swap_hint                  1
+//#define GL_WIN_draw_range_elements        1
+//// #define GL_WIN_phong_shading              1
+//// #define GL_WIN_specular_fog               1
+//
+///* EXT_vertex_array */
+//#define GL_VERTEX_ARRAY_EXT               0x8074
+//#define GL_NORMAL_ARRAY_EXT               0x8075
+//#define GL_COLOR_ARRAY_EXT                0x8076
+//#define GL_INDEX_ARRAY_EXT                0x8077
+//#define GL_TEXTURE_COORD_ARRAY_EXT        0x8078
+//#define GL_EDGE_FLAG_ARRAY_EXT            0x8079
+//#define GL_VERTEX_ARRAY_SIZE_EXT          0x807A
+//#define GL_VERTEX_ARRAY_TYPE_EXT          0x807B
+//#define GL_VERTEX_ARRAY_STRIDE_EXT        0x807C
+//#define GL_VERTEX_ARRAY_COUNT_EXT         0x807D
+//#define GL_NORMAL_ARRAY_TYPE_EXT          0x807E
+//#define GL_NORMAL_ARRAY_STRIDE_EXT        0x807F
+//#define GL_NORMAL_ARRAY_COUNT_EXT         0x8080
+//#define GL_COLOR_ARRAY_SIZE_EXT           0x8081
+//#define GL_COLOR_ARRAY_TYPE_EXT           0x8082
+//#define GL_COLOR_ARRAY_STRIDE_EXT         0x8083
+//#define GL_COLOR_ARRAY_COUNT_EXT          0x8084
+//#define GL_INDEX_ARRAY_TYPE_EXT           0x8085
+//#define GL_INDEX_ARRAY_STRIDE_EXT         0x8086
+//#define GL_INDEX_ARRAY_COUNT_EXT          0x8087
+//#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT   0x8088
+//#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT   0x8089
+//#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
+//#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT  0x808B
+//#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT     0x808C
+//#define GL_EDGE_FLAG_ARRAY_COUNT_EXT      0x808D
+//#define GL_VERTEX_ARRAY_POINTER_EXT       0x808E
+//#define GL_NORMAL_ARRAY_POINTER_EXT       0x808F
+//#define GL_COLOR_ARRAY_POINTER_EXT        0x8090
+//#define GL_INDEX_ARRAY_POINTER_EXT        0x8091
+//#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
+//#define GL_EDGE_FLAG_ARRAY_POINTER_EXT    0x8093
+//#define GL_DOUBLE_EXT                     GL_DOUBLE
+//
+///* EXT_bgra */
+//#define GL_BGR_EXT                        0x80E0
+#define GL_BGRA_EXT                       0x80E1
+//
+///* Extensions */
+//#define GL_EXT_abgr                       1
+//#define GL_EXT_blend_color                1
+//#define GL_EXT_blend_minmax               1
+//#define GL_EXT_blend_subtract             1
+//
+///* EXT_abgr */
+//#define GL_ABGR_EXT                       0x8000
+//
+///* EXT_blend_color */
+#define GL_CONSTANT_COLOR_EXT             0x8001
+//#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002
+//#define GL_CONSTANT_ALPHA_EXT             0x8003
+//#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004
+#define GL_BLEND_COLOR_EXT                0x8005
+//
+///* EXT_blend_minmax */
+#define GL_FUNC_ADD_EXT                   0x8006
+//#define GL_MIN_EXT                        0x8007
+//#define GL_MAX_EXT                        0x8008
+//#define GL_BLEND_EQUATION_EXT             0x8009
+//
+///* EXT_blend_subtract */
+//#define GL_FUNC_SUBTRACT_EXT              0x800A
+//#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B
+//
+///* EXT_paletted_texture */
+//
+///* These must match the GL_COLOR_TABLE_*_SGI enumerants */
+//#define GL_COLOR_TABLE_FORMAT_EXT         0x80D8
+//#define GL_COLOR_TABLE_WIDTH_EXT          0x80D9
+//#define GL_COLOR_TABLE_RED_SIZE_EXT       0x80DA
+//#define GL_COLOR_TABLE_GREEN_SIZE_EXT     0x80DB
+//#define GL_COLOR_TABLE_BLUE_SIZE_EXT      0x80DC
+//#define GL_COLOR_TABLE_ALPHA_SIZE_EXT     0x80DD
+//#define GL_COLOR_TABLE_LUMINANCE_SIZE_EXT 0x80DE
+//#define GL_COLOR_TABLE_INTENSITY_SIZE_EXT 0x80DF
+//
+//#define GL_COLOR_INDEX1_EXT               0x80E2
+//#define GL_COLOR_INDEX2_EXT               0x80E3
+//#define GL_COLOR_INDEX4_EXT               0x80E4
+#define GL_COLOR_INDEX8_EXT               0x80E5
+//#define GL_COLOR_INDEX12_EXT              0x80E6
+//#define GL_COLOR_INDEX16_EXT              0x80E7
+//
+///* WIN_draw_range_elements */
+//#define GL_MAX_ELEMENTS_VERTICES_WIN      0x80E8
+//#define GL_MAX_ELEMENTS_INDICES_WIN       0x80E9
+//
+///* WIN_phong_shading */
+//#define GL_PHONG_WIN                      0x80EA 
+//#define GL_PHONG_HINT_WIN                 0x80EB 
+//
+///* WIN_specular_fog */
+//#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC
+//
+///* For compatibility with OpenGL v1.0 */
+//#define GL_LOGIC_OP GL_INDEX_LOGIC_OP
+//#define GL_TEXTURE_COMPONENTS GL_TEXTURE_INTERNAL_FORMAT
+//
+//// Pi
+//#ifndef M_PI
+//#define M_PI 3.1415926f
+//#endif 
+//
+//#ifndef EGL_FALSE
+//#define EGL_FALSE                      0
+//#endif
+//
+//#ifndef EGL_TRUE
+//#define EGL_TRUE                       1
+//#endif
+//
+//#define EGL_DRAW                       0x3059
+//#define EGL_READ                       0x305A
+//
+//typedef void *	EGLDisplay;
+//typedef void *	EGLConfig;
+//typedef void *	EGLSurface;
+//typedef void *	EGLContext;
+//
+//typedef int				EGLBoolean;
+//typedef unsigned int	EGLint;
+//
+//
+//#define EGL_DEFAULT_DISPLAY ((NativeDisplayType)0)
+//#define EGL_NO_CONTEXT ((EGLContext)0)
+//#define EGL_NO_DISPLAY ((EGLDisplay)0)
+//#define EGL_NO_SURFACE ((EGLSurface)0)
+//
+//typedef void*		NativeDisplayType;
+//typedef void*		NativeWindowType;
+//typedef void*		NativePixmapType;
+
+#define GL_TEXTURE0_ARB                   0x84C0
+#define GL_TEXTURE1_ARB                   0x84C1
+#define GL_TEXTURE2_ARB                   0x84C2
+#define GL_TEXTURE3_ARB                   0x84C3
+//#define GL_TEXTURE4_ARB                   0x84C4
+//#define GL_TEXTURE5_ARB                   0x84C5
+//#define GL_TEXTURE6_ARB                   0x84C6
+//#define GL_TEXTURE7_ARB                   0x84C7
+//#define GL_TEXTURE8_ARB                   0x84C8
+//#define GL_TEXTURE9_ARB                   0x84C9
+//#define GL_TEXTURE10_ARB                  0x84CA
+//#define GL_TEXTURE11_ARB                  0x84CB
+//#define GL_TEXTURE12_ARB                  0x84CC
+//#define GL_TEXTURE13_ARB                  0x84CD
+//#define GL_TEXTURE14_ARB                  0x84CE
+//#define GL_TEXTURE15_ARB                  0x84CF
+//#define GL_TEXTURE16_ARB                  0x84D0
+//#define GL_TEXTURE17_ARB                  0x84D1
+//#define GL_TEXTURE18_ARB                  0x84D2
+//#define GL_TEXTURE19_ARB                  0x84D3
+//#define GL_TEXTURE20_ARB                  0x84D4
+//#define GL_TEXTURE21_ARB                  0x84D5
+//#define GL_TEXTURE22_ARB                  0x84D6
+//#define GL_TEXTURE23_ARB                  0x84D7
+//#define GL_TEXTURE24_ARB                  0x84D8
+//#define GL_TEXTURE25_ARB                  0x84D9
+//#define GL_TEXTURE26_ARB                  0x84DA
+//#define GL_TEXTURE27_ARB                  0x84DB
+//#define GL_TEXTURE28_ARB                  0x84DC
+//#define GL_TEXTURE29_ARB                  0x84DD
+//#define GL_TEXTURE30_ARB                  0x84DE
+//#define GL_TEXTURE31_ARB                  0x84DF
+//#define GL_ACTIVE_TEXTURE_ARB             0x84E0
+//#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1
+#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2
+//
+//#define GL_COMPRESSED_ALPHA_ARB 0x84E9
+//#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA
+//#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
+//#define GL_COMPRESSED_INTENSITY_ARB 0x84EC
+#define GL_COMPRESSED_RGB_ARB 0x84ED
+#define GL_COMPRESSED_RGBA_ARB 0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF
+//#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
+//#define GL_TEXTURE_COMPRESSED_ARB 0x86A1
+//#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
+//#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
+#ifndef GL_UNSIGNED_SHORT_1_5_5_5_REV
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366
+#endif
+//
+
+// ------------------------------------------------------------------------------------------------------
+//  Only function prototypes that were actually used in TGE are
+//    listed here
+// ------------------------------------------------------------------------------------------------------
+	
+	
+	// straightforward conversions
+#define glColor3f(r,g,b) glColor4f(r,g,b,1)
+#define GLdouble F64
+#define glOrtho( left, right, bottom, top, near, far ) glOrthof( left, right, bottom, top, near, far )
+#define glFrustum( left, right, bottom, top, near, far ) glFrustumf( left, right, bottom, top, near, far )
+#define glDepthRange( near, far ) glDepthRangef( near, far )
+
+// functions that need workarounds
+void glBegin( GLint );
+void glEnd();
+
+void glTexCoord2f( GLfloat, GLfloat );
+void glActiveTextureARB( GLint );
+void glMultiTexCoord2fARB( GLint, GLfloat, GLfloat);
+void glPushAttrib( GLint );
+void glPopAttrib();
+void glReadBuffer( GLint );
+void glVertex3f( GLfloat, GLfloat, GLfloat );
+void glVertex2f( GLfloat, GLfloat );
+void glVertex2i( GLint, GLint );
+void glClientActiveTextureARB( GLint );
+void glVertex3fv( const F32 * );
+void glVertex2fv( const F32 * );
+void glNormal3fv( const F32 * );
+void glColor3fv( const F32 * );
+void glColor4fv( const F32 * );
+void glColor3i( GLint, GLint, GLint );
+void glColor3ubv( const GLubyte *v );
+void glColor4ubv( const GLubyte *v );
+void glRecti( GLint, GLint, GLint, GLint );
+void glGetDoublev( GLint, GLdouble * );
+void glPolygonMode( GLint, GLint );
+void glLockArraysEXT( GLint, GLint );
+void glUnlockArraysEXT();
+void glColor3ub( GLint, GLint, GLint );
+void glFogi( GLint, GLint );
+
+// PUAP -Mat see comment in mm file
+//void glDrawBuffer( GLint );
+
+void glColorTableEXT( GLint, GLint, GLint, GLint, GLint, const ColorI * );
+void glBlendColorEXT( GLfloat, GLfloat, GLfloat, GLfloat );
+void glBlendEquationEXT( GLint );
+void glArrayElement( GLint );
+void glFogCoordPointerEXT(GLenum, GLsizei, void *);
+void glTexGeni( GLenum coord, GLenum pname, GLint param );
+void glTexGenfv( GLenum coord, GLenum pname, const GLfloat *params );
+void glClipPlane( GLuint plane, GLdouble * equation );
+GLboolean glAreTexturesResident( GLsizei, const GLuint *, GLboolean*);
+
+void gluOrtho2D( GLfloat, GLfloat, GLfloat, GLfloat );
+GLint gluProject( GLdouble winx, GLdouble winy, GLdouble winz, const F64 *model, const F64 * proj, const GLint * vp, F64 * x, F64 * y, F64 * z );
+GLint gluUnProject( GLdouble winx, GLdouble winy, GLdouble winz, const F64 *model, const F64 * proj, const GLint * vp, F64 * x, F64 * y, F64 * z );
+
+
+#endif //_GL2ES_H_

+ 1263 - 0
engine/source/platformAndroid/AndroidInput.cpp

@@ -0,0 +1,1263 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/AndroidUtil.h"
+#include "platform/platformInput.h"
+#include "platform/event.h"
+#include "console/console.h"
+#include "game/gameInterface.h"
+#include "string/Unicode.h"
+#include "gui/guiCanvas.h"
+
+
+// <Mat> just some random number 50, we'll get a proper value later
+#define Android_DOUBLE_CLICK_TIME	( 50 * 60.0f * 1000.0f)
+
+// Static class variables:
+InputManager* Input::smManager;
+bool           Input::smActive;
+CursorManager* Input::smCursorManager = 0;
+
+
+bool gInputEnabled = false;
+bool gMouseEnabled = false;
+bool gKBEnabled = false;
+bool gMouseActive = false;
+bool gKBActive = false;
+
+//------------------------------------------------------------------------------
+// Helper functions.  Should migrate to an InputManager object at some point.
+bool enableKeyboard(void);
+void disableKeyboard(void);
+bool activateKeyboard(void);
+void deactivateKeyboard(void);
+bool enableMouse(void);
+void disableMouse(void);
+bool activateMouse(void);
+void deactivateMouse(void);
+
+
+
+static void fillAsciiTable();
+
+
+struct touchEvent {
+	S32 number;
+	S32 x;
+	S32 y;
+	touchEvent( S32 a, S32 b, S32 c ) {
+		number = a;
+		x = b;
+		y = c;
+	}
+};
+
+
+Vector<touchEvent> TouchMoveEvents;//<Mat> to make sure we don't have multiple events per frame
+Vector<touchEvent> TouchDownEvents;
+Vector<touchEvent> TouchUpEvents;
+
+// EFM - BEGIN TOUCH CHANGES
+#define MAX_TOUCH_EVENTS 5
+
+struct touchTracker {
+	S32 lastX;
+	S32 lastY;
+	Vector<touchEvent> downEvents;
+	Vector<touchEvent> moveEvents;
+	Vector<touchEvent> upEvents;
+};
+
+touchTracker CombinedTouchEvents[MAX_TOUCH_EVENTS];
+
+struct touchCorrelation {
+	S32 lastX;
+	S32 lastY;
+};
+
+touchCorrelation lastTouches[MAX_TOUCH_EVENTS];
+
+// EFM - END TOUCH CHANGES
+
+//Luma: Tap support
+Vector<touchEvent> TouchTapEvents;
+int processMultipleTouches();
+
+
+//------------------------------------------------------------------------------
+//
+// This function gets the standard ASCII code corresponding to our key code
+// and the existing modifier key state.
+//
+//------------------------------------------------------------------------------
+struct AsciiData
+{
+   struct KeyData
+   {
+      U16   ascii;
+      bool  isDeadChar;
+   };
+
+   KeyData upper;
+   KeyData lower;
+   KeyData goofy;
+};
+
+
+#define NUM_KEYS ( KEY_OEM_102 + 1 )
+#define KEY_FIRST KEY_ESCAPE
+static AsciiData AsciiTable[NUM_KEYS];
+
+void Input::enableMouse()
+{
+    // Do nothing on Android
+}
+
+void Input::disableMouse()
+{
+    // Do nothing on Android
+}
+
+void Input::enableKeyboard()
+{
+    // Do nothing on Android
+}
+
+void Input::disableKeyboard()
+{
+    // Do nothing on Android
+}
+
+bool Input::isMouseEnabled()
+{
+    return true;
+}
+
+bool Input::isKeyboardEnabled()
+{
+    return false;
+}
+ 
+//--------------------------------------------------------------------------
+void Input::init()
+{
+    Con::printf( "Input Init:" );
+   destroy();
+
+   smManager = NULL;
+	//smManager = new AndroidInputManager();
+   smActive = false;
+
+   // stop the double-cursor thing
+   Con::setBoolVariable("$pref::Gui::noClampTorqueCursorToWindow", true);
+   
+   // enable main input
+   Input::enable();
+
+   // Startup the Cursor Manager
+   if(!smCursorManager)
+   {
+      smCursorManager = new CursorManager();
+      if(smCursorManager)
+      {
+         // Add the arrow cursor to the stack
+         smCursorManager->pushCursor(CursorManager::curArrow);
+      }
+      else
+      {
+         Con::printf("   Cursor Manager not enabled.");
+      }
+   }
+	
+	
+	for(int i = 0 ; i < MAX_TOUCH_EVENTS; i++ )
+	{
+		lastTouches[i].lastX = -1;
+		lastTouches[i].lastY = -1;
+	}
+	
+	
+   
+   
+   Con::printf( "" );
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( isJoystickDetected, bool, 1, 1, "Always false on the Android." )
+{
+/*
+   argc; argv;
+   return( DInputDevice::joystickDetected() );
+*/
+   return(false);
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( getJoystickAxes, const char*, 2, 2, "(handle instance)" )
+{
+
+   return( "" );
+}
+
+//------------------------------------------------------------------------------
+static void fillAsciiTable()
+{
+
+}
+
+//------------------------------------------------------------------------------
+U16 Input::getKeyCode( U16 asciiCode )
+{
+   U16 keyCode = 0;
+   U16 i;
+   
+   // This is done three times so the lowerkey will always
+   // be found first. Some foreign keyboards have duplicate
+   // chars on some keys.
+   for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
+   {
+      if ( AsciiTable[i].lower.ascii == asciiCode )
+      {
+         keyCode = i;
+         break;
+      };
+   }
+
+   for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
+   {
+      if ( AsciiTable[i].upper.ascii == asciiCode )
+      {
+         keyCode = i;
+         break;
+      };
+   }
+
+   for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
+   {
+      if ( AsciiTable[i].goofy.ascii == asciiCode )
+      {
+         keyCode = i;
+         break;
+      };
+   }
+
+   return( keyCode );
+}
+
+//------------------------------------------------------------------------------
+U16 Input::getAscii( U16 keyCode, KEY_STATE keyState )
+{
+   if ( keyCode >= NUM_KEYS )
+      return 0;
+
+   switch ( keyState )
+   {
+      case STATE_LOWER:
+         return AsciiTable[keyCode].lower.ascii;
+      case STATE_UPPER:
+         return AsciiTable[keyCode].upper.ascii;
+      case STATE_GOOFY:
+         return AsciiTable[keyCode].goofy.ascii;
+      default:
+         return(0);
+            
+   }
+}
+
+//------------------------------------------------------------------------------
+void Input::destroy()
+{
+   // turn us off.
+   if (gInputEnabled)
+      disable();
+   
+   if ( smManager && smManager->isEnabled() )
+   {
+      smManager->disable();
+      delete smManager;
+      smManager = NULL;
+   }
+}
+
+//------------------------------------------------------------------------------
+bool Input::enable()
+{
+	Con::printf( "[]Input::enable." );
+
+   gInputEnabled = true;
+
+   if ( smManager && !smManager->isEnabled() )
+      return( smManager->enable() );
+
+   enableMouse();
+   //enableKeyboard();
+
+   return( gInputEnabled );
+}
+
+//------------------------------------------------------------------------------
+void Input::disable()
+{
+	Con::printf( "[]Input::disable." );
+
+   gInputEnabled = false;
+
+  if ( smManager && smManager->isEnabled() )
+      smManager->disable();
+
+   disableMouse();
+   //disableKeyboard();
+}
+
+//------------------------------------------------------------------------------
+void Input::activate()
+{
+   smActive = true;
+
+   enableMouse();
+// enableKeyboard();
+}
+
+//------------------------------------------------------------------------------
+void Input::deactivate()
+{
+//Con::printf( "[]Input::deactivate." );
+
+   deactivateMouse();
+   //deactivateKeyboard();
+
+   smActive = false;
+
+}
+
+//------------------------------------------------------------------------------
+void Input::reactivate()
+{
+   // don't think mac needs to do anything right now!!!!!! TBD
+   
+   // This is soo hacky...
+//   SetForegroundWindow( winState.appWindow );
+//   PostMessage( winState.appWindow, WM_ACTIVATE, WA_ACTIVE, NULL );
+}
+
+//------------------------------------------------------------------------------
+bool Input::isEnabled()
+{
+   if ( smManager )
+      return smManager->isEnabled();
+
+   return(gInputEnabled);
+}
+
+//------------------------------------------------------------------------------
+bool Input::isActive()
+{
+   return smActive;
+}
+
+//------------------------------------------------------------------------------
+void Input::process()
+{
+	//only gets called once per frame, create touches and accelerometer events here
+	//post, then pop each event
+
+	if(platState.multipleTouchesEnabled) processMultipleTouches();
+	
+   if (!smActive || !gInputEnabled)
+      return;
+
+   if (!gMouseEnabled || !gMouseActive)
+      return;
+      
+ 
+   if ( smManager && smManager->isEnabled() && smActive )
+      smManager->process();
+}
+
+//------------------------------------------------------------------------------
+InputManager* Input::getManager()
+{
+   return( smManager );
+}
+
+//TODO: is this table right for android too?
+//--------------------------------------------------------------------------
+//#pragma message("input remap table might need tweaking - rumors of ibooks having diff virt keycodes, might need intermediate remap...")
+static U8 VcodeRemap[256] =
+{
+KEY_A,                     // 0x00 
+KEY_S,                     // 0x01 
+KEY_D,                     // 0x02 
+KEY_F,                     // 0x03 
+KEY_H,                     // 0x04 
+KEY_G,                     // 0x05 
+KEY_Z,                     // 0x06 
+KEY_X,                     // 0x07 
+KEY_C,                     // 0x08 
+KEY_V,                     // 0x09 
+KEY_Y,                     // 0x0A       // this is questionable - not normal Y code
+KEY_B,                     // 0x0B 
+KEY_Q,                     // 0x0C 
+KEY_W,                     // 0x0D 
+KEY_E,                     // 0x0E 
+KEY_R,                     // 0x0F 
+KEY_Y,                     // 0x10 
+KEY_T,                     // 0x11 
+KEY_1,                     // 0x12 
+KEY_2,                     // 0x13 
+KEY_3,                     // 0x14 
+KEY_4,                     // 0x15 
+KEY_6,                     // 0x16 
+KEY_5,                     // 0x17 
+KEY_EQUALS,                // 0x18 
+KEY_9,                     // 0x19 
+KEY_7,                     // 0x1A 
+KEY_MINUS,                 // 0x1B 
+KEY_8,                     // 0x1C 
+KEY_0,                     // 0x1D 
+KEY_RBRACKET,              // 0x1E 
+KEY_O,                     // 0x1F 
+KEY_U,                     // 0x20 
+KEY_LBRACKET,              // 0x21 
+KEY_I,                     // 0x22 
+KEY_P,                     // 0x23 
+KEY_RETURN,                // 0x24 
+KEY_L,                     // 0x25 
+KEY_J,                     // 0x26 
+KEY_APOSTROPHE,            // 0x27 
+KEY_K,                     // 0x28 
+KEY_SEMICOLON,             // 0x29 
+KEY_BACKSLASH,             // 0x2A 
+KEY_COMMA,                 // 0x2B 
+KEY_SLASH,                 // 0x2C 
+KEY_N,                     // 0x2D 
+KEY_M,                     // 0x2E 
+KEY_PERIOD,                // 0x2F 
+KEY_TAB,                   // 0x30 
+KEY_SPACE,                 // 0x31 
+KEY_TILDE,                 // 0x32 
+KEY_BACKSPACE,             // 0x33 
+0,                         // 0x34 //?
+KEY_ESCAPE,                // 0x35 
+0,                         // 0x36 //?
+KEY_ALT,                   // 0x37 // best mapping for mac Cmd key
+KEY_LSHIFT,                // 0x38 
+KEY_CAPSLOCK,              // 0x39 
+KEY_MAC_OPT,               // 0x3A // direct map mac Option key -- better than KEY_WIN_WINDOWS
+KEY_CONTROL,               // 0x3B 
+KEY_RSHIFT,                // 0x3C 
+0,                         // 0x3D 
+0,                         // 0x3E 
+0,                         // 0x3F 
+0,                         // 0x40 
+KEY_DECIMAL,               // 0x41 
+0,                         // 0x42 
+KEY_MULTIPLY,              // 0x43 
+0,                         // 0x44 
+KEY_ADD,                   // 0x45 
+KEY_SUBTRACT,              // 0x46 // secondary code?
+KEY_NUMLOCK,               // 0x47 // also known as Clear on mac...
+KEY_SEPARATOR,             // 0x48 // secondary code? for KPEqual
+0,                         // 0x49 
+0,                         // 0x4A 
+KEY_DIVIDE,                // 0x4B 
+KEY_NUMPADENTER,           // 0x4C 
+KEY_DIVIDE,                // 0x4D // secondary code?
+KEY_SUBTRACT,              // 0x4E 
+0,                         // 0x4F 
+0,                         // 0x50 
+KEY_SEPARATOR,             // 0x51 // WHAT IS SEP?  This is KPEqual on mac.
+KEY_NUMPAD0,               // 0x52 
+KEY_NUMPAD1,               // 0x53 
+KEY_NUMPAD2,               // 0x54 
+KEY_NUMPAD3,               // 0x55 
+KEY_NUMPAD4,               // 0x56 
+KEY_NUMPAD5,               // 0x57 
+KEY_NUMPAD6,               // 0x58 
+KEY_NUMPAD7,               // 0x59 
+0,                         // 0x5A 
+KEY_NUMPAD8,               // 0x5B 
+KEY_NUMPAD9,               // 0x5C 
+0,                         // 0x5D 
+0,                         // 0x5E 
+0,                         // 0x5F 
+KEY_F5,                    // 0x60 
+KEY_F6,                    // 0x61 
+KEY_F7,                    // 0x62 
+KEY_F3,                    // 0x63 
+KEY_F8,                    // 0x64 
+KEY_F9,                    // 0x65 
+0,                         // 0x66 
+KEY_F11,                   // 0x67 
+0,                         // 0x68 
+KEY_PRINT,                 // 0x69 
+0,                         // 0x6A 
+KEY_SCROLLLOCK,            // 0x6B 
+0,                         // 0x6C 
+KEY_F10,                   // 0x6D 
+0,                         // 0x6E 
+KEY_F12,                   // 0x6F 
+0,                         // 0x70 
+KEY_PAUSE,                 // 0x71 
+KEY_INSERT,                // 0x72 // also known as mac Help
+KEY_HOME,                  // 0x73 
+KEY_PAGE_UP,               // 0x74 
+KEY_DELETE,                // 0x75 // FwdDel
+KEY_F4,                    // 0x76 
+KEY_END,                   // 0x77 
+KEY_F2,                    // 0x78 
+KEY_PAGE_DOWN,             // 0x79 
+KEY_F1,                    // 0x7A 
+KEY_LEFT,                  // 0x7B 
+KEY_RIGHT,                 // 0x7C 
+KEY_DOWN,                  // 0x7D 
+KEY_UP,                    // 0x7E 
+0,                         // 0x7F 
+0,                         // 0x80 
+0,                         // 0x81 
+0,                         // 0x82 
+0,                         // 0x83 
+0,                         // 0x84 
+0,                         // 0x85 
+0,                         // 0x86 
+0,                         // 0x87 
+0,                         // 0x88 
+0,                         // 0x89 
+0,                         // 0x8A 
+0,                         // 0x8B 
+0,                         // 0x8C 
+0,                         // 0x8D 
+0,                         // 0x8E 
+0,                         // 0x8F 
+
+0,                         // 0x90 
+0,                         // 0x91 
+0,                         // 0x92 
+0,                         // 0x93 
+0,                         // 0x94 
+0,                         // 0x95 
+0,                         // 0x96 
+0,                         // 0x97 
+0,                         // 0x98 
+0,                         // 0x99 
+0,                         // 0x9A 
+0,                         // 0x9B 
+0,                         // 0x9C 
+0,                         // 0x9D 
+0,                         // 0x9E 
+0,                         // 0x9F 
+
+0,                         // 0xA0 
+0,                         // 0xA1 
+0,                         // 0xA2 
+0,                         // 0xA3 
+0,                         // 0xA4 
+0,                         // 0xA5 
+0,                         // 0xA6 
+0,                         // 0xA7 
+0,                         // 0xA8 
+0,                         // 0xA9 
+0,                         // 0xAA 
+0,                         // 0xAB 
+0,                         // 0xAC 
+0,                         // 0xAD 
+0,                         // 0xAE 
+0,                         // 0xAF 
+0,                         // 0xB0 
+0,                         // 0xB1 
+0,                         // 0xB2 
+0,                         // 0xB3 
+0,                         // 0xB4 
+0,                         // 0xB5 
+0,                         // 0xB6 
+0,                         // 0xB7 
+0,                         // 0xB8 
+0,                         // 0xB9 
+0,                         // 0xBA 
+0,                         // 0xBB 
+0,                         // 0xBC 
+0,                         // 0xBD 
+0,                         // 0xBE 
+0,                         // 0xBF 
+0,                         // 0xC0 
+0,                         // 0xC1 
+0,                         // 0xC2 
+0,                         // 0xC3 
+0,                         // 0xC4 
+0,                         // 0xC5 
+0,                         // 0xC6 
+0,                         // 0xC7 
+0,                         // 0xC8 
+0,                         // 0xC9 
+0,                         // 0xCA 
+0,                         // 0xCB 
+0,                         // 0xCC 
+0,                         // 0xCD 
+0,                         // 0xCE 
+0,                         // 0xCF 
+0,                         // 0xD0 
+0,                         // 0xD1 
+0,                         // 0xD2 
+0,                         // 0xD3 
+0,                         // 0xD4 
+0,                         // 0xD5 
+0,                         // 0xD6 
+0,                         // 0xD7 
+0,                         // 0xD8 
+0,                         // 0xD9 
+0,                         // 0xDA 
+0,                         // 0xDB 
+0,                         // 0xDC 
+0,                         // 0xDD 
+0,                         // 0xDE 
+0,                         // 0xDF 
+0,                         // 0xE0 
+0,                         // 0xE1 
+0,                         // 0xE2 
+0,                         // 0xE3 
+0,                         // 0xE4 
+
+0,                         // 0xE5 
+
+0,                         // 0xE6 
+0,                         // 0xE7 
+0,                         // 0xE8 
+0,                         // 0xE9 
+0,                         // 0xEA 
+0,                         // 0xEB 
+0,                         // 0xEC 
+0,                         // 0xED 
+0,                         // 0xEE 
+0,                         // 0xEF 
+   
+0,                         // 0xF0 
+0,                         // 0xF1 
+0,                         // 0xF2 
+0,                         // 0xF3 
+0,                         // 0xF4 
+0,                         // 0xF5 
+   
+0,                         // 0xF6 
+0,                         // 0xF7 
+0,                         // 0xF8 
+0,                         // 0xF9 
+0,                         // 0xFA 
+0,                         // 0xFB 
+0,                         // 0xFC 
+0,                         // 0xFD 
+0,                         // 0xFE 
+0                          // 0xFF 
+};   
+
+
+U8 TranslateOSKeyCode(U8 vcode)
+{
+   return VcodeRemap[vcode];   
+}   
+
+#pragma mark ---- Clipboard functions ----
+//-----------------------------------------------------------------------------
+const char* Platform::getClipboard()
+{
+	return NULL;//no clipboard on Android
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::setClipboard(const char *text)
+{
+	return NULL;//no clipboard on Android
+}
+
+#pragma mark ---- Cursor Functions ----
+//------------------------------------------------------------------------------
+void Input::pushCursor(S32 cursorID)
+{
+   CursorManager* cm = getCursorManager();
+   if(cm)
+      cm->pushCursor(cursorID);
+}
+
+//------------------------------------------------------------------------------
+void Input::popCursor()
+{
+   CursorManager* cm = getCursorManager();
+   if(cm)
+      cm->popCursor();
+}
+
+//------------------------------------------------------------------------------
+void Input::refreshCursor()
+{
+   CursorManager* cm = getCursorManager();
+   if(cm)
+      cm->refreshCursor();
+}
+
+#pragma mark ---- DoubleClick Functions ----
+//------------------------------------------------------------------------------
+U32 Input::getDoubleClickTime()
+{
+	return Android_DOUBLE_CLICK_TIME;
+}
+
+//------------------------------------------------------------------------------
+S32 Input::getDoubleClickWidth()
+{
+   // this is an arbitrary value.
+   return 10;
+}
+
+//------------------------------------------------------------------------------
+S32 Input::getDoubleClickHeight()
+{
+   return getDoubleClickWidth();
+}
+
+#pragma mark -
+
+//------------------------------------------------------------------------------
+bool enableKeyboard()
+{
+   if ( !gInputEnabled )
+      return( false );
+
+   if ( gKBEnabled && gKBActive )
+      return( true );
+
+   gKBEnabled = true;
+   if ( Input::isActive() )
+      gKBEnabled = activateKeyboard();
+
+   if ( gKBEnabled )
+   {
+      Con::printf( "Hardware-direct keyboard enabled." );
+   }
+   else
+   {
+      Con::warnf( "Hardware-direct keyboard failed to enable!" );
+   }
+
+   return( gKBEnabled );
+}
+
+//------------------------------------------------------------------------------
+void disableKeyboard()
+{
+   if ( !gInputEnabled || !gKBEnabled )
+      return;
+
+   deactivateKeyboard();
+   gKBEnabled = false;
+
+   Con::printf( "Hardware-direct keyboard disabled." );
+}
+
+//------------------------------------------------------------------------------
+bool activateKeyboard()
+{
+   if ( !gInputEnabled || !Input::isActive() || !gKBEnabled )
+      return( false );
+
+   OSStatus status = noErr;
+   if (status==noErr)
+      gKBActive = true;
+
+   return( gKBActive );
+}
+
+//------------------------------------------------------------------------------
+void deactivateKeyboard()
+{
+   if ( gInputEnabled && gKBActive )
+   {
+      gKBActive = false;
+   }
+}
+
+//------------------------------------------------------------------------------
+bool enableMouse()
+{
+   if ( !gInputEnabled )
+      return( false );
+
+   if ( gMouseEnabled && gMouseActive )
+      return( true );
+
+   gMouseEnabled = activateMouse();
+
+   return( gMouseEnabled );
+}
+
+//------------------------------------------------------------------------------
+void disableMouse()
+{
+   if ( !gInputEnabled || !gMouseEnabled )
+      return;
+
+   deactivateMouse();
+   gMouseEnabled = false;
+
+   bool hwMouse = false;
+   Con::printf( "%s disabled", hwMouse?"Hardware-direct mouse":"Basic mouse capture");
+}
+
+//------------------------------------------------------------------------------
+bool activateMouse()
+{
+   if ( !gInputEnabled || !Input::isActive() || !gMouseEnabled )
+      return( false );
+   
+   if (gMouseActive)
+      return(true);
+
+   gMouseActive = true;
+
+   return( gMouseActive );
+}
+
+//------------------------------------------------------------------------------
+void deactivateMouse()
+{
+   if ( !gInputEnabled || !gMouseActive )
+       return;
+   
+   gMouseActive = false;
+}
+
+
+//------------------------------------------------------------------------------
+ConsoleFunction( enableMouse, bool, 1, 1, "enableMouse()" )
+{
+   return( enableMouse() );
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( disableMouse, void, 1, 1, "disableMouse()" )
+{
+   disableMouse();
+}
+
+//------------------------------------------------------------------------------
+void printInputState(void)
+{
+   if ( gInputEnabled )
+   {
+         Con::printf( "Low-level input system is enabled." );
+      
+      Con::printf( "- Keyboard is %sabled and %sactive.", 
+            gKBEnabled ? "en" : "dis",
+            gKBActive ? "" : "in" );
+      Con::printf( "- Mouse is %sabled and %sactive.", 
+            gMouseEnabled ? "en" : "dis",
+            gMouseActive ? "" : "in" );
+/*
+      Con::printf( "- Joystick is %sabled and %sactive.", 
+            gJoystickEnabled() ? "en" : "dis",
+            gJoystickActive() ? "" : "in" );
+*/
+   }
+   else
+   {
+      Con::printf( "Low-level input system is disabled." );
+   }
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( echoInputState, void, 1, 1, "echoInputState()" )
+{
+   printInputState();
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( toggleInputState, void, 1, 1, "toggleInputState()" )
+{
+   if (gInputEnabled)
+      Input::disable();
+   else
+      Input::enable();
+
+   printInputState();
+}
+
+//------------------------------------------------------------------------------
+ConsoleFunction( deactivateKeyboard, void, 1, 1, "deactivateKeyboard();")
+{
+   // these are only useful on the windows side. They deal with some vagaries of win32 DirectInput.
+}
+
+ConsoleFunction( activateKeyboard, void, 1, 1, "activateKeyboard();")
+{
+   // these are only useful on the windows side. They deal with some vagaries of win32 DirectInput.
+}
+
+
+//------------------------------------------------------------------------------
+void Input::setCursorPos(S32 x, S32 y)
+{
+	//this gets called from GuiCanvas to set the game mouse cursor
+}
+
+int processMultipleTouches()
+{	
+	char posX[256], posY[256], temp[10], touchNums[256];
+    
+	dMemset(posX, 0, sizeof(posX));
+    dMemset(posY, 0, sizeof(posY));
+    dMemset(touchNums, 0, sizeof(touchNums));
+
+	touchEvent *currentEvent;
+	
+	//Down Events
+	int numTouchDownEvents = TouchDownEvents.size();
+	while( TouchDownEvents.size() > 0 )
+    {
+		currentEvent = &TouchDownEvents.last();
+		dItoa( currentEvent->x, temp );
+		dStrcat( posX, temp );
+		dStrcat( posX, " " );
+		
+		dItoa( currentEvent->y, temp );
+		dStrcat( posY, temp );
+		dStrcat( posY, " " );
+		
+		dItoa( currentEvent->number, temp );
+		dStrcat( touchNums, temp );
+		dStrcat( touchNums, " " );
+		
+		TouchDownEvents.pop_back();
+	}
+	dItoa( numTouchDownEvents, temp );
+    
+    if( numTouchDownEvents > 0 )
+    {
+        InputEvent touchEvent;
+        
+        touchEvent.deviceInst = 0;
+        touchEvent.objInst = SI_TOUCHDOWN;
+        
+        touchEvent.deviceType = ScreenTouchDeviceType;
+        touchEvent.action = SI_TOUCH;
+        touchEvent.objType = SI_TOUCHDOWN;
+        
+        dStrcpy(touchEvent.touchesX, posX);
+        dStrcpy(touchEvent.touchesY, posY);
+        dStrcpy(touchEvent.touchIDs, touchNums);
+        
+        touchEvent.modifier = 0;
+        
+        Game->postEvent(touchEvent);        
+    }
+    
+    // Deprecated in 1.5
+	//if( numTouchDownEvents > 0 )
+    //    Con::executef( 4, "onAndroidTouchDown", touchNums , posX, posY );
+
+	//Move events
+	int numTouchMoveEvents = TouchMoveEvents.size();
+	while( TouchMoveEvents.size() > 0 ) 
+    {
+		currentEvent = &TouchMoveEvents.last();
+		dItoa( currentEvent->x, temp );
+		dStrcat( posX, temp );
+		dStrcat( posX, " " );
+		
+		dItoa( currentEvent->y, temp );
+		dStrcat( posY, temp );
+		dStrcat( posY, " " );
+		
+		dItoa( currentEvent->number, temp );
+		dStrcat( touchNums, temp );
+		dStrcat( touchNums, " " );		
+		
+		TouchMoveEvents.pop_back();
+	}
+	dItoa( numTouchMoveEvents, temp );
+    
+    if( numTouchMoveEvents > 0 )
+    {
+        InputEvent touchEvent;
+        
+        touchEvent.deviceInst = 0;
+        touchEvent.objInst = SI_TOUCHMOVE;
+        
+        touchEvent.deviceType = ScreenTouchDeviceType;
+        touchEvent.action = SI_TOUCH;
+        touchEvent.objType = SI_TOUCHMOVE;
+        
+        dStrcpy(touchEvent.touchesX, posX);
+        dStrcpy(touchEvent.touchesY, posY);
+        dStrcpy(touchEvent.touchIDs, touchNums);
+        
+        touchEvent.modifier = 0;
+        
+        Game->postEvent(touchEvent);        
+    }
+    
+    // Deprecated in 1.5 -MP
+	//if( numTouchMoveEvents > 0 )
+    //    Con::executef( 4, "onAndroidTouchMove", touchNums , posX, posY );
+	
+	//Up events
+	int numTouchUpEvents = TouchUpEvents.size();
+    
+    dMemset(posX, 0, sizeof(posX));
+    dMemset(posY, 0, sizeof(posY));
+    dMemset(touchNums, 0, sizeof(touchNums));
+    
+	while( TouchUpEvents.size() > 0 ) 
+    {
+		currentEvent = &TouchUpEvents.last();
+		dItoa( currentEvent->x, temp );
+		dStrcat( posX, temp );
+		dStrcat( posX, " " );
+		
+		dItoa( currentEvent->y, temp );
+		dStrcat( posY, temp );
+		dStrcat( posY, " " );
+		
+		dItoa( currentEvent->number, temp );
+		dStrcat( touchNums, temp );
+		dStrcat( touchNums, " " );		
+		
+		lastTouches[currentEvent->number].lastX = -1;
+		lastTouches[currentEvent->number].lastY	 = -1;
+		
+        int x;
+        x = -1;
+        
+        lastTouches[currentEvent->number].lastX = -1;
+		lastTouches[currentEvent->number].lastY	 = -1;
+        
+		TouchUpEvents.pop_back();
+	}
+    
+	dItoa( numTouchUpEvents, temp );
+	
+    if( numTouchUpEvents > 0 )
+    {
+        InputEvent touchEvent;
+        
+        touchEvent.deviceInst = 0;
+        touchEvent.objInst = SI_TOUCHUP;
+        
+        touchEvent.deviceType = ScreenTouchDeviceType;
+        touchEvent.action = SI_TOUCH;
+        touchEvent.objType = SI_TOUCHUP;
+        
+        dStrcpy(touchEvent.touchesX, posX);
+        dStrcpy(touchEvent.touchesY, posY);
+        dStrcpy(touchEvent.touchIDs, touchNums);
+        
+        touchEvent.modifier = 0;
+        
+        Game->postEvent(touchEvent);        
+    }
+    
+    // Deprecated in 1.5 -MP
+    //if( numTouchUpEvents > 0 )
+    //    Con::executef( 4, "onAndroidTouchUp", touchNums , posX, posY );
+	
+	//Luma: Tap support
+	posX[0] = '\0';
+	posY[0] = '\0';
+    
+	int numTapEvents = TouchTapEvents.size();
+	
+    while( TouchTapEvents.size() > 0 ) 
+    {
+		currentEvent = &TouchTapEvents.last();
+		sprintf( temp, "%d ", currentEvent->x );
+		dStrcat( posX, temp );
+		
+		sprintf( temp, "%d ", currentEvent->y );
+		dStrcat( posY, temp );
+		
+		TouchTapEvents.pop_back();
+	}
+    
+	sprintf( temp, "%d", numTapEvents );
+    
+	//if( numTapEvents > 0 )
+    //    Con::executef( 4, "onAndroidTouchTap", temp , posX, posY );
+	
+	return numTouchDownEvents + numTouchMoveEvents + numTouchUpEvents;
+}
+
+
+
+//we want these to only be called once per frame!!
+bool createMouseMoveEvent( S32 touchNumber, S32 x, S32 y, S32 lastX, S32 lastY ) //EFM
+{	
+	S32 currentSlot = -1;
+	
+	for( int i = 0 ; (i < MAX_TOUCH_EVENTS) && (currentSlot == -1) ; i++ )
+	{
+		if( (lastX == lastTouches[i].lastX ) &&
+		   (lastY == lastTouches[i].lastY ) )
+		{
+			currentSlot = i;
+		}
+	}
+
+	if( currentSlot == -1 ) return false;
+	
+	ScreenTouchEvent event;
+	event.xPos = x;
+	event.yPos = y;
+	event.action = SI_MOVE;
+	event.touchID = currentSlot;
+    event.numTouches = 0;
+    
+	//Luma: Mouse not moving (no hover for mouse fingers!)
+	Canvas->setCursorPos( Point2I( x, y ) );  
+
+	if( currentSlot != -1 )
+	{
+		lastTouches[currentSlot].lastX = x;
+		lastTouches[currentSlot].lastY = y;
+	}		
+	
+	TouchMoveEvents.push_back( touchEvent( currentSlot, x, y ) );	
+	Game->postEvent(event);
+	
+	return true;//return false if we get bad values or something
+}
+
+
+bool createMouseDownEvent( S32 touchNumber, S32 x, S32 y, U32 numTouches ) 
+{
+	S32 vacantSlot = -1;
+	
+	for( int i = 0 ; (i < MAX_TOUCH_EVENTS) && (vacantSlot == -1) ; i++ )
+	{
+		if( lastTouches[i].lastX == -1 )
+		{
+			vacantSlot = i;
+		}
+	}
+	
+	if( vacantSlot == -1 ) 
+        return false;
+		
+	ScreenTouchEvent event;
+	event.xPos = x;
+	event.yPos = y;
+    event.touchID = vacantSlot;
+	event.action = SI_MAKE;
+	event.numTouches = numTouches;
+    
+	//Luma: Update position
+	Canvas->setCursorPos( Point2I( x, y ) );  		
+	
+	if( vacantSlot != -1 )
+	{
+		lastTouches[vacantSlot].lastX = x;
+		lastTouches[vacantSlot].lastY = y;
+	}	
+
+	TouchDownEvents.push_back( touchEvent( vacantSlot, x, y ) );
+	Game->postEvent(event);
+	
+	return true;//return false if we get bad values or something
+}
+
+bool createMouseUpEvent( S32 touchNumber, S32 x, S32 y, S32 lastX, S32 lastY, U32 numTouches ) //EFM
+{	
+	S32 currentSlot = -1;
+	
+	for( int i = 0 ; (i < MAX_TOUCH_EVENTS) && (currentSlot == -1) ; i++ )
+	{
+		if(( (x == lastTouches[i].lastX) && (y == lastTouches[i].lastY )) ||
+		   ( (lastX == lastTouches[i].lastX ) && (lastY == lastTouches[i].lastY )))
+		{
+			currentSlot = i;
+		}	
+	}
+	
+	if( currentSlot == -1 ) 
+        return false;
+
+	ScreenTouchEvent event;
+	event.xPos = x;
+	event.yPos = y;
+	event.action = SI_BREAK;
+	event.touchID = currentSlot;
+	event.numTouches = numTouches;
+    
+	TouchUpEvents.push_back( touchEvent( currentSlot, x, y ) );	
+	
+	Game->postEvent(event);
+	
+	return true;//return false if we get bad values or something
+}
+
+void clearPendingMultitouchEvents( void ) //EFM
+{	
+    for( int i = 0 ; i < MAX_TOUCH_EVENTS ; i++ )
+	{
+		lastTouches[i].lastX = -1;
+		lastTouches[i].lastY = -1;
+	}
+
+	TouchMoveEvents.clear();
+	TouchDownEvents.clear();
+	TouchUpEvents.clear();
+}
+
+
+//Luma: Tap support
+void createMouseTapEvent( S32 nbrTaps, S32 x, S32 y ) {
+
+	TouchTapEvents.push_back( touchEvent( nbrTaps, x, y ) );
+}
+
+
+// 0 = x, 1 = y, 2 = z
+UIAccelerationValue g_lastAccel[3];
+
+// PUAP -Mat this is polled at AccelerometerUpdateMS, which should be set at around 33 
+/*
+bool createAccelMoveEvent( UIAccelerationValue *accel ) {
+	bool returnVal = false;
+	
+	U32 axis[3] = { SI_XAXIS, SI_YAXIS, SI_ZAXIS }; 
+	
+	for( int i = 0; i < 3; i++ ) {
+		if(accel[i]  != g_lastAccel[i] ) {
+			InputEvent event;
+			event.deviceInst = 0;//joystick number
+			event.fValue = accel[i];
+			event.deviceType = JoystickDeviceType;
+			event.objType = axis[i];
+			event.objInst = i;//axis number
+			event.action = SI_MOVE;
+			event.modifier = 0;
+			Game->postEvent(event);
+			g_lastAccel[i]  = accel[i];
+			returnVal = true;
+		}
+	}
+	return false;
+}
+*/

+ 92 - 0
engine/source/platformAndroid/AndroidMath.cpp

@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/platform.h"
+#include "console/console.h"
+#include "math/mMath.h"
+
+extern void mInstallLibrary_C();
+extern void mInstallLibrary_Vec();
+
+
+//--------------------------------------
+ConsoleFunction( MathInit, void, 1, 10, "(DETECT|C|VEC)")
+{
+   U32 properties = CPU_PROP_C;  // C entensions are always used
+   
+   if (argc == 1)
+   {
+         Math::init(0);
+         return;
+   }
+   for (argc--, argv++; argc; argc--, argv++)
+   {
+      if (dStricmp(*argv, "DETECT") == 0) { 
+         Math::init(0);
+         return;
+      }
+      if (dStricmp(*argv, "C") == 0) { 
+         properties |= CPU_PROP_C; 
+         continue; 
+      }
+      if (dStricmp(*argv, "VEC") == 0) { 
+         properties |= CPU_PROP_ALTIVEC; 
+         continue; 
+      }
+      Con::printf("Error: MathInit(): ignoring unknown math extension '%s'", *argv);
+   }
+   Math::init(properties);
+}
+
+
+
+//------------------------------------------------------------------------------
+void Math::init(U32 properties)
+{
+   if (!properties)
+      // detect what's available
+      properties = PlatformSystemInfo.processor.properties;  
+   else
+      // Make sure we're not asking for anything that's not supported
+      properties &= PlatformSystemInfo.processor.properties;  
+
+   Con::printf("Math Init:");
+   Con::printf("   Installing Standard C extensions");
+   mInstallLibrary_C();
+   
+   #if defined(__VEC__)
+   if (properties & CPU_PROP_ALTIVEC)
+   {
+      Con::printf("   Installing Altivec extensions");
+      mInstallLibrary_Vec();
+   }
+   #endif
+   Con::printf(" ");
+}   
+
+//------------------------------------------------------------------------------
+F32 Platform::getRandom()
+{
+   return platState.platRandom.randF();
+}
+

+ 67 - 0
engine/source/platformAndroid/AndroidMemory.cpp

@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platform/platform.h"
+#include <stdlib.h>
+#include <string.h>
+
+//-----------------------------------------------------------------------------
+
+void* dRealMalloc(dsize_t in_size)
+{
+   return malloc(in_size);
+}
+
+//-----------------------------------------------------------------------------
+
+void dRealFree(void* in_pFree)
+{
+   free(in_pFree);
+}
+
+//-----------------------------------------------------------------------------
+
+void* dMemcpy(void *dst, const void *src, dsize_t size)
+{
+   return memcpy(dst,src,size);
+}   
+
+//-----------------------------------------------------------------------------
+
+void* dMemmove(void *dst, const void *src, dsize_t size)
+{
+   return memmove(dst,src,size);
+}  
+ 
+//-----------------------------------------------------------------------------
+
+void* dMemset(void *dst, int c, dsize_t size)
+{
+   return memset(dst,c,size);   
+}   
+
+//-----------------------------------------------------------------------------
+
+int dMemcmp(const void *ptr1, const void *ptr2, dsize_t len)
+{
+   return(memcmp(ptr1, ptr2, len));
+}

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

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

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

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

+ 98 - 0
engine/source/platformAndroid/AndroidMutex.cpp

@@ -0,0 +1,98 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include <pthread.h>
+#include <stdlib.h>
+#include <errno.h>
+#include "platform/platform.h"
+#include "platform/threads/mutex.h"
+#include "platform/threads/thread.h"
+#include "memory/safeDelete.h"
+
+// TODO: examine & dump errno if pthread_* funcs fail. ( only in debug build )
+
+struct PlatformMutexData
+{
+   pthread_mutex_t   mMutex;
+   bool              locked;
+   U32         lockedByThread;
+};
+
+Mutex::Mutex(void)
+{
+   bool ok;
+   mData = new PlatformMutexData;
+   pthread_mutexattr_t attr;
+   ok = pthread_mutexattr_init(&attr);
+   ok = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
+   ok = pthread_mutex_init(&(mData->mMutex),&attr);
+   AssertFatal(ok == 0, "Mutex() failed: pthread_mutex_init() failed.");
+   
+   mData->locked = false;
+   mData->lockedByThread = 0;
+}
+
+Mutex::~Mutex()
+{
+   bool ok;
+   ok = pthread_mutex_destroy( &(mData->mMutex) );
+   AssertFatal(ok == 0, "~Mutex() failed: pthread_mutex_destroy() failed.");
+   
+   SAFE_DELETE(mData);
+}
+ 
+bool Mutex::lock( bool block)
+{
+   bool ok;
+
+   if(block)
+   {
+      ok = pthread_mutex_lock( &(mData->mMutex) );
+      AssertFatal( ok != EINVAL, "Mutex::lockMutex() failed: invalid mutex.");
+      AssertFatal( ok != EDEADLK, "Mutex::lockMutex() failed: system detected a deadlock!");
+      AssertFatal( ok == 0, "Mutex::lockMutex() failed: pthread_mutex_lock() failed -- unknown reason.");
+   } 
+   else {
+      ok = pthread_mutex_trylock( &(mData->mMutex) );
+      // returns EBUSY if mutex was locked by another thread,
+      // returns EINVAL if mutex was not a valid mutex pointer,
+      // returns 0 if lock succeeded.
+      AssertFatal( ok != EINVAL, "Mutex::lockMutex(non blocking) failed: invalid mutex.");
+      if( ok != 0 )
+         return false;
+
+      AssertFatal( ok == 0, "Mutex::lockMutex(non blocking) failed: pthread_mutex_trylock() failed -- unknown reason.");
+   }
+
+   mData->locked = true;
+   mData->lockedByThread = ThreadManager::getCurrentThreadId();
+   return true;
+}
+
+void Mutex::unlock()
+{
+   bool ok;
+   ok = pthread_mutex_unlock( &(mData->mMutex) );
+   AssertFatal( ok == 0, "Mutex::unlockMutex() failed: pthread_mutex_unlock() failed.");
+   mData->locked = false;
+   mData->lockedByThread = 0;
+}

+ 79 - 0
engine/source/platformAndroid/AndroidNPatch.h

@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+// AndroidNPatch.h
+//
+// mac specific implementation(s) of NPatch functionality
+// since each platform might use slightly diff methods to control.
+
+// current Mac NPatches is ATI TRUFORM implementation, accessed on OS9 via a
+// back door method.  OSX tests for the ATIX extension.
+
+#if !defined(TORQUE_OS_MAC_OSX)
+#define AGLSETINT_NPATCH_FLAG          ((unsigned long)500)
+#define AGLSETINT_NPATCH_LOD           ((unsigned long)501)
+#define AGLSETINT_NPATCH_POINTINTERP   ((unsigned long)502)
+#define AGLSETINT_NPATCH_NORMALINTERP  ((unsigned long)503)
+#endif
+
+// for the moment, this seems to be the best roundup of
+// the npatch extensions on the PC.
+
+#ifndef GL_ATIX_pn_triangles
+#define GL_ATIX_pn_triangles 1
+#define GL_PN_TRIANGLES_ATIX                            0x6090
+#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATIX      0x6091
+#define GL_PN_TRIANGLES_POINT_MODE_ATIX                 0x6092
+#define GL_PN_TRIANGLES_NORMAL_MODE_ATIX                0x6093
+#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATIX          0x6094
+#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATIX          0x6095
+#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATIX           0x6096
+#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATIX         0x6097
+#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATIX      0x6098
+
+#if defined(TORQUE_OS_MAC_OSX) // for the moment...
+extern void glPNTrianglesiATIX(GLenum pname, GLint param);
+extern void glPNTrianglesfATIX(GLenum pname, GLfloat param);
+#endif
+#endif
+
+typedef void (*PFNGLPNTRIANGLESIATIPROC)(GLenum pname, GLint param);
+//typedef void (APIENTRY *PFNGLPNTRIANGLESFATIPROC)(GLenum pname, GLfloat param);
+
+#define GL_NPATCH_EXT_STRING        "GL_ATIX_pn_triangles"
+#define GL_NPATCH_SETINT_STRING     "glPNTrianglesiATIX"
+typedef PFNGLPNTRIANGLESIATIPROC    PFNNPatchSetInt;
+
+#define GETINT_NPATCH_MAX_LEVEL     GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATIX
+
+#define GL_NPATCH_FLAG              GL_PN_TRIANGLES_ATIX
+
+#define SETINT_NPATCH_LOD           GL_PN_TRIANGLES_TESSELATION_LEVEL_ATIX
+
+#define SETINT_NPATCH_POINTINTERP   GL_PN_TRIANGLES_POINT_MODE_ATIX
+#define SETINT_NPATCH_NORMALINTERP  GL_PN_TRIANGLES_NORMAL_MODE_ATIX
+
+#define NPATCH_POINTINTERP_MIN      GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATIX
+#define NPATCH_POINTINTERP_MAX      GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATIX
+
+#define NPATCH_NORMALINTERP_MIN     GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATIX
+#define NPATCH_NORMALINTERP_MAX     GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATIX

+ 884 - 0
engine/source/platformAndroid/AndroidNet.cpp

@@ -0,0 +1,884 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/platform.h"
+#include "platform/event.h"
+#include "platform/platformNetAsync.unix.h"
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <errno.h>
+#include <sys/time.h>
+
+// Header clean-up by William Taysom
+#include <sys/ioctl.h>
+
+// IPX fixes from William Taysom.
+#define IPX_NODE_LEN 6
+
+// for 10.2 compatability...
+#ifndef socklen_t
+#define socklen_t unsigned int
+#endif
+
+struct sockaddr_ipx
+{
+   sa_family_t     sipx_family;
+   U16             sipx_port;
+   U32             sipx_network;
+   unsigned char   sipx_node[IPX_NODE_LEN];
+   U8              sipx_type;
+   unsigned char   sipx_zero; /* 16 byte fill */
+};
+// end wtaysom changes (May 26, 2004)
+
+#include <stdlib.h>
+
+#include "console/console.h"
+#include "game/gameInterface.h"
+#include "io/fileStream.h"
+#include "collection/vector.h"
+
+static Net::Error getLastError();
+static S32 defaultPort = 28000;
+static S32 netPort = 0;
+static int ipxSocket = InvalidSocket;
+static int udpSocket = InvalidSocket;
+
+// local enum for socket states for polled sockets
+enum SocketState
+{
+   InvalidState,
+   Connected,
+   ConnectionPending,
+   Listening,
+   NameLookupRequired
+};
+
+// the Socket structure helps us keep track of the
+// above states
+struct Socket
+{
+      Socket()
+      {
+         fd = InvalidSocket;
+         state = InvalidState;
+         remoteAddr[0] = 0;
+         remotePort = -1;
+      }
+
+      NetSocket fd;
+      S32 state;
+      char remoteAddr[256];
+      S32 remotePort;
+};
+
+// list of polled sockets
+static Vector<Socket*> gPolledSockets;
+
+static Socket* addPolledSocket(NetSocket& fd, S32 state,
+                               char* remoteAddr = NULL, S32 port = -1)
+{
+   Socket* sock = new Socket();
+   sock->fd = fd;
+   sock->state = state;
+   if (remoteAddr)
+      dStrcpy(sock->remoteAddr, remoteAddr);
+   if (port != -1)
+      sock->remotePort = port;
+   gPolledSockets.push_back(sock);
+   return sock;
+}
+
+enum {
+   MaxConnections = 1024,
+};
+   
+   
+bool netSocketWaitForWritable(NetSocket fd, S32 timeoutMs)
+{  
+   fd_set writefds;
+   timeval timeout;
+   
+   FD_ZERO(&writefds);
+   FD_SET( fd, &writefds );
+   
+   timeout.tv_sec = timeoutMs / 1000;
+   timeout.tv_usec = ( timeoutMs % 1000 ) * 1000;
+   
+   if( select(fd + 1, NULL, &writefds, NULL, &timeout) > 0 )
+      return true;
+   
+   return false;
+}
+
+bool Net::init()
+{
+   NetAsync::startAsync();
+   return(true);
+}
+
+void Net::shutdown()
+{
+   while (gPolledSockets.size() > 0)
+      closeConnectTo(gPolledSockets[0]->fd);
+
+   closePort();
+   NetAsync::stopAsync();
+}
+
+static void netToIPSocketAddress(const NetAddress *address, struct sockaddr_in *sockAddr)
+{
+   dMemset(sockAddr, 0, sizeof(struct sockaddr_in));
+   sockAddr->sin_family = AF_INET;
+   sockAddr->sin_port = htons(address->port);
+   char tAddr[20];
+   dSprintf(tAddr, 20, "%d.%d.%d.%d\n", address->netNum[0],  address->netNum[1], address->netNum[2], address->netNum[3]);
+//fprintf(stdout,"netToIPSocketAddress(): %s\n",tAddr);fflush(NULL);
+   sockAddr->sin_addr.s_addr = inet_addr(tAddr);
+}
+
+static void IPSocketToNetAddress(const struct sockaddr_in *sockAddr,  NetAddress *address)
+{
+   address->type = NetAddress::IPAddress;
+   address->port = htons(sockAddr->sin_port);
+   char *tAddr;
+   tAddr = inet_ntoa(sockAddr->sin_addr);
+//fprintf(stdout,"IPSocketToNetAddress(): %s\n",tAddr);fflush(NULL);
+   U8 nets[4];
+   nets[0] = atoi(strtok(tAddr, "."));
+   nets[1] = atoi(strtok(NULL, "."));
+   nets[2] = atoi(strtok(NULL, "."));
+   nets[3] = atoi(strtok(NULL, "."));
+//fprintf(stdout,"0 = %d, 1 = %d, 2 = %d, 3 = %d\n", nets[0], nets[1],  nets[2], nets[3]);
+   address->netNum[0] = nets[0];
+   address->netNum[1] = nets[1];
+   address->netNum[2] = nets[2];
+   address->netNum[3] = nets[3];
+}
+
+static void netToIPXSocketAddress(const NetAddress *address,  sockaddr_ipx *sockAddr)
+{
+   dMemset(sockAddr, 0, sizeof(sockaddr_ipx));
+   sockAddr->sipx_family = AF_INET;
+   sockAddr->sipx_port = htons(address->port);
+   sockAddr->sipx_network = address->netNum[0];
+   sockAddr->sipx_node[0] = address->nodeNum[0];
+   sockAddr->sipx_node[1] = address->nodeNum[1];
+   sockAddr->sipx_node[2] = address->nodeNum[2];
+   sockAddr->sipx_node[3] = address->nodeNum[3];
+   sockAddr->sipx_node[4] = address->nodeNum[4];
+   sockAddr->sipx_node[5] = address->nodeNum[5];
+}
+
+NetSocket Net::openListenPort(U16 port)
+{
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalReading())
+   {
+      U32 ret;
+      Game->journalRead(&ret);
+      return NetSocket(ret);
+   }
+#endif	//TORQUE_ALLOW_JOURNALING
+   NetSocket sock = openSocket();
+   if (sock == InvalidSocket)
+   {
+      Con::errorf("Unable to open listen socket: %s", strerror(errno));
+      return InvalidSocket;
+   }
+
+   if (bind(sock, port) != NoError)
+   {
+      Con::errorf("Unable to bind port %d: %s", port, strerror(errno));
+      ::close(sock);
+      return InvalidSocket;
+   }
+   if (listen(sock, 4) != NoError)
+   {
+      Con::errorf("Unable to listen on port %d: %s", port,  strerror(errno));
+      ::close(sock);
+      return InvalidSocket;
+   }
+
+   setBlocking(sock, false);
+   addPolledSocket(sock, Listening);
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if (Game->isJournalWriting())
+      Game->journalWrite(U32(sock));
+#endif	//TORQUE_ALLOW_JOURNALING
+   return sock;
+}
+
+NetSocket Net::openConnectTo(const char *addressString)
+{
+   if(!dStrnicmp(addressString, "ipx:", 4))
+      return InvalidSocket;
+   if(!dStrnicmp(addressString, "ip:", 3))
+      addressString += 3;  // eat off the ip:
+   char remoteAddr[256];
+   dStrcpy(remoteAddr, addressString);
+
+   char *portString = dStrchr(remoteAddr, ':');
+
+   U16 port;
+   if(portString)
+   {
+      *portString++ = 0;
+      port = htons(dAtoi(portString));
+   }
+   else
+      port = htons(defaultPort);
+
+   if(!dStricmp(remoteAddr, "broadcast"))
+      return InvalidSocket;
+
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalReading())
+   {
+      U32 ret;
+      Game->journalRead(&ret);
+      return NetSocket(ret);
+   }
+#endif	//TORQUE_ALLOW_JOURNALING
+   NetSocket sock = openSocket();
+   setBlocking(sock, false);
+
+   sockaddr_in ipAddr;
+   dMemset(&ipAddr, 0, sizeof(ipAddr));
+
+   if (inet_aton(remoteAddr, &ipAddr.sin_addr) != 0)
+   {
+      ipAddr.sin_port = port;
+      ipAddr.sin_family = AF_INET;
+      if(::connect(sock, (struct sockaddr *)&ipAddr, sizeof(ipAddr)) ==  -1 &&
+         errno != EINPROGRESS)
+      {
+         Con::errorf("Error connecting %s: %s",
+             addressString, strerror(errno));
+         ::close(sock);
+         sock = InvalidSocket;
+      }
+      if(sock != InvalidSocket) {
+         // add this socket to our list of polled sockets
+         addPolledSocket(sock, ConnectionPending);
+      }
+   }
+   else
+   {
+      // need to do an asynchronous name lookup.  first, add the socket
+      // to the polled list
+      addPolledSocket(sock, NameLookupRequired, remoteAddr, port);
+      // queue the lookup
+      gNetAsync.queueLookup(remoteAddr, sock);
+   }
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalWriting())
+      Game->journalWrite(U32(sock));
+#endif	//TORQUE_ALLOW_JOURNALING
+   return sock;
+}
+
+void Net::closeConnectTo(NetSocket sock)
+{
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalReading())
+      return;
+#endif	//TORQUE_ALLOW_JOURNALING
+
+   // if this socket is in the list of polled sockets, remove it
+   for (int i = 0; i < gPolledSockets.size(); ++i)
+      if (gPolledSockets[i]->fd == sock)
+      {
+         delete gPolledSockets[i];
+         gPolledSockets.erase(i);
+         break;
+      }
+
+   closeSocket(sock);
+}
+
+Net::Error Net::sendtoSocket(NetSocket socket, const U8 *buffer, int  bufferSize)
+{
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalReading())
+   {
+      U32 e;
+      Game->journalRead(&e);
+
+      return (Net::Error) e;
+   }
+#endif	//TORQUE_ALLOW_JOURNALING
+   
+   Net::Error e = send(socket, buffer, bufferSize);
+   
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalWriting())
+      Game->journalWrite(U32(e));
+#endif	//TORQUE_ALLOW_JOURNALING
+
+   return e;
+}
+
+bool Net::openPort(S32 port)
+{
+   if(udpSocket != InvalidSocket)
+      close(udpSocket);
+   if(ipxSocket != InvalidSocket)
+      close(ipxSocket);
+
+   udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
+   ipxSocket = socket(AF_IPX, SOCK_DGRAM, 0);
+
+   if(udpSocket != InvalidSocket)
+   {
+      Net::Error error;
+      error = bind(udpSocket, port);
+      if(error == NoError)
+         error = setBufferSize(udpSocket, 32768);
+      if(error == NoError)
+         error = setBroadcast(udpSocket, true);
+      if(error == NoError)
+         error = setBlocking(udpSocket, false);
+      if(error == NoError)
+         Con::printf("UDP initialized on port %d", port);
+      else
+      {
+         close(udpSocket);
+         udpSocket = InvalidSocket;
+         Con::printf("Unable to initialize UDP - error %d", error);
+      }
+   }
+   if(ipxSocket != InvalidSocket)
+   {
+      Net::Error error = NoError;
+      sockaddr_ipx ipxAddress;
+      memset((char *)&ipxAddress, 0, sizeof(ipxAddress));
+      ipxAddress.sipx_family = AF_IPX;
+      ipxAddress.sipx_port = htons(port);
+      S32 err = ::bind(ipxSocket, (struct sockaddr *)&ipxAddress,  sizeof(ipxAddress));
+      if(err)
+         error = getLastError();
+      if(error == NoError)
+         error = setBufferSize(ipxSocket, 32768);
+      if(error == NoError)
+         error = setBroadcast(ipxSocket, true);
+      if(error == NoError)
+         error = setBlocking(ipxSocket, false);
+      if(error == NoError)
+         Con::printf("IPX initialized on port %d", port);
+      else
+      {
+         close(ipxSocket);
+         ipxSocket = InvalidSocket;
+         Con::printf("Unable to initialize IPX - error %d", error);
+      }
+   }
+   netPort = port;
+   return ipxSocket != InvalidSocket || udpSocket != InvalidSocket;
+}
+
+void Net::closePort()
+{
+   if(ipxSocket != InvalidSocket)
+      close(ipxSocket);
+   if(udpSocket != InvalidSocket)
+      close(udpSocket);
+}
+
+Net::Error Net::sendto(const NetAddress *address, const U8 *buffer, S32  bufferSize)
+{
+#ifdef	TORQUE_ALLOW_JOURNALING
+   if(Game->isJournalReading())
+      return NoError;
+#endif	//TORQUE_ALLOW_JOURNALING
+
+   if(address->type == NetAddress::IPAddress)
+   {
+      sockaddr_in ipAddr;
+      netToIPSocketAddress(address, &ipAddr);
+      if(::sendto(udpSocket, (const char*)buffer, bufferSize, 0,
+                  (sockaddr *) &ipAddr, sizeof(sockaddr_in)) == -1)
+         return getLastError();
+      else
+         return NoError;
+   }
+    
+    return NoError;
+}
+
+void Net::process()
+{
+   sockaddr sa;
+
+   PacketReceiveEvent receiveEvent;
+   for(;;)
+   {
+      U32 addrLen = sizeof(sa);
+      S32 bytesRead = -1;
+      if(udpSocket != InvalidSocket)
+         bytesRead = recvfrom(udpSocket, (char *) receiveEvent.data,  MaxPacketDataSize, 0, &sa, &addrLen);
+      if(bytesRead == -1 && ipxSocket != InvalidSocket)
+      {
+         addrLen = sizeof(sa);
+         bytesRead = recvfrom(ipxSocket, (char *) receiveEvent.data,  MaxPacketDataSize, 0, &sa, &addrLen);
+      }
+
+      if(bytesRead == -1)
+         break;
+
+      if(sa.sa_family == AF_INET)
+         IPSocketToNetAddress((sockaddr_in *) &sa,  &receiveEvent.sourceAddress);
+      else
+         continue;
+
+      NetAddress &na = receiveEvent.sourceAddress;
+      if(na.type == NetAddress::IPAddress &&
+         na.netNum[0] == 127 &&
+         na.netNum[1] == 0 &&
+         na.netNum[2] == 0 &&
+         na.netNum[3] == 1 &&
+         na.port == netPort)
+         continue;
+      if(bytesRead <= 0)
+         continue;
+      receiveEvent.size = PacketReceiveEventHeaderSize + bytesRead;
+      Game->postEvent(receiveEvent);
+   }
+
+   // process the polled sockets.  This blob of code performs functions
+   // similar to WinsockProc in winNet.cc
+
+   if (gPolledSockets.size() == 0)
+      return;
+
+   static ConnectedNotifyEvent notifyEvent;
+   static ConnectedAcceptEvent acceptEvent;
+   static ConnectedReceiveEvent cReceiveEvent;
+
+   S32 optval;
+   socklen_t optlen = sizeof(S32);
+   S32 bytesRead;
+   Net::Error err;
+   bool removeSock = false;
+   Socket *currentSock = NULL;
+   sockaddr_in ipAddr;
+   NetSocket incoming = InvalidSocket;
+   char out_h_addr[1024];
+   int out_h_length = 0;
+
+   for (S32 i = 0; i < gPolledSockets.size();
+        /* no increment, this is done at end of loop body */)
+   {
+      removeSock = false;
+      currentSock = gPolledSockets[i];
+      switch (currentSock->state)
+      {
+         case InvalidState:
+            Con::errorf("Error, InvalidState socket in polled sockets  list");
+            break;
+         case ConnectionPending:
+            notifyEvent.tag = currentSock->fd;
+            // see if it is now connected
+            if (getsockopt(currentSock->fd, SOL_SOCKET, SO_ERROR,
+                           &optval, &optlen) == -1)
+            {
+               Con::errorf("Error getting socket options: %s",  strerror(errno));
+               notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
+               Game->postEvent(notifyEvent);
+               removeSock = true;
+            }
+            else
+            {
+               if (optval == EINPROGRESS)
+                  // still connecting...
+                  break;
+
+               if (optval == 0)
+               {
+                  // poll for writable status to be sure we're connected.
+                  bool ready = netSocketWaitForWritable(currentSock->fd,0);
+                  if(!ready)
+                     break;
+                     
+                  // connected.
+                  notifyEvent.state = ConnectedNotifyEvent::Connected;
+                  Game->postEvent(notifyEvent);
+                  currentSock->state = Connected;
+               }
+               else
+               {
+                  // some kind of error
+                  Con::errorf("Error connecting: %s", strerror(errno));
+                  notifyEvent.state =  ConnectedNotifyEvent::ConnectFailed;
+                  Game->postEvent(notifyEvent);
+                  removeSock = true;
+               }
+            }
+            break;
+         case Connected:
+            bytesRead = 0;
+            // try to get some data
+            err = Net::recv(currentSock->fd, cReceiveEvent.data,                            MaxPacketDataSize, &bytesRead);
+            if(err == Net::NoError)
+            {
+               if (bytesRead > 0)
+               {
+                  // got some data, post it
+                  cReceiveEvent.tag = currentSock->fd;
+                  cReceiveEvent.size = ConnectedReceiveEventHeaderSize +
+                     bytesRead;
+                  Game->postEvent(cReceiveEvent);
+               }
+               else
+               {
+                  // zero bytes read means EOF
+                  if (bytesRead < 0)
+                     // ack! this shouldn't happen
+                     Con::errorf("Unexpected error on socket: %s",
+                                 strerror(errno));
+
+                  notifyEvent.tag = currentSock->fd;
+                  notifyEvent.state =  ConnectedNotifyEvent::Disconnected;
+                  Game->postEvent(notifyEvent);
+                  removeSock = true;
+               }
+            }
+            else if (err != Net::NoError && err != Net::WouldBlock)
+            {
+               Con::errorf("Error reading from socket: %s",  strerror(errno));
+               notifyEvent.tag = currentSock->fd;
+               notifyEvent.state = ConnectedNotifyEvent::Disconnected;
+               Game->postEvent(notifyEvent);
+               removeSock = true;
+            }
+            break;
+         case NameLookupRequired:
+            // is the lookup complete?
+            if (!gNetAsync.checkLookup(
+                   currentSock->fd, out_h_addr, &out_h_length,
+                   sizeof(out_h_addr)))
+               break;
+
+            notifyEvent.tag = currentSock->fd;
+            if (out_h_length == -1)
+            {
+               Con::errorf("DNS lookup failed: %s",  currentSock->remoteAddr);
+               notifyEvent.state = ConnectedNotifyEvent::DNSFailed;
+               removeSock = true;
+            }
+            else
+            {
+               // try to connect
+               dMemcpy(&(ipAddr.sin_addr.s_addr), out_h_addr,  out_h_length);
+               ipAddr.sin_port = currentSock->remotePort;
+               ipAddr.sin_family = AF_INET;
+               if(::connect(currentSock->fd, (struct sockaddr *)&ipAddr,
+                            sizeof(ipAddr)) == -1)
+               {
+                  if (errno == EINPROGRESS)
+                  {
+                     notifyEvent.state =  ConnectedNotifyEvent::DNSResolved;
+                     currentSock->state = ConnectionPending;
+                  }
+                  else
+                  {
+                     Con::errorf("Error connecting to %s: %s",
+                                 currentSock->remoteAddr,  strerror(errno));
+                     notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
+                     removeSock = true;
+                  }
+               }
+               else
+               {
+                  notifyEvent.state = ConnectedNotifyEvent::Connected;
+                  currentSock->state = Connected;
+               }
+            }
+            Game->postEvent(notifyEvent);           
+            break;
+         case Listening:
+            incoming =
+               Net::accept(currentSock->fd, &acceptEvent.address);
+            if(incoming != InvalidSocket)
+            {
+               acceptEvent.portTag = currentSock->fd;
+               acceptEvent.connectionTag = incoming;
+               setBlocking(incoming, false);
+               addPolledSocket(incoming, Connected);
+               Game->postEvent(acceptEvent);
+            }
+            break;
+      }
+
+      // only increment index if we're not removing the connection,  since
+      // the removal will shift the indices down by one
+      if (removeSock)
+         closeConnectTo(currentSock->fd);
+      else
+         i++;
+   }
+}
+
+NetSocket Net::openSocket()
+{
+   int retSocket;
+   retSocket = socket(AF_INET, SOCK_STREAM, 0);
+
+   if(retSocket == InvalidSocket)
+      return InvalidSocket;
+   else
+      return retSocket;
+}
+
+Net::Error Net::closeSocket(NetSocket socket)
+{
+   if(socket != InvalidSocket)
+   {
+      // if we're quitting, allow the OS to close the sockets.
+      // this is here to work around a bug in close(). 
+      if(platState.quit)
+         return NoError;
+         
+      if(!close(socket))
+         return NoError;
+      else
+         return getLastError();
+   }
+   else
+      return NotASocket;
+}
+
+Net::Error Net::connect(NetSocket socket, const NetAddress *address)
+{
+   if(address->type != NetAddress::IPAddress)
+      return WrongProtocolType;
+   sockaddr_in socketAddress;
+   netToIPSocketAddress(address, &socketAddress);
+   if(!::connect(socket, (sockaddr *) &socketAddress,  sizeof(socketAddress)))
+      return NoError;
+   return getLastError();
+}
+
+Net::Error Net::listen(NetSocket socket, S32 backlog)
+{
+   if(!::listen(socket, backlog))
+      return NoError;
+   return getLastError();
+}
+
+NetSocket Net::accept(NetSocket acceptSocket, NetAddress *remoteAddress)
+{
+   sockaddr_in socketAddress;
+   U32 addrLen = sizeof(socketAddress);
+
+   int retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress,  &addrLen);
+   if(retVal != InvalidSocket)
+   {
+      IPSocketToNetAddress(&socketAddress, remoteAddress);
+      return retVal;
+   }
+   return InvalidSocket;
+}
+
+Net::Error Net::bind(NetSocket socket, U16 port)
+{
+   S32 error;
+
+   sockaddr_in socketAddress;
+   dMemset((char *)&socketAddress, 0, sizeof(socketAddress));
+   socketAddress.sin_family = AF_INET;
+   // It's entirely possible that there are two NIC cards.
+   // We let the user specify which one the server runs on.
+
+   // thanks to [TPG]P1aGu3 for the name
+   const char* serverIP = Con::getVariable( "Pref::Net::BindAddress" );
+   // serverIP is guaranteed to be non-0.
+   AssertFatal( serverIP, "serverIP is NULL!" );
+
+   if( serverIP[0] != '\0' ) {
+      // we're not empty
+      socketAddress.sin_addr.s_addr = inet_addr( serverIP );
+
+      if( socketAddress.sin_addr.s_addr != INADDR_NONE ) {
+     Con::printf( "Binding server port to %s", serverIP );
+      } else {
+     Con::warnf( ConsoleLogEntry::General,
+             "inet_addr() failed for %s while binding!",
+             serverIP );
+     socketAddress.sin_addr.s_addr = INADDR_ANY;
+      }
+
+   } else {
+      Con::printf( "Binding server port to default IP" );
+      socketAddress.sin_addr.s_addr = INADDR_ANY;
+   }
+
+   socketAddress.sin_port = htons(port);
+   error = ::bind(socket, (sockaddr *) &socketAddress,  sizeof(socketAddress));
+
+   if(!error)
+      return NoError;
+   return getLastError();
+}
+
+Net::Error Net::setBufferSize(NetSocket socket, S32 bufferSize)
+{
+   S32 error;
+   error = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)  &bufferSize, sizeof(bufferSize));
+   if(!error)
+      error = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)  &bufferSize, sizeof(bufferSize));
+   if(!error)
+      return NoError;
+   return getLastError();
+}
+
+Net::Error Net::setBroadcast(NetSocket socket, bool broadcast)
+{
+   S32 bc = broadcast;
+   S32 error = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc,  sizeof(bc));
+   if(!error)
+      return NoError;
+   return getLastError();
+}
+
+Net::Error Net::setBlocking(NetSocket socket, bool blockingIO)
+{
+   int notblock = !blockingIO;
+   S32 error = ioctl(socket, FIONBIO, &notblock);
+   if(!error)
+      return NoError;
+   return getLastError();
+}
+
+Net::Error Net::send(NetSocket socket, const U8 *buffer, S32 bufferSize)
+{
+   errno = 0;
+   S32 bytesWritten = ::send(socket, (const char*)buffer, bufferSize, 0);
+   if(bytesWritten == -1)
+      Con::errorf("Could not write to socket. Error: %s",strerror(errno));
+   
+   return getLastError();
+}
+
+Net::Error Net::recv(NetSocket socket, U8 *buffer, S32 bufferSize, S32  *bytesRead)
+{
+   *bytesRead = ::recv(socket, (char*)buffer, bufferSize, 0);
+   if(*bytesRead == -1)
+      return getLastError();
+   return NoError;
+}
+
+bool Net::compareAddresses(const NetAddress *a1, const NetAddress *a2)
+{
+   if((a1->type != a2->type)  ||
+      (*((U32 *)a1->netNum) != *((U32 *)a2->netNum)) ||
+      (a1->port != a2->port))
+      return false;
+
+   if(a1->type == NetAddress::IPAddress)
+      return true;
+   for(S32 i = 0; i < 6; i++)
+      if(a1->nodeNum[i] != a2->nodeNum[i])
+         return false;
+   return true;
+}
+
+bool Net::stringToAddress(const char *addressString, NetAddress  *address)
+{
+   // assume IP if it doesn't have ipx: at the front.
+
+   if(!dStrnicmp(addressString, "ip:", 3))
+      addressString += 3;  // eat off the ip:
+
+   sockaddr_in ipAddr;
+   char remoteAddr[256];
+   if(strlen(addressString) > 255)
+      return false;
+
+   dStrcpy(remoteAddr, addressString);
+
+   char *portString = dStrchr(remoteAddr, ':');
+   if(portString)
+      *portString++ = '\0';
+
+   struct hostent *hp;
+   if(!dStricmp(remoteAddr, "broadcast"))
+      ipAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
+   else
+   {
+      if (inet_aton(remoteAddr,&ipAddr.sin_addr) == 0) // error
+      {
+         if((hp = gethostbyname(remoteAddr)) == 0)
+            return false;
+         else
+            memcpy(&ipAddr.sin_addr.s_addr, hp->h_addr,  sizeof(in_addr));
+      }
+   }
+   if(portString)
+      ipAddr.sin_port = htons(dAtoi(portString));
+   else
+      ipAddr.sin_port = htons(defaultPort);
+   ipAddr.sin_family = AF_INET;
+   IPSocketToNetAddress(&ipAddr, address);
+   return true;
+}
+
+void Net::addressToString(const NetAddress *address, char  addressString[256])
+{
+   if(address->type == NetAddress::IPAddress)
+   {
+      sockaddr_in ipAddr;
+      netToIPSocketAddress(address, &ipAddr);
+
+      if(ipAddr.sin_addr.s_addr == htonl(INADDR_BROADCAST))
+         dSprintf(addressString, 256, "IP:Broadcast:%d",  ntohs(ipAddr.sin_port));
+      else
+         dSprintf(addressString, 256, "IP:%s:%d",  inet_ntoa(ipAddr.sin_addr),
+                  ntohs(ipAddr.sin_port));
+//         dSprintf(addressString, 256, "IP:%d:%d",  ipAddr.sin_addr.s_addr,
+//            ntohs(ipAddr.sin_port));
+   }
+   else
+   {
+      return;
+      dSprintf(addressString, 256,  "IPX:%.2X%.2X%.2X%.2X:%.2X%.2X%.2X%.2X%.2X%.2X:%d",
+               address->netNum[0], address->netNum[1],  address->netNum[2], address->netNum[3],
+               address->nodeNum[0], address->nodeNum[1],  address->nodeNum[2], address->nodeNum[3], address->nodeNum[4],  address->nodeNum[5],
+               address->port);
+   }
+}
+
+Net::Error getLastError()
+{
+   if (errno == EAGAIN)
+      return Net::WouldBlock;
+   if (errno == 0)
+      return Net::NoError;
+      
+   return Net::UnknownError;
+}

+ 289 - 0
engine/source/platformAndroid/AndroidOGLVideo.cpp

@@ -0,0 +1,289 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+// Portions taken from OpenGL Full Screen.c sample from Apple Computer, Inc.
+// (that's where many of the lead helper functions originated from, but code
+//  has been significantly changed & revised.)
+
+#include "platformAndroid/platformAndroid.h"
+#include "platformAndroid/platformGL.h"
+#include "platformAndroid/AndroidOGLVideo.h"
+#include "console/console.h"
+#include "math/mPoint.h"
+#include "platform/event.h"
+#include "game/gameInterface.h"
+#include "console/consoleInternal.h"
+#include "console/ast.h"
+#include "io/fileStream.h"
+#include "platformAndroid/AndroidUtil.h"
+#include "platformAndroid/AndroidEvents.h"
+#include "graphics/dgl.h"
+#include "debug/profiler.h"
+
+//Luma: Tap support
+extern void createMouseTapEvent(S32 nbrTaps, S32 x, S32 y);
+
+//extern bool createAccelMoveEvent( UIAccelerationValue *accel );
+
+extern bool setScreenOrientation(bool, bool);
+// TODO: Card Profiling code isn't doing anything.
+extern StringTableEntry gScreenOrientation;
+extern bool gScreenUpsideDown;
+
+
+//-Mat we should update the accelereometer once per frame
+U32 AccelerometerUpdateMS = sgTimeManagerProcessInterval; // defines period between accelerometer updates updates in Milliseconds
+
+#pragma mark -
+
+//-----------------------------------------------------------------------------------------
+// Creates a dummy AGL context, so that naughty objects that call OpenGL before the window
+//  exists will not crash the game.
+//  If for some reason we fail to get a default contet, assert -- something's very wrong.
+//-----------------------------------------------------------------------------------------
+void initDummyAgl(void)
+{
+}
+
+U32 nAllDevs;
+
+
+#pragma mark -
+//------------------------------------------------------------------------------
+OpenGLDevice::OpenGLDevice()
+{
+    // Set the device name:
+    mDeviceName = "OpenGL";
+    
+    // macs games are not generally full screen only
+    mFullScreenOnly = false;
+}
+
+//------------------------------------------------------------------------------
+void OpenGLDevice::initDevice()
+{
+    //instead of caling enum monitors and enumdisplaymodes on that, we're just going to put in the ones that we know we have
+    
+    mResolutionList.push_back(Resolution(320, 480, 16));
+    mResolutionList.push_back(Resolution(480, 320, 16));
+    
+    mResolutionList.push_back(Resolution(320, 480, 32));
+    mResolutionList.push_back(Resolution(480, 320, 32));
+    
+    mResolutionList.push_back(Resolution(640, 960, 16));
+    mResolutionList.push_back(Resolution(960, 640, 16));
+    
+    mResolutionList.push_back(Resolution(640, 960, 32));
+    mResolutionList.push_back(Resolution(960, 640, 32));
+    
+    mResolutionList.push_back(Resolution(768, 1024, 16));
+    mResolutionList.push_back(Resolution(1024, 768, 16));
+    
+    mResolutionList.push_back(Resolution(768, 1024, 32));
+    mResolutionList.push_back(Resolution(1024, 768, 32));
+    
+    mResolutionList.push_back(Resolution(1536, 2048, 16));
+    mResolutionList.push_back(Resolution(2048, 1536, 16));
+    
+    mResolutionList.push_back(Resolution(1536, 2048, 32));
+    mResolutionList.push_back(Resolution(2048, 1536, 32));
+    
+    mResolutionList.push_back(Resolution(640, 1136, 16));
+    mResolutionList.push_back(Resolution(1136, 640, 16));
+    
+    mResolutionList.push_back(Resolution(640, 1136, 32));
+    mResolutionList.push_back(Resolution(1136, 640, 32));
+    
+}
+
+//------------------------------------------------------------------------------
+// Activate
+//  this is called once, as a result of createCanvas() in scripts.
+//  dumps OpenGL driver info for the current screen
+//  creates an initial window via setScreenMode
+bool OpenGLDevice::activate(U32 width, U32 height, U32 bpp, bool fullScreen)
+{
+    Con::printf(" OpenGLDevice activating...");
+    
+    // gets opengl rendering capabilities of the screen pointed to by platState.hDisplay
+    // sets up dgl with the capabilities info, & reports opengl status.
+    
+    getGLCapabilities();
+    
+    // Create the window or capture fullscreen
+    if (!setScreenMode(width, height, bpp, fullScreen, true, false))
+        return false;
+    
+    // set the displayDevice pref to "OpenGL"
+    Con::setVariable("$pref::Video::displayDevice", mDeviceName);
+    
+    // set vertical sync now because it doesnt need setting every time we setScreenMode()
+    setVerticalSync(!Con::getBoolVariable("$pref::Video::disableVerticalSync"));
+    
+    return true;
+}
+
+//------------------------------------------------------------------------------
+// returns TRUE if textures need resurrecting in future...
+//------------------------------------------------------------------------------
+bool OpenGLDevice::cleanupContextAndWindow()
+{
+    Con::printf("Cleaning up the display device...");
+    return true;
+}
+
+
+//------------------------------------------------------------------------------
+void OpenGLDevice::shutdown()
+{
+    Con::printf("Shutting down the OpenGL display device...");
+}
+
+
+//------------------------------------------------------------------------------
+// This is the real workhorse function of the DisplayDevice...
+//
+bool OpenGLDevice::setScreenMode(U32 width, U32 height, U32 bpp, bool fullScreen, bool forceIt, bool repaint)
+{
+    
+    Con::printf(" set screen mode %i x %i x %i, %s, %s, %s", width, height, bpp,
+                fullScreen ? "fullscreen" : "windowed",
+                forceIt ? "force it" : "dont force it",
+                repaint ? "repaint" : "dont repaint"
+                );
+    
+    // validation, early outs --------------------------------------------------
+    // sanity check. some scripts are liable to pass in bad values.
+    if (!bpp)
+        bpp = platState.desktopBitsPixel;
+    
+    Resolution newRes = Resolution(width, height, bpp);
+    
+    // if no values changing and we're not forcing a change, kick out. prevents thrashing.
+    if (!forceIt && smIsFullScreen == fullScreen && smCurrentRes == newRes)
+        return (true);
+    
+    // we have a new context, this is now safe to do:
+    // delete any contexts or windows that exist, and kill the texture manager.
+    bool needResurrect = cleanupContextAndWindow();
+    
+    Con::printf(">> Attempting to change display settings to %s %dx%dx%d...",
+                fullScreen ? "fullscreen" : "windowed", newRes.w, newRes.h, newRes.bpp);
+    
+    // set torque variables ----------------------------------------------------
+    // save window size for dgl
+    Platform::setWindowSize(newRes.w, newRes.h);
+    
+    // update smIsFullScreen and pref
+    smIsFullScreen = fullScreen;
+    
+    Con::setBoolVariable("$pref::Video::fullScreen", smIsFullScreen);
+    
+    // save resolution
+    smCurrentRes = newRes;
+    
+    // save resolution to prefs
+    char buf[32];
+    
+    if (fullScreen)
+    {
+        dSprintf(buf, sizeof(buf), "%d %d %d", newRes.w, newRes.h, newRes.bpp);
+        Con::setVariable("$pref::Video::resolution", buf);
+    }
+    else
+    {
+        dSprintf(buf, sizeof(buf), "%d %d", newRes.w, newRes.h);
+        Con::setVariable("$pref::Video::windowedRes", buf);
+    }
+    
+    // begin rendering again ----------------------------------------------------
+    if (needResurrect)
+    {
+        // Reload the textures gl names
+        Con::printf("Resurrecting the texture manager...");
+        Game->textureResurrect();
+    }
+    
+    if (repaint)
+        Con::evaluate("resetCanvas();");
+    
+    return true;
+}
+
+
+//------------------------------------------------------------------------------
+void OpenGLDevice::swapBuffers()
+{
+    [platState.ctx swapBuffers];
+}
+
+
+//------------------------------------------------------------------------------
+const char *OpenGLDevice::getDriverInfo()
+{
+    return NULL;
+}
+
+struct AndroidGamma
+{
+    F32 r, g, b;
+    F32 scale;
+};
+
+//------------------------------------------------------------------------------
+bool OpenGLDevice::getGammaCorrection(F32 &g)
+{
+    return true;
+}
+
+//------------------------------------------------------------------------------
+bool OpenGLDevice::setGammaCorrection(F32 g)
+{
+    return true;
+}
+
+//------------------------------------------------------------------------------
+bool OpenGLDevice::setVerticalSync(bool on)
+{
+    return true;
+}
+
+
+Resolution Video::getDesktopResolution()
+{
+    return Resolution(ANDROID_DEFAULT_RESOLUTION_X, ANDROID_DEFAULT_RESOLUTION_Y, ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH);
+}
+
+DisplayDevice *OpenGLDevice::create()
+{
+    // set up a dummy default agl context.
+    // this will be replaced later with the window's context,
+    // but we need agl_ctx to be valid at all times,
+    // since some things try to make gl calls before the device is activated.
+    
+    // create the DisplayDevice
+    OpenGLDevice *newOGLDevice = new OpenGLDevice();
+    
+    newOGLDevice->initDevice();
+    
+    return newOGLDevice;
+}

+ 60 - 0
engine/source/platformAndroid/AndroidOGLVideo.h

@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef _ANDROIDOGLVIDEO_H_
+#define _ANDROIDOGLVIDEO_H_
+
+#import "UIKit/UIKit.h"
+#import "UIKit/UIAccelerometer.h"
+
+#include "platform/platformVideo.h"
+
+class OpenGLDevice : public DisplayDevice
+{
+private:
+    
+    /// Gamma value
+    F32 mGamma;
+    
+    /// Cleans up the opengl context, and destroys the rendering window
+    bool cleanupContextAndWindow();
+    
+public:
+    OpenGLDevice();
+    static DisplayDevice* create();
+    
+    /// The following are inherited from DisplayDevice
+    void initDevice();
+    bool activate( U32 width, U32 height, U32 bpp, bool fullScreen );
+    
+    void shutdown();
+    
+    bool setScreenMode( U32 width, U32 height, U32 bpp, bool fullScreen, bool forceIt = false, bool repaint = true );
+    void swapBuffers();
+    
+    const char* getDriverInfo();
+    bool getGammaCorrection(F32 &g);
+    bool setGammaCorrection(F32 g);
+    bool setVerticalSync( bool on );
+};
+
+#endif //ANDROIDOGLVIDEO_H_

+ 237 - 0
engine/source/platformAndroid/AndroidOutlineGL.cpp

@@ -0,0 +1,237 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+// The debug render modes are only built in a debug build, 
+// partially because a release build should not need them
+// and partially because using aglMacro.h or cglMacro.h would prevent us from
+// playing this little function-pointer-hijacking trick
+#if defined(TORQUE_DEBUG)
+
+#define NO_REDEFINE_GL_FUNCS
+
+#include "platformAndroid/platformGL.h"
+#include "console/console.h"
+
+bool gOutlineEnabled = false;
+
+void (* glDrawElementsProcPtr) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices) = glDrawElements;
+void (* glDrawArraysProcPtr) (GLenum mode, GLint first, GLsizei count) = glDrawArrays;
+void (* glNormDrawElements) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices) = glDrawElements;
+void (* glNormDrawArrays) (GLenum mode, GLint first, GLsizei count) = glDrawArrays;      
+
+
+/// A utility for the outline drawing routines
+static U32 getIndex(GLenum type, const void *indices, U32 i)
+{
+   if(type == GL_UNSIGNED_BYTE)
+      return ((U8 *) indices)[i];
+   else if(type == GL_UNSIGNED_SHORT)
+      return ((U16 *) indices)[i];
+   else
+      return ((U32 *) indices)[i];
+}
+
+void glOutlineDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
+{ 
+   if(mode == GL_POLYGON)
+      mode = GL_LINE_LOOP;
+
+   if(mode == GL_POINTS || mode == GL_LINE_STRIP || mode == GL_LINE_LOOP || mode == GL_LINES)   
+      glDrawElements( mode, count, type, indices );
+   else
+   {
+      glBegin(GL_LINES);
+      if(mode == GL_TRIANGLE_STRIP)
+      {
+         U32 i;
+         for(i = 0; i < count - 1; i++)
+         {
+            glArrayElement(getIndex(type, indices, i));
+            glArrayElement(getIndex(type, indices, i + 1));
+            if(i + 2 != count)
+            {
+               glArrayElement(getIndex(type, indices, i));
+               glArrayElement(getIndex(type, indices, i + 2));
+            }
+         }
+      }
+      else if(mode == GL_TRIANGLE_FAN)
+      {
+         for(U32 i = 1; i < count; i ++)
+         {
+            glArrayElement(getIndex(type, indices, 0));
+            glArrayElement(getIndex(type, indices, i));
+            if(i != count - 1)
+            {
+               glArrayElement(getIndex(type, indices, i));
+               glArrayElement(getIndex(type, indices, i + 1));
+            }
+         }
+      }
+      else if(mode == GL_TRIANGLES)
+      {
+         for(U32 i = 3; i <= count; i += 3)
+         {
+            glArrayElement(getIndex(type, indices, i - 3));
+            glArrayElement(getIndex(type, indices, i - 2));
+            glArrayElement(getIndex(type, indices, i - 2));
+            glArrayElement(getIndex(type, indices, i - 1));
+            glArrayElement(getIndex(type, indices, i - 3));
+            glArrayElement(getIndex(type, indices, i - 1));
+         }
+      }
+      else if(mode == GL_QUADS)
+      {
+         for(U32 i = 4; i <= count; i += 4)
+         {
+            glArrayElement(getIndex(type, indices, i - 4));
+            glArrayElement(getIndex(type, indices, i - 3));
+            glArrayElement(getIndex(type, indices, i - 3));
+            glArrayElement(getIndex(type, indices, i - 2));
+            glArrayElement(getIndex(type, indices, i - 2));
+            glArrayElement(getIndex(type, indices, i - 1));
+            glArrayElement(getIndex(type, indices, i - 4));
+            glArrayElement(getIndex(type, indices, i - 1));
+         }
+      }
+      else if(mode == GL_QUAD_STRIP)
+      {
+         if(count < 4)
+            return;
+         glArrayElement(getIndex(type, indices, 0));
+         glArrayElement(getIndex(type, indices, 1));
+         for(U32 i = 4; i <= count; i += 2)
+         {
+            glArrayElement(getIndex(type, indices, i - 4));
+            glArrayElement(getIndex(type, indices, i - 2));
+
+            glArrayElement(getIndex(type, indices, i - 3));
+            glArrayElement(getIndex(type, indices, i - 1));
+
+            glArrayElement(getIndex(type, indices, i - 2));
+            glArrayElement(getIndex(type, indices, i - 1));
+         }
+      }
+      glEnd();
+   }
+}
+
+void glOutlineDrawArrays(GLenum mode, GLint first, GLsizei count) 
+{ 
+   if(mode == GL_POLYGON)
+      mode = GL_LINE_LOOP;
+
+   if(mode == GL_POINTS || mode == GL_LINE_STRIP || mode == GL_LINE_LOOP || mode == GL_LINES)   
+      glDrawArrays( mode, first, count );
+   else
+   {
+      glBegin(GL_LINES);
+      if(mode == GL_TRIANGLE_STRIP)
+      {
+         U32 i;
+         for(i = 0; i < count - 1; i++) 
+         {
+            glArrayElement(first + i);
+            glArrayElement(first + i + 1);
+            if(i + 2 != count)
+            {
+               glArrayElement(first + i);
+               glArrayElement(first + i + 2);
+            }
+         }
+      }
+      else if(mode == GL_TRIANGLE_FAN)
+      {
+         for(U32 i = 1; i < count; i ++)
+         {
+            glArrayElement(first);
+            glArrayElement(first + i);
+            if(i != count - 1)
+            {
+               glArrayElement(first + i);
+               glArrayElement(first + i + 1);
+            }
+         }
+      }
+      else if(mode == GL_TRIANGLES)
+      {
+         for(U32 i = 3; i <= count; i += 3)
+         {
+            glArrayElement(first + i - 3);
+            glArrayElement(first + i - 2);
+            glArrayElement(first + i - 2);
+            glArrayElement(first + i - 1);
+            glArrayElement(first + i - 3);
+            glArrayElement(first + i - 1);
+         }
+      }
+      else if(mode == GL_QUADS)
+      {
+         for(U32 i = 4; i <= count; i += 4)
+         {
+            glArrayElement(first + i - 4);
+            glArrayElement(first + i - 3);
+            glArrayElement(first + i - 3);
+            glArrayElement(first + i - 2);
+            glArrayElement(first + i - 2);
+            glArrayElement(first + i - 1);
+            glArrayElement(first + i - 4);
+            glArrayElement(first + i - 1);
+         }
+      }
+      else if(mode == GL_QUAD_STRIP)
+      {
+         if(count < 4)
+            return;
+         glArrayElement(first + 0);
+         glArrayElement(first + 1);
+         for(U32 i = 4; i <= count; i += 2)
+         {
+            glArrayElement(first + i - 4);
+            glArrayElement(first + i - 2);
+
+            glArrayElement(first + i - 3);
+            glArrayElement(first + i - 1);
+
+            glArrayElement(first + i - 2);
+            glArrayElement(first + i - 1);
+         }
+      }
+      glEnd();
+   }
+}
+
+ConsoleFunction(GLEnableOutline,void,2,2,"GLEnableOutline( true | false ) - sets whether to render wireframe") 
+{
+   gOutlineEnabled = dAtob(argv[1]);
+   if(gOutlineEnabled)
+   {
+      glDrawElementsProcPtr = glOutlineDrawElements;
+      glDrawArraysProcPtr = glOutlineDrawArrays;
+      Con::printf("swapped to outline mode funcs");
+   } else {
+      glDrawElementsProcPtr = glDrawElements;
+      glDrawArraysProcPtr = glDrawArrays;
+      Con::printf("swapped to normal funcs");
+   }
+}
+#endif

+ 51 - 0
engine/source/platformAndroid/AndroidOutlineGL.h

@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef __ANDROIDOUTLINE__
+#define __ANDROIDOUTLINE__
+
+#if defined(TORQUE_DEBUG)
+#ifndef __GL_OUTLINE_FUNCS__
+#define __GL_OUTLINE_FUNCS__
+
+extern bool gOutlineEnabled;
+
+extern void (* glDrawElementsProcPtr) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+extern void (* glDrawArraysProcPtr) (GLenum mode, GLint first, GLsizei count);
+
+void glOutlineDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+void glOutlineDrawArrays(GLenum mode, GLint first, GLsizei count);
+
+extern void (* glNormDrawElements) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+extern void (* glNormDrawArrays) (GLenum mode, GLint first, GLsizei count);
+
+#ifndef NO_REDEFINE_GL_FUNCS
+#define glDrawElements glDrawElementsProcPtr
+#define glDrawArrays glDrawArraysProcPtr
+#else 
+//#warning glDrawElements and glDrawArrays not redefined
+#endif // NO_REDEFINE_GL_FUNCS
+#endif // __GL_OUTLINE_FUNCS__
+#endif // TORQUE_DEBUG
+
+#endif // __ANDROIDOUTLINE__
+

+ 217 - 0
engine/source/platformAndroid/AndroidPlatform.cpp

@@ -0,0 +1,217 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+
+
+#include <unistd.h>
+#include "platform/platform.h"
+#include "console/console.h"
+#include "string/stringTable.h"
+#include "platform/platformInput.h"
+#include "platform/threads/thread.h"
+
+
+#pragma mark ---- Various Directories ----
+//-----------------------------------------------------------------------------
+const char* Platform::getUserDataDirectory() 
+{
+   // application support directory is most in line with the current usages of this function.
+   // this may change with later usage
+   // perhaps the user data directory should be pref-controlled?
+   //NSString *nsDataDir = [@"~/Library/Application Support/" stringByStandardizingPath];
+    //-Mat using Documents directory in same folder as .app 
+   //TODO: replace objc
+	/*NSString *nsDataDir = [@"~/Documents/" stringByStandardizingPath];
+   return StringTable->insert([nsDataDir UTF8String]);
+   */
+	return StringTable->insert("");
+
+}
+
+//-----------------------------------------------------------------------------
+const char* Platform::getUserHomeDirectory() 
+{
+	//TODO: replace objc
+		/*
+   return StringTable->insert([[@"~/" stringByStandardizingPath] UTF8String]);
+   */
+	return StringTable->insert("");
+}
+
+//-----------------------------------------------------------------------------
+StringTableEntry Platform::osGetTemporaryDirectory()
+{
+	//TODO: replace objc
+   /*NSString *tdir = NSTemporaryDirectory();
+   const char *path = [tdir UTF8String];
+   return StringTable->insert(path);
+   */
+	return StringTable->insert("");
+}
+
+//-----------------------------------------------------------------------------
+S32 Platform::messageBox(const UTF8 *title, const UTF8 *message, MBButtons buttons, MBIcons icon)
+{
+    Platform::AlertOK( title, message );//<Mat> maybe add in a a way to do other buttons
+    return 1;
+}
+
+#pragma mark ---- File IO ----
+//-----------------------------------------------------------------------------
+bool Platform::pathCopy(const char* source, const char* dest, bool nooverwrite)
+{
+	//TODO: replace objc
+	/*
+   NSFileManager *manager = [NSFileManager defaultManager];
+   @autoreleasepool {
+   
+      NSString *nsource = [@(source) stringByStandardizingPath];
+      NSString *ndest   = [@(dest) stringByStandardizingPath];
+      NSString *ndestFolder = [ndest stringByDeletingLastPathComponent];
+      
+      if(! [manager fileExistsAtPath:nsource])
+      {
+         Con::errorf("Platform::pathCopy: no file exists at %s",source);
+         return false;
+      }
+       
+       //Catcher for the errors.
+       NSError* returnValue = nil;
+      
+      if( [manager fileExistsAtPath:ndest] )
+      {
+         if(nooverwrite)
+         {
+            Con::errorf("Platform::pathCopy file already exists at %s",dest);
+            return false;
+         }
+          
+         Con::warnf("Deleting files at path: %s", dest);
+         bool deleted = [manager removeItemAtPath:ndest error:&returnValue];
+         if(!deleted)
+         {
+            Con::errorf("Copy failed! Could not delete files at path: %s", dest);
+            return false;
+         }
+      }
+      
+      if([manager fileExistsAtPath:ndestFolder] == NO)
+      {
+         ndestFolder = [ndestFolder stringByAppendingString:@"/"]; // createpath requires a trailing slash
+         Platform::createPath([ndestFolder UTF8String]);
+      }
+      
+      bool ret = [manager copyItemAtPath:nsource toPath:ndest error:&returnValue];
+      
+      return ret;
+   }
+   */
+	return false;
+   
+}
+
+//-----------------------------------------------------------------------------
+bool Platform::fileRename(const char *source, const char *dest)
+{
+	//TODO: replace objc
+	/*
+   if(source == NULL || dest == NULL)
+      return false;
+      
+   NSFileManager *manager = [NSFileManager defaultManager];
+   
+   NSString *nsource = [manager stringWithFileSystemRepresentation:source length:dStrlen(source)];
+   NSString *ndest   = [manager stringWithFileSystemRepresentation:dest length:dStrlen(dest)];
+   
+   if(! [manager fileExistsAtPath:nsource])
+   {
+      Con::errorf("Platform::fileRename: no file exists at %s",source);
+      return false;
+   }
+   
+   if( [manager fileExistsAtPath:ndest] )
+   {
+      Con::warnf("Platform::fileRename: Deleting files at path: %s", dest);
+   }
+    
+    NSError* returnValue = NULL;
+   
+   bool ret = [manager moveItemAtPath:nsource toPath:ndest error:&returnValue];
+  
+   return ret;
+   */
+   return false;
+}
+
+
+#pragma mark ---- ShellExecute ----
+class ExecuteThread : public Thread
+{
+   const char* zargs;
+   const char* directory;
+   const char* executable;
+public:
+   ExecuteThread(const char *_executable, const char *_args /* = NULL */, const char *_directory /* = NULL */) : Thread(0, NULL, false, true)
+   {
+      zargs = dStrdup(_args);
+      directory = dStrdup(_directory);
+      executable = dStrdup(_executable);
+      start();
+   }
+   
+   virtual void run(void* arg);
+};
+
+static char* _unDoubleQuote(char* arg)
+{
+   U32 len = dStrlen(arg);
+   if(!len)
+      return arg;
+
+   if(arg[0] == '"' && arg[len-1] == '"')
+   {
+      arg[len - 1] = '\0';
+      return arg + 1;
+   }
+   return arg;
+}
+
+void ExecuteThread::run(void* arg)
+{
+
+}
+
+ConsoleFunction(shellExecute, bool, 2, 4, "(executable, [args], [directory])")
+{
+   return true; // Bug: BPNC error: need feedback on whether the command was sucessful
+}
+
+
+void Input::setCursorShape(U32 cursorID)
+{
+    //no cursors on Android except Torque cursors
+}
+
+void Input::setCursorState(bool on)
+{
+}
+

+ 81 - 0
engine/source/platformAndroid/AndroidProcessControl.cpp

@@ -0,0 +1,81 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/event.h"
+#include "game/gameInterface.h"
+#include "platformAndroid/AndroidEvents.h"
+#include <pthread.h>
+
+
+void Platform::postQuitMessage(const U32 in_quitVal)
+{
+   platState.quit = true;
+   Event quitEvent;
+   quitEvent.type = QuitEventType;
+
+   Game->postEvent(quitEvent);
+}
+
+void Platform::debugBreak()
+{
+   Platform::outputDebugString((const char *)"\pDEBUG_BREAK!");
+}
+
+void Platform::forceShutdown(S32 returnValue)
+{
+   exit(returnValue);
+}   
+
+void Platform::restartInstance()
+{
+   // execl() leaves open file descriptors open, that's the main reason it's not
+   // used here. We want to start fresh.
+   
+   if( Game->isRunning() )
+   {
+      Con::errorf("The game is still running, we cant relaunch now!");
+      return;
+   }
+   //TODO: replace
+   /*
+   // get the path to the torque executable
+   CFBundleRef mainBundle =  CFBundleGetMainBundle();
+   CFURLRef execURL = CFBundleCopyExecutableURL(mainBundle);
+   CFStringRef execString = CFURLCopyFileSystemPath(execURL, kCFURLPOSIXPathStyle);
+
+   // append ampersand so that we can launch without blocking.
+   // encase in quotes so that spaces in the path are accepted.
+   CFMutableStringRef mut = CFStringCreateMutableCopy(NULL, 0, execString);
+   CFStringInsert(mut, 0, CFSTR("\""));
+   CFStringAppend(mut, CFSTR("\" & "));
+   
+   U32 len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(mut), kCFStringEncodingUTF8);
+   char *execCString = new char[len+1];
+   CFStringGetCString(mut, execCString, len, kCFStringEncodingUTF8);
+   execCString[len - 1] = '\0';
+   
+   Con::printf("---- %s -----",execCString);
+   system(execCString);
+   delete[] execCString;
+   */
+}

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

@@ -0,0 +1,257 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+//
+//  AndroidMiniProfiler.mm
+//  Torque2D
+//
+//  Created by puap on 9/26/08.
+//  Copyright 2008  PUAP. All rights reserved.
+//
+
+#import "AndroidProfiler.h"
+
+//PUAP
+//--------------------------------------------------------------------------------------------------------------------------------------------
+AndroidProfilerData g_AndroidProfilerData[ANDROID_PROFILER_MAX_CALLS];
+int	g_AndroidProfilerCount = 0;
+bool g_AndroidProfilerReady = false;
+
+void AndroidProfilerResetAll() {
+	for(int i=0; i<Android_PROFILER_MAX_CALLS; i++){
+		g_AndroidProfilerData[i].name = NULL;
+		g_AndroidProfilerData[i].timeMach = 0;
+		g_AndroidProfilerData[i].timeMS = 0;
+		g_AndroidProfilerData[i].type = 0;
+		g_AndroidProfilerData[i].invokes = 0;
+	}
+	g_AndroidProfilerCount = 0;
+}
+
+
+void AndroidProfilerProfilerInit() {
+	g_AndroidProfilerReady = true;
+	
+	AndroidProfilerResetAll();
+	printf( "\n\nIniting PUAP Profiler\n");
+}
+
+
+void AndroidProfilerStart( const char *name ) {
+	if( g_AndroidProfilerReady ) {
+
+		int i = g_AndroidProfilerCount++;
+		g_AndroidProfilerData[i].name = name;
+		g_AndroidProfilerData[i].timeMach = mach_absolute_time();
+		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
+		g_AndroidProfilerData[i].type = 0;
+		g_AndroidProfilerData[i].invokes = 0;
+	
+		if(g_AndroidProfilerCount >= ANDROID_PROFILER_MAX_CALLS){
+			g_AndroidProfilerReady = false;
+		}
+	}
+}	
+
+void AndroidProfilerEnd( const char *name ) {
+	if( g_AndroidProfilerReady ) {
+
+		int i = g_AndroidProfilerCount++;
+		g_AndroidProfilerData[i].name = name;
+		g_AndroidProfilerData[i].timeMach = mach_absolute_time();
+		g_AndroidProfilerData[i].timeMS = Platform::getRealMilliseconds();
+		g_AndroidProfilerData[i].type = 1;
+		g_AndroidProfilerData[i].invokes = 0;
+
+		if(g_AndroidProfilerCount >= ANDROID_PROFILER_MAX_CALLS){
+			g_AndroidProfilerReady = false;
+	}	
+	}
+}
+
+int AndroidProfilerFindProfileEnd( const char *name, int startCount){
+	int invokes = 0;
+	for( int i = (startCount+1); i < g_AndroidProfilerCount; i++ ) {
+		if(g_AndroidProfilerData[i].name == name || dStrcmp(g_AndroidProfilerData[i].name, name)==0){
+			if(g_AndroidProfilerData[i].type == 1){
+				if(invokes == 0){
+					return i;
+	}
+				else{
+					g_AndroidProfilerData[i].invokes = invokes;
+					invokes--;
+	}
+}
+			else{
+				invokes++;
+				g_AndroidProfilerData[i].invokes = invokes;
+		}
+	}
+	}
+	return -1;
+}
+
+int AndroidProfilerGetCount(){
+	return g_AndroidProfilerCount;
+}
+
+char pfbuffer[1024];
+void AndroidProfilerPrintResult( int item ) {
+
+	if(g_AndroidProfilerData[item].type == 0){
+		int endItem = AndroidProfilerFindProfileEnd(g_AndroidProfilerData[item].name, item);
+		if(endItem < 0){
+			return; //didn't find the end of this one
+}
+		U32 startTimeMS = g_AndroidProfilerData[item].timeMS;
+		U32 endTimeMS = g_AndroidProfilerData[endItem].timeMS;
+
+		dSprintf(pfbuffer, 1024, "%s, %d, %d, %d\n",
+				 g_AndroidProfilerData[item].name, startTimeMS, endTimeMS, endTimeMS - startTimeMS);
+		printf( pfbuffer, "%s" );
+
+	}
+}
+
+void AndroidProfilerPrintAllResults() {
+	
+	dSprintf(pfbuffer, 1024, "\n\n \t Time Per Frame \t Average Time \t Calls Per Frame (avg) \t Time Per Call \t Name \n" );
+	printf("%s", pfbuffer);
+	
+	for( int i = 0; i < g_AndroidProfilerCount; i++ ) {
+		AndroidProfilerPrintResult( i );
+	}
+	
+	dSprintf(pfbuffer, 1024, "\n 	<----------------------------------------------------------------------------------->\n " );
+	printf("%s", pfbuffer);
+}
+
+
+//-Mat get instruction names
+
+/// The opcodes for the TorqueScript VM.
+const char *InstructionName[] =  {
+"OP_FUNC_DECL",
+"OP_CREATE_OBJECT",
+"OP_ADD_OBJECT",
+"OP_END_OBJECT",
+"OP_JMPIFFNOT",
+"OP_JMPIFNOT",
+"OP_JMPIFF",
+"OP_JMPIF",
+"OP_JMPIFNOT_NP",
+"OP_JMPIF_NP",
+"OP_JMP",
+"OP_RETURN",
+"OP_CMPEQ",
+"OP_CMPGR",
+"OP_CMPGE",
+"OP_CMPLT",
+"OP_CMPLE",
+"OP_CMPNE",
+"OP_XOR",
+"OP_MOD",
+"OP_BITAND",
+"OP_BITOR",
+"OP_NOT",
+"OP_NOTF",
+"OP_ONESCOMPLEMENT",
+
+"OP_SHR",
+"OP_SHL",
+"OP_AND",
+"OP_OR",
+
+"OP_ADD",
+"OP_SUB",
+"OP_MUL",
+"OP_DIV",
+"OP_NEG",
+
+"OP_SETCURVAR",
+"OP_SETCURVAR_CREATE",
+"OP_SETCURVAR_ARRAY",
+"OP_SETCURVAR_ARRAY_CREATE",
+
+"OP_LOADVAR_UINT",
+"OP_LOADVAR_FLT",
+"OP_LOADVAR_STR",
+
+"OP_SAVEVAR_UINT",
+"OP_SAVEVAR_FLT",
+"OP_SAVEVAR_STR",
+
+"OP_SETCUROBJECT",
+"OP_SETCUROBJECT_NEW",
+"OP_SETCUROBJECT_INTERNAL",
+
+"OP_SETCURFIELD",
+"OP_SETCURFIELD_ARRAY",
+
+"OP_LOADFIELD_UINT",
+"OP_LOADFIELD_FLT",
+"OP_LOADFIELD_STR",
+
+"OP_SAVEFIELD_UINT",
+"OP_SAVEFIELD_FLT",
+"OP_SAVEFIELD_STR",
+
+"OP_STR_TO_UINT",
+"OP_STR_TO_FLT",
+"OP_STR_TO_NONE",
+"OP_FLT_TO_UINT",
+"OP_FLT_TO_STR",
+"OP_FLT_TO_NONE",
+"OP_UINT_TO_FLT",
+"OP_UINT_TO_STR",
+"OP_UINT_TO_NONE",
+
+"OP_LOADIMMED_UINT",
+"OP_LOADIMMED_FLT",
+"OP_TAG_TO_STR",
+"OP_LOADIMMED_STR",
+"OP_DOCBLOCK_STR",
+"OP_LOADIMMED_IDENT",
+
+"OP_CALLFUNC_RESOLVE",
+"OP_CALLFUNC",
+
+"OP_ADVANCE_STR",
+"OP_ADVANCE_STR_APPENDCHAR",
+"OP_ADVANCE_STR_COMMA",
+"OP_ADVANCE_STR_NUL",
+"OP_REWIND_STR",
+"OP_TERMINATE_REWIND_STR",
+"OP_COMPARE_STR",
+
+"OP_PUSH",
+"OP_PUSH_FRAME",
+
+"OP_BREAK",
+
+"OP_INVALID"
+};
+
+
+const char *getInstructionName( int index ) {
+	return InstructionName[index];
+}

+ 83 - 0
engine/source/platformAndroid/AndroidProfiler.h

@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+//
+//  AndroidMiniProfiler.h
+//  Torque2D
+//
+//  Created by puap on 9/26/08.
+//  Copyright 2008  PUAP. All rights reserved.
+//
+
+#ifndef _ANDROID_PROFILER_H
+#define _ANDROID_PROFILER_H
+
+#include "torqueConfig.h"
+
+#ifdef TORQUE_OS_ANDROID
+//#define TORQUE_OS_ANDROID_PROFILE
+
+#define ANDROID_PROFILER_START( _x ) AndroidProfilerProfileStartName( #_x );
+#define ANDROID_PROFILER_END( _x )	AndroidProfilerProfileEndName( #_x );
+
+//--------------------------------------------------------------------------------------------------------------------------------------------
+
+#include <stdio.h>
+#include "collection/vector.h"
+#import <mach/mach_time.h>
+#include "console/console.h"
+
+#define ANDROID_PROFILER_MAX_CALLS 256
+
+class AndroidProfilerData {
+public:
+	//make an array of these s we can still count in recursive functions
+	U32 timeMach;//time stamp
+	U32 timeMS;//time stamp
+	const char *name;//name of this profile
+	int type; //0 for start 1 for end
+	int invokes;//Number of times we have recursed into this profile. Used with start[]
+};
+
+
+//PUAP
+//--------------------------------------------------------------------------------------------------------------------------------------------
+
+void AndroidProfilerResetAll();
+void AndroidProfilerProfilerInit();
+int AndroidProfilerGetCount();
+
+void AndroidProfilerStart( const char *name );
+void AndroidProfilerEnd( const char *name );
+
+int AndroidProfilerFindProfileEnd( const char *name, int startCount);
+
+void AndroidProfilerPrintResult( int item );
+void AndroidProfilerPrintAllResults();
+
+//-Mat to get instruction names
+const char *getInstructionName( int index );
+
+
+#endif//TORQUE_OS_ANDROID
+
+#endif// _ANDROID_PROFILER_H

+ 113 - 0
engine/source/platformAndroid/AndroidSemaphore.cpp

@@ -0,0 +1,113 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+// platformSemaphore.h does not ask for any inter process communication,
+// and the posix semaphores require a file to be created on disk.
+// which could create annoyances if the appication crashes...
+// so we'll just roll our own semaphore here.
+
+// note: this is not a bulletproof solution to the starving problem...
+// see: The Little Book of Semapores, by Allen B. Downey, at http://greenteapress.com/semaphores/
+
+#include <pthread.h>
+#include "platform/platform.h"
+#include "platform/threads/semaphore.h"
+
+struct PlatformSemaphore
+{
+   pthread_mutex_t mDarkroom;
+//   pthread_mutex_t mFoyer; // second lock, to help control starving.
+   pthread_cond_t  mCond;
+   S32 count;
+};
+
+Semaphore::Semaphore(S32 initialCount)
+{
+   bool ok;
+   PlatformSemaphore* semaphore = new PlatformSemaphore();
+   ok = pthread_mutex_init(&semaphore->mDarkroom,NULL);
+   AssertFatal(ok == 0,"Create semaphore failed at creating mutex mDarkroom.");
+//   ok = pthread_mutex_init(&semaphore->mFoyer,NULL);
+//   AssertFatal(ok != 0,"Create semaphore failed at creating mutex mFoyer.");
+   ok = pthread_cond_init(&semaphore->mCond,NULL);
+   AssertFatal(ok == 0,"Create semaphore failed at creating condition mCond.");
+   
+   semaphore->count = initialCount;
+   mData = semaphore;
+}
+
+Semaphore::~Semaphore()
+{
+   pthread_mutex_destroy(&mData->mDarkroom);
+//   pthread_mutex_destroy(&mData->mFoyer);
+   pthread_cond_destroy(&mData->mCond);
+   
+   delete mData;
+}
+
+bool Semaphore::acquire( bool block, S32 timeoutMS )
+{ 
+	
+   bool ok;
+   AssertFatal(mData, "Semaphore::acquireSemaphore: invalid semaphore");
+   
+   ok = pthread_mutex_lock(&mData->mDarkroom);
+   AssertFatal(ok == 0,"Mutex Lock failed on mDarkroom in acquireSemaphore().");
+   
+   if(mData->count <= 0 && !block) {
+      ok = pthread_mutex_unlock(&mData->mDarkroom);
+      AssertFatal(ok == 0,"Mutex Unlock failed on mDarkroom when not blocking in acquireSemaphore().");
+      return false;
+   }
+   
+   
+   while( mData->count <= 0 )
+   {
+      ok = pthread_cond_wait(&mData->mCond, &mData->mDarkroom); // releases mDarkroom while blocked.
+      AssertFatal(ok == 0,"Waiting on mCond failed in acquireSemaphore().");
+   }   
+   
+   mData->count--;
+   
+   ok = pthread_mutex_unlock(&mData->mDarkroom);
+   AssertFatal(ok == 0,"Mutex Unlock failed on mDarkroom when leaving acquireSemaphore().");
+   
+   return true;
+}
+
+void Semaphore::release()
+{
+   bool ok;
+   AssertFatal(mData, "Semaphore::releaseSemaphore: invalid semaphore");
+   
+   ok = pthread_mutex_lock(&mData->mDarkroom);
+   AssertFatal(ok == 0,"Mutex Lock failed on mDarkroom in releaseSemaphore().");   
+   
+   mData->count++;
+   if(mData->count > 0) {
+      ok = pthread_cond_signal(&mData->mCond);
+      AssertFatal(ok == 0,"Signaling mCond failed in releaseSemaphore().");  
+   }
+   
+   ok = pthread_mutex_unlock(&mData->mDarkroom);
+    AssertFatal(ok == 0,"Mutex Unlock failed on mDarkroom when leaving releaseSemaphore().");
+}

+ 67 - 0
engine/source/platformAndroid/AndroidStreamSource.cc

@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "AndroidStreamSource.h"
+#include "SoundEngine.h"
+
+#define BUFFERSIZE 32768
+
+AndroidStreamSource::AndroidStreamSource(const char *filename)  {
+	this->registerObject();
+	int len = dStrlen( filename );
+	mFilename = new char[len + 1];
+	dStrcpy( mFilename, filename );
+	//SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
+}
+
+AndroidStreamSource::~AndroidStreamSource() {
+	stop();
+	delete [] mFilename;
+	//SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
+}
+
+bool AndroidStreamSource::isPlaying() {
+	return true;
+}
+
+bool AndroidStreamSource::start( bool loop ) {
+	SoundEngine::SoundEngine_LoadBackgroundMusicTrack( mFilename, true, false );
+	SoundEngine::SoundEngine_StartBackgroundMusic();
+	if( !loop ) {
+		//stop at end
+		SoundEngine::SoundEngine_StopBackgroundMusic( true );
+		Con::executef(1,"onAndroidStreamEnd");
+	}
+	return true;
+}
+
+bool AndroidStreamSource::stop() {
+	//false == stop now
+	SoundEngine::SoundEngine_StopBackgroundMusic( false );
+	SoundEngine::SoundEngine_UnloadBackgroundMusicTrack();
+	return true;
+}
+    
+bool AndroidStreamSource::setVolume( F32 volume) {
+    SoundEngine::SoundEngine_SetBackgroundMusicVolume(volume);
+    return true;
+}

+ 40 - 0
engine/source/platformAndroid/AndroidStreamSource.h

@@ -0,0 +1,40 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef _ANDROIDSTREAMSOURCE_H_
+#define _ANDROIDSTREAMSOURCE_H_
+
+#include "sim/simBase.h"
+
+class AndroidStreamSource: public SimObject
+{
+	public:
+	char * mFilename;
+	AndroidStreamSource(const char *filename);
+	~AndroidStreamSource();
+	bool isPlaying();
+	bool start( bool loop = false );
+	bool stop();
+    bool setVolume( F32 volume);
+};
+
+#endif // _ANDROIDSTREAMSOURCE_H_

+ 425 - 0
engine/source/platformAndroid/AndroidStrings.cpp

@@ -0,0 +1,425 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/platform.h"
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdio.h>
+#include "console/console.h"
+#include "debug/profiler.h"
+
+char *dStrdup_r(const char *src, const char *file, dsize_t line)
+{
+   char *buffer = (char *) dMalloc_r(dStrlen(src) + 1, file, line);
+   dStrcpy(buffer, src);
+   return buffer;
+}
+
+char *dStrnew(const char *src)
+{
+   char *buffer = new char[dStrlen(src) + 1];
+   dStrcpy(buffer, src);
+   return buffer;
+}
+
+char* dStrcat(char *dst, const char *src)
+{
+   return strcat(dst,src);
+}   
+
+char* dStrncat(char *dst, const char *src, dsize_t len)
+{
+   return strncat(dst,src,len);
+}
+
+// concatenates a list of src's onto the end of dst
+// the list of src's MUST be terminated by a NULL parameter
+// dStrcatl(dst, sizeof(dst), src1, src2, NULL);
+char* dStrcatl(char *dst, dsize_t dstSize, ...)
+{
+   const char* src;
+   char *p = dst;
+
+   AssertFatal(dstSize > 0, "dStrcatl: destination size is set zero");
+   dstSize--;  // leave room for string termination
+
+   // find end of dst
+   while (dstSize && *p)
+   {
+       p++;
+      dstSize--;
+   }
+   
+   va_list args;
+   va_start(args, dstSize);
+
+   // concatenate each src to end of dst
+   while ( (src = va_arg(args, const char*)) != NULL )
+      while( dstSize && *src )
+      {
+         *p++ = *src++;
+         dstSize--;   
+      }
+
+   va_end(args);
+
+   // make sure the string is terminated 
+   *p = 0;
+
+   return dst;
+}   
+
+
+// copy a list of src's into dst
+// the list of src's MUST be terminated by a NULL parameter
+// dStrccpyl(dst, sizeof(dst), src1, src2, NULL);
+char* dStrcpyl(char *dst, dsize_t dstSize, ...)
+{
+   const char* src;
+   char *p = dst;
+
+   AssertFatal(dstSize > 0, "dStrcpyl: destination size is set zero");
+   dstSize--;  // leave room for string termination
+
+   va_list args;
+   va_start(args, dstSize);
+
+   // concatenate each src to end of dst
+   while ( (src = va_arg(args, const char*)) != NULL )
+      while( dstSize && *src )
+      {
+         *p++ = *src++;
+         dstSize--;   
+      }
+
+   va_end(args);
+
+   // make sure the string is terminated 
+   *p = 0;
+
+   return dst;
+}   
+
+
+int dStrcmp(const char *str1, const char *str2)
+{
+   return strcmp(str1, str2);   
+}
+
+int dStrcmp( const UTF16 *str1, const UTF16 *str2)
+{
+    int ret;
+    const UTF16 *a, *b;
+    a = str1;
+    b = str2;
+    
+    while(*a && *b && (ret = *a - *b) == 0)
+    {
+        a++, b++;
+    }
+    
+    if ( *a == 0 && *b != 0 )
+        return -1;
+    
+    if ( *b == 0 && *a != 0 )
+        return 1;
+    
+    return ret;
+}
+
+ 
+int dStricmp(const char *str1, const char *str2)
+{
+   char c1, c2;
+   while (1)
+   {
+      c1 = tolower(*str1++);
+      c2 = tolower(*str2++);
+      if (c1 < c2) return -1;
+      if (c1 > c2) return 1;
+      if (c1 == 0) return 0;
+   }
+}  
+
+int dStrncmp(const char *str1, const char *str2, dsize_t len)
+{
+   return strncmp(str1, str2, len);   
+}  
+ 
+int dStrnicmp(const char *str1, const char *str2, dsize_t len)
+{
+   S32 i;
+   char c1, c2;
+   for (i=0; i<len; i++)
+   {
+      c1 = tolower(*str1++);
+      c2 = tolower(*str2++);
+      if (c1 < c2) return -1;
+      if (c1 > c2) return 1;
+      if (!c1) return 0;
+     }
+   return 0;
+}   
+
+
+char* dStrcpy(char *dst, const char *src)
+{
+   AssertFatal(dst && src, "bad strings passed to dStrcpy()");
+   return strcpy(dst,src);
+}   
+
+char* dStrncpy(char *dst, const char *src, dsize_t len)
+{
+   return strncpy(dst,src,len);
+}   
+
+dsize_t dStrlen(const char *str)
+{
+   return str ? strlen(str) : 0;
+}   
+
+
+char* dStrupr(char *str)
+{
+   char* saveStr = str;
+   while (*str)
+   {
+      *str = toupper(*str);
+      str++;
+   }
+   return saveStr;
+}   
+
+
+char* dStrlwr(char *str)
+{
+   char* saveStr = str;
+   while (*str)
+   {
+      *str = tolower(*str);
+      str++;
+   }
+   return saveStr;
+}   
+
+
+char* dStrchr(char *str, int c)
+{
+   return strchr(str,c);
+}   
+
+
+const char* dStrchr(const char *str, int c)
+{
+   return strchr(str,c);
+}   
+
+const char* dStrrchr(const char *str, int c)
+{
+   return strrchr(str,c);
+}   
+
+
+char* dStrrchr(char *str, int c)
+{
+   return strrchr(str,c);
+}   
+
+dsize_t dStrspn(const char *str, const char *set)
+{
+   return(strspn(str, set));
+}
+
+dsize_t dStrcspn(const char *str, const char *set)
+{
+   return strcspn(str, set);
+}   
+
+
+char* dStrstr(char *str1, char *str2)
+{
+   return strstr(str1,str2);
+}
+
+char* dStrstr(const char *str1, const char *str2)
+{
+   return strstr(str1,str2);
+}   
+
+char* dStrtok(char *str, const char *sep)
+{
+   return strtok(str, sep);
+}
+
+
+int dAtoi(const char *str)
+{
+   if(!str)
+      return 0;
+   return atoi(str);
+}  
+
+ 
+float dAtof(const char *str)
+{
+   if(!str)
+      return 0;
+   return atof(str);   
+}   
+
+bool dAtob(const char *str)
+{
+   return !dStricmp(str, "true") || !dStricmp(str, "1") || (0!=dAtoi(str));
+}   
+
+bool dIsalnum(const char c)
+{
+   return isalnum(c);
+}
+
+bool dIsalpha(const char c)
+{
+   return(isalpha(c));
+}
+
+bool dIsspace(const char c)
+{
+   return(isspace(c));
+}
+
+bool dIsdigit(const char c)
+{
+   return(isdigit(c));
+}
+
+void dPrintf(const char *format, ...)
+{
+   va_list args;
+   va_start(args, format);
+   vprintf(format, args);
+}   
+
+int dVprintf(const char *format, void *arglist)
+{
+   S32 len = vprintf(format, (char*)arglist);
+
+   return (len);
+}   
+
+int dSprintf(char *buffer, dsize_t bufferSize, const char *format, ...)
+{
+   va_list args;
+   va_start(args, format);
+   S32 len = vsprintf(buffer, format, args);
+
+    // Sanity!
+    AssertFatal(len <= bufferSize, "dSprintf - String format exceeded buffer size.  This will cause corruption.");
+    
+   return (len);
+}   
+
+
+int dVsprintf(char *buffer, dsize_t bufferSize, const char *format, void *arglist)
+{
+	S32 len = vsprintf(buffer, format, (char*)arglist);
+
+    // Sanity!
+    AssertFatal(len <= bufferSize, "dSprintf - String format exceeded buffer size.  This will cause corruption.");
+    
+   return (len);
+}   
+
+//%PUAP% -Mat -----------------------------------------------------------------------------------------------
+
+int dStrrev(char* str)
+{
+	int l=dStrlen(str)-1; //get the string length
+	for(int x=0;x < l;x++,l--)
+	{
+		str[x]^=str[l];  //triple XOR Trick
+		str[l]^=str[x];  //for not using a temp
+		str[x]^=str[l];
+	}
+	return l;
+}
+
+//-Mat hack
+int dItoa(int n, char s[])
+{
+	int i, sign;
+	
+	if ((sign = n) < 0)  /* record sign */
+		n = -n;          /* make n positivNSStringe */
+	i = 0;
+	do {       /* generate digits in reverse order */
+		s[i++] = n % 10 + '0';   /* get next digit */
+	} while ((n /= 10) > 0);     /* delete it */
+	if (sign < 0)
+		s[i++] = '-';
+	s[i] = '\0';
+    
+    // Reverse string.
+	dStrrev(s);
+    
+    // Return length.
+    return dStrlen(s);
+} 
+
+//%PUAP%-----------------------------------------------------------------------------------------------------
+
+
+int dSscanf(const char *buffer, const char *format, ...)
+{
+   va_list args;
+   va_start(args, format);
+   return vsscanf(buffer, format, args);   
+}   
+
+int dFflushStdout()
+{
+   return fflush(stdout);
+}
+
+int dFflushStderr()
+{
+   return fflush(stderr);
+}
+
+void dQsort(void *base, U32 nelem, U32 width, int (QSORT_CALLBACK *fcmp)(const void *, const void *))
+{
+   qsort(base, nelem, width, fcmp);
+}   
+
+//TODO: need this?
+StringTableEntry Platform::createUUID( void )
+{
+    /*CFUUIDRef ref = CFUUIDCreate(nil);
+    NSString* uuid = (__bridge_transfer NSString *)CFUUIDCreateString(nil,ref);
+    CFRelease(ref);
+
+    StringTableEntry uuidString = StringTable->insert([uuid UTF8String]);
+    return uuidString;*/
+	return StringTable->insert("");
+}

+ 181 - 0
engine/source/platformAndroid/AndroidThread.cpp

@@ -0,0 +1,181 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include <pthread.h>
+#include "platform/threads/thread.h"
+#include "platform/platformSemaphore.h"
+#include "platform/threads/mutex.h"
+#include "platform/platformTLS.h"
+#include "memory/safeDelete.h"
+#include <stdlib.h>
+
+struct PlatformThreadData
+{
+   ThreadRunFunction       mRunFunc;
+   void*                   mRunArg;
+   Thread*                 mThread;
+   Semaphore               mGateway; // default count is 1
+   U32                     mThreadID;
+};
+
+//-----------------------------------------------------------------------------
+// Function:    ThreadRunHandler
+// Summary:     Calls Thread::run() with the thread's specified run argument.
+//               Neccesary because Thread::run() is provided as a non-threaded
+//               way to execute the thread's run function. So we have to keep
+//               track of the thread's lock here.
+static void *ThreadRunHandler(void * arg)
+{
+   PlatformThreadData *mData = reinterpret_cast<PlatformThreadData*>(arg);
+   Thread *thread = mData->mThread;
+
+   mData->mThreadID = ThreadManager::getCurrentThreadId();
+   ThreadManager::addThread(thread);
+   thread->run(mData->mRunArg);
+
+	mData->mGateway.release();
+   // we could delete the Thread here, if it wants to be auto-deleted...
+   if(thread->autoDelete)
+   {
+      ThreadManager::removeThread(thread);
+      delete thread;
+   }
+   // return value for pthread lib's benefit
+   return NULL;
+   // the end of this function is where the created pthread will die.
+}
+   
+//-----------------------------------------------------------------------------
+Thread::Thread(ThreadRunFunction func, void* arg, bool start_thread, bool autodelete)
+{
+   mData = new PlatformThreadData;
+   mData->mRunFunc = func;
+   mData->mRunArg = arg;
+   mData->mThread = this;
+   mData->mThreadID = 0;
+   autoDelete = autodelete;
+   
+   if(start_thread)
+      start();
+}
+
+Thread::~Thread()
+{
+   stop();
+   join();
+
+   SAFE_DELETE(mData);
+}
+
+void Thread::start()
+{
+   if(isAlive())
+      return;
+
+   // cause start to block out other pthreads from using this Thread, 
+   // at least until ThreadRunHandler exits.
+   mData->mGateway.acquire();
+
+   // reset the shouldStop flag, so we'll know when someone asks us to stop.
+   shouldStop = false;
+
+   pthread_create((pthread_t*)(&mData->mThreadID), NULL, ThreadRunHandler, mData);
+}
+
+bool Thread::join()
+{
+   if(!isAlive())
+      return true;
+
+   // not using pthread_join here because pthread_join cannot deal
+   // with multiple simultaneous calls.
+   mData->mGateway.acquire();
+   mData->mGateway.release();
+   return true;
+}
+
+void Thread::run(void* arg)
+{
+   if(mData->mRunFunc)
+      mData->mRunFunc(arg);
+}
+
+bool Thread::isAlive()
+{
+   if(mData->mThreadID == 0)
+      return false;
+
+   if( mData->mGateway.acquire(false) ) 
+   {
+     mData->mGateway.release();
+     return false; // we got the lock, it aint alive.
+   }
+   else
+     return true; // we could not get the lock, it must be alive.
+}
+
+U32 Thread::getId()
+{
+   return mData->mThreadID;
+}
+
+U32 ThreadManager::getCurrentThreadId()
+{
+   return (U32)pthread_self();
+}
+
+bool ThreadManager::compare(U32 threadId_1, U32 threadId_2)
+{
+   return (bool)pthread_equal((pthread_t)threadId_1, (pthread_t)threadId_2);
+}
+
+
+
+class PlatformThreadStorage
+{
+public:
+   pthread_key_t mThreadKey;
+};
+
+ThreadStorage::ThreadStorage()
+{
+   mThreadStorage = (PlatformThreadStorage *) mStorage;
+   constructInPlace(mThreadStorage);
+
+   pthread_key_create(&mThreadStorage->mThreadKey, NULL);
+}
+
+ThreadStorage::~ThreadStorage()
+{
+   pthread_key_delete(mThreadStorage->mThreadKey);
+}
+
+void *ThreadStorage::get()
+{
+   return pthread_getspecific(mThreadStorage->mThreadKey);
+}
+
+void ThreadStorage::set(void *value)
+{
+   pthread_setspecific(mThreadStorage->mThreadKey, value);
+}
+

+ 143 - 0
engine/source/platformAndroid/AndroidTime.cpp

@@ -0,0 +1,143 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformAndroid/platformAndroid.h"
+#include "game/gameInterface.h"
+
+#include <unistd.h>
+//--------------------------------------
+void Platform::getLocalTime(LocalTime &lt)
+{
+   struct tm systime;
+   time_t long_time;
+
+   /// Get time as long integer.
+   time( &long_time );
+   /// Convert to local time, thread safe.
+   localtime_r( &long_time, &systime );
+   
+   /// Fill the return struct
+   lt.sec      = systime.tm_sec;
+   lt.min      = systime.tm_min;
+   lt.hour     = systime.tm_hour;
+   lt.month    = systime.tm_mon;
+   lt.monthday = systime.tm_mday;
+   lt.weekday  = systime.tm_wday;
+   lt.year     = systime.tm_year;
+   lt.yearday  = systime.tm_yday;
+   lt.isdst    = systime.tm_isdst;
+}   
+
+/// Gets the time in seconds since the Epoch
+U32 Platform::getTime()
+{
+   time_t epoch_time;
+   time( &epoch_time );
+   return epoch_time;
+}   
+
+//TODO: mach?
+static mach_timebase_info_data_t InitTimebaseInfo();
+static mach_timebase_info_data_t timebase_info = InitTimebaseInfo();
+static double absolute_to_seconds;
+static double seconds_to_absolute;
+static double absolute_to_millis;
+static double millis_to_absolute;
+
+mach_timebase_info_data_t InitTimebaseInfo()
+{
+	mach_timebase_info_data_t timebase_info;
+	mach_timebase_info(&timebase_info);
+	absolute_to_seconds = timebase_info.numer / (1000000000.0 * timebase_info.denom);
+	seconds_to_absolute = 1.0 / absolute_to_seconds;
+	absolute_to_millis = timebase_info.numer / (1000000.0 * timebase_info.denom);
+	millis_to_absolute = 1.0 / absolute_to_millis;
+	
+	return timebase_info;
+}
+
+/// Gets the time in milliseconds since some epoch. In this case, system start time.
+/// Storing milisec in a U32 overflows every 49.71 days
+U32 Platform::getRealMilliseconds()
+{
+   // Duration is a S32 value.
+   // if negative, it is in microseconds.
+   // if positive, it is in milliseconds.
+	
+	Duration durTime = mach_absolute_time() * absolute_to_millis;
+   U32 ret;
+   if( durTime < 0 )
+      ret = durTime / -1000;
+   else 
+      ret = durTime;
+
+   return ret;
+}   
+
+U32 Platform::getVirtualMilliseconds()
+{
+   return platState.currentTime;   
+}   
+
+void Platform::advanceTime(U32 delta)
+{
+   platState.currentTime += delta;
+}   
+
+/// Asks the operating system to put the process to sleep for at least ms milliseconds
+void Platform::sleep(U32 ms)
+{
+   // note: this will overflow if you want to sleep for more than 49 days. just so ye know.
+   
+   //Luma:	Re-enable sleeping... why was it commented out? No sense in that!
+   usleep( ms * 1000 );
+}
+
+#pragma mark ---- TimeManager ----
+//--------------------------------------
+static void _AndroidUpdateSleepTicks()
+{
+   if (platState.backgrounded)
+      platState.sleepTicks = Platform::getBackgroundSleepTime();
+   else
+      platState.sleepTicks = sgTimeManagerProcessInterval;
+}
+
+//--------------------------------------
+void TimeManager::process()
+{
+   _AndroidUpdateSleepTicks();
+         
+   U32 curTime = Platform::getRealMilliseconds(); // GTC returns Milliseconds, FYI.
+   S32 elapsedTime = curTime - platState.lastTimeTick;
+
+   if(elapsedTime <= platState.sleepTicks)
+   {
+      Platform::sleep(platState.sleepTicks - elapsedTime);
+   }
+
+   platState.lastTimeTick = Platform::getRealMilliseconds();
+
+   TimeEvent event;
+   event.elapsedTime = elapsedTime;
+   Game->postEvent(event);
+}

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

@@ -0,0 +1,252 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "AndroidUtil.h"
+#include "io/stream.h"
+#include "io/fileStream.h"
+#include "io/memstream.h"
+#include "graphics/gPalette.h"
+#include "graphics/gBitmap.h"
+#include "memory/frameAllocator.h"
+#include "console/console.h"
+#include "platformAndroid/platformAndroid.h"
+
+//For networking bsd and IP
+#include <netinet/in.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+
+
+
+
+//Luma:	Orientation support
+int gAndroidGameCurrentOrientation = UIDeviceOrientationLandscapeRight;
+TCPObject* gpTCPObject = NULL;
+char gszTCPAddress[256];
+
+//-----------------------------------------------------------------------------
+void Platform::outputDebugString( const char *string )
+{
+    fprintf(stderr, "%s", string);
+    fprintf(stderr, "\n" );
+    fflush(stderr);
+}
+
+//--------------------------------------
+bool GBitmap::readPNGiPhone(Stream& io_rStream)
+{
+    int filesize = io_rStream.getStreamSize();
+    U8 *buff = new U8[filesize+1024];
+    
+    CGDataProviderRef data_provider = CGDataProviderCreateWithData(nil, buff, filesize, nil);
+    CGImageRef apple_image = CGImageCreateWithPNGDataProvider(data_provider, nil, false, kCGRenderingIntentDefault);
+    
+    // Choose alpha strategy based on whether the source image has alpha or not.
+    int width = CGImageGetWidth(apple_image);
+    int height = CGImageGetHeight(apple_image);
+    U32 rowBytes = width * 4;
+    
+    // Set up the row pointers...
+    AssertISV(width <= 1024, "Error, cannot load images wider than 1024 pixels!");
+    AssertISV(height <= 1024, "Error, cannot load images taller than 1024 pixels!");
+
+    BitmapFormat format = RGBA;
+    // actually allocate the bitmap space...
+    allocateBitmap(width, height,
+                   false,            // don't extrude miplevels...
+                   format);          // use determined format...
+
+    U8 *pBase = (U8*)getBits();
+    
+    CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
+    CGContextRef texture_context = CGBitmapContextCreate(pBase, width, height, 8, rowBytes, color_space, kCGImageAlphaPremultipliedLast);
+    
+    CGContextDrawImage(texture_context, CGRectMake(0.0, 0.0, width, height), apple_image);
+    
+    
+    CGImageRelease(apple_image);
+    CGDataProviderRelease(data_provider);
+
+    delete [] buff;
+    return true;
+}
+
+
+//Luma:	Orientation support
+int _AndroidGameGetOrientation()
+{
+    return gAndroidGameCurrentOrientation;
+}
+void _AndroidGameSetCurrentOrientation(int iOrientation)
+{
+    gAndroidGameCurrentOrientation = iOrientation;
+}
+
+S32 _AndroidGetPortraitTouchoffset()
+{
+    S32 offset = 0;
+    
+    S32 deviceType = Con::getIntVariable("$pref::Android::DeviceType");
+    
+    bool retinaEnabled = Con::getBoolVariable("$pref::Android::RetinaEnabled");
+    
+    if (deviceType == 2)
+        offset = 500;
+    else if (deviceType == 1)
+        offset = retinaEnabled ? 500 : 250;
+    else
+        offset = retinaEnabled ? 320 : 160;
+    
+    return offset;
+}
+
+//Luma: Ability to get the Local IP (Internal IP) for an Android as opposed to it's External one
+void _AndroidGetLocalIP(unsigned char *pcIPString)
+{
+    int a,b,c,d ; 
+    struct ifaddrs* interface;
+    char* addr;
+    
+    if (getifaddrs(&interface) == 0) 
+    {
+        struct ifaddrs* allInterfaces = interface;
+        while (interface != NULL) 
+        {
+            const struct sockaddr_in* address = (const struct sockaddr_in*) interface->ifa_addr;
+            addr = inet_ntoa(address->sin_addr);
+            if ((address->sin_family == AF_INET) && (strcmp(addr, "127.0.0.1" )))
+            {
+                break;
+            }
+            interface = interface->ifa_next;
+        }
+        freeifaddrs(allInterfaces);
+    }
+    
+    if(interface)
+    {
+        sscanf( addr, "%i.%i.%i.%i", &a, &b, &c, &d);
+    }
+    else
+    {
+        a = 0;
+        b = 0;
+        c = 0;
+        d = 0;
+        
+    }
+    pcIPString[0] = (unsigned char)a;
+    pcIPString[1] = (unsigned char)b;
+    pcIPString[2] = (unsigned char)c;
+    pcIPString[3] = (unsigned char)d;
+}
+
+
+//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
+static void TCPObjectConnectCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *dataIn, void *info)
+{
+    if(type == kCFSocketConnectCallBack) 
+    {
+        if(dataIn) 
+        {
+            SInt32 error = *((SInt32*)dataIn);
+            Con::printf("Error connecting with CFSocker: Error code %d\n",error);
+        }
+    }
+    
+    //regardless, we want to connect to the TCPObject if we opened the socket or not so that it can continue its process properly
+    if(gpTCPObject)
+    {
+        gpTCPObject->connect(gszTCPAddress);
+        gpTCPObject = NULL;
+    }
+}
+ 
+
+//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
+CFSocketRef CreateCFSocketToURLAndPort(const char *ipAddress, U16 port)
+{
+    CFSocketContext context;
+    context.version = 0;
+    context.info = NULL;
+    context.retain = NULL;
+    context.release = NULL;
+    context.copyDescription = NULL;
+                                    
+    CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault,
+                                        PF_INET,
+                                        SOCK_STREAM,
+                                        IPPROTO_TCP,
+                                        kCFSocketConnectCallBack,
+                                        TCPObjectConnectCallback,
+                                        &context);
+
+    struct sockaddr_in addr4;
+    memset(&addr4, 0, sizeof(addr4));
+
+    addr4.sin_family = AF_INET;
+    addr4.sin_len = sizeof(addr4);
+    addr4.sin_port = htons(port);
+    inet_aton(ipAddress, &addr4.sin_addr);
+
+    //TODO: objc
+    /*NSData *address = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
+    CFSocketConnectToAddress(socket, (__bridge CFDataRef)address, -1);
+
+    CFRunLoopSourceRef source;
+    source = CFSocketCreateRunLoopSource(NULL, socket, 1);
+    CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
+    CFRelease(source);*/
+    
+    return socket;
+}
+
+
+//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
+void OpenAndroidNetworkingAndConnectToTCPObject(TCPObject *psTCPObject, const char *pcAddress)
+{
+    
+    char remoteAddr[256];
+    //store TCPObject and Port in globals
+    gpTCPObject = psTCPObject;
+    if(psTCPObject)
+    {
+        dStrcpy(gszTCPAddress, pcAddress);
+    }
+    
+    //break up url / port to pass in	
+    dStrcpy(remoteAddr, pcAddress);
+    U16		port = 80;
+    char	*portString = dStrchr(remoteAddr, ':');
+    if(portString)
+    {
+        *portString++ = 0;
+        port = dAtoi(portString);
+    }
+
+    //call socket create function
+    CreateCFSocketToURLAndPort(remoteAddr, port);
+}
+
+
+

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

@@ -0,0 +1,39 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef _ANDROIDUTIL_H_
+#define _ANDROIDUTIL_H_
+
+
+#include "network/tcpObject.h"
+
+int _AndroidGameGetOrientation();
+void _AndroidGameSetCurrentOrientation(int iOrientation);
+S32 _AndroidGetPortraitTouchoffset();
+
+//Luma: Ability to get the Local IP (Internal IP) for an Android as opposed to it's External one
+void _AndroidGetLocalIP(unsigned char *pcIPString);
+
+//Luma: Make sure that the Android Radio is on before connection via TCP... NOTE: sometimes the Radio wont be ready for immediate use after this is processed... need to see why
+void OpenAndroidNetworkingAndConnectToTCPObject(TCPObject *psTCPObject, const char *pcAddress);
+
+#endif // _iOSUTIL_H_

+ 418 - 0
engine/source/platformAndroid/AndroidWindow.cpp

@@ -0,0 +1,418 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+
+#include "platformAndroid/platformAndroid.h"
+#include "platform/platformVideo.h"
+#include "platformAndroid/AndroidOGLVideo.h"
+#include "platformAndroid/AndroidConsole.h"
+#include "platform/platformInput.h"
+#include "game/gameInterface.h"
+#include "console/consoleTypes.h"
+#include "console/console.h"
+#include "platformAndroid/AndroidEvents.h"
+#include "platform/threads/thread.h"
+
+#include "platformAndroid/AndroidWindow.h"
+
+#include "platformAndroid/platformGL.h"
+
+bool setScreenOrientation(bool, bool);
+bool getStatusBarHidden();
+bool setStatusBarHidden(bool);
+void setStatusBarType(S32);
+
+//------------------------------------------------------------------------------
+#pragma mark ---- PlatState ----
+AndroidPlatState platState;
+
+AndroidPlatState::AndroidPlatState()
+{
+
+
+    captureDisplay = true;
+    fadeWindows = true;
+    backgrounded = false;
+    minimized = false;
+
+    quit = false;
+
+    portrait = true;//-Mat Android is in portrait mode by default
+
+
+    // start with something reasonable.
+    desktopBitsPixel = ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH;
+    desktopWidth = ANDROID_DEFAULT_RESOLUTION_X;
+    desktopHeight = ANDROID_DEFAULT_RESOLUTION_Y;
+    fullscreen = true;
+
+    osVersion = 0;
+
+    dStrcpy(appWindowTitle, "Android Torque Game Engine");
+
+    // Semaphore for alerts. We put the app in a modal state by blocking the main
+    alertSemaphore = Semaphore::createSemaphore(0);
+
+    // directory that contains main.cs . This will help us detect whether we are
+    // running with the scripts in the bundle or not.
+    mainDotCsDir = NULL;
+
+    mainLoopTimer = NULL;
+}
+
+
+//------------------------------------------------------------------------------
+// DGL, the Gui, and TS use this for various purposes.
+const Point2I &Platform::getWindowSize()
+{
+    return platState.windowSize;
+}
+
+
+//------------------------------------------------------------------------------
+// save the window size, for DGL's use
+void Platform::setWindowSize(U32 newWidth, U32 newHeight)
+{
+    platState.windowSize.set(newWidth, newHeight);
+}
+
+//------------------------------------------------------------------------------
+// Issue a minimize event. The standard handler will handle it.
+void Platform::minimizeWindow()
+{
+    //no minimizing on Android
+}
+
+void Platform::restoreWindow()
+{
+    //no minimizing on Android
+}
+
+//------------------------------------------------------------------------------
+void Platform::setWindowTitle(const char *title)
+{
+    //no window titles on Android
+}
+
+
+
+#pragma mark ---- Init funcs  ----
+//------------------------------------------------------------------------------
+void Platform::init()
+{
+    Con::setVariable("$platform", "Android");
+    
+    AndroidConsole::create();
+
+    //if ( !AndroidConsole::isEnabled() )
+    Input::init();
+
+    // allow users to specify whether to capture the display or not when going fullscreen
+    Con::addVariable("pref::mac::captureDisplay", TypeBool, &platState.captureDisplay);
+    Con::addVariable("pref::mac::fadeWindows", TypeBool, &platState.fadeWindows);
+
+    // create the opengl display device
+    DisplayDevice *dev = NULL;
+    Con::printf("Video Init:");
+    Video::init();
+    dev = OpenGLDevice::create();
+    if (dev)
+        Con::printf("   Accelerated OpenGL display device detected.");
+    else
+        Con::printf("   Accelerated OpenGL display device not detected.");
+
+    // and now we can install the device.
+    Video::installDevice(dev);
+    Con::printf("");
+}
+
+//------------------------------------------------------------------------------
+void Platform::shutdown()
+{
+    setMouseLock(false);
+    Video::destroy();
+    Input::destroy();
+    AndroidConsole::destroy();
+}
+
+
+//Hidden by Default. 1 Black Opaque, 2 Black Translucent
+S32 gStatusBarType = 0;
+bool gStatusBarHidden = true;
+
+//Landscape by default. 0 Landscape, 1 Portrait
+S32 gScreenOrientation = 0;
+bool gScreenUpsideDown = true;
+
+
+//------------------------------------------------------------------------------
+void Platform::initWindow(const Point2I &initialSize, const char *name)
+{
+    S32 resolutionWidth = ANDROID_DEFAULT_RESOLUTION_X;
+    S32 resolutionHeight = ANDROID_DEFAULT_RESOLUTION_Y;
+
+    // First fetch the values from the prefs.
+    U32 iDeviceOrientation = (U32) Con::getIntVariable("$pref::Android::ScreenOrientation");
+
+    // 0: iPhone
+    // 1: iPad
+    // 2: iPhone 5
+    if (iDeviceType == 2)
+    {
+        resolutionWidth = 1136;
+        resolutionHeight = 640;
+    }
+    else
+    {
+        U32 scaleFactor = retinaEnabled ? 2 : 1;
+
+        resolutionWidth = iDeviceType ? (1024 * scaleFactor) : (480 * scaleFactor);
+        resolutionHeight = iDeviceType ? (768 * scaleFactor) : (320 * scaleFactor);
+    }
+
+    Point2I startRes;
+
+    if (!iDeviceOrientation)
+    {
+        startRes.x = resolutionWidth;
+        startRes.y = resolutionHeight;
+    }
+    else
+    {
+        //portrait, swap width height.
+        startRes.x = resolutionHeight;
+        startRes.y = resolutionWidth;
+    }
+
+    dSprintf(platState.appWindowTitle, sizeof(platState.appWindowTitle), name);
+
+    platState.windowSize.x = startRes.x;
+    platState.windowSize.y = startRes.y;
+
+    //Get screen orientation prefs //Based on 0 Landscape, 1 Portrait
+    gScreenOrientation = iDeviceOrientation;
+    gScreenUpsideDown = Con::getBoolVariable("$pref::Android::ScreenUpsideDown");
+
+    //Default to landscape, and run into portrait if requested.
+    platState.portrait = false;
+
+    if (gScreenOrientation != 0) //fuzzytodo :add a constant
+    {
+        //Could handle other options here, later.
+        platState.portrait = true;
+    }
+
+    //We should now have a good windowSize, it will be default if initial size was bad
+    T2DView * glView;
+    CGRect rect;
+
+    rect.origin.x = 0;
+    rect.origin.y = 0;
+
+    rect.size.width = platState.windowSize.x;
+    rect.size.height = platState.windowSize.y;
+
+    glView = (T2DView *) platState.Window;
+    
+    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2)
+        glView.contentScaleFactor = [[UIScreen mainScreen] scale];
+    
+    platState.ctx = glView;
+    
+    //get status bar pref // 0 Hidden , 1 BlackOpaque , 2 BlackTranslucent
+    
+    S32 tempType = Con::getIntVariable("$pref::Android::StatusBarType");
+    setStatusBarType(tempType);
+    
+    //set screen orientation
+    setScreenOrientation(platState.portrait, gScreenUpsideDown);
+    
+    bool fullScreen;
+    U32 bpp = Con::getIntVariable("$pref::Android::ScreenDepth"); //ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH;
+    if (!bpp)
+    {
+        Con::printf("Default BPP Chosen , $pref::Android::ScreenDepth was not found.");
+        bpp = ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH;
+    }
+    
+    fullScreen = true;
+    //
+    DisplayDevice::init();
+    
+    // this will create a rendering context & window
+    bool ok = Video::setDevice("OpenGL", platState.windowSize.x, platState.windowSize.y, bpp, fullScreen);
+    if (!ok)
+    {
+        AssertFatal( false, "Could not find a compatible display device!" );
+    }
+    
+    //Luma:	Clear frame buffer to BLACK to start with
+    //NOTE:	This should probably be set by the user to be the color closest to Default.png in order to minimize any popping effect... $pref:: anyone? Are $pref::s even valid at this point in the Init process?
+    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+    glClear(GL_COLOR_BUFFER_BIT);
+}
+
+//--------------------------------------
+// run app function: not applicable to Android
+//--------------------------------------
+// run other apps
+int runApp(const char *fileName, const char *batchArgs, bool blocking = false)
+{
+    return 0;
+}
+
+bool appIsRunning(int batchId)
+{
+    return false;
+}
+
+bool Platform::openWebBrowser(const char *webAddress)
+{
+    NSString *string = [[NSString alloc] initWithUTF8String:webAddress];
+    NSURL *url = [[NSURL alloc] initWithString:string];
+    bool ret = [platState.application openURL:url];
+
+    return ret;// this bails on the application, switching to Safari
+}
+
+bool isStatusBarHidden()
+{
+    if (platState.application.statusBarHidden == YES)
+    {
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+}
+
+bool setStatusBarHidden(bool hidden)
+{
+    if (hidden)
+    {
+        platState.application.statusBarHidden = YES;
+        gStatusBarHidden = true;
+
+        return true;
+    }
+    else
+    {
+        platState.application.statusBarHidden = NO;
+        gStatusBarHidden = false;
+
+        return false;
+    }
+}
+
+void setStatusBarType(S32 type)
+{
+    switch (type)
+    {
+        case 0: //Hidden
+            setStatusBarHidden(true);
+            break;
+        case 1: //Black Opaque
+            platState.application.statusBarStyle = UIStatusBarStyleBlackOpaque;
+            setStatusBarHidden(false);
+            break;
+        case 2: //Black Transparent
+            platState.application.statusBarStyle = UIStatusBarStyleBlackTranslucent;
+            setStatusBarHidden(false);
+            break;
+        default:
+            platState.application.statusBarStyle = UIStatusBarStyleDefault;
+    }
+
+    gStatusBarType = type;
+}
+
+
+bool setScreenOrientation(bool portrait, bool upsidedown)
+{
+    bool success = false;
+
+    CGPoint point;
+    if (platState.portrait)
+    {
+        point.x = platState.windowSize.x / 2;
+        point.y = platState.windowSize.y / 2;
+    }
+    else
+    {
+        point.x = platState.windowSize.y / 2;
+        point.y = platState.windowSize.x / 2;
+    }
+
+
+    [platState.ctx centerOnPoint:point];
+
+    if (portrait)
+    {//normal upright
+        if (upsidedown)
+        {//button on top
+            [platState.ctx rotateToAngle:M_PI + (M_PI / 2.0)];//rotate to 90 degrees
+            platState.application.statusBarOrientation = UIInterfaceOrientationPortraitUpsideDown;
+            success = true;
+        } else
+        {//button on bottom
+            [platState.ctx rotateToAngle:(M_PI / 2.0)];//rotate to 270 degrees
+            platState.application.statusBarOrientation = UIInterfaceOrientationPortrait;
+            success = true;
+        }
+    } else
+    {//landscape/ sideways
+        if (upsidedown)
+        {//button on left
+            [platState.ctx rotateToAngle:0];//rotate to -180 (0) degrees
+            platState.application.statusBarOrientation = UIInterfaceOrientationLandscapeLeft;
+            success = true;
+        } else
+        {//button on right
+            [platState.ctx rotateToAngle:(M_PI)];//rotate to 180 degrees
+            platState.application.statusBarOrientation = UIInterfaceOrientationLandscapeRight;
+            success = true;
+        }
+    }
+
+    return success;
+}
+
+ConsoleFunction(setScreenOrientation, bool, 3, 3, "Sets the orientation of the screen ( portrait/landscape, upside down or right-side up )\n"
+        "@(bool portrait, bool upside_down)"){
+    return setScreenOrientation(dAtob(argv[1]), dAtob(argv[2]));
+}
+
+
+ConsoleFunction(getStatusBarHidden, bool, 1, 1, " Checks whether the status bar is hidden\n"
+        "@return Returns true if hidden and false if not"){
+    return isStatusBarHidden();
+}
+
+ConsoleFunction(setStatusBarHidden, bool, 2, 2, " Hides/unhides the Android status bar \n"
+        "@return true == status bar is hidden, false == status bar is visible"){
+    return setStatusBarHidden(dAtob(argv[1]));
+}
+
+ConsoleFunction(setStatusBarType, void, 2, 2, " Set the status bar type. 0 hidden, 1 Black Opaque, 2 Black Translucent \n"){
+    return setStatusBarType(dAtoi(argv[1]));
+}

+ 21 - 0
engine/source/platformAndroid/AndroidWindow.h

@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------

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

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

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

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

+ 108 - 0
engine/source/platformAndroid/T2DAppDelegate.cpp

@@ -0,0 +1,108 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import "platformiOS/T2DAppDelegate.h"
+
+#include "platform/platformInput.h"
+#include "platformiOS/iOSUtil.h"
+#include "console/console.h"
+
+extern void _iOSGameInnerLoop();
+extern void _iOSGameResignActive();
+extern void _iOSGameBecomeActive();
+extern void _iOSGameWillTerminate();
+
+// Store current orientation for easy access
+extern void _iOSGameChangeOrientation(S32 newOrientation);
+UIDeviceOrientation currentOrientation;
+
+bool _iOSTorqueFatalError = false;
+
+@implementation T2DAppDelegate
+
+@synthesize window = _window;
+
+
+- (void)applicationDidFinishLaunching:(UIApplication *)application {
+    
+	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
+	//Also we set the currentRotation up so its not invalid
+	currentOrientation = [UIDevice currentDevice].orientation;
+	//So we make a selector to handle that, called didRotate (lower down in the code)
+	[[NSNotificationCenter defaultCenter] addObserver:self
+											 selector:@selector(didRotate:)
+												 name:UIDeviceOrientationDidChangeNotification
+											   object:nil];
+}
+
+- (void)applicationWillResignActive:(UIApplication *)application
+{
+    _iOSGameResignActive();
+}
+
+- (void)applicationDidEnterBackground:(UIApplication *)application
+{
+    /*
+     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
+     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
+     */
+}
+
+- (void)applicationWillEnterForeground:(UIApplication *)application
+{
+    /*
+     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
+     */
+}
+
+- (void)applicationDidBecomeActive:(UIApplication *)application
+{
+    if(!_iOSTorqueFatalError)
+        _iOSGameBecomeActive();
+}
+
+- (void)applicationWillTerminate:(UIApplication *)application
+{
+    _iOSGameWillTerminate();
+	
+	[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
+}
+
+- (void)didRotate:(NSNotification *)notification
+{
+    //Default to landscape left
+	UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
+	if(currentOrientation != orientation)
+	{
+		//Change the orientation
+		currentOrientation = orientation;
+		//Tell the rest of the engine
+		_iOSGameChangeOrientation(currentOrientation);
+	}
+}
+
+- (void) runMainLoop
+{
+	_iOSGameInnerLoop();
+}
+
+@end

+ 32 - 0
engine/source/platformAndroid/T2DAppDelegate.h

@@ -0,0 +1,32 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import <UIKit/UIKit.h>
+#import <GLKit/GLKit.h>
+
+@interface T2DAppDelegate : NSObject <UIApplicationDelegate, GLKViewDelegate, GLKViewControllerDelegate> {
+	IBOutlet UIWindow *window;
+}
+
+@property (nonatomic, strong) UIWindow *window;
+
+@end

+ 205 - 0
engine/source/platformAndroid/T2DView.cpp

@@ -0,0 +1,205 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import "platformiOS/T2DView.h"
+//#import <QuartzCore/QuartzCore.h>
+//#include "platformiPhone/iPhoneEvents.h"
+
+#import "platformiOS/platformiOS.h"
+#import "platformiOS/platformGL.h"
+#import "platformiOS/iOSOGLVideo.h"
+#include "console/console.h"
+#include "math/mPoint.h"
+#include "platform/event.h"
+#include "game/gameInterface.h"
+#include "console/consoleInternal.h"
+#include "console/ast.h"
+#include "io/fileStream.h"
+#include "platformiOS/iOSUtil.h"
+#include "platformiOS/iOSEvents.h"
+#include "graphics/dgl.h"
+#include "debug/profiler.h"
+
+#define USE_DEPTH_BUFFER 0
+
+extern bool createMouseMoveEvent(S32 i, S32 x, S32 y, S32 lastX, S32 lastY);
+extern bool createMouseDownEvent(S32 touchNumber, S32 x, S32 y, U32 numTouches);
+extern bool createMouseUpEvent(S32 touchNumber, S32 x, S32 y, S32 lastX, S32 lastY, U32 numTouches); //EFM
+extern void createMouseTapEvent( S32 nbrTaps, S32 x, S32 y );
+
+bool retinaEnabled;
+
+void ConvertToRetina(CGPoint *p)
+{
+    p->x *= 2;
+    p->y *= 2;
+}
+
+@implementation T2DView
+
+@synthesize context = _context;
+@synthesize currentAngle;
+@synthesize isLayedOut;
+
+-(void)swapBuffers {
+	if( self.isLayedOut == true ) {
+		[self.context presentRenderbuffer:GL_RENDERBUFFER_OES];
+	}
+}
+
+- (void)layoutSubviews {
+}
+
+-(void)rotateByAngle:(CGFloat)angle {
+	
+	CGAffineTransform transform = self.transform;
+    
+	transform = CGAffineTransformRotate(transform, angle);
+	self.transform = transform;
+}
+
+-(void)rotateToAngle:(CGFloat)angle {
+	CGFloat rotateAmount = (angle - currentAngle);//need to make this work better
+	if( rotateAmount == 0 ) {
+		return;
+	}
+	currentAngle = angle;
+	[self rotateByAngle:rotateAmount];
+}
+
+-(void)centerOnPoint:(CGPoint)point {
+	self.center = point;
+}
+
+- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
+{
+    
+    NSUInteger touchCount = 0;
+    // Enumerates through all touch objects
+    for (UITouch *touch in touches)
+    {
+        CGPoint point = [touch locationInView:self];
+        
+        if (retinaEnabled)
+        {
+            ConvertToRetina(&point);
+        }
+        
+        S32 orientation = _iOSGameGetOrientation();
+        if (UIDeviceOrientationIsPortrait(orientation))
+        {
+            point.y -= _iOSGetPortraitTouchoffset();
+        }
+        
+        int numTouches = [touch tapCount];
+        createMouseDownEvent(touchCount, point.x, point.y, numTouches);
+        touchCount++;
+    }
+}
+
+
+extern Vector<Event *> TouchMoveEvents;
+
+
+- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
+{
+    
+    NSUInteger touchCount = 0;
+    // Enumerates through all touch objects
+    for (UITouch *touch in touches)
+    {
+        CGPoint point = [touch locationInView:self];
+        CGPoint prevPoint = [touch previousLocationInView:self]; //EFM
+        
+        if (retinaEnabled)
+        {
+            ConvertToRetina(&point);
+            ConvertToRetina(&prevPoint);
+        }
+        
+        S32 orientation = _iOSGameGetOrientation();
+        if (UIDeviceOrientationIsPortrait(orientation))
+        {
+            point.y -= _iOSGetPortraitTouchoffset();
+            prevPoint.y -= _iOSGetPortraitTouchoffset();
+        }
+        
+        createMouseMoveEvent(touchCount, point.x, point.y, prevPoint.x, prevPoint.y);
+        touchCount++;
+    }
+    
+}
+
+- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
+{
+    
+    NSUInteger touchCount = 0;
+    // Enumerates through all touch objects
+    for (UITouch *touch in touches)
+    {
+        CGPoint point = [touch locationInView:self];
+        CGPoint prevPoint = [touch previousLocationInView:self]; //EFM
+        
+        if (retinaEnabled)
+        {
+            ConvertToRetina(&point);
+            ConvertToRetina(&prevPoint);
+        }
+        
+        S32 orientation = _iOSGameGetOrientation();
+        if (UIDeviceOrientationIsPortrait(orientation))
+        {
+            point.y -= _iOSGetPortraitTouchoffset();
+            prevPoint.y -= _iOSGetPortraitTouchoffset();
+        }
+        
+        int tc = [touch tapCount];
+        createMouseUpEvent(touchCount, point.x, point.y, prevPoint.x, prevPoint.y, tc);
+        touchCount++;
+        
+        //Luma: Tap support
+        
+        if (tc > 0)
+        {
+            // this was a tap, so create a tap event
+            createMouseTapEvent(tc, (int) point.x, (int) point.y);
+        }
+    }
+    
+}
+
+- (void)touchesChangedWithEvent:(UIEvent *)event
+{
+    Con::printf("Touches Changed with Event");
+}
+
+- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
+{
+    [self touchesEnded:touches withEvent:event];
+}
+
+bool gScreenAutoRotate = false;
+int currentRotate = 0;
+#define ROTATE_LEFT		0
+#define ROTATE_RIGHT	1
+#define ROTATE_UP		2
+@end

+ 38 - 0
engine/source/platformAndroid/T2DView.h

@@ -0,0 +1,38 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import <GLKit/GLKit.h>
+
+@interface T2DView : GLKView {
+}
+
+@property (strong, nonatomic) EAGLContext *context;
+@property (nonatomic) CGFloat currentAngle;//for knowing our current oriantion
+@property (nonatomic) BOOL isLayedOut;
+
+- (void)swapBuffers;
+- (void)rotateByAngle:(CGFloat)angle;//rotate BY a certain degree
+- (void)rotateToAngle:(CGFloat)angle;//rotate TO a certain degree
+- (void)centerOnPoint:(CGPoint)point;//set the center position
+
+
+@end

+ 259 - 0
engine/source/platformAndroid/T2DViewController.cpp

@@ -0,0 +1,259 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import "T2DViewController.h"
+#import "platformiOS/platformGL.h"
+#include "platformiOS/iOSWindow.h"
+#include "platformiOS/platformiOS.h"
+#include "graphics/dgl.h"
+
+extern iOSPlatState platState;
+
+
+#define USE_DEPTH_BUFFER 0
+
+extern bool retinaEnabled;
+
+extern void ConvertToRetina (CGPoint *p);
+
+extern bool _iOSTorqueFatalError;
+extern int _iOSRunTorqueMain( id appID,  UIView *Window, T2DViewController *Controller );
+
+//-Mat we should update the accelereometer once per frame
+extern U32  AccelerometerUpdateMS;
+extern void _iOSGameInnerLoop();
+
+@implementation T2DViewController
+
+@synthesize context = _context;
+@synthesize connectionData = _connectionData;
+@synthesize connection = _connection;
+- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
+{
+    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
+    if (self) {
+        // Custom initialization
+    }
+    return self;
+}
+
+- (void)didReceiveMemoryWarning
+{
+    // Releases the view if it doesn't have a superview.
+    [super didReceiveMemoryWarning];
+    
+    // Release any cached data, images, etc that aren't in use.
+}
+
+#pragma mark - View lifecycle
+
+
+-(void)swapBuffers {
+	if( isLayedOut == true ) {
+		[self.context presentRenderbuffer:GL_RENDERBUFFER_OES];
+	}
+}
+
+- (BOOL)createFramebuffer {
+	
+	glGenFramebuffersOES(1, &viewFramebuffer);
+	glGenRenderbuffersOES(1, &viewRenderbuffer);
+	
+	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
+	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
+	[self.context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.view.layer];
+	glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
+	
+	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
+	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
+	
+	if (USE_DEPTH_BUFFER) {
+		glGenRenderbuffersOES(1, &depthRenderbuffer);
+		glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
+		glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
+		glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
+	}
+	
+	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
+		NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
+		return NO;
+	}
+	
+	return YES;
+}
+
+
+- (void)destroyFramebuffer {
+	
+	glDeleteFramebuffersOES(1, &viewFramebuffer);
+	viewFramebuffer = 0;
+	glDeleteRenderbuffersOES(1, &viewRenderbuffer);
+	viewRenderbuffer = 0;
+	
+	if(depthRenderbuffer) {
+		glDeleteRenderbuffersOES(1, &depthRenderbuffer);
+		depthRenderbuffer = 0;
+	}
+}
+
+// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
+- (void)viewDidLoad
+{
+    [super viewDidLoad];
+    
+    self.context = [[EAGLContext alloc]
+                    initWithAPI:kEAGLRenderingAPIOpenGLES1];
+    
+    if (!self.context) {
+        NSLog(@"Failed to create ES context");
+    }
+    
+    T2DView *view = (T2DView *) self.view;
+    view.context = self.context;
+    
+	if( AccelerometerUpdateMS <= 0 ) {
+        //Luma:	This variable needs to be store MS value, not Seconds value
+        AccelerometerUpdateMS = 33; // 33 ms
+	}
+	
+	//Luma: Do division by 1000.0f here to get the seconds value that the UIAccelerometer needs
+	//[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(AccelerometerUpdateMS / 1000.0f)];//this value is in seconds
+	//[[UIAccelerometer sharedAccelerometer] setDelegate:self];
+    
+	[EAGLContext setCurrentContext:self.context];
+	[self createFramebuffer];
+	
+    view.isLayedOut = true;
+    
+    //by default, we are in portrait(upright) mode
+	view.currentAngle = (M_PI / 2.0);
+    
+    platState.multipleTouchesEnabled = true;
+    [self.view setMultipleTouchEnabled:YES];
+    
+    retinaEnabled = false;
+    
+    if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2)
+        retinaEnabled = true;
+    
+    UIApplication * application = [UIApplication sharedApplication];
+    id appDelegate = [application delegate];
+    
+	_iOSTorqueFatalError = false;
+	if(!_iOSRunTorqueMain( appDelegate, self.view, self ))
+	{
+		_iOSTorqueFatalError = true;
+		return;
+	};
+}
+
+- (void)viewDidUnload
+{
+    [super viewDidUnload];
+    // Release any retained subviews of the main view.
+    if ([EAGLContext currentContext] == self.context) {
+        [EAGLContext setCurrentContext:nil];
+    }
+    
+    self.context = nil;
+}
+
+- (void)update
+{
+    _iOSGameInnerLoop();
+}
+
+- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
+{
+    // Return YES for supported orientations
+    
+    switch (interfaceOrientation)
+    {
+        case UIDeviceOrientationPortraitUpsideDown:
+            return mOrientationPortraitUpsideDownSupported;
+            break;
+            
+        case UIDeviceOrientationPortrait:
+            return mOrientationPortraitSupported;
+            break;
+            
+        case UIDeviceOrientationLandscapeRight:
+            return mOrientationLandscapeRightSupported;
+            break;
+            
+        case UIDeviceOrientationLandscapeLeft:
+            return mOrientationLandscapeLeftSupported;
+            break;
+            
+        default:
+            break;
+    }
+    
+    return NO;
+}
+
+
+- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
+{
+    return UIInterfaceOrientationLandscapeRight;
+}
+
+void supportLandscape( bool enable)
+{
+    platState.viewController->mOrientationLandscapeLeftSupported = enable;
+    platState.viewController->mOrientationLandscapeRightSupported = enable;
+}
+
+ConsoleFunction(supportLandscape, void, 2, 2, "supportLandscape( bool ) "
+                "enable or disable Landscape")
+{
+    bool enable = true;
+    if( argc > 1 )
+        enable = dAtob( argv[1] );
+    
+    supportLandscape(enable);
+}
+
+void supportPortrait( bool enable )
+{
+    platState.viewController->mOrientationPortraitSupported = enable;
+    platState.viewController->mOrientationPortraitUpsideDownSupported = enable;
+}
+
+ConsoleFunction(supportPortrait, void, 2, 2, "supportPortrait( bool ) "
+                "enable or disable portrait")
+{
+    bool enable = true;
+    if( argc > 1 )
+        enable = dAtob( argv[1] );
+    
+    supportPortrait(enable);
+}
+
+
+- (void)viewDidLayoutSubviews
+{
+    [self destroyFramebuffer];
+	[self createFramebuffer];
+}
+
+@end

+ 59 - 0
engine/source/platformAndroid/T2DViewController.h

@@ -0,0 +1,59 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import <GLKit/GLKit.h>
+
+
+@interface T2DViewController : GLKViewController {
+	/* The pixel dimensions of the backbuffer */
+	GLint backingWidth;
+	GLint backingHeight;
+	
+    /* OpenGL names for the renderbuffer and framebuffers used to render to this view */
+	GLuint viewRenderbuffer, viewFramebuffer;
+	
+	/* OpenGL name for the depth buffer that is attached to viewFramebuffer, if it exists (0 if it does not exist) */
+	GLuint depthRenderbuffer;
+    
+    GLuint _vertexBuffer;
+    GLuint _indexBuffer;
+    GLuint _vertexArray;
+    
+    bool isLayedOut;
+    
+@public
+    NSURLConnection *connection;
+    NSMutableData *connectionData;
+    bool mOrientationLandscapeRightSupported;
+    bool mOrientationLandscapeLeftSupported;
+    bool mOrientationPortraitSupported;
+    bool mOrientationPortraitUpsideDownSupported;
+}
+
+@property (strong, nonatomic) EAGLContext *context;
+
+@property (nonatomic, strong) NSURLConnection   *connection;
+@property (nonatomic, strong) NSMutableData     *connectionData;
+
+void supportLandscape( bool );
+void supportPortrait( bool );
+@end

+ 301 - 0
engine/source/platformAndroid/main.cpp

@@ -0,0 +1,301 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#import <UIKit/UIKit.h>
+
+#import "platformiOS/platformiOS.h"
+#import "platformiOS/T2DAppDelegate.h"
+#import "platformiOS/iOSEvents.h"
+#import "platformiOS/iOSUtil.h"
+#include "platform/threads/thread.h"
+#include "game/gameInterface.h"
+#include "io/fileObject.h"
+
+extern void clearPendingMultitouchEvents( void );
+
+S32 gLastStart = 0;
+
+bool appIsRunning = true;
+
+int _iOSRunTorqueMain( id appID, UIView * Window, T2DViewController *viewController)
+{
+    UIApplication *app = [UIApplication sharedApplication];
+    platState.viewController = viewController;
+    
+	platState.appID = appID;
+	platState.firstThreadId = ThreadManager::getCurrentThreadId();
+	platState.Window = Window;
+	platState.application = app;
+	
+	// Hidden by default.
+	platState.application.statusBarHidden = YES;
+	
+	printf("performing mainInit()\n");
+    
+	platState.lastTimeTick = Platform::getRealMilliseconds();
+    
+	if(!Game->mainInitialize(platState.argc, platState.argv))
+	{
+		return 0;
+	}
+
+    return true;
+}
+
+void _iOSGameInnerLoop()
+{
+    if (!appIsRunning)
+    {
+        return;
+    }
+    else if (Game->isRunning())
+    {
+		S32 start = Platform::getRealMilliseconds();
+		
+        Game->mainLoop();
+				
+        gLastStart = start;
+        
+	}
+	else
+	{
+		Game->mainShutdown();
+        
+		// Need to actually exit the application now
+		exit(0);
+	}
+}
+
+void _iOSGameResignActive()
+{
+    if ( Con::isFunction("oniOSResignActive") )
+        Con::executef( 1, "oniOSResignActive" );
+    
+    appIsRunning = false;
+}
+
+void _iOSGameBecomeActive()
+{
+	clearPendingMultitouchEvents( );
+    
+    if ( Con::isFunction("oniOSBecomeActive") )
+        Con::executef( 1, "oniOSBecomeActive" );
+    
+    appIsRunning = true;
+}
+
+void _iOSGameWillTerminate()
+{
+    if ( Con::isFunction("oniOSWillTerminate") )
+        Con::executef( 1, "oniOSWillTerminate" );
+    
+	Con::executef( 1, "onExit" );
+    
+	Game->mainShutdown();
+}
+
+// Store current orientation for easy access
+void _iOSGameChangeOrientation(S32 newOrientation)
+{    
+	_iOSGameSetCurrentOrientation(newOrientation);
+    
+    return;
+    
+    bool enableAutoOrientation = Con::getBoolVariable("$pref::iOS::EnableOrientationRotation");
+    int screenOrientation = Con::getIntVariable("$pref::iOS::ScreenOrientation");
+    bool allowOtherOrientation = Con::getBoolVariable("$pref::iOS::EnableOtherOrientationRotation");
+
+    // The rotation matching the project orientation must be allowed for any to occur
+    if (enableAutoOrientation)
+    {
+        // Start "collecting animations"
+        [UIView beginAnimations: nil context: nil];
+        
+        //  If the project is designed for landscape or it allows landscape rotation
+        if (screenOrientation == 0 || allowOtherOrientation)
+        {
+            if (newOrientation == UIDeviceOrientationLandscapeLeft)
+            {
+                platState.Window.transform = CGAffineTransformMakeRotation(M_PI*1.5);
+                Con::executef(1, "oniOSOrientationToLandscapeLeft");
+                //  Show animations
+                [UIView commitAnimations];
+                
+                return;
+            }
+            
+            if (newOrientation == UIDeviceOrientationLandscapeRight)
+            {
+                platState.Window.transform = CGAffineTransformMakeRotation(M_PI_2);
+                Con::executef(1, "oniOSOrientationToLandscapeRight");
+                //  Show animations
+                [UIView commitAnimations];
+                
+                return;
+            }
+        }
+        
+        // If the project is designed for portrait or it allows portrait rotation
+        if (screenOrientation == 1 ||  allowOtherOrientation)
+        {
+            if (newOrientation == UIDeviceOrientationPortrait)
+            {
+                platState.Window.transform = CGAffineTransformMakeRotation(M_PI*1.5);
+                Con::executef(1, "oniOSOrientationToPortrait");
+                //  Show animations
+                [UIView commitAnimations];
+                
+                return;
+            }
+            
+            if (newOrientation == UIDeviceOrientationPortraitUpsideDown)
+            {
+                platState.Window.transform = CGAffineTransformMakeRotation(M_PI_2);
+                Con::executef(1, "oniOSOrientationToPortraitUpsideDown");
+                //  Show animations
+                [UIView commitAnimations];
+                
+                return;
+            }
+        }
+        
+        // Show animations
+        [UIView commitAnimations];
+    }
+}
+
+static void _iOSGetTxtFileArgs(int &argc, char** argv, int maxargc)
+{
+    argc = 0;
+    
+    const U32 kMaxTextLen = 2048;
+    
+    U32 textLen;
+    
+    char* text = new char[kMaxTextLen];
+    
+    // Open the file, kick out if we can't
+    File cmdfile;
+    
+    File::Status err = cmdfile.open("iOSCmdLine.txt", cmdfile.Read);
+    
+    // Re-organise function to handle memory deletion better
+    if (err == File::Ok)
+    {
+        // read in the first kMaxTextLen bytes, kick out if we get errors or no data
+        err = cmdfile.read(kMaxTextLen-1, text, &textLen);
+        
+        if (((err == File::Ok || err == File::EOS) || textLen > 0))
+        {
+            // Null terminate
+            text[textLen++] = '\0';
+            
+            // Truncate to the 1st line of the file
+            for(int i = 0; i < textLen; i++)
+            {
+                if( text[i] == '\n' || text[i] == '\r' )
+                {
+                    text[i] = '\0';
+                    textLen = i+1;
+                    break;
+                }
+            }
+            
+            // Tokenize the args with nulls, save them in argv, count them in argc
+            char* tok;
+            
+            for(tok = dStrtok(text, " "); tok && argc < maxargc; tok = dStrtok(NULL, " "))
+                argv[argc++] = tok;
+		}
+	}
+	
+	// Close file and delete memory before returning
+    cmdfile.close();
+    
+	delete[] text;
+    
+	text = NULL;
+}
+
+int main(int argc, char *argv[])
+{
+    @autoreleasepool
+    {
+        int kMaxCmdlineArgs = 32; //Arbitrary
+        
+        printf("Initial Command Line\n");
+        
+        for( int i = 0; i < argc; i++ )
+        {
+            printf("%i : %s", i, argv[i] );
+        }
+        
+        NSString *nsStrVersion = [UIDevice currentDevice ].systemVersion;
+        const char *strVersion = [nsStrVersion UTF8String ];
+        platState.osVersion = dAtof( strVersion);
+        
+        // Find Main.cs .
+        const char* cwd = Platform::getMainDotCsDir();
+        
+        // Change to the directory that contains main.cs
+        Platform::setCurrentDirectory(cwd);
+        
+        // get the actual command line args
+        S32   newArgc = argc;
+        
+        const char* newArgv[kMaxCmdlineArgs];
+        
+        for(int i=0; i < argc && i < kMaxCmdlineArgs; i++)
+            newArgv[i] = argv[i];
+        
+        // get the text file args
+        S32 textArgc;
+        char* textArgv[kMaxCmdlineArgs];
+        
+        _iOSGetTxtFileArgs(textArgc, textArgv, kMaxCmdlineArgs);
+        
+        // merge them
+        int i=0;
+        
+        while(i < textArgc && newArgc < kMaxCmdlineArgs)
+            newArgv[newArgc++] = textArgv[i++];
+        
+        // store them in platState
+        platState.argc = newArgc;
+        platState.argv = newArgv;
+        
+        printf("\nMerged Command Line\n");
+        
+        for( int i = 0; i < platState.argc; i++ )
+        {
+            printf("%i : %s", i, platState.argv[i] );
+        }
+        
+        printf("\n");
+        
+        // now, we run UIApplication which calls back and starts thread or timer
+        platState.appReturn = UIApplicationMain(argc, argv, nil, NSStringFromClass([T2DAppDelegate class]));
+        
+        printf("exiting...\n");
+        return(platState.appReturn);
+    }
+}

+ 512 - 0
engine/source/platformAndroid/menus/popupMenu.cpp

@@ -0,0 +1,512 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#include "platformiOS/platformiOS.h"
+#include "platform/menus/popupMenu.h"
+#include "memory/safeDelete.h"
+#include "gui/guiCanvas.h"
+#include "platformiOS/iOSUtil.h"
+
+
+//The iPhone has it's own type of menu system
+#if 0 // PUAP -Mat file menus only can't use on iPhone
+
+
+//-----------------------------------------------------------------------------
+// Platform Menu Data
+//-----------------------------------------------------------------------------
+class PlatformPopupMenuData
+{
+public:
+   // We assign each new menu item an arbitrary integer tag.
+   static S32 getTag()
+   {
+      static S32 lastTag = 'TORQ';
+      return ++lastTag;
+   }
+
+   MenuRef mMenu;
+   S32 tag;
+   PlatformPopupMenuData()
+   {
+      mMenu = NULL;
+      tag = getTag();
+   }
+
+   ~PlatformPopupMenuData()
+   {
+      if(mMenu)
+         CFRelease(mMenu);
+      mMenu = NULL;
+   }
+};
+
+void PopupMenu::createPlatformPopupMenuData()
+{
+   mData = new PlatformPopupMenuData;
+}
+
+void PopupMenu::deletePlatformPopupMenuData()
+{
+   SAFE_DELETE(mData);
+}
+
+void PopupMenu::createPlatformMenu()
+{
+   OSStatus err = CreateNewMenu( mData->tag, kMenuAttrAutoDisable,&(mData->mMenu));
+   RetainMenu(mData->mMenu);
+   AssertFatal(err == noErr, "Could not create Carbon MenuRef");
+}
+
+static int _getModifierMask(const char* accel)
+{
+   int ret = 0;
+   if(dStrstr(accel, "ctrl"))
+      ret |= kMenuControlModifier;
+   if(dStrstr(accel, "shift"))
+      ret |= kMenuShiftModifier;
+   if(dStrstr(accel, "alt"))
+      ret |= kMenuOptionModifier;
+   if(!(dStrstr(accel, "cmd") || dStrstr(accel, "command")))
+      ret |= kMenuNoCommandModifier;
+   
+   return ret;
+}
+
+static void _assignCommandKeys(const char* accel, MenuRef menu, MenuItemIndex item)
+{
+   if(!(accel && *accel))
+      return;
+   
+   // get the modifier keys
+   char* _accel = dStrdup(accel);
+   _accel = dStrlwr(_accel);
+   int mods = _getModifierMask(_accel);
+
+   // accel is space or dash delimted.
+   // the modifier key is either the last token in accel, or the first char in accel.
+   char* key = dStrrchr(_accel, ' ');
+   if(!key)
+      key = dStrrchr(_accel, '-');
+   if(!key)
+      key = _accel;
+   else
+      key++;
+      
+   if(dStrlen(key) <= 1)
+   {
+      key[0] = dToupper(key[0]);
+      SetMenuItemCommandKey(menu, item, false, key[0]);
+   }
+   else
+   {
+      SInt16 glyph = kMenuNullGlyph;
+
+      //*** A lot of these mappings came from a listing at http://developer.apple.com/releasenotes/Carbon/HIToolboxOlderNotes.html
+      if(!dStricmp(key, "DELETE"))
+         glyph = kMenuDeleteRightGlyph;
+         
+      else if(!dStricmp(key, "HOME"))
+         glyph = kMenuNorthwestArrowGlyph;
+         
+      else if(!dStricmp(key, "END"))
+         glyph = kMenuSoutheastArrowGlyph;
+         
+      else if(!dStricmp(key, "BACKSPACE"))
+         glyph =  kMenuDeleteLeftGlyph;
+         
+      else if(!dStricmp(key, "TAB"))
+         glyph =  kMenuTabRightGlyph;
+         
+      else if(!dStricmp(key, "RETURN"))
+         glyph =  kMenuReturnGlyph;
+         
+      else if(!dStricmp(key, "ENTER"))
+         glyph =  kMenuEnterGlyph;
+         
+      else if(!dStricmp(key, "PG UP"))
+         glyph =  kMenuPageUpGlyph;
+         
+      else if(!dStricmp(key, "PG DOWN"))
+         glyph =  kMenuPageDownGlyph;
+         
+      else if(!dStricmp(key, "ESC"))
+         glyph =  kMenuEscapeGlyph;
+         
+      else if(!dStricmp(key, "LEFT"))
+         glyph =  kMenuLeftArrowGlyph;
+         
+      else if(!dStricmp(key, "RIGHT"))
+         glyph =  kMenuRightArrowGlyph;
+         
+      else if(!dStricmp(key, "UP"))
+         glyph =  kMenuUpArrowGlyph;
+
+      else if(!dStricmp(key, "DOWN"))
+         glyph =  kMenuDownArrowGlyph;
+
+      else if(!dStricmp(key, "SPACE"))
+         glyph =  kMenuSpaceGlyph;
+
+      else if(!dStricmp(key, "F1"))
+         glyph =  kMenuF1Glyph;
+
+      else if(!dStricmp(key, "F2"))
+         glyph =  kMenuF2Glyph;
+
+      else if(!dStricmp(key, "F3"))
+         glyph =  kMenuF3Glyph;
+
+      else if(!dStricmp(key, "F4"))
+         glyph =  kMenuF4Glyph;
+
+      else if(!dStricmp(key, "F5"))
+         glyph =  kMenuF5Glyph;
+
+      else if(!dStricmp(key, "F6"))
+         glyph =  kMenuF6Glyph;
+
+      else if(!dStricmp(key, "F7"))
+         glyph =  kMenuF7Glyph;
+
+      else if(!dStricmp(key, "F8"))
+         glyph =  kMenuF8Glyph;
+
+      else if(!dStricmp(key, "F9"))
+         glyph =  kMenuF9Glyph;
+
+      else if(!dStricmp(key, "F10"))
+         glyph =  kMenuF10Glyph;
+
+      else if(!dStricmp(key, "F11"))
+         glyph =  kMenuF11Glyph;
+
+      else if(!dStricmp(key, "F12"))
+         glyph =  kMenuF12Glyph;
+
+      else if(!dStricmp(key, "F13"))
+         glyph =  kMenuF13Glyph;
+
+      else if(!dStricmp(key, "F14"))
+         glyph =  kMenuF14Glyph;
+
+      else if(!dStricmp(key, "F15"))
+         glyph =  kMenuF15Glyph;
+
+      SetMenuItemKeyGlyph(menu, item, glyph);
+   }
+
+   SetMenuItemModifiers(menu, item, mods);
+}
+
+
+S32 PopupMenu::insertItem(S32 pos, const char *title, const char* accel)
+{
+   MenuItemIndex item;
+   CFStringRef cftitle;
+   MenuItemAttributes attr = 0;
+   
+   if(title && *title)
+      cftitle = CFStringCreateWithCString(NULL,title,kCFStringEncodingUTF8);
+   else
+   {
+      cftitle = CFSTR("-");
+      attr = kMenuItemAttrSeparator;
+   }
+      
+   InsertMenuItemTextWithCFString(mData->mMenu, cftitle, pos, attr, kHICommandTorque + 1);
+
+   // ensure that we have the correct index for the new menu item
+   MenuRef outref;
+   GetIndMenuItemWithCommandID(mData->mMenu, kHICommandTorque+1, 1, &outref, &item);
+   SetMenuItemCommandID(mData->mMenu, item, kHICommandTorque);
+   
+   // save a ref to the PopupMenu that owns this item.
+   PopupMenu* thisMenu = this;
+   SetMenuItemProperty(mData->mMenu, item, 'GG2d', 'ownr', sizeof(PopupMenu*), &thisMenu);
+   
+   // construct the accelerator keys
+   _assignCommandKeys(accel, mData->mMenu, item);
+   
+   S32 tag = PlatformPopupMenuData::getTag();
+   SetMenuItemRefCon(mData->mMenu, item, tag);
+   
+   return tag;
+}
+
+S32 PopupMenu::insertSubMenu(S32 pos, const char *title, PopupMenu *submenu)
+{
+   for(S32 i = 0;i < mSubmenus->size();i++)
+   {
+      if(submenu == (*mSubmenus)[i])
+      {
+         Con::errorf("PopupMenu::insertSubMenu - Attempting to add submenu twice");
+         return -1;
+      }
+   }
+
+   CFStringRef cftitle = CFStringCreateWithCString(NULL,title,kCFStringEncodingUTF8);
+   InsertMenuItemTextWithCFString(mData->mMenu, cftitle, pos, 0, kHICommandTorque + 1);
+   // ensure that we have the correct index for the new menu item
+   MenuRef outref;
+   MenuItemIndex item;
+   GetIndMenuItemWithCommandID(mData->mMenu, kHICommandTorque+1, 1, &outref, &item);
+   SetMenuItemCommandID(mData->mMenu, item, 0);
+   
+   S32 tag = PlatformPopupMenuData::getTag();
+   SetMenuItemRefCon( mData->mMenu, item, tag);
+   
+   // store a pointer to the PopupMenu this item represents. See PopupMenu::removeItem()
+   SetMenuItemProperty(mData->mMenu, item, 'GG2d', 'subm', sizeof(PopupMenu*), submenu);
+   
+   SetMenuItemHierarchicalMenu( mData->mMenu, item, submenu->mData->mMenu);
+   mSubmenus->addObject(submenu);
+   
+   return tag;
+}
+
+void PopupMenu::removeItem(S32 itemPos)
+{
+   PopupMenu* submenu;
+   itemPos++; // adjust torque -> mac menu index
+
+   OSStatus err = GetMenuItemProperty(mData->mMenu, itemPos, 'GG2d', 'subm', sizeof(PopupMenu*),NULL,&submenu);
+   if(err == noErr)
+      mSubmenus->removeObject(submenu);
+      
+   // deleting the item decrements the ref count on the mac submenu.
+   DeleteMenuItem(mData->mMenu, itemPos);
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+void PopupMenu::enableItem(S32 pos, bool enable)
+{
+   pos++; // adjust torque -> mac menu index.
+   if(enable)
+      EnableMenuItem(mData->mMenu, pos);
+   else
+      DisableMenuItem(mData->mMenu, pos);
+}
+
+void PopupMenu::checkItem(S32 pos, bool checked)
+{
+   CheckMenuItem(mData->mMenu, pos, checked);
+}
+
+void PopupMenu::checkRadioItem(S32 firstPos, S32 lastPos, S32 checkPos)
+{
+   // uncheck items
+   for(int i = firstPos; i <= lastPos; i++)
+      checkItem( i, false);
+   
+   // check the selected item
+   checkItem( checkPos, true);
+}
+
+bool PopupMenu::isItemChecked(S32 pos)
+{
+   CharParameter mark;
+   GetItemMark(mData->mMenu, pos, &mark);
+   return (mark == checkMark);
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+// this method really isn't necessary for the mac implementation
+bool PopupMenu::canHandleID(U32 iD)
+{
+   for(S32 i = 0;i < mSubmenus->size();i++)
+   {
+      PopupMenu *subM = dynamic_cast<PopupMenu *>((*mSubmenus)[i]);
+      if(subM == NULL)
+         continue;
+
+      if(subM->canHandleID(iD))
+         return true;
+   }
+
+   UInt32 refcon;
+   U32 nItems = CountMenuItems(mData->mMenu);
+   for(int i = 1; i <= nItems; i++)
+   {
+      GetMenuItemRefCon(mData->mMenu, i, &refcon);
+      if(refcon == iD)
+         return true;
+   }
+
+   return false;
+}
+
+bool PopupMenu::handleSelect(U32 command, const char *text /* = NULL */)
+{
+   // [tom, 8/20/2006] Pass off to a sub menu if it's for them
+   for(S32 i = 0;i < mSubmenus->size();i++)
+   {
+      PopupMenu *subM = dynamic_cast<PopupMenu *>((*mSubmenus)[i]);
+      if(subM == NULL)
+         continue;
+
+      if(subM->canHandleID(command))
+      {
+         return subM->handleSelect(command, text);
+      }
+   }
+
+   // ensure that this menu actually has an item with the specificed command / refcon.
+   // this is not strictly necessary, we're just doing it here to keep the behavior
+   // in line with the windows implementation.
+   UInt32 refcon;
+   U32 nItems = CountMenuItems(mData->mMenu);
+   S32 pos = -1;
+   for(int i = 1; i <= nItems; i++)
+   {
+      GetMenuItemRefCon(mData->mMenu, i, &refcon);
+      if(refcon == command)
+         pos = i;
+   }
+   if(pos == -1)
+   {
+      Con::errorf("PopupMenu::handleSelect - Could not find menu item position for ID %d ... this shouldn't happen!", command);
+      return false;
+   }
+
+   char textbuf[1024];
+   if(!text)
+   {
+      CFStringRef cfstr;
+      CopyMenuItemTextAsCFString(mData->mMenu, pos, &cfstr);
+      CFStringGetCString(cfstr,textbuf,sizeof(textbuf) - 1,kCFStringEncodingUTF8);
+      text = textbuf;
+   }
+   
+   // [tom, 8/20/2006] Wasn't handled by a submenu, pass off to script
+   return dAtob(Con::executef(this, 4, "onSelectItem", Con::getIntArg(pos - 1), text ? text : ""));
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+void PopupMenu::showPopup(S32 x /* = -1 */, S32 y /* = -1 */)
+{
+   if(x < 0 || y < 0)
+   {
+      Point2I p = Canvas->getCursorPos();
+      x = p.x;
+      y = p.y;
+   }
+
+   CGPoint native = iPhoneTorqueToNativeCoords(x, y);
+   U32 result = PopUpMenuSelect(mData->mMenu, native.y, native.x, 0);
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+void PopupMenu::attachToMenuBar(S32 pos, const char *title)
+{
+   CFStringRef cftitle = CFStringCreateWithCString(NULL,title,kCFStringEncodingUTF8);
+   SetMenuTitleWithCFString(mData->mMenu, cftitle);
+   InsertMenu(mData->mMenu, pos);
+}
+
+void PopupMenu::removeFromMenuBar()
+{
+   DeleteMenu(mData->tag);
+}
+
+#pragma mark -
+#pragma mark ---- menu event handler ----
+bool iPhoneHandleMenuCommand(void* hiCommand)
+{
+   HICommand *cmd = (HICommand*)hiCommand;
+   
+   if(cmd->commandID != kHICommandTorque)
+      return false;
+   
+   MenuRef menu = cmd->menu.menuRef;
+   MenuItemIndex item = cmd->menu.menuItemIndex;
+   
+   PopupMenu* torqueMenu;
+   OSStatus err = GetMenuItemProperty(menu, item, 'GG2d', 'ownr', sizeof(PopupMenu*), NULL, &torqueMenu);
+   AssertFatal(err == noErr, "Could not resolve the PopupMenu stored on a native menu item");
+   
+   UInt32 command;
+   err = GetMenuItemRefCon(menu, item, &command);
+   AssertFatal(err == noErr, "Could not find the tag of a native menu item");
+   
+   if(!torqueMenu->canHandleID(command))
+      Con::errorf("menu claims it cannot handle that id. how odd.");
+      
+   return torqueMenu->handleSelect(command,NULL);
+
+}
+
+
+
+#else
+S32 PopupMenu::insertItem(S32 pos, const char *title, const char* accel)
+{ return 0; }
+
+S32 PopupMenu::insertSubMenu(S32 pos, const char *title, PopupMenu *submenu)
+{ return 0; }
+
+void PopupMenu::removeItem(S32 itemPos)
+{}
+
+void PopupMenu::enableItem(S32 pos, bool enable)
+{}
+
+void PopupMenu::checkItem(S32 pos, bool checked)
+{}
+
+void PopupMenu::checkRadioItem(S32 firstPos, S32 lastPos, S32 checkPos)
+{}
+
+bool PopupMenu::isItemChecked(S32 pos)
+{ return false; }
+
+bool PopupMenu::canHandleID(U32 iD)
+{ return false; }
+
+bool PopupMenu::handleSelect(U32 command, const char *text /* = NULL */)
+{ return false; }
+
+void PopupMenu::showPopup(S32 x /* = -1 */, S32 y /* = -1 */)
+{}
+
+void PopupMenu::attachToMenuBar(S32 pos, const char *title)
+{}
+
+void PopupMenu::removeFromMenuBar()
+{}
+
+
+void PopupMenu::createPlatformPopupMenuData()
+{}
+
+void PopupMenu::deletePlatformPopupMenuData()
+{}
+
+void PopupMenu::createPlatformMenu()
+{}
+
+
+#endif

+ 141 - 0
engine/source/platformAndroid/platformAndroid.h

@@ -0,0 +1,141 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+#ifndef _PLATFORMIOS_H_
+#define _PLATFORMIOS_H_
+
+#import "UIKit/UIKit.h"
+
+
+#include "platform/platform.h"
+#include "math/mMath.h"
+#include "platformiOS/iOSEvents.h"
+
+#include "platformiOS/iOSOGLVideo.h"
+
+#include "platformiOS/T2DView.h"
+#include "platformiOS/T2DViewController.h"
+
+// Mich Note: Do not try to spend too much time analyzing this class.
+// It is planned to refactor the iOS platform layer and replace this
+// with a platform state similar to what OS X uses.
+class iOSPlatState
+{
+public:
+    bool              captureDisplay;
+    bool              fadeWindows;
+
+    id				 appID;
+    UIView			 *Window;
+    char              appWindowTitle[256];
+    bool              quit;
+    T2DView           *ctx;
+    T2DViewController *viewController;
+    bool              ctxNeedsUpdate;
+
+    bool			portrait;
+
+    S32               desktopBitsPixel;
+    S32               desktopWidth;
+    S32               desktopHeight;
+    U32               currentTime;
+    bool				 fullscreen;
+
+    U32               osVersion;
+
+    bool              tsmActive;
+
+    U32               firstThreadId;
+    U32               torqueThreadId;
+
+    void*             alertSemaphore;
+    S32               alertHit;
+    //   DialogRef         alertDlg;
+    //   EventQueueRef     mainEventQueue;
+
+    RandomLCG        platRandom;
+
+    bool              mouseLocked;
+    bool              backgrounded;
+    bool              minimized;
+
+    S32               sleepTicks;
+    S32               lastTimeTick;
+
+    Point2I           windowSize;
+
+    U32               appReturn;
+
+    U32               argc;
+    const char**      argv;
+
+
+    StringTableEntry  mainDotCsDir;
+
+    NSTimer			 *mainLoopTimer;
+    NSTimeInterval	 timerInterval;
+    UIApplication	*application;
+    //-Mat
+    bool		multipleTouchesEnabled;
+
+    iOSPlatState();
+};
+
+/// Global singleton that encapsulates a lot of mac platform state & globals.
+extern iOSPlatState platState;
+
+/// @name Misc Mac Plat Functions
+/// Functions that are used by multiple files in the mac plat, but too trivial
+/// to require their own header file.
+/// @{
+/// Fills gGLState with info about this gl renderer's capabilities.
+void getGLCapabilities(void);
+
+
+/// Display a file dialog.
+/// calls FileDialog::Execute() on \p dialog
+/// @param dialog The FileDialog object to Execute. A void* is used to cut down on header dependencies.
+/// @see platform/nativeDialogs/fileDialog.h
+void iOSShowDialog(void* dialog);
+
+/// Translates a Mac keycode to a Torque keycode
+U8 TranslateOSKeyCode(U8 vcode);
+/// @}
+
+/// @name Misc Mac Plat constants
+/// @{
+
+/// earlier versions of OSX don't have these convinience macros, so manually stick them here.
+#ifndef IntToFixed
+#define IntToFixed(a)    ((Fixed)(a) <<16)
+#define FixedToInt(a)   ((short)(((Fixed)(a) + fixed1/2) >> 16))
+#endif
+
+/// mouse wheel sensitivity factor
+const S32 kTMouseWheelMagnificationFactor = 25;
+
+/// @}
+
+
+
+#endif //_PLATFORMIOS_H_
+

+ 263 - 0
engine/source/platformAndroid/platformGL.h

@@ -0,0 +1,263 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2013 GarageGames, LLC
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+// IN THE SOFTWARE.
+//-----------------------------------------------------------------------------
+
+
+#ifndef _PLATFORMGL_H_
+#define _PLATFORMGL_H_
+
+#ifdef __OBJC__
+	#import <QuartzCore/QuartzCore.h>
+//#import <OpenGLES/EAGL.h>
+	#import <OpenGLES/ES1/gl.h>
+	#import <OpenGLES/ES1/glext.h>
+#else
+#include <QuartzCore/QuartzCore.h>
+//#include <OpenGLES/EAGL.h>
+#include <OpenGLES/ES1/gl.h>
+#include <OpenGLES/ES1/glext.h>
+#endif
+
+//------------------------------------------------------------------------------
+/// Overrides and implentations of opengl API to account for ogles differences
+// Include after OpenGLES headers
+#include "platformiOS/iOSGL2ES.h"
+
+
+/// Using aglMacro.h gives us signifigant performance gains in opengl immediate mode ( glVertex etc )
+#if !defined(TORQUE_DEBUG)
+//#define USE_AGL_MACRO
+#endif
+
+#if defined(USE_AGL_MACRO)
+#if !defined(AGLContext)
+typedef struct __AGLContextRec       *AGLContext;
+#endif
+#include <AGL/aglMacro.h>
+extern AGLContext agl_ctx;
+#endif
+
+
+#define MIN_RESOLUTION_X				1
+#define MIN_RESOLUTION_Y				1
+#define MIN_RESOLUTION_BIT_DEPTH		16
+#define MIN_RESOLUTION_XY_STRING		"480 320"
+
+#define IOS_DEFAULT_RESOLUTION_X		480
+#define IOS_DEFAULT_RESOLUTION_Y		480
+
+#define IOS_MAX_RESOLUTION_X			2048
+#define IOS_MAX_RESOLUTION_Y			2048
+
+#define IOS_DEFAULT_RESOLUTION_BIT_DEPTH	32
+
+#define IOS_SCREEN_PORTRAIT			0
+#define IOS_SCREEN_LANDSCAPE			1
+#define IOS_SCREEN_RIGHT_SIDE_UP		3
+#define IOS_SCREEN_UPSIDE_DOWN		4
+
+
+/// Allows outline mode drawing via a function pointer swapping trick.
+/// Must be included AFTER all the OpenGL headers.
+#include "platformiOS/iOSOutlineGL.h"
+
+
+//------------------------------------------------------------------------------
+/// This is legacy stuff for the d3d wrapper layer.
+// The code that requires these stubs should probably be ifdef'd out of any non w32 build
+//------------------------------------------------------------------------------
+extern GLboolean glAvailableVertexBufferEXT();
+extern GLint glAllocateVertexBufferEXT(GLsizei size, GLint format, GLboolean preserve);
+extern void* glLockVertexBufferEXT(GLint handle, GLsizei size);
+extern void glUnlockVertexBufferEXT(GLint handle);
+extern void glSetVertexBufferEXT(GLint handle);
+extern void glOffsetVertexBufferEXT(GLint handle, GLuint offset);
+extern void glFillVertexBufferEXT(GLint handle, GLint first, GLsizei count);
+extern void glFreeVertexBufferEXT(GLint handle);
+// these are extensions for glAllocateVertexBufferEXT
+#define GL_V12MTVFMT_EXT                      0x8702
+#define GL_V12MTNVFMT_EXT                     0x8703
+#define GL_V12FTVFMT_EXT                      0x8704
+#define GL_V12FMTVFMT_EXT                     0x8705
+//------------------------------------------------------------------------------
+
+// make sure this is defined, as we need to use it when around.
+// some versions of OSX only define the SGIS version ( same hexcode )
+//#ifndef GL_CLAMP_TO_EDGE_EXT
+//#define GL_CLAMP_TO_EDGE_EXT                     0x812F
+//#endif
+
+/// GL state information.
+struct GLState
+{
+   bool suppARBMultitexture;
+   bool suppEXTblendcolor;
+   bool suppEXTblendminmax;
+   bool suppPackedPixels;
+   bool suppTexEnvAdd;
+   bool suppLockedArrays;
+
+   bool suppTextureEnvCombine;
+   bool suppVertexArrayRange;
+   bool suppFogCoord;
+   bool suppEdgeClamp;
+
+   bool suppTextureCompression;
+   bool suppS3TC;
+   bool suppFXT1;
+   bool suppTexAnisotropic;
+
+   bool suppPalettedTexture;
+   bool suppVertexBuffer;
+   bool suppSwapInterval;
+
+   GLint maxFSAASamples;
+
+   unsigned int triCount[4];
+   unsigned int primCount[4];
+   unsigned int primMode; // 0-3
+
+   GLfloat maxAnisotropy;
+   GLint   maxTextureUnits;
+};
+
+extern GLState gGLState;
+
+extern bool gOpenGLDisablePT;
+extern bool gOpenGLDisableCVA;
+extern bool gOpenGLDisableTEC;
+extern bool gOpenGLDisableARBMT;
+extern bool gOpenGLDisableFC;
+extern bool gOpenGLDisableTCompress;
+extern bool gOpenGLNoEnvColor;
+extern float gOpenGLGammaCorrection;
+extern bool gOpenGLNoDrawArraysAlpha;
+
+//------------------------------------------------------------------------------
+/// Inline state getters for dgl
+//------------------------------------------------------------------------------
+inline void dglSetRenderPrimType(unsigned int type)
+{
+   gGLState.primMode = type;
+}
+
+inline void dglClearPrimMetrics()
+{
+   for(int i = 0; i < 4; i++)
+      gGLState.triCount[i] = gGLState.primCount[i] = 0;
+}
+
+inline bool dglDoesSupportPalettedTexture()
+{
+   return gGLState.suppPalettedTexture && (gOpenGLDisablePT == false);
+}
+
+inline bool dglDoesSupportCompiledVertexArray()
+{
+   return gGLState.suppLockedArrays && (gOpenGLDisableCVA == false);
+}
+
+inline bool dglDoesSupportTextureEnvCombine()
+{
+   return gGLState.suppTextureEnvCombine && (gOpenGLDisableTEC == false);
+}
+
+inline bool dglDoesSupportARBMultitexture()
+{
+   return gGLState.suppARBMultitexture && (gOpenGLDisableARBMT == false);
+}
+
+inline bool dglDoesSupportEXTBlendColor()
+{
+   return gGLState.suppEXTblendcolor;
+}
+
+inline bool dglDoesSupportEXTBlendMinMax()
+{
+   return gGLState.suppEXTblendminmax;
+}
+
+inline bool dglDoesSupportVertexArrayRange()
+{
+   return gGLState.suppVertexArrayRange;
+}
+
+inline bool dglDoesSupportFogCoord()
+{
+   return gGLState.suppFogCoord && (gOpenGLDisableFC == false);
+}
+
+inline bool dglDoesSupportEdgeClamp()
+{
+   return gGLState.suppEdgeClamp;
+}
+
+inline bool dglDoesSupportTextureCompression()
+{
+   return gGLState.suppTextureCompression && (gOpenGLDisableTCompress == false);
+}
+
+inline bool dglDoesSupportS3TC()
+{
+   return gGLState.suppS3TC;
+}
+
+inline bool dglDoesSupportFXT1()
+{
+   return gGLState.suppFXT1;
+}
+
+inline bool dglDoesSupportTexEnvAdd()
+{
+   return gGLState.suppTexEnvAdd;
+}
+
+inline bool dglDoesSupportTexAnisotropy()
+{
+   return gGLState.suppTexAnisotropic;
+}
+
+inline bool dglDoesSupportVertexBuffer()
+{
+   return false;
+}
+
+inline GLfloat dglGetMaxAnisotropy()
+{
+   return gGLState.maxAnisotropy;
+}
+
+inline GLint dglGetMaxTextureUnits()
+{
+   if (dglDoesSupportARBMultitexture())
+      return gGLState.maxTextureUnits;
+   else
+      return 1; 
+}
+
+//------------------------------------------------------------------------------
+/// For radeon cards we can do fast FSAA mode switching.
+/// Sets Full Scene Anti-Aliasing (FSAA) samples ( 1x, 2x, 4x ) via aglSetInteger()
+//------------------------------------------------------------------------------
+#define ATI_FSAA_LEVEL ((unsigned long)510)  
+void dglSetFSAASamples(GLint aasamp);
+
+#endif // _PLATFORMGL_H_